• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

lightningnetwork / lnd / 9915780197

13 Jul 2024 12:30AM UTC coverage: 49.268% (-9.1%) from 58.413%
9915780197

push

github

web-flow
Merge pull request #8653 from ProofOfKeags/fn-prim

DynComms [0/n]: `fn` package additions

92837 of 188433 relevant lines covered (49.27%)

1.55 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

0.0
/peer/test_utils.go
1
package peer
2

3
import (
4
        "bytes"
5
        crand "crypto/rand"
6
        "encoding/binary"
7
        "io"
8
        "math/rand"
9
        "net"
10
        "sync/atomic"
11
        "testing"
12
        "time"
13

14
        "github.com/btcsuite/btcd/btcec/v2"
15
        "github.com/btcsuite/btcd/btcutil"
16
        "github.com/btcsuite/btcd/chaincfg/chainhash"
17
        "github.com/btcsuite/btcd/wire"
18
        "github.com/lightningnetwork/lnd/chainntnfs"
19
        "github.com/lightningnetwork/lnd/channeldb"
20
        "github.com/lightningnetwork/lnd/channelnotifier"
21
        "github.com/lightningnetwork/lnd/fn"
22
        "github.com/lightningnetwork/lnd/htlcswitch"
23
        "github.com/lightningnetwork/lnd/input"
24
        "github.com/lightningnetwork/lnd/keychain"
25
        "github.com/lightningnetwork/lnd/lntest/channels"
26
        "github.com/lightningnetwork/lnd/lntest/mock"
27
        "github.com/lightningnetwork/lnd/lnwallet"
28
        "github.com/lightningnetwork/lnd/lnwallet/chainfee"
29
        "github.com/lightningnetwork/lnd/lnwire"
30
        "github.com/lightningnetwork/lnd/netann"
31
        "github.com/lightningnetwork/lnd/pool"
32
        "github.com/lightningnetwork/lnd/queue"
33
        "github.com/lightningnetwork/lnd/shachain"
34
        "github.com/stretchr/testify/require"
35
)
36

37
const (
38
        broadcastHeight = 100
39

40
        // timeout is a timeout value to use for tests which need to wait for
41
        // a return value on a channel.
42
        timeout = time.Second * 5
43

44
        // testCltvRejectDelta is the minimum delta between expiry and current
45
        // height below which htlcs are rejected.
46
        testCltvRejectDelta = 13
47
)
48

49
var (
50
        testKeyLoc = keychain.KeyLocator{Family: keychain.KeyFamilyNodeKey}
51
)
52

53
// noUpdate is a function which can be used as a parameter in
54
// createTestPeerWithChannel to call the setup code with no custom values on
55
// the channels set up.
56
var noUpdate = func(a, b *channeldb.OpenChannel) {}
×
57

58
type peerTestCtx struct {
59
        peer          *Brontide
60
        channel       *lnwallet.LightningChannel
61
        notifier      *mock.ChainNotifier
62
        publishTx     <-chan *wire.MsgTx
63
        mockSwitch    *mockMessageSwitch
64
        db            *channeldb.DB
65
        privKey       *btcec.PrivateKey
66
        mockConn      *mockMessageConn
67
        customChan    chan *customMsg
68
        chanStatusMgr *netann.ChanStatusManager
69
}
70

