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

lightningnetwork / lnd / 14445630877

14 Apr 2025 12:28PM UTC coverage: 58.622%. First build
14445630877

Pull #9699

github

web-flow
Merge 29a66f31c into 7438f2227
Pull Request #9699: htlcswitch+peer [2/2]: thread context through in preparation for passing to graph DB calls

142 of 208 new or added lines in 14 files covered. (68.27%)

97202 of 165812 relevant lines covered (58.62%)

1.82 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
        "context"
6
        crand "crypto/rand"
7
        "encoding/binary"
8
        "io"
9
        "math/rand"
10
        "net"
11
        "sync/atomic"
12
        "testing"
13
        "time"
14

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

41
const (
42
        broadcastHeight = 100
43

44
        // timeout is a timeout value to use for tests which need to wait for
45
        // a return value on a channel.
46
        timeout = time.Second * 5
47

48
        // testCltvRejectDelta is the minimum delta between expiry and current
49
        // height below which htlcs are rejected.
50
        testCltvRejectDelta = 13
51
)
52

53
var (
54
        testKeyLoc = keychain.KeyLocator{Family: keychain.KeyFamilyNodeKey}
55
)
56

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

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

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

×
82
        params := createTestPeer(t)
×
83

×
84
        var (
×
85
                publishTx     = params.publishTx
×
86
                mockSwitch    = params.mockSwitch
×
87
                alicePeer     = params.peer
×
88
                notifier      = params.notifier
×
89
                aliceKeyPriv  = params.privKey
×
90
                dbAlice       = params.db
×
91
                chanStatusMgr = params.chanStatusMgr
×
92
        )
×
93

×
94
        err := chanStatusMgr.Start()
×
95
        require.NoError(t, err)
×
96
        t.Cleanup(func() {
×
97
                require.NoError(t, chanStatusMgr.Stop())
×
98
        })
×
99

100
        aliceKeyPub := alicePeer.IdentityKey()
×
101
        estimator := alicePeer.cfg.FeeEstimator
×
102

×
103
        channelCapacity := btcutil.Amount(10 * 1e8)
×
104
        channelBal := channelCapacity / 2
×
105
        aliceDustLimit := btcutil.Amount(200)
×
106
        bobDustLimit := btcutil.Amount(1300)
×
107
        csvTimeoutAlice := uint32(5)
×
108
        csvTimeoutBob := uint32(4)
×
109
        isAliceInitiator := true
×
110

×
111
        prevOut := &wire.OutPoint{
×
112
                Hash:  channels.TestHdSeed,
×
113
                Index: 0,
×
114
        }
×
115
        fundingTxIn := wire.NewTxIn(prevOut, nil, nil)
×
116

×
117
        bobKeyPriv, bobKeyPub := btcec.PrivKeyFromBytes(
×
118
                channels.BobsPrivKey,
×
119
        )
×
120

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

×
176
        bobRoot, err := chainhash.NewHash(bobKeyPriv.Serialize())
×
177
        if err != nil {
×
178
                return nil, err
×
179
        }
×
180
        bobPreimageProducer := shachain.NewRevocationProducer(*bobRoot)
×
181
        bobFirstRevoke, err := bobPreimageProducer.AtIndex(0)
×
182
        if err != nil {
×
183
                return nil, err
×
184
        }
×
185
        bobCommitPoint := input.ComputeCommitmentPoint(bobFirstRevoke[:])
×
186

×
187
        aliceRoot, err := chainhash.NewHash(aliceKeyPriv.Serialize())
×
188
        if err != nil {
×
189
                return nil, err
×
190
        }
×
191
        alicePreimageProducer := shachain.NewRevocationProducer(*aliceRoot)
×
192
        aliceFirstRevoke, err := alicePreimageProducer.AtIndex(0)
×
193
        if err != nil {
×
194
                return nil, err
×
195
        }
×
196
        aliceCommitPoint := input.ComputeCommitmentPoint(aliceFirstRevoke[:])
×
197

×
198
        aliceCommitTx, bobCommitTx, err := lnwallet.CreateCommitmentTxns(
×
199
                channelBal, channelBal, &aliceCfg, &bobCfg, aliceCommitPoint,
×
200
                bobCommitPoint, *fundingTxIn, channeldb.SingleFunderTweaklessBit,
×
201
                isAliceInitiator, 0,
×
202
        )
×
203
        if err != nil {
×
204
                return nil, err
×
205
        }
×
206

