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

lightningnetwork / lnd / 14721313522

29 Apr 2025 01:25AM UTC coverage: 58.598% (+0.006%) from 58.592%
14721313522

Pull #9489

github

web-flow
Merge 290053529 into b34afa33f
Pull Request #9489: multi: add BuildOnion, SendOnion, and TrackOnion RPCs

360 of 553 new or added lines in 10 files covered. (65.1%)

83 existing lines in 10 files now uncovered.

97747 of 166809 relevant lines covered (58.6%)

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
        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/v2"
22
        graphdb "github.com/lightningnetwork/lnd/graph/db"
23
        "github.com/lightningnetwork/lnd/htlcswitch"
24
        "github.com/lightningnetwork/lnd/input"
25
        "github.com/lightningnetwork/lnd/keychain"
26
        "github.com/lightningnetwork/lnd/kvdb"
27
        "github.com/lightningnetwork/lnd/lntest/channels"
28
        "github.com/lightningnetwork/lnd/lntest/mock"
29
        "github.com/lightningnetwork/lnd/lntypes"
30
        "github.com/lightningnetwork/lnd/lnwallet"
31
        "github.com/lightningnetwork/lnd/lnwallet/chainfee"
32
        "github.com/lightningnetwork/lnd/lnwire"
33
        "github.com/lightningnetwork/lnd/netann"
34
        "github.com/lightningnetwork/lnd/pool"
35
        "github.com/lightningnetwork/lnd/queue"
36
        "github.com/lightningnetwork/lnd/shachain"
37
        "github.com/stretchr/testify/require"
38
)
39

40
const (
41
        broadcastHeight = 100
42

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

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

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

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

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

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

×
81
        params := createTestPeer(t)
×
82

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
376
        return nil
×
377
}
×
378

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

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

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

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

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

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

407
// ShortChanID returns the mockUpdateHandler's cid.
NEW
408
func (m *mockUpdateHandler) ShortChanID() lnwire.ShortChannelID {
×
NEW
409
        return lnwire.NewShortChanIDFromInt(0)
×
NEW
410
}
×
411

412
// Bandwidth currently returns a dummy value.
413
func (m *mockUpdateHandler) Bandwidth() lnwire.MilliSatoshi { return 0 }
×
414

415
// EligibleToForward currently returns a dummy value.
416
func (m *mockUpdateHandler) EligibleToForward() bool { return false }
×
417

418
// MayAddOutgoingHtlc currently returns nil.
419
func (m *mockUpdateHandler) MayAddOutgoingHtlc(lnwire.MilliSatoshi) error { return nil }
×
420

421
type mockMessageConn struct {
422
        t *testing.T
423

424
        // MessageConn embeds our interface so that the mock does not need to
425
        // implement every function. The mock will panic if an unspecified function
426
        // is called.
427
        MessageConn
428

429
        // writtenMessages is a channel that our mock pushes written messages into.
430
        writtenMessages chan []byte
431

432
        readMessages   chan []byte
433
        curReadMessage []byte
434

435
        // writeRaceDetectingCounter is incremented on any function call
436
        // associated with writing to the connection. The race detector will
437
        // trigger on this counter if a data race exists.
438
        writeRaceDetectingCounter int
439

440
        // readRaceDetectingCounter is incremented on any function call
441
        // associated with reading from the connection. The race detector will
442
        // trigger on this counter if a data race exists.
443
        readRaceDetectingCounter int
444
}
445

446
func (m *mockUpdateHandler) EnableAdds(dir htlcswitch.LinkDirection) bool {
×
447
        if dir == htlcswitch.Outgoing {
×
448
                return m.isOutgoingAddBlocked.Swap(false)
×
449
        }
×
450

451
        return m.isIncomingAddBlocked.Swap(false)
×
452
}
453

454
func (m *mockUpdateHandler) DisableAdds(dir htlcswitch.LinkDirection) bool {
×
455
        if dir == htlcswitch.Outgoing {
×
456
                return !m.isOutgoingAddBlocked.Swap(true)
×
457
        }
×
458

459
        return !m.isIncomingAddBlocked.Swap(true)
×
460
}
461