71
// createTestPeerWithChannel creates a channel between two nodes, and returns a
72
// peer for one of the nodes, together with the channel seen from both nodes.
73
// It takes an updateChan function which can be used to modify the default
74
// values on the channel states for each peer.
75
func createTestPeerWithChannel(t *testing.T, updateChan func(a,
76
        b *channeldb.OpenChannel)) (*peerTestCtx, error) {
×
77

×
78
        params := createTestPeer(t)
×
79

×
80
        var (
×
81
                publishTx     = params.publishTx
×
82
                mockSwitch    = params.mockSwitch
×
83
                alicePeer     = params.peer
×
84
                notifier      = params.notifier
×
85
                aliceKeyPriv  = params.privKey
×
86
                dbAlice       = params.db
×
87
                chanStatusMgr = params.chanStatusMgr
×
88
        )
×
89

×
90
        err := chanStatusMgr.Start()
×
91
        require.NoError(t, err)
×
92
        t.Cleanup(func() {
×
93
                require.NoError(t, chanStatusMgr.Stop())
×
94
        })
×
95

96
        aliceKeyPub := alicePeer.IdentityKey()
×
97
        estimator := alicePeer.cfg.FeeEstimator
×
98

×
99
        channelCapacity := btcutil.Amount(10 * 1e8)
×
100
        channelBal := channelCapacity / 2
×
101
        aliceDustLimit := btcutil.Amount(200)
×
102
        bobDustLimit := btcutil.Amount(1300)
×
103
        csvTimeoutAlice := uint32(5)
×
104
        csvTimeoutBob := uint32(4)
×
105
        isAliceInitiator := true
×
106

×
107
        prevOut := &wire.OutPoint{
×
108
                Hash:  channels.TestHdSeed,
×
109
                Index: 0,
×
110
        }
×
111
        fundingTxIn := wire.NewTxIn(prevOut, nil, nil)
×
112

×
113
        bobKeyPriv, bobKeyPub := btcec.PrivKeyFromBytes(
×
114
                channels.BobsPrivKey,
×
115
        )
×
116

×
117
        aliceCfg := channeldb.ChannelConfig{
×
118
                ChannelConstraints: channeldb.ChannelConstraints{
×
119
                        DustLimit:        aliceDustLimit,
×
120
                        MaxPendingAmount: lnwire.MilliSatoshi(rand.Int63()),
×
121
                        ChanReserve:      btcutil.Amount(rand.Int63()),
×
122
                        MinHTLC:          lnwire.MilliSatoshi(rand.Int63()),
×
123
                        MaxAcceptedHtlcs: uint16(rand.Int31()),
×
124
                        CsvDelay:         uint16(csvTimeoutAlice),
×
125
                },
×
126
                MultiSigKey: keychain.KeyDescriptor{
×
127
                        PubKey: aliceKeyPub,
×
128
                },
×
129
                RevocationBasePoint: keychain.KeyDescriptor{
×
130
                        PubKey: aliceKeyPub,
×
131
                },
×
132
                PaymentBasePoint: keychain.KeyDescriptor{
×
133
                        PubKey: aliceKeyPub,
×
134
                },
×
135
                DelayBasePoint: keychain.KeyDescriptor{
×
136
                        PubKey: aliceKeyPub,
×
137
                },
×
138
                HtlcBasePoint: keychain.KeyDescriptor{
×
139
                        PubKey: aliceKeyPub,
×
140
                },
×
141
        }
×
142
        bobCfg := channeldb.ChannelConfig{
×
143
                ChannelConstraints: channeldb.ChannelConstraints{
×
144
                        DustLimit:        bobDustLimit,
×
145
                        MaxPendingAmount: lnwire.MilliSatoshi(rand.Int63()),
×
146
                        ChanReserve:      btcutil.Amount(rand.Int63()),
×
147
                        MinHTLC:          lnwire.MilliSatoshi(rand.Int63()),
×
148
                        MaxAcceptedHtlcs: uint16(rand.Int31()),
×
149
                        CsvDelay:         uint16(csvTimeoutBob),
×
150
                },
×
151
                MultiSigKey: keychain.KeyDescriptor{
×
152
                        PubKey: bobKeyPub,
×
153
                },
×
154
                RevocationBasePoint: keychain.KeyDescriptor{
×
155
                        PubKey: bobKeyPub,
×
156
                },
×
157
                PaymentBasePoint: keychain.KeyDescriptor{
×
158
                        PubKey: bobKeyPub,
×
159
                },
×
160
                DelayBasePoint: keychain.KeyDescriptor{
×
161
                        PubKey: bobKeyPub,
×
162
                },
×
163
                HtlcBasePoint: keychain.KeyDescriptor{
×
164
                        PubKey: bobKeyPub,
×
165
                },
×
166
        }
×
167

×
168
        bobRoot, err := chainhash.NewHash(bobKeyPriv.Serialize())
×
169
        if err != nil {
×
170
                return nil, err
×
171
        }
×
172
        bobPreimageProducer := shachain.NewRevocationProducer(*bobRoot)
×
173
        bobFirstRevoke, err := bobPreimageProducer.AtIndex(0)
×
174
        if err != nil {
×
175
                return nil, err
×
176
        }
×
177
        bobCommitPoint := input.ComputeCommitmentPoint(bobFirstRevoke[:])
×
178

×
179
        aliceRoot, err := chainhash.NewHash(aliceKeyPriv.Serialize())
×
180
        if err != nil {
×
181
                return nil, err
×
182
        }
×
183
        alicePreimageProducer := shachain.NewRevocationProducer(*aliceRoot)
×
184
        aliceFirstRevoke, err := alicePreimageProducer.AtIndex(0)
×
185
        if err != nil {
×
186
                return nil, err
×
187
        }
×
188
        aliceCommitPoint := input.ComputeCommitmentPoint(aliceFirstRevoke[:])
×
189

×
190
        aliceCommitTx, bobCommitTx, err := lnwallet.CreateCommitmentTxns(
×
191
                channelBal, channelBal, &aliceCfg, &bobCfg, aliceCommitPoint,
×
192
                bobCommitPoint, *fundingTxIn, channeldb.SingleFunderTweaklessBit,
×
193
                isAliceInitiator, 0,
×
194
        )
×
195
        if err != nil {
×
196
                return nil, err
×
197
        }
×
198

199
        dbBob, err := channeldb.Open(t.TempDir())
×
200
        if err != nil {
×
201
                return nil, err
×
202
        }
×
203
        t.Cleanup(func() {
×
204
                require.NoError(t, dbBob.Close())
×
205
        })
×
206

207
        feePerKw, err := estimator.EstimateFeePerKW(1)
×
208
        if err != nil {
×
209
                return nil, err
×
210
        }
×
211

212
        // TODO(roasbeef): need to factor in commit fee?
213
        aliceCommit := channeldb.ChannelCommitment{
×
214
                CommitHeight:  0,
×
215
                LocalBalance:  lnwire.NewMSatFromSatoshis(channelBal),
×
216
                RemoteBalance: lnwire.NewMSatFromSatoshis(channelBal),
×
217
                FeePerKw:      btcutil.Amount(feePerKw),
×
218
                CommitFee:     feePerKw.FeeForWeight(input.CommitWeight),
×
219
                CommitTx:      aliceCommitTx,
×
220
                CommitSig:     bytes.Repeat([]byte{1}, 71),
×
221
        }
×
222
        bobCommit := channeldb.ChannelCommitment{
×
223
                CommitHeight:  0,
×
224
                LocalBalance:  lnwire.NewMSatFromSatoshis(channelBal),
×
225
                RemoteBalance: lnwire.NewMSatFromSatoshis(channelBal),
×
226
                FeePerKw:      btcutil.Amount(feePerKw),
×
227
                CommitFee:     feePerKw.FeeForWeight(input.CommitWeight),
×
228
                CommitTx:      bobCommitTx,
×
229
                CommitSig:     bytes.Repeat([]byte{1}, 71),
×
230
        }
×
231

×
232
        var chanIDBytes [8]byte
×
233
        if _, err := io.ReadFull(crand.Reader, chanIDBytes[:]); err != nil {
×
234
                return nil, err
×
235
        }
×
236

237
        shortChanID := lnwire.NewShortChanIDFromInt(
×
238
                binary.BigEndian.Uint64(chanIDBytes[:]),
×
239
        )
×
240

×
241
        aliceChannelState := &channeldb.OpenChannel{
×
242
                LocalChanCfg:            aliceCfg,
×
243
                RemoteChanCfg:           bobCfg,
×
244
                IdentityPub:             aliceKeyPub,
×
245
                FundingOutpoint:         *prevOut,
×
246
                ShortChannelID:          shortChanID,
×
247
                ChanType:                channeldb.SingleFunderTweaklessBit,
×
248
                IsInitiator:             isAliceInitiator,
×
249
                Capacity:                channelCapacity,
×
250
                RemoteCurrentRevocation: bobCommitPoint,
×
251
                RevocationProducer:      alicePreimageProducer,
×
252
                RevocationStore:         shachain.NewRevocationStore(),
×
253
                LocalCommitment:         aliceCommit,
×
254
                RemoteCommitment:        aliceCommit,
×
255
                Db:                      dbAlice.ChannelStateDB(),
×
256
                Packager:                channeldb.NewChannelPackager(shortChanID),
×
257
                FundingTxn:              channels.TestFundingTx,
×
258
        }
×
259
        bobChannelState := &channeldb.OpenChannel{
×
260
                LocalChanCfg:            bobCfg,
×
261
                RemoteChanCfg:           aliceCfg,
×
262
                IdentityPub:             bobKeyPub,
×
263
                FundingOutpoint:         *prevOut,
×
264
                ChanType:                channeldb.SingleFunderTweaklessBit,
×
265
                IsInitiator:             !isAliceInitiator,
×
266
                Capacity:                channelCapacity,
×
267
                RemoteCurrentRevocation: aliceCommitPoint,
×
268
                RevocationProducer:      bobPreimageProducer,
×
269
                RevocationStore:         shachain.NewRevocationStore(),
×
270
                LocalCommitment:         bobCommit,
×
271
                RemoteCommitment:        bobCommit,
×
272
                Db:                      dbBob.ChannelStateDB(),
×
273
                Packager:                channeldb.NewChannelPackager(shortChanID),
×
274
        }
×
275

×
276
        // Set custom values on the channel states.
×
277
        updateChan(aliceChannelState, bobChannelState)
×
278

×
279
        aliceAddr := alicePeer.cfg.Addr.Address
×
280
        if err := aliceChannelState.SyncPending(aliceAddr, 0); err != nil {
×
281
                return nil, err
×
282
        }
×
283

284
        bobAddr := &net.TCPAddr{
×
285
                IP:   net.ParseIP("127.0.0.1"),
×
286
                Port: 18556,
×
287
        }
×
288

×
289
        if err := bobChannelState.SyncPending(bobAddr, 0); err != nil {
×
290
                return nil, err
×
291
        }
×
292

293
        aliceSigner := input.NewMockSigner(
×
294
                []*btcec.PrivateKey{aliceKeyPriv}, nil,
×
295
        )
×
296
        bobSigner := input.NewMockSigner(
×
297
                []*btcec.PrivateKey{bobKeyPriv}, nil,
×
298
        )
×
299

×
300
        alicePool := lnwallet.NewSigPool(1, aliceSigner)
×
301
        channelAlice, err := lnwallet.NewLightningChannel(
×
302
                aliceSigner, aliceChannelState, alicePool,
×
303
        )
×
304
        if err != nil {
×
305
                return nil, err
×
306
        }
×
307
        _ = alicePool.Start()
×
308
        t.Cleanup(func() {
×
309
                require.NoError(t, alicePool.Stop())
×
310
        })
×
311

312
        bobPool := lnwallet.NewSigPool(1, bobSigner)
×
313
        channelBob, err := lnwallet.NewLightningChannel(
×
314
                bobSigner, bobChannelState, bobPool,
×
315
        )
×
316
        if err != nil {
×
317
                return nil, err
×
318
        }
×
319
        _ = bobPool.Start()
×
320
        t.Cleanup(func() {
×
321
                require.NoError(t, bobPool.Stop())
×
322
        })
×
323

324
        alicePeer.remoteFeatures = lnwire.NewFeatureVector(
×
325
                nil, lnwire.Features,
×
326
        )
×
327

×
328
        chanID := lnwire.NewChanIDFromOutPoint(channelAlice.ChannelPoint())
×
329
        alicePeer.activeChannels.Store(chanID, channelAlice)
×
330

×
331
        alicePeer.wg.Add(1)
×
332
        go alicePeer.channelManager()
×
333

×
334
        return &peerTestCtx{
×
335
                peer:       alicePeer,
×
336
                channel:    channelBob,
×
337
                notifier:   notifier,
×
338
                publishTx:  publishTx,
×
339
                mockSwitch: mockSwitch,
×
340
        }, nil
×
341
}
342