207
        dbBob := channeldb.OpenForTesting(t, t.TempDir())
×
208

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

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

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

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

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

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

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

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

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

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

×
302
        alicePool := lnwallet.NewSigPool(1, aliceSigner)
×
303
        channelAlice, err := lnwallet.NewLightningChannel(
×
304
                aliceSigner, aliceChannelState, alicePool,
×
305
                lnwallet.WithLeafStore(&lnwallet.MockAuxLeafStore{}),
×
306
                lnwallet.WithAuxSigner(lnwallet.NewAuxSignerMock(
×
307
                        lnwallet.EmptyMockJobHandler,
×
308
                )),
×
309
        )
×
310
        if err != nil {
×
311
                return nil, err
×
312
        }
×
313
        _ = alicePool.Start()
×
314
        t.Cleanup(func() {
×
315
                require.NoError(t, alicePool.Stop())
×
316
        })
×
317

318
        bobPool := lnwallet.NewSigPool(1, bobSigner)
×
319
        channelBob, err := lnwallet.NewLightningChannel(
×
320
                bobSigner, bobChannelState, bobPool,
×
321
                lnwallet.WithLeafStore(&lnwallet.MockAuxLeafStore{}),
×
322
                lnwallet.WithAuxSigner(lnwallet.NewAuxSignerMock(
×
323
                        lnwallet.EmptyMockJobHandler,
×
324
                )),
×
325
        )
×
326
        if err != nil {
×
327
                return nil, err
×
328
        }
×
329
        _ = bobPool.Start()
×
330
        t.Cleanup(func() {
×
331
                require.NoError(t, bobPool.Stop())
×
332
        })
×
333

334
        alicePeer.remoteFeatures = lnwire.NewFeatureVector(
×
335
                nil, lnwire.Features,
×
336
        )
×
337

×
338
        chanID := lnwire.NewChanIDFromOutPoint(channelAlice.ChannelPoint())
×
339
        alicePeer.activeChannels.Store(chanID, channelAlice)
×
340

×
341
        alicePeer.cg.WgAdd(1)
×
342
        go alicePeer.channelManager()
×
343

×
344
        return &peerTestCtx{
×
345
                peer:       alicePeer,
×
346
                channel:    channelBob,
×
347
                notifier:   notifier,
×
348
                publishTx:  publishTx,
×
349
                mockSwitch: mockSwitch,
×
350
                mockConn:   params.mockConn,
×
351
        }, nil
×
352
}
353

354
// mockMessageSwitch is a mock implementation of the messageSwitch interface
355
// used for testing without relying on a *htlcswitch.Switch in unit tests.
356
type mockMessageSwitch struct {
357
        links []htlcswitch.ChannelUpdateHandler
358
}
359

360
// BestHeight currently returns a dummy value.
361
func (m *mockMessageSwitch) BestHeight() uint32 {
×
362
        return 0
×
363
}
×
364

365
// CircuitModifier currently returns a dummy value.
366
func (m *mockMessageSwitch) CircuitModifier() htlcswitch.CircuitModifier {
×
367
        return nil
×
368
}
×
369

370
// RemoveLink currently does nothing.
371
func (m *mockMessageSwitch) RemoveLink(cid lnwire.ChannelID) {}
×
372

373
// CreateAndAddLink currently returns a dummy value.
374
func (m *mockMessageSwitch) CreateAndAddLink(cfg htlcswitch.ChannelLinkConfig,
375
        lnChan *lnwallet.LightningChannel) error {
×
376

×
377
        return nil
×
378
}
×
379

380
// GetLinksByInterface returns the active links.
381
func (m *mockMessageSwitch) GetLinksByInterface(pub [33]byte) (
382
        []htlcswitch.ChannelUpdateHandler, error) {
×
383

×
384
        return m.links, nil
×
385
}
×
386

387
// mockUpdateHandler is a mock implementation of the ChannelUpdateHandler
388
// interface. It is used in mockMessageSwitch's GetLinksByInterface method.
389
type mockUpdateHandler struct {
390
        cid                  lnwire.ChannelID
391
        isOutgoingAddBlocked atomic.Bool
392
        isIncomingAddBlocked atomic.Bool
393
}
394

395
// newMockUpdateHandler creates a new mockUpdateHandler.
396
func newMockUpdateHandler(cid lnwire.ChannelID) *mockUpdateHandler {
×
397
        return &mockUpdateHandler{
×
398
                cid: cid,
×
399
        }
×
400
}
×
401