462
func (m *mockUpdateHandler) IsFlushing(dir htlcswitch.LinkDirection) bool {
×
463
        switch dir {
×
464
        case htlcswitch.Outgoing:
×
465
                return m.isOutgoingAddBlocked.Load()
×
466
        case htlcswitch.Incoming:
×
467
                return m.isIncomingAddBlocked.Load()
×
468
        }
469

470
        return false
×
471
}
472

473
func (m *mockUpdateHandler) OnFlushedOnce(hook func()) {
×
474
        hook()
×
475
}
×
476
func (m *mockUpdateHandler) OnCommitOnce(
477
        _ htlcswitch.LinkDirection, hook func(),
478
) {
×
479

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

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

×
488
        return c
×
489
}
×
490

491
func newMockConn(t *testing.T, expectedMessages int) *mockMessageConn {
×
492
        return &mockMessageConn{
×
493
                t:               t,
×
494
                writtenMessages: make(chan []byte, expectedMessages),
×
495
                readMessages:    make(chan []byte, 1),
×
496
        }
×
497
}
×
498

499
// SetWriteDeadline mocks setting write deadline for our conn.
500
func (m *mockMessageConn) SetWriteDeadline(time.Time) error {
×
501
        m.writeRaceDetectingCounter++
×
502
        return nil
×
503
}
×
504

505
// Flush mocks a message conn flush.
506
func (m *mockMessageConn) Flush() (int, error) {
×
507
        m.writeRaceDetectingCounter++
×
508
        return 0, nil
×
509
}
×
510

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

×
516
        msgCopy := make([]byte, len(msg))
×
517
        copy(msgCopy, msg)
×
518

×
519
        select {
×
520
        case m.writtenMessages <- msgCopy:
×
521
        case <-time.After(timeout):
×
522
                m.t.Fatalf("timeout sending message: %v", msgCopy)
×
523
        }
524

525
        return nil
×
526
}
527

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

535
        case <-time.After(timeout):
×
536
                m.t.Fatalf("timeout waiting for write: %v", expected)
×
537
        }
538
}
539

540
func (m *mockMessageConn) SetReadDeadline(t time.Time) error {
×
541
        m.readRaceDetectingCounter++
×
542
        return nil
×
543
}
×
544

545
func (m *mockMessageConn) ReadNextHeader() (uint32, error) {
×
546
        m.readRaceDetectingCounter++
×
547
        m.curReadMessage = <-m.readMessages
×
548
        return uint32(len(m.curReadMessage)), nil
×
549
}
×
550

551
func (m *mockMessageConn) ReadNextBody(buf []byte) ([]byte, error) {
×
552
        m.readRaceDetectingCounter++
×
553
        return m.curReadMessage, nil
×
554
}
×
555

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

560
func (m *mockMessageConn) LocalAddr() net.Addr {
×
561
        return nil
×
562
}
×
563

564
func (m *mockMessageConn) Close() error {
×
565
        return nil
×
566
}
×
567

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

×
576
        aliceKeyPriv, aliceKeyPub := btcec.PrivKeyFromBytes(
×
577
                channels.AlicesPrivKey,
×
578
        )
×
579

×
580
        aliceKeySigner := keychain.NewPrivKeyMessageSigner(
×
581
                aliceKeyPriv, nodeKeyLocator,
×
582
        )
×
583

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

×
594
        errBuffer, err := queue.NewCircularBuffer(ErrorBufferSize)
×
595
        require.NoError(t, err)
×
596

×
597
        chainIO := &mock.ChainIO{
×
598
                BestHeight: broadcastHeight,
×
599
        }
×
600

×
601
        publishTx := make(chan *wire.MsgTx)
×
602
        wallet := &lnwallet.LightningWallet{
×
603
                WalletController: &mock.WalletController{
×
604
                        RootKey:               aliceKeyPriv,
×
605
                        PublishedTransactions: publishTx,
×
606
                },
×
607
        }
×
608

×
609
        const chanActiveTimeout = time.Minute