343
// mockMessageSwitch is a mock implementation of the messageSwitch interface
344
// used for testing without relying on a *htlcswitch.Switch in unit tests.
345
type mockMessageSwitch struct {
346
        links []htlcswitch.ChannelUpdateHandler
347
}
348

349
// BestHeight currently returns a dummy value.
350
func (m *mockMessageSwitch) BestHeight() uint32 {
×
351
        return 0
×
352
}
×
353

354
// CircuitModifier currently returns a dummy value.
355
func (m *mockMessageSwitch) CircuitModifier() htlcswitch.CircuitModifier {
×
356
        return nil
×
357
}
×
358

359
// RemoveLink currently does nothing.
360
func (m *mockMessageSwitch) RemoveLink(cid lnwire.ChannelID) {}
×
361

362
// CreateAndAddLink currently returns a dummy value.
363
func (m *mockMessageSwitch) CreateAndAddLink(cfg htlcswitch.ChannelLinkConfig,
364
        lnChan *lnwallet.LightningChannel) error {
×
365

×
366
        return nil
×
367
}
×
368

369
// GetLinksByInterface returns the active links.
370
func (m *mockMessageSwitch) GetLinksByInterface(pub [33]byte) (
371
        []htlcswitch.ChannelUpdateHandler, error) {
×
372

×
373
        return m.links, nil
×
374
}
×
375