402
// HandleChannelUpdate currently does nothing.
403
func (m *mockUpdateHandler) HandleChannelUpdate(msg lnwire.Message) {}
×
404

405
// ChanID returns the mockUpdateHandler's cid.
406
func (m *mockUpdateHandler) ChanID() lnwire.ChannelID { return m.cid }
×
407

408
// Bandwidth currently returns a dummy value.
409
func (m *mockUpdateHandler) Bandwidth() lnwire.MilliSatoshi { return 0 }
×
410

411
// EligibleToForward currently returns a dummy value.
412
func (m *mockUpdateHandler) EligibleToForward() bool { return false }
×
413

414
// MayAddOutgoingHtlc currently returns nil.
415
func (m *mockUpdateHandler) MayAddOutgoingHtlc(lnwire.MilliSatoshi) error { return nil }
×
416

417
type mockMessageConn struct {
418
        t *testing.T
419

420
        // MessageConn embeds our interface so that the mock does not need to
421
        // implement every function. The mock will panic if an unspecified function
422
        // is called.
423
        MessageConn
424

425
        // writtenMessages is a channel that our mock pushes written messages into.
426
        writtenMessages chan []byte
427

428
        readMessages   chan []byte
429
        curReadMessage []byte
430

431
        // writeRaceDetectingCounter is incremented on any function call
432
        // associated with writing to the connection. The race detector will
433
        // trigger on this counter if a data race exists.
434
        writeRaceDetectingCounter int
435

436
        // readRaceDetectingCounter is incremented on any function call
437
        // associated with reading from the connection. The race detector will
438
        // trigger on this counter if a data race exists.
439
        readRaceDetectingCounter int
440
}
441

442
func (m *mockUpdateHandler) EnableAdds(dir htlcswitch.LinkDirection) bool {
×
443
        if dir == htlcswitch.Outgoing {
×
444
                return m.isOutgoingAddBlocked.Swap(false)
×
445
        }
×
446

447
        return m.isIncomingAddBlocked.Swap(false)
×
448
}
449

450
func (m *mockUpdateHandler) DisableAdds(dir htlcswitch.LinkDirection) bool {
×
451
        if dir == htlcswitch.Outgoing {
×
452
                return !m.isOutgoingAddBlocked.Swap(true)
×
453
        }
×
454

455
        return !m.isIncomingAddBlocked.Swap(true)
×
456
}
457

458
func (m *mockUpdateHandler) IsFlushing(dir htlcswitch.LinkDirection) bool {
×
459
        switch dir {
×
460
        case htlcswitch.Outgoing:
×
461
                return m.isOutgoingAddBlocked.Load()
×
462
        case htlcswitch.Incoming:
×
463
                return m.isIncomingAddBlocked.Load()
×
464
        }
465

466
        return false
×
467
}
468

469
func (m *mockUpdateHandler) OnFlushedOnce(hook func()) {
×
470
        hook()
×
471
}
×
472
func (m *mockUpdateHandler) OnCommitOnce(
473
        _ htlcswitch.LinkDirection, hook func(),
474
) {
×
475

×
476
        hook()
×
477
}
×
478
func (m *mockUpdateHandler) InitStfu() <-chan fn.Result[lntypes.ChannelParty] {
×
479
        // TODO(proofofkeags): Implement
×
480
        c := make(chan fn.Result[lntypes.ChannelParty], 1)
×
481

×
482
        c <- fn.Errf[lntypes.ChannelParty]("InitStfu not yet implemented")
×
483

×
484
        return c
×
485
}
×
486

487
func newMockConn(t *testing.T, expectedMessages int) *mockMessageConn {
×
488
        return &mockMessageConn{
×
489
                t:               t,
×
490
                writtenMessages: make(chan []byte, expectedMessages),
×
491
                readMessages:    make(chan []byte, 1),
×
492
        }
×
493
}
×
494

495
// SetWriteDeadline mocks setting write deadline for our conn.
496
func (m *mockMessageConn) SetWriteDeadline(time.Time) error {
×
497
        m.writeRaceDetectingCounter++
×
498
        return nil
×
499
}
×
500

501
// Flush mocks a message conn flush.
502
func (m *mockMessageConn) Flush() (int, error) {
×
503
        m.writeRaceDetectingCounter++
×
504
        return 0, nil
×
505
}
×
506

