-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
Copy pathrbf_coop_test.go
1691 lines (1386 loc) · 47.6 KB
/
rbf_coop_test.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 chancloser
import (
"bytes"
"context"
"encoding/hex"
"errors"
"fmt"
"math/rand"
"testing"
"time"
"github.com/btcsuite/btcd/btcec/v2"
"github.com/btcsuite/btcd/btcec/v2/ecdsa"
"github.com/btcsuite/btcd/btcutil"
"github.com/btcsuite/btcd/chaincfg"
"github.com/btcsuite/btcd/mempool"
"github.com/btcsuite/btcd/txscript"
"github.com/btcsuite/btcd/wire"
"github.com/lightningnetwork/lnd/fn/v2"
"github.com/lightningnetwork/lnd/input"
"github.com/lightningnetwork/lnd/lntest/wait"
"github.com/lightningnetwork/lnd/lntypes"
"github.com/lightningnetwork/lnd/lnwallet/chainfee"
"github.com/lightningnetwork/lnd/lnwire"
"github.com/lightningnetwork/lnd/protofsm"
"github.com/lightningnetwork/lnd/tlv"
"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/require"
)
var (
localAddr = lnwire.DeliveryAddress(append(
[]byte{txscript.OP_1, txscript.OP_DATA_32},
bytes.Repeat([]byte{0x01}, 32)...,
))
remoteAddr = lnwire.DeliveryAddress(append(
[]byte{txscript.OP_1, txscript.OP_DATA_32},
bytes.Repeat([]byte{0x02}, 32)...,
))
localSigBytes = fromHex("3045022100cd496f2ab4fe124f977ffe3caa09f757" +
"6d8a34156b4e55d326b4dffc0399a094022013500a0510b5094bff220c7" +
"4656879b8ca0369d3da78004004c970790862fc03")
localSig = sigMustParse(localSigBytes)
localSigWire = mustWireSig(&localSig)
remoteSigBytes = fromHex("304502210082235e21a2300022738dabb8e1bbd9d1" +
"9cfb1e7ab8c30a23b0afbb8d178abcf3022024bf68e256c534ddfaf966b" +
"f908deb944305596f7bdcc38d69acad7f9c868724")
remoteSig = sigMustParse(remoteSigBytes)
remoteWireSig = mustWireSig(&remoteSig)
localTx = wire.MsgTx{Version: 2}
closeTx = wire.NewMsgTx(2)
)
func sigMustParse(sigBytes []byte) ecdsa.Signature {
sig, err := ecdsa.ParseSignature(sigBytes)
if err != nil {
panic(err)
}
return *sig
}
func mustWireSig(e input.Signature) lnwire.Sig {
wireSig, err := lnwire.NewSigFromSignature(e)
if err != nil {
panic(err)
}
return wireSig
}
func fromHex(s string) []byte {
r, err := hex.DecodeString(s)
if err != nil {
panic("invalid hex in source file: " + s)
}
return r
}
func randOutPoint(t *testing.T) wire.OutPoint {
var op wire.OutPoint
if _, err := rand.Read(op.Hash[:]); err != nil {
t.Fatalf("unable to generate random outpoint: %v", err)
}
op.Index = rand.Uint32()
return op
}
func randPubKey(t *testing.T) *btcec.PublicKey {
priv, err := btcec.NewPrivateKey()
if err != nil {
t.Fatalf("unable to generate private key: %v", err)
}
return priv.PubKey()
}
func assertStateTransitions[Event any, Env protofsm.Environment](
t *testing.T, stateSub protofsm.StateSubscriber[Event, Env],
expectedStates []protofsm.State[Event, Env]) {
t.Helper()
for _, expectedState := range expectedStates {
newState, err := fn.RecvOrTimeout(
stateSub.NewItemCreated.ChanOut(), 10*time.Millisecond,
)
require.NoError(t, err, "expected state: %T", expectedState)
require.IsType(t, expectedState, newState)
}
// We should have no more states.
select {
case newState := <-stateSub.NewItemCreated.ChanOut():
t.Fatalf("unexpected state transition: %v", newState)
default:
}
}
// unknownEvent is a dummy event that is used to test that the state machine
// transitions properly fail when an unknown event is received.
type unknownEvent struct {
}
func (u *unknownEvent) protocolSealed() {
}
// assertUnknownEventFail asserts that the state machine fails as expected
// given an unknown event.
func assertUnknownEventFail(t *testing.T, startingState ProtocolState) {
t.Helper()
// Any other event should be ignored.
t.Run("unknown_event", func(t *testing.T) {
closeHarness := newCloser(t, &harnessCfg{
initialState: fn.Some(startingState),
})
defer closeHarness.stopAndAssert()
closeHarness.expectFailure(ErrInvalidStateTransition)
closeHarness.chanCloser.SendEvent(
context.Background(), &unknownEvent{},
)
// There should be no further state transitions.
closeHarness.assertNoStateTransitions()
})
}
type harnessCfg struct {
initialState fn.Option[ProtocolState]
thawHeight fn.Option[uint32]
localUpfrontAddr fn.Option[lnwire.DeliveryAddress]
remoteUpfrontAddr fn.Option[lnwire.DeliveryAddress]
}
// rbfCloserTestHarness is a test harness for the RBF closer.
type rbfCloserTestHarness struct {
*testing.T
cfg *harnessCfg
chanCloser *RbfChanCloser
env Environment
newAddrErr error
pkScript []byte
peerPub btcec.PublicKey
startingState RbfState
feeEstimator *mockFeeEstimator
chanObserver *mockChanObserver
signer *mockCloseSigner
daemonAdapters *dummyAdapters
errReporter *mockErrorReporter
stateSub protofsm.StateSubscriber[ProtocolEvent, *Environment]
}
var errfailAddr = fmt.Errorf("fail")
// failNewAddrFunc causes the newAddrFunc to fail.
func (r *rbfCloserTestHarness) failNewAddrFunc() {
r.T.Helper()
r.newAddrErr = errfailAddr
}
func (r *rbfCloserTestHarness) newAddrFunc() (
lnwire.DeliveryAddress, error) {
r.T.Helper()
return lnwire.DeliveryAddress{}, r.newAddrErr
}
func (r *rbfCloserTestHarness) assertExpectations() {
r.T.Helper()
r.feeEstimator.AssertExpectations(r.T)
r.chanObserver.AssertExpectations(r.T)
r.daemonAdapters.AssertExpectations(r.T)
r.errReporter.AssertExpectations(r.T)
r.signer.AssertExpectations(r.T)
}
func (r *rbfCloserTestHarness) stopAndAssert() {
r.T.Helper()
defer r.chanCloser.RemoveStateSub(r.stateSub)
r.chanCloser.Stop()
r.assertExpectations()
}
func (r *rbfCloserTestHarness) assertStartupAssertions() {
r.T.Helper()
// When the state machine has started up, we recv a starting state
// transition for the initial state.
expectedStates := []RbfState{r.startingState}
assertStateTransitions(r.T, r.stateSub, expectedStates)
// Registering the spend transaction should have been called.
r.daemonAdapters.AssertCalled(
r.T, "RegisterSpendNtfn", &r.env.ChanPoint, r.pkScript,
r.env.Scid.BlockHeight,
)
}
func (r *rbfCloserTestHarness) assertNoStateTransitions() {
select {
case newState := <-r.stateSub.NewItemCreated.ChanOut():
r.T.Fatalf("unexpected state transition: %T", newState)
case <-time.After(10 * time.Millisecond):
}
}
func (r *rbfCloserTestHarness) assertStateTransitions(states ...RbfState) {
assertStateTransitions(r.T, r.stateSub, states)
}
func (r *rbfCloserTestHarness) currentState() RbfState {
state, err := r.chanCloser.CurrentState()
require.NoError(r.T, err)
return state
}
type shutdownExpect struct {
isInitiator bool
allowSend bool
recvShutdown bool
finalBalances fn.Option[ShutdownBalances]
}
func (r *rbfCloserTestHarness) expectShutdownEvents(expect shutdownExpect) {
r.T.Helper()
r.chanObserver.On("FinalBalances").Return(expect.finalBalances)
if expect.isInitiator {
r.chanObserver.On("NoDanglingUpdates").Return(expect.allowSend)
} else {
r.chanObserver.On("NoDanglingUpdates").Return(
expect.allowSend,
).Maybe()
}
// When we're receiving a shutdown, we should also disable incoming
// adds.
if expect.recvShutdown {
r.chanObserver.On("DisableIncomingAdds").Return(nil)
}
// If a close is in progress, this is an RBF iteration, the link has
// already been cleaned up, so we don't expect any assertions, other
// than to check the closing state.
if expect.finalBalances.IsSome() {
return
}
r.chanObserver.On("DisableOutgoingAdds").Return(nil)
r.chanObserver.On(
"MarkShutdownSent", mock.Anything, expect.isInitiator,
).Return(nil)
r.chanObserver.On("DisableChannel").Return(nil)
}
func (r *rbfCloserTestHarness) expectFinalBalances(
b fn.Option[ShutdownBalances]) {
r.chanObserver.On("FinalBalances").Return(b)
}
func (r *rbfCloserTestHarness) expectIncomingAddsDisabled() {
r.T.Helper()
r.chanObserver.On("DisableIncomingAdds").Return(nil)
}
type msgMatcher func([]lnwire.Message) bool
func singleMsgMatcher[M lnwire.Message](f func(M) bool) msgMatcher {
return func(msgs []lnwire.Message) bool {
if len(msgs) != 1 {
return false
}
wireMsg := msgs[0]
msg, ok := wireMsg.(M)
if !ok {
return false
}
if f == nil {
return true
}
return f(msg)
}
}
func (r *rbfCloserTestHarness) expectMsgSent(matcher msgMatcher) {
r.T.Helper()
if matcher == nil {
r.daemonAdapters.On(
"SendMessages", r.peerPub, mock.Anything,
).Return(nil)
} else {
r.daemonAdapters.On(
"SendMessages", r.peerPub, mock.MatchedBy(matcher),
).Return(nil)
}
}
func (r *rbfCloserTestHarness) expectFeeEstimate(absoluteFee btcutil.Amount,
numTimes int) {
r.T.Helper()
// TODO(roasbeef): mo assertions for dust case
r.feeEstimator.On(
"EstimateFee", mock.Anything, mock.Anything, mock.Anything,
mock.Anything,
).Return(absoluteFee, nil).Times(numTimes)
}
func (r *rbfCloserTestHarness) expectFailure(err error) {
r.T.Helper()
errorMatcher := func(e error) bool {
return errors.Is(e, err)
}
r.errReporter.On("ReportError", mock.MatchedBy(errorMatcher)).Return()
}
func (r *rbfCloserTestHarness) expectNewCloseSig(
localScript, remoteScript []byte, fee btcutil.Amount,
closeBalance btcutil.Amount) {
r.T.Helper()
r.signer.On(
"CreateCloseProposal", fee, localScript, remoteScript,
mock.Anything,
).Return(&localSig, &localTx, closeBalance, nil)
}
func (r *rbfCloserTestHarness) waitForMsgSent() {
r.T.Helper()
err := wait.Predicate(func() bool {
return r.daemonAdapters.msgSent.Load()
}, time.Second*3)
require.NoError(r.T, err)
}
func (r *rbfCloserTestHarness) expectRemoteCloseFinalized(
localCoopSig, remoteCoopSig input.Signature, localScript,
remoteScript []byte, fee btcutil.Amount,
balanceAfterClose btcutil.Amount, isLocal bool) {
r.expectNewCloseSig(
localScript, remoteScript, fee, balanceAfterClose,
)
r.expectCloseFinalized(
localCoopSig, remoteCoopSig, localScript, remoteScript,
fee, balanceAfterClose, isLocal,
)
r.expectMsgSent(singleMsgMatcher[*lnwire.ClosingSig](nil))
}
func (r *rbfCloserTestHarness) expectCloseFinalized(
localCoopSig, remoteCoopSig input.Signature, localScript,
remoteScript []byte, fee btcutil.Amount,
balanceAfterClose btcutil.Amount, isLocal bool) {
// The caller should obtain the final signature.
r.signer.On("CompleteCooperativeClose",
localCoopSig, remoteCoopSig, localScript,
remoteScript, fee, mock.Anything,
).Return(closeTx, balanceAfterClose, nil)
// The caller should also mark the transaction as broadcast on disk.
r.chanObserver.On("MarkCoopBroadcasted", closeTx, isLocal).Return(nil)
// Finally, we expect that the daemon executor should broadcast the
// above transaction.
r.daemonAdapters.On(
"BroadcastTransaction", closeTx, mock.Anything,
).Return(nil)
}
func (r *rbfCloserTestHarness) expectChanPendingClose() {
var nilTx *wire.MsgTx
r.chanObserver.On("MarkCoopBroadcasted", nilTx, true).Return(nil)
}
func (r *rbfCloserTestHarness) assertLocalClosePending() {
// We should then remain in the outer close negotiation state.
r.assertStateTransitions(&ClosingNegotiation{})
// If we examine the final resting state, we should see that the we're
// now in the negotiation state still for our local peer state.
currentState := assertStateT[*ClosingNegotiation](r)
// From this, we'll assert the resulting peer state, and that the co-op
// close txn is known.
closePendingState, ok := currentState.PeerState.GetForParty(
lntypes.Local,
).(*ClosePending)
require.True(r.T, ok)
require.Equal(r.T, closeTx, closePendingState.CloseTx)
}
type dustExpectation uint
const (
noDustExpect dustExpectation = iota
localDustExpect
remoteDustExpect
)
func (d dustExpectation) String() string {
switch d {
case noDustExpect:
return "no dust"
case localDustExpect:
return "local dust"
case remoteDustExpect:
return "remote dust"
default:
return "unknown"
}
}
// expectHalfSignerIteration asserts that we carry out 1/2 of the locally
// initiated signer iteration. This constitutes sending a ClosingComplete
// message to the remote party, and all the other intermediate steps.
func (r *rbfCloserTestHarness) expectHalfSignerIteration(
initEvent ProtocolEvent, balanceAfterClose, absoluteFee btcutil.Amount,
dustExpect dustExpectation) {
ctx := context.Background()
numFeeCalls := 2
// If we're using the SendOfferEvent as a trigger, we only need to call
// the few estimation once.
if _, ok := initEvent.(*SendOfferEvent); ok {
numFeeCalls = 1
}
// We'll now expect that fee estimation is called, and then
// send in the flushed event. We expect two calls: one to
// figure out if we can pay the fee, and then another when we
// actually pay the fee.
r.expectFeeEstimate(absoluteFee, numFeeCalls)
// Next, we'll assert that we receive calls to generate a new
// commitment signature, and then send out the commit
// ClosingComplete message to the remote peer.
r.expectNewCloseSig(
localAddr, remoteAddr, absoluteFee, balanceAfterClose,
)
// We expect that only the closer and closee sig is set as both
// parties have a balance.
msgExpect := singleMsgMatcher(func(m *lnwire.ClosingComplete) bool {
r.T.Helper()
switch {
case m.CloserNoClosee.IsSome():
r.T.Logf("closer no closee field set, expected: %v",
dustExpect)
return dustExpect == remoteDustExpect
case m.NoCloserClosee.IsSome():
r.T.Logf("no close closee field set, expected: %v",
dustExpect)
return dustExpect == localDustExpect
default:
r.T.Logf("no dust field set, expected: %v", dustExpect)
return (m.CloserAndClosee.IsSome() &&
dustExpect == noDustExpect)
}
})
r.expectMsgSent(msgExpect)
r.chanCloser.SendEvent(ctx, initEvent)
// Based on the init event, we'll either just go to the closing
// negotiation state, or go through the channel flushing state first.
var expectedStates []RbfState
switch initEvent.(type) {
case *ShutdownReceived:
expectedStates = []RbfState{
&ChannelFlushing{}, &ClosingNegotiation{},
}
case *SendOfferEvent:
expectedStates = []RbfState{&ClosingNegotiation{}}
case *ChannelFlushed:
// If we're sending a flush event here, then this means that we
// also have enough balance to cover the fee so we'll have
// another inner transition to the negotiation state.
expectedStates = []RbfState{
&ClosingNegotiation{}, &ClosingNegotiation{},
}
default:
r.T.Fatalf("unknown event type: %T", initEvent)
}
// We should transition from the negotiation state back to
// itself.
//
// TODO(roasbeef): take in expected set of transitions!!!
// * or base off of event, if shutdown recv'd know we're doing a full
// loop
r.assertStateTransitions(expectedStates...)
// If we examine the final resting state, we should see that
// the we're now in the LocalOffersSent for our local peer
// state.
currentState := assertStateT[*ClosingNegotiation](r)
// From this, we'll assert the resulting peer state.
offerSentState, ok := currentState.PeerState.GetForParty(
lntypes.Local,
).(*LocalOfferSent)
require.True(r.T, ok)
// The proposed fee, as well as our local signature should be
// properly stashed in the state.
require.Equal(r.T, absoluteFee, offerSentState.ProposedFee)
require.Equal(r.T, localSigWire, offerSentState.LocalSig)
}
func (r *rbfCloserTestHarness) assertSingleRbfIteration(
initEvent ProtocolEvent, balanceAfterClose, absoluteFee btcutil.Amount,
dustExpect dustExpectation) {
ctx := context.Background()
// We'll now send in the send offer event, which should trigger 1/2 of
// the RBF loop, ending us in the LocalOfferSent state.
r.expectHalfSignerIteration(
initEvent, balanceAfterClose, absoluteFee, noDustExpect,
)
// Now that we're in the local offer sent state, we'll send the
// response of the remote party, which completes one iteration
localSigEvent := &LocalSigReceived{
SigMsg: lnwire.ClosingSig{
CloserScript: localAddr,
CloseeScript: remoteAddr,
ClosingSigs: lnwire.ClosingSigs{
CloserAndClosee: newSigTlv[tlv.TlvType3](
remoteWireSig,
),
},
},
}
// Before we send the event, we expect the close the final signature to
// be combined/obtained, and for the close to finalized on disk.
r.expectCloseFinalized(
&localSig, &remoteSig, localAddr, remoteAddr, absoluteFee,
balanceAfterClose, true,
)
r.chanCloser.SendEvent(ctx, localSigEvent)
// We should transition to the pending closing state now.
r.assertLocalClosePending()
}
func (r *rbfCloserTestHarness) assertSingleRemoteRbfIteration(
initEvent *OfferReceivedEvent, balanceAfterClose,
absoluteFee btcutil.Amount, sequence uint32, iteration bool) {
ctx := context.Background()
// When we receive the signature below, our local state machine should
// move to finalize the close.
r.expectRemoteCloseFinalized(
&localSig, &remoteSig, initEvent.SigMsg.CloseeScript,
initEvent.SigMsg.CloserScript,
absoluteFee, balanceAfterClose, false,
)
r.chanCloser.SendEvent(ctx, initEvent)
// Our outer state should transition to ClosingNegotiation state.
r.assertStateTransitions(&ClosingNegotiation{})
// If this is an iteration, then we'll go from ClosePending ->
// RemoteCloseStart -> ClosePending. So we'll assert an extra transition
// here.
if iteration {
r.assertStateTransitions(&ClosingNegotiation{})
}
// If we examine the final resting state, we should see that the we're
// now in the ClosePending state for the remote peer.
currentState := assertStateT[*ClosingNegotiation](r)
// From this, we'll assert the resulting peer state.
pendingState, ok := currentState.PeerState.GetForParty(
lntypes.Remote,
).(*ClosePending)
require.True(r.T, ok)
// The proposed fee, as well as our local signature should be properly
// stashed in the state.
require.Equal(r.T, closeTx, pendingState.CloseTx)
}
func assertStateT[T ProtocolState](h *rbfCloserTestHarness) T {
h.T.Helper()
currentState, ok := h.currentState().(T)
require.True(h.T, ok)
return currentState
}
// newRbfCloserTestHarness creates a new test harness for the RBF closer.
func newRbfCloserTestHarness(t *testing.T,
cfg *harnessCfg) *rbfCloserTestHarness {
ctx := context.Background()
startingHeight := 200
chanPoint := randOutPoint(t)
chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
scid := lnwire.NewShortChanIDFromInt(rand.Uint64())
peerPub := randPubKey(t)
msgMapper := NewRbfMsgMapper(uint32(startingHeight), chanID, *peerPub)
initialState := cfg.initialState.UnwrapOr(&ChannelActive{})
defaultFeeRate := chainfee.FeePerKwFloor
feeEstimator := &mockFeeEstimator{}
mockObserver := &mockChanObserver{}
errReporter := &mockErrorReporter{}
mockSigner := &mockCloseSigner{}
harness := &rbfCloserTestHarness{
T: t,
cfg: cfg,
startingState: initialState,
feeEstimator: feeEstimator,
signer: mockSigner,
chanObserver: mockObserver,
errReporter: errReporter,
peerPub: *peerPub,
}
env := Environment{
ChainParams: chaincfg.RegressionNetParams,
ChanPeer: *peerPub,
ChanPoint: chanPoint,
ChanID: chanID,
Scid: scid,
DefaultFeeRate: defaultFeeRate.FeePerVByte(),
ThawHeight: cfg.thawHeight,
RemoteUpfrontShutdown: cfg.remoteUpfrontAddr,
LocalUpfrontShutdown: cfg.localUpfrontAddr,
NewDeliveryScript: harness.newAddrFunc,
FeeEstimator: feeEstimator,
ChanObserver: mockObserver,
CloseSigner: mockSigner,
}
harness.env = env
var pkScript []byte
harness.pkScript = pkScript
spendEvent := protofsm.RegisterSpend[ProtocolEvent]{
OutPoint: chanPoint,
HeightHint: scid.BlockHeight,
PkScript: pkScript,
PostSpendEvent: fn.Some[RbfSpendMapper](SpendMapper),
}
daemonAdapters := newDaemonAdapters()
harness.daemonAdapters = daemonAdapters
protoCfg := RbfChanCloserCfg{
ErrorReporter: errReporter,
Daemon: daemonAdapters,
InitialState: initialState,
Env: &env,
InitEvent: fn.Some[protofsm.DaemonEvent](&spendEvent),
MsgMapper: fn.Some[protofsm.MsgMapper[ProtocolEvent]](
msgMapper,
),
CustomPollInterval: fn.Some(time.Nanosecond),
}
// Before we start we always expect an initial spend event.
daemonAdapters.On(
"RegisterSpendNtfn", &chanPoint, pkScript, scid.BlockHeight,
).Return(nil)
chanCloser := protofsm.NewStateMachine(protoCfg)
chanCloser.Start(ctx)
harness.stateSub = chanCloser.RegisterStateEvents()
harness.chanCloser = &chanCloser
return harness
}
func newCloser(t *testing.T, cfg *harnessCfg) *rbfCloserTestHarness {
chanCloser := newRbfCloserTestHarness(t, cfg)
// We should start in the active state, and have our spend req
// daemon event handled.
chanCloser.assertStartupAssertions()
return chanCloser
}
// TestRbfChannelActiveTransitions tests the transitions of from the
// ChannelActive state.
func TestRbfChannelActiveTransitions(t *testing.T) {
ctx := context.Background()
localAddr := lnwire.DeliveryAddress(bytes.Repeat([]byte{0x01}, 20))
remoteAddr := lnwire.DeliveryAddress(bytes.Repeat([]byte{0x02}, 20))
feeRate := chainfee.SatPerVByte(1000)
// Test that if a spend event is received, the FSM transitions to the
// CloseFin terminal state.
t.Run("spend_event", func(t *testing.T) {
closeHarness := newCloser(t, &harnessCfg{
localUpfrontAddr: fn.Some(localAddr),
})
defer closeHarness.stopAndAssert()
closeHarness.chanCloser.SendEvent(ctx, &SpendEvent{})
closeHarness.assertStateTransitions(&CloseFin{})
})
// If we send in a local shutdown event, but fail to get an addr, the
// state machine should terminate.
t.Run("local_initiated_close_addr_fail", func(t *testing.T) {
closeHarness := newCloser(t, &harnessCfg{})
defer closeHarness.stopAndAssert()
closeHarness.failNewAddrFunc()
closeHarness.expectFailure(errfailAddr)
// We don't specify an upfront shutdown addr, and don't specify
// on here in the vent, so we should call new addr, but then
// fail.
closeHarness.chanCloser.SendEvent(ctx, &SendShutdown{})
// We shouldn't have transitioned to a new state.
closeHarness.assertNoStateTransitions()
})
// Initiating the shutdown should have us transition to the shutdown
// pending state. We should also emit events to disable the channel,
// and also send a message to our target peer.
t.Run("local_initiated_close_ok", func(t *testing.T) {
closeHarness := newCloser(t, &harnessCfg{
localUpfrontAddr: fn.Some(localAddr),
})
defer closeHarness.stopAndAssert()
// Once we send the event below, we should get calls to the
// chan observer, the msg sender, and the link control.
closeHarness.expectShutdownEvents(shutdownExpect{
isInitiator: true,
allowSend: true,
})
closeHarness.expectMsgSent(nil)
// If we send the shutdown event, we should transition to the
// shutdown pending state.
closeHarness.chanCloser.SendEvent(
ctx, &SendShutdown{IdealFeeRate: feeRate},
)
closeHarness.assertStateTransitions(&ShutdownPending{})
// If we examine the internal state, it should be consistent
// with the fee+addr we sent in.
currentState := assertStateT[*ShutdownPending](closeHarness)
require.Equal(
t, feeRate, currentState.IdealFeeRate.UnsafeFromSome(),
)
require.Equal(
t, localAddr,
currentState.ShutdownScripts.LocalDeliveryScript,
)
// Wait till the msg has been sent to assert our expectations.
//
// TODO(roasbeef): can use call.WaitFor here?
closeHarness.waitForMsgSent()
})
// TODO(roasbeef): thaw height fail
// When we receive a shutdown, we should transition to the shutdown
// pending state, with the local+remote shutdown addrs known.
t.Run("remote_initiated_close_ok", func(t *testing.T) {
closeHarness := newCloser(t, &harnessCfg{
localUpfrontAddr: fn.Some(localAddr),
})
defer closeHarness.stopAndAssert()
// We assert our shutdown events, and also that we eventually
// send a shutdown to the remote party. We'll hold back the
// send in this case though, as we should only send once the no
// updates are dangling.
closeHarness.expectShutdownEvents(shutdownExpect{
isInitiator: false,
allowSend: false,
recvShutdown: true,
})
// Next, we'll emit the recv event, with the addr of the remote
// party.
closeHarness.chanCloser.SendEvent(
ctx, &ShutdownReceived{ShutdownScript: remoteAddr},
)
// We should transition to the shutdown pending state.
closeHarness.assertStateTransitions(&ShutdownPending{})
currentState := assertStateT[*ShutdownPending](closeHarness)
// Both the local and remote shutdown scripts should be set.
require.Equal(
t, localAddr,
currentState.ShutdownScripts.LocalDeliveryScript,
)
require.Equal(
t, remoteAddr,
currentState.ShutdownScripts.RemoteDeliveryScript,
)
})
// Any other event should be ignored.
assertUnknownEventFail(t, &ChannelActive{})
}
// TestRbfShutdownPendingTransitions tests the transitions of the RBF closer
// once we get to the shutdown pending state. In this state, we wait for either
// a shutdown to be received, or a notification that we're able to send a
// shutdown ourselves.
func TestRbfShutdownPendingTransitions(t *testing.T) {
t.Parallel()
ctx := context.Background()
startingState := &ShutdownPending{}
// Test that if a spend event is received, the FSM transitions to the
// CloseFin terminal state.
t.Run("spend_event", func(t *testing.T) {
closeHarness := newCloser(t, &harnessCfg{
initialState: fn.Some[ProtocolState](
startingState,
),
localUpfrontAddr: fn.Some(localAddr),
})
defer closeHarness.stopAndAssert()
closeHarness.chanCloser.SendEvent(ctx, &SpendEvent{})
closeHarness.assertStateTransitions(&CloseFin{})
})
// If the remote party sends us a diff shutdown addr than we expected,
// then we'll fail.
t.Run("initiator_shutdown_recv_validate_fail", func(t *testing.T) {
closeHarness := newCloser(t, &harnessCfg{
initialState: fn.Some[ProtocolState](
startingState,
),
remoteUpfrontAddr: fn.Some(remoteAddr),
})
defer closeHarness.stopAndAssert()
// We should fail as the shutdown script isn't what we
// expected.
closeHarness.expectFailure(ErrUpfrontShutdownScriptMismatch)
// We'll now send in a ShutdownReceived event, but with a
// different address provided in the shutdown message. This
// should result in an error.
closeHarness.chanCloser.SendEvent(ctx, &ShutdownReceived{
ShutdownScript: localAddr,
})
// We shouldn't have transitioned to a new state.
closeHarness.assertNoStateTransitions()
})
// Otherwise, if the shutdown is well composed, then we should
// transition to the ChannelFlushing state.
t.Run("initiator_shutdown_recv_ok", func(t *testing.T) {
firstState := *startingState
firstState.IdealFeeRate = fn.Some(
chainfee.FeePerKwFloor.FeePerVByte(),
)
firstState.ShutdownScripts = ShutdownScripts{
LocalDeliveryScript: localAddr,
RemoteDeliveryScript: remoteAddr,
}
closeHarness := newCloser(t, &harnessCfg{
initialState: fn.Some[ProtocolState](
&firstState,
),
localUpfrontAddr: fn.Some(localAddr),
remoteUpfrontAddr: fn.Some(remoteAddr),
})
defer closeHarness.stopAndAssert()
// We should disable the outgoing adds for the channel at this
// point as well.
closeHarness.expectFinalBalances(fn.None[ShutdownBalances]())
closeHarness.expectIncomingAddsDisabled()
// We'll send in a shutdown received event, with the expected
// co-op close addr.
closeHarness.chanCloser.SendEvent(
ctx, &ShutdownReceived{ShutdownScript: remoteAddr},
)
// We should transition to the channel flushing state.
closeHarness.assertStateTransitions(&ChannelFlushing{})
// Now we'll ensure that the flushing state has the proper
// co-op close state.
currentState := assertStateT[*ChannelFlushing](closeHarness)
require.Equal(t, localAddr, currentState.LocalDeliveryScript)