376
// mockUpdateHandler is a mock implementation of the ChannelUpdateHandler
377
// interface. It is used in mockMessageSwitch's GetLinksByInterface method.
378
type mockUpdateHandler struct {
379
        cid                  lnwire.ChannelID
380
        isOutgoingAddBlocked atomic.Bool
381
        isIncomingAddBlocked atomic.Bool
382
}
383

384
// newMockUpdateHandler creates a new mockUpdateHandler.
385
func newMockUpdateHandler(cid lnwire.ChannelID) *mockUpdateHandler {
×
386
        return &mockUpdateHandler{
×
387
                cid: cid,
×
388
        }
×
389
}
×
390

391
// HandleChannelUpdate currently does nothing.
392
func (m *mockUpdateHandler) HandleChannelUpdate(msg lnwire.Message) {}
×
393

394
// ChanID returns the mockUpdateHandler's cid.
395
func (m *mockUpdateHandler) ChanID() lnwire.ChannelID { return m.cid }
×
396

397
// Bandwidth currently returns a dummy value.
398
func (m *mockUpdateHandler) Bandwidth() lnwire.MilliSatoshi { return 0 }
×
399

400
// EligibleToForward currently returns a dummy value.
401
func (m *mockUpdateHandler) EligibleToForward() bool { return false }
×
402