507
// WriteMessage mocks sending of a message on our connection. It will push
508
// the bytes sent into the mock's writtenMessages channel.
509
func (m *mockMessageConn) WriteMessage(msg []byte) error {
×
510
        m.writeRaceDetectingCounter++
×
511

×
512
        msgCopy := make([]byte, len(msg))
×
513
        copy(msgCopy, msg)
×
514

×
515
        select {
×
516
        case m.writtenMessages <- msgCopy:
×
517
        case <-time.After(timeout):
×
518
                m.t.Fatalf("timeout sending message: %v", msgCopy)
×
519
        }
520

521
        return nil
×
522
}
523

524
// assertWrite asserts that our mock as had WriteMessage called with the byte
525
// slice we expect.
526
func (m *mockMessageConn) assertWrite(expected []byte) {
×
527
        select {
×
528
        case actual := <-m.writtenMessages:
×
529
                require.Equal(m.t, expected, actual)
×
530

531
        case <-time.After(timeout):
×
532
                m.t.Fatalf("timeout waiting for write: %v", expected)
×
533
        }
534
}
535

536
func (m *mockMessageConn) SetReadDeadline(t time.Time) error {
×
537
        m.readRaceDetectingCounter++
×
538
        return nil
×
539
}
×
540

541
func (m *mockMessageConn) ReadNextHeader() (uint32, error) {
×
542
        m.readRaceDetectingCounter++
×
543
        m.curReadMessage = <-m.readMessages
×
544
        return uint32(len(m.curReadMessage)), nil
×
545
}
×
546

547
func (m *mockMessageConn) ReadNextBody(buf []byte) ([]byte, error) {
×
548
        m.readRaceDetectingCounter++
×
549
        return m.curReadMessage, nil
×
550
}
×
551

552
func (m *mockMessageConn) RemoteAddr() net.Addr {
×
553
        return nil
×
554
}
×
555

556
func (m *mockMessageConn) LocalAddr() net.Addr {
×
557
        return nil
×
558
}
×
559

560
func (m *mockMessageConn) Close() error {
×
561
        return nil
×
562
}
×
563