×
610

×
611
        dbPath := t.TempDir()
×
612

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

×
623
        dbAliceGraph, err := graphdb.NewChannelGraph(&graphdb.Config{
×
624
                KVDB: graphBackend,
×
625
        })
×
626
        require.NoError(t, err)
×
627
        require.NoError(t, dbAliceGraph.Start())
×
628
        t.Cleanup(func() {
×
629
                require.NoError(t, dbAliceGraph.Stop())
×
630
        })
×
631

632
        dbAliceChannel := channeldb.OpenForTesting(t, dbPath)
×
633

×
634
        nodeSignerAlice := netann.NewNodeSigner(aliceKeySigner)
×
635

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

×
652
                        return nil
×
653
                },
×
654
        })
655
        require.NoError(t, err)
×
656

×
657
        interceptableSwitchNotifier := &mock.ChainNotifier{
×
658
                EpochChan: make(chan *chainntnfs.BlockEpoch, 1),
×
659
        }
×
660
        interceptableSwitchNotifier.EpochChan <- &chainntnfs.BlockEpoch{
×
661
                Height: 1,
×
662
        }
×
663

×
664
        interceptableSwitch, err := htlcswitch.NewInterceptableSwitch(
×
665
                &htlcswitch.InterceptableSwitchConfig{
×
666
                        CltvRejectDelta:    testCltvRejectDelta,
×
667
                        CltvInterceptDelta: testCltvRejectDelta + 3,
×
668
                        Notifier:           interceptableSwitchNotifier,
×
669
                },
×
670
        )
×
671
        require.NoError(t, err)
×
672

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

×
681
        mockSwitch := &mockMessageSwitch{}
×
682

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

691
        writeBufferPool := pool.NewWriteBuffer(
×
692
                pool.DefaultWriteBufferGCInterval,
×
693
                pool.DefaultWriteBufferExpiryInterval,
×
694
        )
×
695

×
696
        writePool := pool.NewWrite(
×
697
                writeBufferPool, 1, timeout,
×
698
        )
×
699
        require.NoError(t, writePool.Start())
×
700

×
701
        readBufferPool := pool.NewReadBuffer(
×
702
                pool.DefaultReadBufferGCInterval,
×
703
                pool.DefaultReadBufferExpiryInterval,
×
704
        )
×
705

×
706
        readPool := pool.NewRead(
×
707
                readBufferPool, 1, timeout,
×
708
        )
×
709
        require.NoError(t, readPool.Start())
×
710

×
711
        mockConn := newMockConn(t, 1)
×
712

×
713
        receivedCustomChan := make(chan *customMsg)
×
714

×
715
        var pubKey [33]byte
×
716
        copy(pubKey[:], aliceKeyPub.SerializeCompressed())
×
717

×
718
        estimator := chainfee.NewStaticEstimator(12500, 0)
×
719

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

×
748
                        receivedCustomChan <- &customMsg{
×
749
                                peer: peer,
×
750
                                msg:  *msg,
×
751
                        }
×
752

×
753
                        return nil
×
754
                },
×
755
                PongBuf: make([]byte, lnwire.MaxPongBytes),
756
                FetchLastChanUpdate: func(chanID lnwire.ShortChannelID,
757
                ) (*lnwire.ChannelUpdate1, error) {
×
758

×
759
                        return &lnwire.ChannelUpdate1{}, nil
×
760
                },
×
761
        }
762

763
        alicePeer := NewBrontide(*cfg)
×
764

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

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

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

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

×
799
        msgReader := bytes.NewReader(rawMsg)
×
800
        nextMsg, err := lnwire.ReadMessage(msgReader, 0)
×
801
        require.NoError(t, err)
×
802

×
803
        _, ok := nextMsg.(*lnwire.Init)
×
804
        require.True(t, ok)
×
805

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

×
815
        var b bytes.Buffer
×
816
        _, err = lnwire.WriteMessage(&b, initReplyMsg, 0)
×
817
        require.NoError(t, err)
×
818

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

×
824
        return done
×
825
}
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