403
// MayAddOutgoingHtlc currently returns nil.
404
func (m *mockUpdateHandler) MayAddOutgoingHtlc(lnwire.MilliSatoshi) error { return nil }
×
405

406
type mockMessageConn struct {
407
        t *testing.T
408

409
        // MessageConn embeds our interface so that the mock does not need to
410
        // implement every function. The mock will panic if an unspecified function
411
        // is called.
412
        MessageConn
413

414
        // writtenMessages is a channel that our mock pushes written messages into.
415
        writtenMessages chan []byte
416

417
        readMessages   chan []byte
418
        curReadMessage []byte
419

420
        // writeRaceDetectingCounter is incremented on any function call
421
        // associated with writing to the connection. The race detector will
422
        // trigger on this counter if a data race exists.
423
        writeRaceDetectingCounter int
424

425
        // readRaceDetectingCounter is incremented on any function call
426
        // associated with reading from the connection. The race detector will
427
        // trigger on this counter if a data race exists.
428
        readRaceDetectingCounter int
429
}
430

431
func (m *mockUpdateHandler) EnableAdds(dir htlcswitch.LinkDirection) bool {
×
432
        if dir == htlcswitch.Outgoing {
×
433
                return m.isOutgoingAddBlocked.Swap(false)
×
434
        }
×
435

436
        return m.isIncomingAddBlocked.Swap(false)
×
437
}
438

439
func (m *mockUpdateHandler) DisableAdds(dir htlcswitch.LinkDirection) bool {
×
440
        if dir == htlcswitch.Outgoing {
×
441
                return !m.isOutgoingAddBlocked.Swap(true)
×
442
        }
×
443

444
        return !m.isIncomingAddBlocked.Swap(true)
×
445
}
446

447
func (m *mockUpdateHandler) IsFlushing(dir htlcswitch.LinkDirection) bool {
×
448
        switch dir {
×
449
        case htlcswitch.Outgoing:
×
450
                return m.isOutgoingAddBlocked.Load()
×
451
        case htlcswitch.Incoming:
×
452
                return m.isIncomingAddBlocked.Load()
×
453
        }
454

455
        return false
×
456
}
457

458
func (m *mockUpdateHandler) OnFlushedOnce(hook func()) {
×
459
        hook()
×
460
}
×
461
func (m *mockUpdateHandler) OnCommitOnce(
462
        _ htlcswitch.LinkDirection, hook func(),
463
) {
×
464

×
465
        hook()
×
466
}
×
467