564
// createTestPeer creates a new peer for testing and returns a context struct
565
// containing necessary handles and mock objects for conducting tests on peer
566
// functionalities.
567
func createTestPeer(t *testing.T) *peerTestCtx {
×
568
        nodeKeyLocator := keychain.KeyLocator{
×
569
                Family: keychain.KeyFamilyNodeKey,
×
570
        }
×
571

×
572
        aliceKeyPriv, aliceKeyPub := btcec.PrivKeyFromBytes(
×
573
                channels.AlicesPrivKey,
×
574
        )
×
575

×
576
        aliceKeySigner := keychain.NewPrivKeyMessageSigner(
×
577
                aliceKeyPriv, nodeKeyLocator,
×
578
        )
×
579

×
580
        aliceAddr := &net.TCPAddr{
×
581
                IP:   net.ParseIP("127.0.0.1"),
×
582
                Port: 18555,
×
583
        }
×
584
        cfgAddr := &lnwire.NetAddress{
×
585
                IdentityKey: aliceKeyPub,
×
586
                Address:     aliceAddr,
×
587
                ChainNet:    wire.SimNet,
×
588
        }
×
589

×
590
        errBuffer, err := queue.NewCircularBuffer(ErrorBufferSize)
×
591
        require.NoError(t, err)
×
592

×
593
        chainIO := &mock.ChainIO{
×
594
                BestHeight: broadcastHeight,
×
595
        }
×
596

×
597
        publishTx := make(chan *wire.MsgTx)
×
598
        wallet := &lnwallet.LightningWallet{
×
599
                WalletController: &mock.WalletController{
×
600
                        RootKey:               aliceKeyPriv,
×
601
                        PublishedTransactions: publishTx,
×
602
                },
×
603
        }
×
604

×
605
        const chanActiveTimeout = time.Minute
×
606

×
607
        dbPath := t.TempDir()
×
608

×
609
        graphBackend, err := kvdb.GetBoltBackend(&kvdb.BoltBackendConfig{
×
610
                DBPath:            dbPath,
×
611
                DBFileName:        "graph.db",
×
612
                NoFreelistSync:    true,
×
613
                AutoCompact:       false,
×
614
                AutoCompactMinAge: kvdb.DefaultBoltAutoCompactMinAge,
×
615
                DBTimeout:         kvdb.DefaultDBTimeout,
×
616
        })
×
617
        require.NoError(t, err)
×
618

×
619
        dbAliceGraph, err := graphdb.NewChannelGraph(&graphdb.Config{
×
620
                KVDB: graphBackend,
×
621
        })
×
622
        require.NoError(t, err)
×
623
        require.NoError(t, dbAliceGraph.Start())
×
624
        t.Cleanup(func() {
×
625
                require.NoError(t, dbAliceGraph.Stop())
×
626
        })
×
627

628
        dbAliceChannel := channeldb.OpenForTesting(t, dbPath)
×
629

×
630
        nodeSignerAlice := netann.NewNodeSigner(aliceKeySigner)
×
631

×
632
        chanStatusMgr, err := netann.NewChanStatusManager(&netann.
×
633
                ChanStatusConfig{
×
634
                ChanStatusSampleInterval: 30 * time.Second,
×
635
                ChanEnableTimeout:        chanActiveTimeout,
×
636
                ChanDisableTimeout:       2 * time.Minute,
×
637
                DB:                       dbAliceChannel.ChannelStateDB(),
×
638
                Graph:                    dbAliceGraph,
×
639
                MessageSigner:            nodeSignerAlice,
×
640
                OurPubKey:                aliceKeyPub,
×
641
                OurKeyLoc:                testKeyLoc,
×
642
                IsChannelActive: func(lnwire.ChannelID) bool {
×
643
                        return true
×
644
                },
×
645
                ApplyChannelUpdate: func(*lnwire.ChannelUpdate1,
646
                        *wire.OutPoint, bool) error {
×
647

×
648
                        return nil
×
649
                },
×
650
        })
651
        require.NoError(t, err)
×
652

×
653
        interceptableSwitchNotifier := &mock.ChainNotifier{
×
654
                EpochChan: make(chan *chainntnfs.BlockEpoch, 1),
×
655
        }
×
656
        interceptableSwitchNotifier.EpochChan <- &chainntnfs.BlockEpoch{
×
657
                Height: 1,
×
658
        }
×
659

×
660
        interceptableSwitch, err := htlcswitch.NewInterceptableSwitch(
×
661
                &htlcswitch.InterceptableSwitchConfig{
×
662
                        CltvRejectDelta:    testCltvRejectDelta,
×
663
                        CltvInterceptDelta: testCltvRejectDelta + 3,
×
664
                        Notifier:           interceptableSwitchNotifier,
×
665
                },
×
666
        )
×
667
        require.NoError(t, err)
×
668

×
669
        // TODO(yy): create interface for lnwallet.LightningChannel so we can
×
670
        // easily mock it without the following setups.
×
671
        notifier := &mock.ChainNotifier{
×
672
                SpendChan: make(chan *chainntnfs.SpendDetail),
×
673
                EpochChan: make(chan *chainntnfs.BlockEpoch),
×
674
                ConfChan:  make(chan *chainntnfs.TxConfirmation),
×
675
        }
×
676

×
677
        mockSwitch := &mockMessageSwitch{}
×
678

×
679
        // TODO(yy): change ChannelNotifier to be an interface.
×
680
        channelNotifier := channelnotifier.New(dbAliceChannel.ChannelStateDB())
×
681
        require.NoError(t, channelNotifier.Start())
×
682
        t.Cleanup(func() {
×
683
                require.NoError(t, channelNotifier.Stop(),
×
684
                        "stop channel notifier failed")
×
685
        })
×
686

687
        writeBufferPool := pool.NewWriteBuffer(
×
688
                pool.DefaultWriteBufferGCInterval,
×
689
                pool.DefaultWriteBufferExpiryInterval,
×
690
        )
×
691

×
692
        writePool := pool.NewWrite(
×
693
                writeBufferPool, 1, timeout,
×
694
        )
×
695
        require.NoError(t, writePool.Start())
×
696

×
697
        readBufferPool := pool.NewReadBuffer(
×
698
                pool.DefaultReadBufferGCInterval,
×
699
                pool.DefaultReadBufferExpiryInterval,
×
700
        )
×
701

×
702
        readPool := pool.NewRead(
×
703
                readBufferPool, 1, timeout,
×
704
        )
×
705
        require.NoError(t, readPool.Start())
×
706

×
707
        mockConn := newMockConn(t, 1)
×
708

×
709
        receivedCustomChan := make(chan *customMsg)
×
710

×
711
        var pubKey [33]byte
×
712
        copy(pubKey[:], aliceKeyPub.SerializeCompressed())
×
713

×
714
        estimator := chainfee.NewStaticEstimator(12500, 0)
×
715

×
716
        cfg := &Config{
×
717
                Addr:              cfgAddr,
×
718
                PubKeyBytes:       pubKey,
×
719
                ErrorBuffer:       errBuffer,
×
720
                ChainIO:           chainIO,
×
721
                Switch:            mockSwitch,
×
722
                ChanActiveTimeout: chanActiveTimeout,
×
723
                InterceptSwitch:   interceptableSwitch,
×
724
                ChannelDB:         dbAliceChannel.ChannelStateDB(),
×
725
                FeeEstimator:      estimator,
×
726
                Wallet:            wallet,
×
727
                ChainNotifier:     notifier,
×
728
                ChanStatusMgr:     chanStatusMgr,
×
729
                Features: lnwire.NewFeatureVector(
×
730
                        nil, lnwire.Features,
×
731
                ),
×
732
                DisconnectPeer: func(b *btcec.PublicKey) error {
×
733
                        return nil
×
734
                },
×
735
                ChannelNotifier:               channelNotifier,
736
                PrunePersistentPeerConnection: func([33]byte) {},
×
737
                LegacyFeatures:                lnwire.EmptyFeatureVector(),
738
                WritePool:                     writePool,
739
                ReadPool:                      readPool,
740
                Conn:                          mockConn,
741
                HandleCustomMessage: func(
742
                        peer [33]byte, msg *lnwire.Custom) error {
×
743

×
744
                        receivedCustomChan <- &customMsg{
×
745
                                peer: peer,
×
746
                                msg:  *msg,
×
747
                        }
×
748

×
749
                        return nil
×
750
                },
×
751
                PongBuf: make([]byte, lnwire.MaxPongBytes),
752
                FetchLastChanUpdate: func(_ context.Context,
753
                        _ lnwire.ShortChannelID) (*lnwire.ChannelUpdate1,
NEW
754
                        error) {
×
755

×
756
                        return &lnwire.ChannelUpdate1{}, nil
×
757
                },
×
758
        }
759

760
        alicePeer := NewBrontide(*cfg)
×
761

×
762
        return &peerTestCtx{
×
763
                publishTx:     publishTx,
×
764
                mockSwitch:    mockSwitch,
×
765
                peer:          alicePeer,
×
766
                notifier:      notifier,
×
767
                db:            dbAliceChannel,
×
768
                privKey:       aliceKeyPriv,
×
769
                mockConn:      mockConn,
×
770
                customChan:    receivedCustomChan,
×
771
                chanStatusMgr: chanStatusMgr,
×
772
        }
×
773
}
774

