forked from lightningnetwork/lnd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchannel.go
2853 lines (2448 loc) · 100 KB
/
channel.go
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
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package lnwallet
import (
"bytes"
"container/list"
"crypto/sha256"
"fmt"
"sync"
"sync/atomic"
"github.com/davecgh/go-spew/spew"
"github.com/lightningnetwork/lnd/chainntnfs"
"github.com/lightningnetwork/lnd/channeldb"
"github.com/lightningnetwork/lnd/lnwire"
"github.com/roasbeef/btcd/blockchain"
"github.com/roasbeef/btcd/chaincfg/chainhash"
"encoding/hex"
"github.com/roasbeef/btcd/btcec"
"github.com/roasbeef/btcd/txscript"
"github.com/roasbeef/btcd/wire"
"github.com/roasbeef/btcutil"
"github.com/roasbeef/btcutil/txsort"
)
var zeroHash chainhash.Hash
var (
// ErrChanClosing is returned when a caller attempts to close a channel
// that has already been closed or is in the process of being closed.
ErrChanClosing = fmt.Errorf("channel is being closed, operation disallowed")
// ErrNoWindow is returned when revocation window is exausted.
ErrNoWindow = fmt.Errorf("unable to sign new commitment, the current" +
" revocation window is exhausted")
// ErrMaxWeightCost is returned when the cost/weight (see segwit)
// exceeds the widely used maximum allowed policy weight limit. In this
// case the commitment transaction can't be propagated through the
// network.
ErrMaxWeightCost = fmt.Errorf("commitment transaction exceed max " +
"available cost")
// ErrMaxHTLCNumber is returned when a proposed HTLC would exceed the
// maximum number of allowed HTLC's if committed in a state transition
ErrMaxHTLCNumber = fmt.Errorf("commitment transaction exceed max " +
"htlc number")
// ErrInsufficientBalance is returned when a proposed HTLC would
// exceed the available balance.
ErrInsufficientBalance = fmt.Errorf("insufficient local balance")
)
const (
// InitialRevocationWindow is the number of revoked commitment
// transactions allowed within the commitment chain. This value allows
// a greater degree of de-synchronization by allowing either parties to
// extend the other's commitment chain non-interactively, and also
// serves as a flow control mechanism to a degree.
InitialRevocationWindow = 1
)
// channelState is an enum like type which represents the current state of a
// particular channel.
// TODO(roasbeef): actually update state
type channelState uint8
const (
// channelPending indicates this channel is still going through the
// funding workflow, and isn't yet open.
channelPending channelState = iota
// channelOpen represents an open, active channel capable of
// sending/receiving HTLCs.
channelOpen
// channelClosing represents a channel which is in the process of being
// closed.
channelClosing
// channelClosed represents a channel which has been fully closed. Note
// that before a channel can be closed, ALL pending HTLCs must be
// settled/removed.
channelClosed
// channelDispute indicates that an un-cooperative closure has been
// detected within the channel.
channelDispute
// channelPendingPayment indicates that there a currently outstanding
// HTLCs within the channel.
channelPendingPayment
)
// PaymentHash represents the sha256 of a random value. This hash is used to
// uniquely track incoming/outgoing payments within this channel, as well as
// payments requested by the wallet/daemon.
type PaymentHash [32]byte
const maxUint16 uint16 = ^uint16(0)
// UpdateType is the exact type of an entry within the shared HTLC log.
type updateType uint8
const (
// Add is an update type that adds a new HTLC entry into the log.
// Either side can add a new pending HTLC by adding a new Add entry
// into their update log.
Add updateType = iota
// Fail is an update type which removes a prior HTLC entry from the
// log. Adding a Fail entry to ones log will modify the _remote_
// parties update log once a new commitment view has been evaluated
// which contains the Fail entry.
Fail
// Settle is an update type which settles a prior HTLC crediting the
// balance of the receiving node. Adding a Settle entry to a log will
// result in the settle entry being removed on the log as well as the
// original add entry from the remote party's log after the next state
// transition.
Settle
)
// PaymentDescriptor represents a commitment state update which either adds,
// settles, or removes an HTLC. PaymentDescriptors encapsulate all necessary
// metadata w.r.t to an HTLC, and additional data pairing a settle message to
// the original added HTLC.
// TODO(roasbeef): LogEntry interface??
// * need to separate attrs for cancel/add/settle
type PaymentDescriptor struct {
// RHash is the payment hash for this HTLC. The HTLC can be settled iff
// the preimage to this hash is presented.
RHash PaymentHash
// RPreimage is the preimage that settles the HTLC pointed to wthin the
// log by the ParentIndex.
RPreimage PaymentHash
// Timeout is the absolute timeout in blocks, after which this HTLC
// expires.
Timeout uint32
// Amount is the HTLC amount in satoshis.
Amount btcutil.Amount
// Index is the log entry number that his HTLC update has within the
// log. Depending on if IsIncoming is true, this is either an entry the
// remote party added, or one that we added locally.
Index uint64
// ParentIndex is the index of the log entry that this HTLC update
// settles or times out.
ParentIndex uint64
// addCommitHeight[Remote|Local] encodes the height of the commitment
// which included this HTLC on either the remote or local commitment
// chain. This value is used to determine when an HTLC is fully
// "locked-in".
addCommitHeightRemote uint64
addCommitHeightLocal uint64
// removeCommitHeight[Remote|Local] encodes the height of the
// commitment which removed the parent pointer of this
// PaymentDescriptor either due to a timeout or a settle. Once both
// these heights are above the tail of both chains, the log entries can
// safely be removed.
removeCommitHeightRemote uint64
removeCommitHeightLocal uint64
// Payload is an opaque blob which is used to complete multi-hop
// routing.
Payload []byte
// [our|their|]PkScript are the raw public key scripts that encodes the
// redemption rules for this particular HTLC. These fields will only be
// populated iff the EntryType of this PaymentDescriptor is Add.
// ourPkScript is the ourPkScript from the context of our local
// commitment chain. theirPkScript is the latest pkScript from the
// context of the remote commitment chain.
//
// NOTE: These values may change within the logs themselves, however,
// they'll stay consistent within the commitment chain entries
// themselves.
ourPkScript []byte
theirPkScript []byte
// EntryType denotes the exact type of the PaymentDescriptor. In the
// case of a Timeout, or Settle type, then the Parent field will point
// into the log to the HTLC being modified.
EntryType updateType
// isDust[Local|Remote] denotes if this HTLC is below the dust limit in
// locally or remotely.
isDustLocal bool
isDustRemote bool
// isForwarded denotes if an incoming HTLC has been forwarded to any
// possible upstream peers in the route.
isForwarded bool
}
// commitment represents a commitment to a new state within an active channel.
// New commitments can be initiated by either side. Commitments are ordered
// into a commitment chain, with one existing for both parties. Each side can
// independently extend the other side's commitment chain, up to a certain
// "revocation window", which once reached, disallows new commitments until
// the local nodes receives the revocation for the remote node's chain tail.
type commitment struct {
// height represents the commitment height of this commitment, or the
// update number of this commitment.
height uint64
// [our|their]MessageIndex are indexes into the HTLC log, up to which
// this commitment transaction includes. These indexes allow both sides
// to independently, and concurrent send create new commitments. Each
// new commitment sent to the remote party includes an index in the
// shared log which details which of their updates we're including in
// this new commitment.
ourMessageIndex uint64
theirMessageIndex uint64
// txn is the commitment transaction generated by including any HTLC
// updates whose index are below the two indexes listed above. If this
// commitment is being added to the remote chain, then this txn is
// their version of the commitment transactions. If the local commit
// chain is being modified, the opposite is true.
txn *wire.MsgTx
// sig is a signature for the above commitment transaction.
sig []byte
// [our|their]Balance represents the settled balances at this point
// within the commitment chain. This balance is computed by properly
// evaluating all the add/remove/settle log entries before the listed
// indexes.
ourBalance btcutil.Amount
theirBalance btcutil.Amount
// fee is the amount that will be paid as fees for this commitment
// transaction. The fee is recorded here so that it can be added
// back and recalculated for each new update to the channel state.
fee btcutil.Amount
// htlcs is the set of HTLCs which remain unsettled within this
// commitment.
outgoingHTLCs []PaymentDescriptor
incomingHTLCs []PaymentDescriptor
}
// toChannelDelta converts the target commitment into a format suitable to be
// written to disk after an accepted state transition.
// TODO(roasbeef): properly fill in refund timeouts
func (c *commitment) toChannelDelta(ourCommit bool) (*channeldb.ChannelDelta, error) {
numHtlcs := len(c.outgoingHTLCs) + len(c.incomingHTLCs)
// Save output indexes for RHash values found, so we don't return the
// same output index more than once.
dups := make(map[PaymentHash][]uint16)
delta := &channeldb.ChannelDelta{
LocalBalance: c.ourBalance,
RemoteBalance: c.theirBalance,
UpdateNum: c.height,
CommitFee: c.fee,
Htlcs: make([]*channeldb.HTLC, 0, numHtlcs),
}
// Check to see if element (e) exists in slice (s)
contains := func(s []uint16, e uint16) bool {
for _, a := range s {
if a == e {
return true
}
}
return false
}
// As we also store the output index of the HTLC for continence
// purposes, we create a small helper function to locate the output
// index of a particular HTLC within the current commitment
// transaction.
locateOutputIndex := func(p *PaymentDescriptor) (uint16, error) {
var (
idx uint16
found bool
)
pkScript := p.theirPkScript
if ourCommit {
pkScript = p.ourPkScript
}
for i, txOut := range c.txn.TxOut {
if bytes.Equal(txOut.PkScript, pkScript) &&
txOut.Value == int64(p.Amount) {
if contains(dups[p.RHash], uint16(i)) {
continue
}
found = true
idx = uint16(i)
dups[p.RHash] = append(dups[p.RHash], idx)
break
}
}
if !found {
return 0, fmt.Errorf("unable to find htlc: script=%x, value=%v",
pkScript, p.Amount)
}
return idx, nil
}
var (
index uint16
err error
)
for _, htlc := range c.outgoingHTLCs {
if (ourCommit && htlc.isDustLocal) ||
(!ourCommit && htlc.isDustRemote) {
index = maxUint16
} else if index, err = locateOutputIndex(&htlc); err != nil {
return nil, fmt.Errorf("unable to find outgoing htlc: %v", err)
}
h := &channeldb.HTLC{
Incoming: false,
Amt: htlc.Amount,
RHash: htlc.RHash,
RefundTimeout: htlc.Timeout,
RevocationDelay: 0,
OutputIndex: index,
}
delta.Htlcs = append(delta.Htlcs, h)
}
for _, htlc := range c.incomingHTLCs {
if (ourCommit && htlc.isDustLocal) ||
(!ourCommit && htlc.isDustRemote) {
index = maxUint16
} else if index, err = locateOutputIndex(&htlc); err != nil {
return nil, fmt.Errorf("unable to find incoming htlc: %v", err)
}
h := &channeldb.HTLC{
Incoming: true,
Amt: htlc.Amount,
RHash: htlc.RHash,
RefundTimeout: htlc.Timeout,
RevocationDelay: 0,
OutputIndex: index,
}
delta.Htlcs = append(delta.Htlcs, h)
}
return delta, nil
}
// commitmentChain represents a chain of unrevoked commitments. The tail of the
// chain is the latest fully signed, yet unrevoked commitment. Two chains are
// tracked, one for the local node, and another for the remote node. New
// commitments we create locally extend the remote node's chain, and vice
// versa. Commitment chains are allowed to grow to a bounded length, after
// which the tail needs to be "dropped" before new commitments can be received.
// The tail is "dropped" when the owner of the chain sends a revocation for the
// previous tail.
type commitmentChain struct {
// commitments is a linked list of commitments to new states. New
// commitments are added to the end of the chain with increase height.
// Once a commitment transaction is revoked, the tail is incremented,
// freeing up the revocation window for new commitments.
commitments *list.List
// startingHeight is the starting height of this commitment chain on a
// session basis.
startingHeight uint64
}
// newCommitmentChain creates a new commitment chain from an initial height.
func newCommitmentChain(initialHeight uint64) *commitmentChain {
return &commitmentChain{
commitments: list.New(),
startingHeight: initialHeight,
}
}
// addCommitment extends the commitment chain by a single commitment. This
// added commitment represents a state update propsed by either party. Once the
// commitment prior to this commitment is revoked, the commitment becomes the
// new defacto state within the channel.
func (s *commitmentChain) addCommitment(c *commitment) {
s.commitments.PushBack(c)
}
// advanceTail reduces the length of the commitment chain by one. The tail of
// the chain should be advanced once a revocation for the lowest unrevoked
// commitment in the chain is received.
func (s *commitmentChain) advanceTail() {
s.commitments.Remove(s.commitments.Front())
}
// tip returns the latest commitment added to the chain.
func (s *commitmentChain) tip() *commitment {
return s.commitments.Back().Value.(*commitment)
}
// tail returns the lowest unrevoked commitment transaction in the chain.
func (s *commitmentChain) tail() *commitment {
return s.commitments.Front().Value.(*commitment)
}
// updateLog is an append-only log that stores updates to a node's commitment
// chain. This structure can be seen as the "mempool" within Lightning where
// changes are stored before they're committed to the chain. Once an entry has
// been committed in both the local and remote commitment chain, then it can be
// removed from this log.
//
// TODO(roasbeef): create lightning package, move commitment and update to
// package?
// * also move state machine, separate from lnwallet package
// * possible embed updateLog within commitmentChain.
type updateLog struct {
// logIndex is a monotonically increasing integer that tracks the total
// number of update entries ever applied to the log. When sending new
// commitment states, we include all updates up to this index.
logIndex uint64
// ackIndex is a special "pointer" index into the log that tracks the
// position which, up to, all changes have been ACK'd by the remote
// party. When receiving new commitment states, we include all of our
// updates up to this index to restore the commitment view.
ackedIndex uint64
// pendingACKIndex is another special "pointer" index into the log that
// tracks our logIndex value right before we extend the remote party's
// commitment chain. Once we receive an ACK for this changes, then we
// set ackedIndex=pendingAckIndex.
//
// TODO(roasbeef): eventually expand into list when we go back to a
// sliding window format
pendingAckIndex uint64
// List is the updatelog itself, we embed this value so updateLog has
// access to all the method of a list.List.
*list.List
// updateIndex is an index that maps a particular entries index to the
// list element within the list.List above.
updateIndex map[uint64]*list.Element
}
// newUpdateLog creates a new updateLog instance.
func newUpdateLog() *updateLog {
return &updateLog{
List: list.New(),
updateIndex: make(map[uint64]*list.Element),
}
}
// appendUpdate appends a new update to the tip of the updateLog. The entry is
// also added to index accordingly.
func (u *updateLog) appendUpdate(pd *PaymentDescriptor) {
u.updateIndex[u.logIndex] = u.PushBack(pd)
u.logIndex++
}
// lookup attempts to look up an update entry according to it's index value. In
// the case that the entry isn't found, a nil pointer is returned.
func (u *updateLog) lookup(i uint64) *PaymentDescriptor {
return u.updateIndex[i].Value.(*PaymentDescriptor)
}
// remove attempts to remove an entry from the update log. If the entry is
// found, then the entry will be removed from the update log and index.
func (u *updateLog) remove(i uint64) {
entry := u.updateIndex[i]
u.Remove(entry)
delete(u.updateIndex, i)
}
// initiateTransition marks that the caller has extended the commitment chain
// of the remote party with the contents of the updateLog. This function will
// mark the log index value at this point so it can later be marked as ACK'd.
func (u *updateLog) initiateTransition() {
u.pendingAckIndex = u.logIndex
}
// ackTransition updates the internal indexes of the updateLog to mark that the
// last pending state transition has been accepted by the remote party. To do
// so, we mark the prior pendingAckIndex as fully ACK'd.
func (u *updateLog) ackTransition() {
u.ackedIndex = u.pendingAckIndex
u.pendingAckIndex = 0
}
// compactLogs performs garbage collection within the log removing HTLCs which
// have been removed from the point-of-view of the tail of both chains. The
// entries which timeout/settle HTLCs are also removed.
func compactLogs(ourLog, theirLog *updateLog,
localChainTail, remoteChainTail uint64) {
compactLog := func(logA, logB *updateLog) {
var nextA *list.Element
for e := logA.Front(); e != nil; e = nextA {
nextA = e.Next()
htlc := e.Value.(*PaymentDescriptor)
if htlc.EntryType == Add {
continue
}
// If the HTLC hasn't yet been removed from either
// chain, the skip it.
if htlc.removeCommitHeightRemote == 0 ||
htlc.removeCommitHeightLocal == 0 {
continue
}
// Otherwise if the height of the tail of both chains
// is at least the height in which the HTLC was
// removed, then evict the settle/timeout entry along
// with the original add entry.
if remoteChainTail >= htlc.removeCommitHeightRemote &&
localChainTail >= htlc.removeCommitHeightLocal {
logA.remove(htlc.Index)
logB.remove(htlc.ParentIndex)
}
}
}
compactLog(ourLog, theirLog)
compactLog(theirLog, ourLog)
}
// LightningChannel implements the state machine which corresponds to the
// current commitment protocol wire spec. The state machine implemented allows
// for asynchronous fully desynchronized, batched+pipelined updates to
// commitment transactions allowing for a high degree of non-blocking
// bi-directional payment throughput.
//
// In order to allow updates to be fully non-blocking, either side is able to
// create multiple new commitment states up to a pre-determined window size.
// This window size is encoded within InitialRevocationWindow. Before the start
// of a session, both side should send out revocation messages with nil
// preimages in order to populate their revocation window for the remote party.
// Ths method .ExtendRevocationWindow() is used to extend the revocation window
// by a single revocation.
//
// The state machine has for main methods:
// * .SignNextCommitment()
// * Called one one wishes to sign the next commitment, either initiating a
// new state update, or responding to a received commitment.
// * .ReceiveNewCommitment()
// * Called upon receipt of a new commitment from the remote party. If the
// new commitment is valid, then a revocation should immediately be
// generated and sent.
// * .RevokeCurrentCommitment()
// * Revokes the current commitment. Should be called directly after
// receiving a new commitment.
// * .ReceiveRevocation()
// * Processes a revocation from the remote party. If successful creates a
// new defacto broadcastable state.
//
// See the individual comments within the above methods for further details.
type LightningChannel struct {
signer Signer
signDesc *SignDescriptor
channelEvents chainntnfs.ChainNotifier
sync.RWMutex
pendingACK bool
status channelState
// feeEstimator is used to calculate the fee rate for the channel's
// commitment and cooperative close transactions.
feeEstimator FeeEstimator
// Capcity is the total capacity of this channel.
Capacity btcutil.Amount
// currentHeight is the current height of our local commitment chain.
// This is also the same as the number of updates to the channel we've
// accepted.
currentHeight uint64
// revocationWindowEdge is the edge of the current revocation window.
// New revocations for prior states created by this channel extend the
// edge of this revocation window. The existence of a revocation window
// allows the remote party to initiate new state updates independently
// until the window is exhausted.
revocationWindowEdge uint64
// usedRevocations is a slice of revocations given to us by the remote
// party that we've used. This slice is extended each time we create a
// new commitment. The front of the slice is popped off once we receive
// a revocation for a prior state. This head element then becomes the
// next set of keys/hashes we expect to be revoked.
usedRevocations []*lnwire.RevokeAndAck
// revocationWindow is a window of revocations sent to use by the
// remote party, allowing us to create new commitment transactions
// until depleted. The revocations don't contain a valid preimage,
// only an additional key/hash allowing us to create a new commitment
// transaction for the remote node that they are able to revoke. If
// this slice is empty, then we cannot make any new updates to their
// commitment chain.
revocationWindow []*lnwire.RevokeAndAck
// remoteCommitChain is the remote node's commitment chain. Any new
// commitments we initiate are added to the tip of this chain.
remoteCommitChain *commitmentChain
// localCommitChain is our local commitment chain. Any new commitments
// received are added to the tip of this chain. The tail (or lowest
// height) in this chain is our current accepted state, which we are
// able to broadcast safely.
localCommitChain *commitmentChain
channelState *channeldb.OpenChannel
// [local|remote]Log is a (mostly) append-only log storing all the HTLC
// updates to this channel. The log is walked backwards as HTLC updates
// are applied in order to re-construct a commitment transaction from a
// commitment. The log is compacted once a revocation is received.
localUpdateLog *updateLog
remoteUpdateLog *updateLog
// rHashMap is a map with PaymentHashes pointing to their respective
// PaymentDescriptors. We insert *PaymentDescriptors whenever we
// receive HTLCs. When a state transition happens (settling or
// canceling the HTLC), rHashMap will provide an efficient
// way to lookup the original PaymentDescriptor.
rHashMap map[PaymentHash][]*PaymentDescriptor
LocalDeliveryScript []byte
RemoteDeliveryScript []byte
// FundingWitnessScript is the witness script for the 2-of-2 multi-sig
// that opened the channel.
FundingWitnessScript []byte
fundingTxIn *wire.TxIn
fundingP2WSH []byte
// ForceCloseSignal is a channel that is closed to indicate that a
// local system has initiated a force close by broadcasting the current
// commitment transaction directly on-chain.
ForceCloseSignal chan struct{}
// UnilateralCloseSignal is a channel that is closed to indicate that
// the remote party has performed a unilateral close by broadcasting
// their version of the commitment transaction on-chain.
UnilateralCloseSignal chan struct{}
// UnilateralClose is a channel that will be sent upon by the close
// observer once the unilateral close of a channel is detected.
UnilateralClose chan *UnilateralCloseSummary
// ContractBreach is a channel that is used to communicate the data
// necessary to fully resolve the channel in the case that a contract
// breach is detected. A contract breach occurs it is detected that the
// counterparty has broadcast a prior *revoked* state.
ContractBreach chan *BreachRetribution
// LocalFundingKey is the public key under control by the wallet that
// was used for the 2-of-2 funding output which created this channel.
LocalFundingKey *btcec.PublicKey
// RemoteFundingKey is the public key for the remote channel counter
// party which used for the 2-of-2 funding output which created this
// channel.
RemoteFundingKey *btcec.PublicKey
// availableLocalBalance represent the amount of available money which
// might be processed by this channel at the specific point of time.
availableLocalBalance btcutil.Amount
shutdown int32
quit chan struct{}
}
// NewLightningChannel creates a new, active payment channel given an
// implementation of the chain notifier, channel database, and the current
// settled channel state. Throughout state transitions, then channel will
// automatically persist pertinent state to the database in an efficient
// manner.
func NewLightningChannel(signer Signer, events chainntnfs.ChainNotifier,
fe FeeEstimator, state *channeldb.OpenChannel) (*LightningChannel, error) {
lc := &LightningChannel{
signer: signer,
channelEvents: events,
feeEstimator: fe,
currentHeight: state.NumUpdates,
remoteCommitChain: newCommitmentChain(state.NumUpdates),
localCommitChain: newCommitmentChain(state.NumUpdates),
channelState: state,
revocationWindowEdge: state.NumUpdates,
localUpdateLog: newUpdateLog(),
remoteUpdateLog: newUpdateLog(),
rHashMap: make(map[PaymentHash][]*PaymentDescriptor),
Capacity: state.Capacity,
LocalDeliveryScript: state.OurDeliveryScript,
RemoteDeliveryScript: state.TheirDeliveryScript,
FundingWitnessScript: state.FundingWitnessScript,
ForceCloseSignal: make(chan struct{}),
UnilateralClose: make(chan *UnilateralCloseSummary, 1),
UnilateralCloseSignal: make(chan struct{}),
ContractBreach: make(chan *BreachRetribution, 1),
LocalFundingKey: state.OurMultiSigKey,
RemoteFundingKey: state.TheirMultiSigKey,
quit: make(chan struct{}),
}
// Initialize both of our chains using current un-revoked commitment
// for each side.
lc.localCommitChain.addCommitment(&commitment{
height: lc.currentHeight,
ourBalance: state.OurBalance,
ourMessageIndex: 0,
theirBalance: state.TheirBalance,
theirMessageIndex: 0,
fee: state.CommitFee,
})
walletLog.Debugf("ChannelPoint(%v), starting local commitment: %v",
state.ChanID, newLogClosure(func() string {
return spew.Sdump(lc.localCommitChain.tail())
}),
)
// To obtain the proper height for the remote node's commitment state,
// we'll need to fetch the tail end of their revocation log from the
// database.
logTail, err := state.RevocationLogTail()
if err != nil && err != channeldb.ErrNoActiveChannels &&
err != channeldb.ErrNoPastDeltas {
return nil, err
}
remoteCommitment := &commitment{
ourBalance: state.OurBalance,
ourMessageIndex: 0,
theirBalance: state.TheirBalance,
theirMessageIndex: 0,
fee: state.CommitFee,
}
if logTail == nil {
remoteCommitment.height = 0
} else {
remoteCommitment.height = logTail.UpdateNum + 1
}
lc.remoteCommitChain.addCommitment(remoteCommitment)
walletLog.Debugf("ChannelPoint(%v), starting remote commitment: %v",
state.ChanID, newLogClosure(func() string {
return spew.Sdump(lc.remoteCommitChain.tail())
}),
)
// If we're restarting from a channel with history, then restore the
// update in-memory update logs to that of the prior state.
if lc.currentHeight != 0 {
lc.restoreStateLogs()
}
// Create the sign descriptor which we'll be using very frequently to
// request a signature for the 2-of-2 multi-sig from the signer in
// order to complete channel state transitions.
fundingPkScript, err := witnessScriptHash(state.FundingWitnessScript)
if err != nil {
return nil, err
}
lc.fundingTxIn = wire.NewTxIn(state.FundingOutpoint, nil, nil)
lc.fundingP2WSH = fundingPkScript
lc.signDesc = &SignDescriptor{
PubKey: lc.channelState.OurMultiSigKey,
WitnessScript: lc.channelState.FundingWitnessScript,
Output: &wire.TxOut{
PkScript: lc.fundingP2WSH,
Value: int64(lc.channelState.Capacity),
},
HashType: txscript.SigHashAll,
InputIndex: 0,
}
// We'll only launch a close observer if the ChainNotifier
// implementation is non-nil. Passing a nil value indicates that the
// channel shouldn't be actively watched for.
if lc.channelEvents != nil {
// Register for a notification to be dispatched if the funding
// outpoint has been spent. This indicates that either us or
// the remote party has broadcasted a commitment transaction
// on-chain.
fundingOut := &lc.fundingTxIn.PreviousOutPoint
// As a height hint, we'll try to use the opening height, but
// if the channel isn't yet open, then we'll use the height it
// was broadcast at.
heightHint := lc.channelState.ShortChanID.BlockHeight
if heightHint == 0 {
heightHint = lc.channelState.FundingBroadcastHeight
}
channelCloseNtfn, err := lc.channelEvents.RegisterSpendNtfn(
fundingOut, heightHint,
)
if err != nil {
return nil, err
}
// Launch the close observer which will vigilantly watch the
// network for any broadcasts the current or prior commitment
// transactions, taking action accordingly.
go lc.closeObserver(channelCloseNtfn)
}
// Initialize the available local balance
s := lc.StateSnapshot()
lc.availableLocalBalance = s.LocalBalance
return lc, nil
}
// BreachRetribution contains all the data necessary to bring a channel
// counterparty to justice claiming ALL lingering funds within the channel in
// the scenario that they broadcast a revoked commitment transaction. A
// BreachRetribution is created by the closeObserver if it detects an
// uncooperative close of the channel which uses a revoked commitment
// transaction. The BreachRetribution is then sent over the ContractBreach
// channel in order to allow the subscriber of the channel to dispatch justice.
type BreachRetribution struct {
// BreachTransaction is the transaction which breached the channel
// contract by spending from the funding multi-sig with a revoked
// commitment transaction.
BreachTransaction *wire.MsgTx
// RevokedStateNum is the revoked state number which was broadcast.
RevokedStateNum uint64
// PendingHTLCs is a slice of the HTLCs which were pending at this
// point within the channel's history transcript.
PendingHTLCs []*channeldb.HTLC
// LocalOutputSignDesc is a SignDescriptor which is capable of
// generating the signature necessary to sweep the output within the
// BreachTransaction that pays directly us.
LocalOutputSignDesc *SignDescriptor
// LocalOutpoint is the outpoint of the output paying to us (the local
// party) within the breach transaction.
LocalOutpoint wire.OutPoint
// RemoteOutputSignDesc is a SignDescriptor which is capable of
// generating the signature required to claim the funds as described
// within the revocation clause of the remote party's commitment
// output.
RemoteOutputSignDesc *SignDescriptor
// RemoteOutpoint is the output of the output paying to the remote
// party within the breach transaction.
RemoteOutpoint wire.OutPoint
}
// newBreachRetribution creates a new fully populated BreachRetribution for the
// passed channel, at a particular revoked state number, and one which targets
// the passed commitment transaction.
func newBreachRetribution(chanState *channeldb.OpenChannel, stateNum uint64,
broadcastCommitment *wire.MsgTx) (*BreachRetribution, error) {
commitHash := broadcastCommitment.TxHash()
// Query the on-disk revocation log for the snapshot which was recorded
// at this particular state num.
revokedSnapshot, err := chanState.FindPreviousState(stateNum)
if err != nil {
return nil, err
}
// With the state number broadcast known, we can now derive/restore the
// proper revocation preimage necessary to sweep the remote party's
// output.
revocationPreimage, err := chanState.RevocationStore.LookUp(stateNum)
if err != nil {
return nil, err
}
// Once we derive the revocation leaf, we can then re-create the
// revocation public key used within this state. This is needed in
// order to create the proper script below.
localCommitKey := chanState.OurCommitKey
revocationKey := DeriveRevocationPubkey(localCommitKey, revocationPreimage[:])
remoteCommitkey := chanState.TheirCommitKey
remoteDelay := chanState.RemoteCsvDelay
// Next, reconstruct the scripts as they were present at this state
// number so we can have the proper witness script to sign and include
// within the final witness.
remotePkScript, err := commitScriptToSelf(remoteDelay,
remoteCommitkey, revocationKey)
if err != nil {
return nil, err
}
remoteWitnessHash, err := witnessScriptHash(remotePkScript)
if err != nil {
return nil, err
}
localPkScript, err := commitScriptUnencumbered(localCommitKey)
if err != nil {
return nil, err
}
// In order to fully populate the breach retribution struct, we'll need
// to find the exact index of the local+remote commitment outputs.
localOutpoint := wire.OutPoint{
Hash: commitHash,
}
remoteOutpoint := wire.OutPoint{
Hash: commitHash,
}
for i, txOut := range broadcastCommitment.TxOut {
switch {
case bytes.Equal(txOut.PkScript, localPkScript):
localOutpoint.Index = uint32(i)
case bytes.Equal(txOut.PkScript, remoteWitnessHash):
remoteOutpoint.Index = uint32(i)
}
}
// Finally, with all the necessary data constructed, we can create the
// BreachRetribution struct which houses all the data necessary to
// swiftly bring justice to the cheating remote party.
return &BreachRetribution{
BreachTransaction: broadcastCommitment,
RevokedStateNum: stateNum,
PendingHTLCs: revokedSnapshot.Htlcs,
LocalOutpoint: localOutpoint,
LocalOutputSignDesc: &SignDescriptor{
PubKey: localCommitKey,
Output: &wire.TxOut{
PkScript: localPkScript,
Value: int64(revokedSnapshot.LocalBalance),
},
HashType: txscript.SigHashAll,
},
RemoteOutpoint: remoteOutpoint,
RemoteOutputSignDesc: &SignDescriptor{
PubKey: localCommitKey,
PrivateTweak: revocationPreimage[:],
WitnessScript: remotePkScript,
Output: &wire.TxOut{
PkScript: remoteWitnessHash,
Value: int64(revokedSnapshot.RemoteBalance),
},
HashType: txscript.SigHashAll,
},
}, nil
}
// closeObserver is a goroutine which watches the network for any spends of the
// multi-sig funding output. A spend from the multi-sig output may occur under
// the following three scenarios: a cooperative close, a unilateral close, and
// a uncooperative contract breaching close. In the case of the last scenario a
// BreachRetribution struct is created and sent over the ContractBreach channel
// notifying subscribers that the counterparty has violated the condition of
// the channel by broadcasting a revoked prior state.
//
// NOTE: This MUST be run as a goroutine.
func (lc *LightningChannel) closeObserver(channelCloseNtfn *chainntnfs.SpendEvent) {
walletLog.Infof("Close observer for ChannelPoint(%v) active",
lc.channelState.ChanID)
var (
commitSpend *chainntnfs.SpendDetail
ok bool
)
select {
// If the daemon is shutting down, then this notification channel will
// be closed, so check the second read-value to avoid a false positive.
case commitSpend, ok = <-channelCloseNtfn.Spend:
if !ok {
return
}
// Otherwise, we've beeen signalled to bail out early by the
// caller/maintainer of this channel.
case <-lc.quit:
// As we're exiting before the spend notification has been
// triggered, we'll cancel the notification intent so the
// ChainNotiifer can free up the resources.
channelCloseNtfn.Cancel()
return
}
// If we've already initiated a local cooperative or unilateral close