468
func newMockConn(t *testing.T, expectedMessages int) *mockMessageConn {
×
469
        return &mockMessageConn{
×
470
                t:               t,
×
471
                writtenMessages: make(chan []byte, expectedMessages),
×
472
                readMessages:    make(chan []byte, 1),
×
473
        }
×
474
}
×
475

476
// SetWriteDeadline mocks setting write deadline for our conn.
477
func (m *mockMessageConn) SetWriteDeadline(time.Time) error {
×
478
        m.writeRaceDetectingCounter++
×
479
        return nil
×
480
}
×
481

482
// Flush mocks a message conn flush.
483
func (m *mockMessageConn) Flush() (int, error) {
×
484
        m.writeRaceDetectingCounter++
×
485
        return 0, nil
×
486
}
×
487

488
// WriteMessage mocks sending of a message on our connection. It will push
489
// the bytes sent into the mock's writtenMessages channel.
490
func (m *mockMessageConn) WriteMessage(msg []byte) error {
×
491
        m.writeRaceDetectingCounter++
×
492
        select {
×
493
        case m.writtenMessages <- msg:
×
494
        case <-time.After(timeout):
×
495
                m.t.Fatalf("timeout sending message: %v", msg)
×
496
        }
497

498
        return nil
×
499
}
500

501
// assertWrite asserts that our mock as had WriteMessage called with the byte
502
// slice we expect.
503
func (m *mockMessageConn) assertWrite(expected []byte) {
×
504
        select {
×
505
        case actual := <-m.writtenMessages:
×
506
                require.Equal(m.t, expected, actual)
×
507

508
        case <-time.After(timeout):
×
509
                m.t.Fatalf("timeout waiting for write: %v", expected)
×
510
        }
511
}
512

513
func (m *mockMessageConn) SetReadDeadline(t time.Time) error {
×
514
        m.readRaceDetectingCounter++
×
515
        return nil
×
516
}
×
517

518
func (m *mockMessageConn) ReadNextHeader() (uint32, error) {
×
519
        m.readRaceDetectingCounter++
×
520
        m.curReadMessage = <-m.readMessages
×
521
        return uint32(len(m.curReadMessage)), nil
×
522
}
×
523

524
func (m *mockMessageConn) ReadNextBody(buf []byte) ([]byte, error) {
×
525
        m.readRaceDetectingCounter++
×
526
        return m.curReadMessage, nil
×
527
}
×
528

529
func (m *mockMessageConn) RemoteAddr() net.Addr {
×
530
        return nil
×
531
}
×
532

533
func (m *mockMessageConn) LocalAddr() net.Addr {
×
534
        return nil
×
535
}
×
536

537
func (m *mockMessageConn) Close() error {
×
538
        return nil
×
539
}
×
540