775
// startPeer invokes the `Start` method on the specified peer and handles any
776
// initial startup messages for testing.
777
func startPeer(t *testing.T, mockConn *mockMessageConn,
778
        peer *Brontide) <-chan struct{} {
×
779

×
780
        // Start the peer in a goroutine so that we can handle and test for
×
781
        // startup messages. Successfully sending and receiving init message,
×
782
        // indicates a successful startup.
×
783
        done := make(chan struct{})
×
784
        go func() {
×
785
                require.NoError(t, peer.Start())
×
786
                close(done)
×
787
        }()
×
788

789
        // Receive the init message that should be the first message received on
790
        // startup.
791
        rawMsg, err := fn.RecvOrTimeout[[]byte](
×
792
                mockConn.writtenMessages, timeout,
×
793
        )
×
794
        require.NoError(t, err)
×
795

×
796
        msgReader := bytes.NewReader(rawMsg)
×
797
        nextMsg, err := lnwire.ReadMessage(msgReader, 0)
×
798
        require.NoError(t, err)
×
799

×
800
        _, ok := nextMsg.(*lnwire.Init)
×
801
        require.True(t, ok)
×
802

×
803
        // Write the reply for the init message to complete the startup.
×
804
        initReplyMsg := lnwire.NewInitMessage(
×
805
                lnwire.NewRawFeatureVector(
×
806
                        lnwire.DataLossProtectRequired,
×
807
                        lnwire.GossipQueriesOptional,
×
808
                ),
×
809
                lnwire.NewRawFeatureVector(),
×
810
        )
×
811

×
812
        var b bytes.Buffer
×
813
        _, err = lnwire.WriteMessage(&b, initReplyMsg, 0)
×
814
        require.NoError(t, err)
×
815

×
816
        ok = fn.SendOrQuit[[]byte, struct{}](
×
817
                mockConn.readMessages, b.Bytes(), make(chan struct{}),
×
818
        )
×
819
        require.True(t, ok)
×
820

×
821
        return done
×
822
}
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