-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathupdate.go
More file actions
459 lines (395 loc) · 14 KB
/
update.go
File metadata and controls
459 lines (395 loc) · 14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
// Copyright 2021 - See NOTICE file for copyright holders.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package client
import (
"context"
"github.com/pkg/errors"
"perun.network/go-perun/channel"
"perun.network/go-perun/log"
pcontext "perun.network/go-perun/pkg/context"
"perun.network/go-perun/pkg/sync/atomic"
"perun.network/go-perun/wallet"
"perun.network/go-perun/wire"
)
// handleChannelUpdate forwards incoming channel update requests to the
// respective channel's update handler (Channel.handleUpdateReq). If the channel
// is unknown, an error is logged.
//
// This handler is dispatched from the Client.Handle routine.
func (c *Client) handleChannelUpdate(uh UpdateHandler, p wire.Address, m ChannelUpdateProposal) {
ch, ok := c.channels.Get(m.Base().ID())
if !ok {
if !c.cacheVersion1Update(uh, p, m) {
c.logChan(m.Base().ID()).WithField("peer", p).Error("received update for unknown channel")
}
return
}
pidx := ch.Idx() ^ 1
ch.handleUpdateReq(pidx, m, uh)
}
func (c *Client) cacheVersion1Update(uh UpdateHandler, p wire.Address, m ChannelUpdateProposal) bool {
c.version1Cache.mu.Lock()
defer c.version1Cache.mu.Unlock()
if !(m.Base().State.Version == 1 && c.version1Cache.enabled > 0) {
return false
}
c.version1Cache.cache = append(c.version1Cache.cache, cachedUpdate{
uh: uh,
p: p,
m: m,
})
return true
}
type (
// ChannelUpdate is a channel update proposal.
ChannelUpdate struct {
// State is the proposed new state.
State *channel.State
// ActorIdx is the actor causing the new state. It does not need to
// coincide with the sender of the request.
ActorIdx channel.Index
}
// An UpdateHandler decides how to handle incoming channel update requests
// from other channel participants.
UpdateHandler interface {
// HandleUpdate is the user callback called by the channel controller on an
// incoming update request. The first argument contains the current state
// of the channel before the update is applied. Clone it if you want to
// modify it.
HandleUpdate(*channel.State, ChannelUpdate, *UpdateResponder)
}
// UpdateHandlerFunc is an adapter type to allow the use of functions as
// update handlers. UpdateHandlerFunc(f) is an UpdateHandler that calls
// f when HandleUpdate is called.
UpdateHandlerFunc func(*channel.State, ChannelUpdate, *UpdateResponder)
// The UpdateResponder allows the user to react to the incoming channel update
// request. If the user wants to accept the update, Accept() should be called,
// otherwise Reject(), possibly giving a reason for the rejection.
// Only a single function must be called and every further call causes a
// panic.
UpdateResponder struct {
channel *Channel
pidx channel.Index
req ChannelUpdateProposal
called atomic.Bool
}
// RequestTimedOutError indicates that a peer has not responded within the
// expected time period.
RequestTimedOutError string
)
// HandleUpdate calls the update handler function.
func (f UpdateHandlerFunc) HandleUpdate(s *channel.State, u ChannelUpdate, r *UpdateResponder) {
f(s, u, r)
}
// Accept lets the user signal that they want to accept the channel update.
func (r *UpdateResponder) Accept(ctx context.Context) error {
if ctx == nil {
return errors.New("context must not be nil")
}
if !r.called.TrySet() {
log.Panic("multiple calls on channel update responder")
}
return r.channel.handleUpdateAcc(ctx, r.pidx, r.req)
}
// Reject lets the user signal that they reject the channel update.
func (r *UpdateResponder) Reject(ctx context.Context, reason string) error {
if ctx == nil {
return errors.New("context must not be nil")
}
if !r.called.TrySet() {
log.Panic("multiple calls on channel update responder")
}
return r.channel.handleUpdateRej(ctx, r.pidx, r.req, reason)
}
// Update proposes the `next` state to all channel participants.
// `next` should not be modified while this function runs.
//
// Returns nil if all peers accept the update. Returns RequestTimedOutError if
// any peer did not respond before the context expires or is cancelled. Returns
// an error if any runtime error occurs or any peer rejects the update.
func (c *Channel) Update(ctx context.Context, next *channel.State) (err error) {
if ctx == nil {
return errors.New("context must not be nil")
}
// Lock machine while update is in progress.
if !c.machMtx.TryLockCtx(ctx) {
return errors.Errorf("locking machine mutex in time: %v", ctx.Err())
}
defer c.machMtx.Unlock()
if err := c.validTwoPartyUpdateState(next); err != nil {
return err
}
return c.update(ctx, next)
}
// Like Update, but assumes channel locked and update validated.
func (c *Channel) update(ctx context.Context, next *channel.State) (err error) {
return c.updateGeneric(ctx, next, func(mcu *msgChannelUpdate) wire.Msg { return mcu })
}
// Like update, but for generic update types.
func (c *Channel) updateGeneric(
ctx context.Context,
next *channel.State,
prepareMsg func(*msgChannelUpdate) wire.Msg,
) (err error) {
up := makeChannelUpdate(next, c.machine.Idx())
if err = c.machine.Update(ctx, up.State, up.ActorIdx); err != nil {
return errors.WithMessage(err, "updating machine")
}
// if anything goes wrong from now on, we discard the update.
// TODO: this is insecure after we sent our signature.
defer func() { c.handleUpdateError(ctx, err) }()
sig, err := c.machine.Sig(ctx)
if err != nil {
return errors.WithMessage(err, "signing update")
}
resRecv, err := c.conn.NewUpdateResRecv(up.State.Version)
if err != nil {
return errors.WithMessage(err, "creating update response receiver")
}
// nolint:errcheck
defer resRecv.Close()
msgUpdate := &msgChannelUpdate{
ChannelUpdate: up,
Sig: sig,
}
msg := prepareMsg(msgUpdate)
if err = c.conn.Send(ctx, msg); err != nil {
return errors.WithMessage(err, "sending update")
}
pidx, res, err := resRecv.Next(ctx)
if err != nil {
if pcontext.IsContextError(err) {
err = newRequestTimedOutError("channel update", err.Error())
return err
}
return errors.WithMessage(err, "receiving update response")
}
c.Log().Tracef("Received update response (%T): %v", res, res)
if rej, ok := res.(*msgChannelUpdateRej); ok {
return newPeerRejectedError("channel update", rej.Reason)
}
acc := res.(*msgChannelUpdateAcc) // safe by predicate of the updateResRecv
if err := c.machine.AddSig(ctx, pidx, acc.Sig); err != nil {
return errors.WithMessage(err, "adding peer signature")
}
return c.enableNotifyUpdate(ctx)
}
func (c *Channel) handleUpdateError(ctx context.Context, updateErr error) {
if updateErr != nil {
if derr := c.machine.DiscardUpdate(ctx); derr != nil {
// discarding update should never fail
c.Log().Warn("discarding update failed:", derr)
}
}
}
// UpdateBy updates the channel state using the update function and proposes the
// new state to all other channel participants. The update function must not
// update the version counter.
//
// Returns nil if all peers accept the update. Returns RequestTimedOutError if
// any peer did not respond before the context expires or is cancelled. Returns
// an error if any runtime error occurs or any peer rejects the update.
func (c *Channel) UpdateBy(ctx context.Context, update func(*channel.State) error) (err error) {
if ctx == nil {
return errors.New("context must not be nil")
}
// Lock machine while update is in progress.
if !c.machMtx.TryLockCtx(ctx) {
return errors.Errorf("locking machine mutex in time: %v", ctx.Err())
}
defer c.machMtx.Unlock()
return c.updateBy(ctx,
func(state *channel.State) error {
// apply update
if err := update(state); err != nil {
return err
}
// validate
return c.validTwoPartyUpdateState(state)
},
)
}
// Like UpdateBy, but assumes channel locked and update validated.
func (c *Channel) updateBy(ctx context.Context, update func(*channel.State) error) (err error) {
state := c.machine.State().Clone()
if err := update(state); err != nil {
return err
}
state.Version++
return c.update(ctx, state)
}
// handleUpdateReq is called by the controller on incoming channel update
// requests.
func (c *Channel) handleUpdateReq(
pidx channel.Index,
req ChannelUpdateProposal,
uh UpdateHandler,
) {
c.machMtx.Lock() // Lock machine while update is in progress.
defer c.machMtx.Unlock()
if err := c.machine.CheckUpdate(req.Base().State, req.Base().ActorIdx, req.Base().Sig, pidx); err != nil {
// TODO: how to handle invalid updates? Just drop and ignore them?
c.logPeer(pidx).Warnf("invalid update received: %v", err)
return
}
responder := &UpdateResponder{channel: c, pidx: pidx, req: req}
client := c.client
if prop, ok := req.(*virtualChannelFundingProposal); ok {
client.handleVirtualChannelFundingProposal(c, prop, responder)
return
}
if prop, ok := req.(*virtualChannelSettlementProposal); ok {
client.handleVirtualChannelSettlementProposal(c, prop, responder)
return
}
if ui, ok := c.subChannelFundings.Filter(req.Base().ChannelUpdate); ok {
ui.HandleUpdate(req.Base().ChannelUpdate, responder)
return
}
if ui, ok := c.subChannelWithdrawals.Filter(req.Base().ChannelUpdate); ok {
ui.HandleUpdate(req.Base().ChannelUpdate, responder)
return
}
if err := c.validTwoPartyUpdate(req.Base().ChannelUpdate, pidx); err != nil {
// TODO: how to handle invalid updates? Just drop and ignore them?
c.logPeer(pidx).Warnf("invalid update received: %v", err)
return
}
uh.HandleUpdate(c.machine.State(), req.Base().ChannelUpdate, responder)
}
func (c *Channel) handleUpdateAcc(
ctx context.Context,
pidx channel.Index,
req ChannelUpdateProposal,
) (err error) {
defer func() {
if err != nil {
c.logPeer(pidx).Errorf("error accepting state: %v", err)
}
}()
// machine.Update and AddSig should never fail after CheckUpdate...
if err = c.machine.Update(ctx, req.Base().State, req.Base().ActorIdx); err != nil {
return errors.WithMessage(err, "updating machine")
}
// if anything goes wrong from now on, we discard the update.
// TODO: this is insecure after we sent our signature.
defer func() {
if err != nil {
// we discard the update if anything went wrong
if derr := c.machine.DiscardUpdate(ctx); derr != nil {
// discarding update should never fail at this point
err = errors.WithMessagef(derr,
"sending accept message failed: %v, then discarding update failed", err)
}
}
}()
if err = c.machine.AddSig(ctx, pidx, req.Base().Sig); err != nil {
return errors.WithMessage(err, "adding peer signature")
}
var sig wallet.Sig
sig, err = c.machine.Sig(ctx)
if err != nil {
return errors.WithMessage(err, "signing updated state")
}
// If subchannel is final, register settlement update at parent channel.
if c.IsSubChannel() && req.Base().State.IsFinal {
c.Parent().registerSubChannelSettlement(c.ID(), req.Base().State.Balances)
}
msgUpAcc := &msgChannelUpdateAcc{
ChannelID: c.ID(),
Version: req.Base().State.Version,
Sig: sig,
}
if err := c.conn.Send(ctx, msgUpAcc); err != nil {
return errors.WithMessage(err, "sending accept message")
}
return c.enableNotifyUpdate(ctx)
}
func (c *Channel) handleUpdateRej(
ctx context.Context,
pidx channel.Index,
req ChannelUpdateProposal,
reason string,
) (err error) {
defer func() {
if err != nil {
c.logPeer(pidx).Errorf("error rejecting state: %v", err)
}
}()
msgUpRej := &msgChannelUpdateRej{
ChannelID: c.ID(),
Version: req.Base().State.Version,
Reason: reason,
}
return errors.WithMessage(c.conn.Send(ctx, msgUpRej), "sending reject message")
}
// enableNotifyUpdate enables the current staging state of the machine. If the
// state is final, machine.EnableFinal is called. Finally, if there is a
// notification on channel updates, the enabled state is sent on it.
func (c *Channel) enableNotifyUpdate(ctx context.Context) error {
var err error
from := c.machine.State()
to := c.machine.StagingState()
if to.IsFinal {
err = c.machine.EnableFinal(ctx)
} else {
err = c.machine.EnableUpdate(ctx)
}
if err != nil {
return errors.WithMessage(err, "enabling update")
}
if c.onUpdate != nil {
c.onUpdate(from, to)
}
return nil
}
// OnUpdate sets up a callback to state updates for the channel.
// The subscription cannot be canceled, but it can be replaced.
// The States that are passed to the callback are not clones but pointers to the
// State in the channel machine, so they must not be modified. If you need to
// modify the State, .Clone() them first.
func (c *Channel) OnUpdate(cb func(from, to *channel.State)) {
c.onUpdate = cb
}
// validTwoPartyUpdate performs additional protocol-dependent checks on the
// proposed update that go beyond the machine's checks:
// * Actor and signer must be the same.
// * Sub-allocations do not change.
func (c *Channel) validTwoPartyUpdate(up ChannelUpdate, sigIdx channel.Index) error {
if up.ActorIdx != sigIdx {
return errors.Errorf(
"Currently, only update proposals with the proposing peer as actor are allowed.")
}
if err := channel.SubAllocsAssertEqual(c.machine.State().Locked, up.State.Locked); err != nil {
return errors.WithMessage(err, "sub-allocation changed")
}
return nil
}
func (c *Channel) validTwoPartyUpdateState(next *channel.State) error {
up := makeChannelUpdate(next, c.machine.Idx())
return c.validTwoPartyUpdate(up, c.machine.Idx())
}
func makeChannelUpdate(next *channel.State, actor channel.Index) ChannelUpdate {
return ChannelUpdate{
State: next,
ActorIdx: actor,
}
}
// Error implements error interface for RequestTimedOutError.
func (e RequestTimedOutError) Error() string {
return string(e)
}
func newRequestTimedOutError(requestType, msg string) error {
return errors.Wrap(RequestTimedOutError("peer did not respond to the "+requestType), msg)
}