541
// createTestPeer creates a new peer for testing and returns a context struct
542
// containing necessary handles and mock objects for conducting tests on peer
543
// functionalities.
544
func createTestPeer(t *testing.T) *peerTestCtx {
×
545
        nodeKeyLocator := keychain.KeyLocator{
×
546
                Family: keychain.KeyFamilyNodeKey,
×
547
        }
×
548

×
549
        aliceKeyPriv, aliceKeyPub := btcec.PrivKeyFromBytes(
×
550
                channels.AlicesPrivKey,
×
551
        )
×
552

×
553
        aliceKeySigner := keychain.NewPrivKeyMessageSigner(
×
554
                aliceKeyPriv, nodeKeyLocator,
×
555
        )
×
556

×
557
        aliceAddr := &net.TCPAddr{
×
558
                IP:   net.ParseIP("127.0.0.1"),
×
559
                Port: 18555,
×
560
        }
×
561
        cfgAddr := &lnwire.NetAddress{
×
562
                IdentityKey: aliceKeyPub,
×
563
                Address:     aliceAddr,
×
564
                ChainNet:    wire.SimNet,
×
565
        }
×
566

×
567
        errBuffer, err := queue.NewCircularBuffer(ErrorBufferSize)
×
568
        require.NoError(t, err)
×
569

×
570
        chainIO := &mock.ChainIO{
×
571
                BestHeight: broadcastHeight,
×
572
        }
×
573

×
574
        publishTx := make(chan *wire.MsgTx)
×
575
        wallet := &lnwallet.LightningWallet{
×
576
                WalletController: &mock.WalletController{
×
577
                        RootKey:               aliceKeyPriv,
×
578
                        PublishedTransactions: publishTx,
×
579
                },
×
580
        }
×
581

×
582
        const chanActiveTimeout = time.Minute
×
583

×
584
        dbAlice, err := channeldb.Open(t.TempDir())
×
585
        require.NoError(t, err)
×
586
        t.Cleanup(func() {
×
587
                require.NoError(t, dbAlice.Close())
×
588
        })
×
589

590
        nodeSignerAlice := netann.NewNodeSigner(aliceKeySigner)
×
591

×
592
        chanStatusMgr, err := netann.NewChanStatusManager(&netann.
×
593
                ChanStatusConfig{
×
594
                ChanStatusSampleInterval: 30 * time.Second,
×
595
                ChanEnableTimeout:        chanActiveTimeout,
×
596
                ChanDisableTimeout:       2 * time.Minute,
×
597
                DB:                       dbAlice.ChannelStateDB(),
×
598
                Graph:                    dbAlice.ChannelGraph(),
×
599
                MessageSigner:            nodeSignerAlice,
×
600
                OurPubKey:                aliceKeyPub,
×
601
                OurKeyLoc:                testKeyLoc,
×
602
                IsChannelActive: func(lnwire.ChannelID) bool {
×
603
                        return true
×
604
                },
×
605
                ApplyChannelUpdate: func(*lnwire.ChannelUpdate,
606
                        *wire.OutPoint, bool) error {
×
607

×
608
                        return nil
×
609
                },
×
610
        })
611
        require.NoError(t, err)
×
612

×
613
        interceptableSwitchNotifier := &mock.ChainNotifier{
×
614
                EpochChan: make(chan *chainntnfs.BlockEpoch, 1),
×
615
        }
×
616
        interceptableSwitchNotifier.EpochChan <- &chainntnfs.BlockEpoch{
×
617
                Height: 1,
×
618
        }
×
619

×
620
        interceptableSwitch, err := htlcswitch.NewInterceptableSwitch(
×
621
                &htlcswitch.InterceptableSwitchConfig{
×
622
                        CltvRejectDelta:    testCltvRejectDelta,
×
623
                        CltvInterceptDelta: testCltvRejectDelta + 3,
×
624
                        Notifier:           interceptableSwitchNotifier,
×
625
                },
×
626
        )
×
627
        require.NoError(t, err)
×
628

×
629
        // TODO(yy): create interface for lnwallet.LightningChannel so we can
×
630
        // easily mock it without the following setups.
×
631
        notifier := &mock.ChainNotifier{
×
632
                SpendChan: make(chan *chainntnfs.SpendDetail),
×
633
                EpochChan: make(chan *chainntnfs.BlockEpoch),
×
634
                ConfChan:  make(chan *chainntnfs.TxConfirmation),
×
635
        }
×
636

×
637
        mockSwitch := &mockMessageSwitch{}
×
638

×
639
        // TODO(yy): change ChannelNotifier to be an interface.
×
640
        channelNotifier := channelnotifier.New(dbAlice.ChannelStateDB())
×
641
        require.NoError(t, channelNotifier.Start())
×
642
        t.Cleanup(func() {
×
643
                require.NoError(t, channelNotifier.Stop(),
×
644
                        "stop channel notifier failed")
×
645
        })
×
646

647
        writeBufferPool := pool.NewWriteBuffer(
×
648
                pool.DefaultWriteBufferGCInterval,
×
649
                pool.DefaultWriteBufferExpiryInterval,
×
650
        )
×
651

×
652
        writePool := pool.NewWrite(
×
653
                writeBufferPool, 1, timeout,
×
654
        )
×
655
        require.NoError(t, writePool.Start())
×
656

×
657
        readBufferPool := pool.NewReadBuffer(
×
658
                pool.DefaultReadBufferGCInterval,
×
659
                pool.DefaultReadBufferExpiryInterval,
×
660
        )
×
661

×
662
        readPool := pool.NewRead(
×
663
                readBufferPool, 1, timeout,
×
664
        )
×
665
        require.NoError(t, readPool.Start())
×
666

×
667
        mockConn := newMockConn(t, 1)
×
668

×
669
        receivedCustomChan := make(chan *customMsg)
×
670

×
671
        var pubKey [33]byte
×
672
        copy(pubKey[:], aliceKeyPub.SerializeCompressed())
×
673

×
674
        estimator := chainfee.NewStaticEstimator(12500, 0)
×
675

×
676
        cfg := &Config{
×
677
                Addr:              cfgAddr,
×
678
                PubKeyBytes:       pubKey,
×
679
                ErrorBuffer:       errBuffer,
×
680
                ChainIO:           chainIO,
×
681
                Switch:            mockSwitch,
×
682
                ChanActiveTimeout: chanActiveTimeout,
×
683
                InterceptSwitch:   interceptableSwitch,
×
684
                ChannelDB:         dbAlice.ChannelStateDB(),
×
685
                FeeEstimator:      estimator,
×
686
                Wallet:            wallet,
×
687
                ChainNotifier:     notifier,
×
688
                ChanStatusMgr:     chanStatusMgr,
×
689
                Features: lnwire.NewFeatureVector(
×
690
                        nil, lnwire.Features,
×
691
                ),
×
692
                DisconnectPeer: func(b *btcec.PublicKey) error {
×
693
                        return nil
×
694
                },
×
695
                ChannelNotifier:               channelNotifier,
696
                PrunePersistentPeerConnection: func([33]byte) {},
×
697
                LegacyFeatures:                lnwire.EmptyFeatureVector(),
698
                WritePool:                     writePool,
699
                ReadPool:                      readPool,
700
                Conn:                          mockConn,
701
                HandleCustomMessage: func(
702
                        peer [33]byte, msg *lnwire.Custom) error {
×
703

×
704
                        receivedCustomChan <- &customMsg{
×
705
                                peer: peer,
×
706
                                msg:  *msg,
×
707
                        }
×
708

×
709
                        return nil
×
710
                },
×
711
                PongBuf: make([]byte, lnwire.MaxPongBytes),
712
        }
713

714
        alicePeer := NewBrontide(*cfg)
×
715

×
716
        return &peerTestCtx{
×
717
                publishTx:     publishTx,
×
718
                mockSwitch:    mockSwitch,
×
719
                peer:          alicePeer,
×
720
                notifier:      notifier,
×
721
                db:            dbAlice,
×
722
                privKey:       aliceKeyPriv,
×
723
                mockConn:      mockConn,
×
724
                customChan:    receivedCustomChan,
×
725
                chanStatusMgr: chanStatusMgr,
×
726
        }
×
727
}
728

729
// startPeer invokes the `Start` method on the specified peer and handles any
730
// initial startup messages for testing.
731
func startPeer(t *testing.T, mockConn *mockMessageConn,
732
        peer *Brontide) <-chan struct{} {
×
733

×
734
        // Start the peer in a goroutine so that we can handle and test for
×
735
        // startup messages. Successfully sending and receiving init message,
×
736
        // indicates a successful startup.
×
737
        done := make(chan struct{})
×
738
        go func() {
×
739
                require.NoError(t, peer.Start())
×
740
                close(done)
×
741
        }()
×
742

743
        // Receive the init message that should be the first message received on
744
        // startup.
745
        rawMsg, err := fn.RecvOrTimeout[[]byte](
×
746
                mockConn.writtenMessages, timeout,
×
747
        )
×
748
        require.NoError(t, err)
×
749

×
750
        msgReader := bytes.NewReader(rawMsg)
×
751
        nextMsg, err := lnwire.ReadMessage(msgReader, 0)
×
752
        require.NoError(t, err)
×
753

×
754
        _, ok := nextMsg.(*lnwire.Init)
×
755
        require.True(t, ok)
×
756

×
757
        // Write the reply for the init message to complete the startup.
×
758
        initReplyMsg := lnwire.NewInitMessage(
×
759
                lnwire.NewRawFeatureVector(
×
760
                        lnwire.DataLossProtectRequired,
×
761
                        lnwire.GossipQueriesOptional,
×
762
                ),
×
763
                lnwire.NewRawFeatureVector(),
×
764
        )
×
765

×
766
        var b bytes.Buffer
×
767
        _, err = lnwire.WriteMessage(&b, initReplyMsg, 0)
×
768
        require.NoError(t, err)
×
769

×
770
        ok = fn.SendOrQuit[[]byte, struct{}](
×
771
                mockConn.readMessages, b.Bytes(), make(chan struct{}),
×
772
        )
×
773
        require.True(t, ok)
×
774

×
775
        return done
×
776
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc