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

lightningnetwork / lnd / 17871584347

19 Sep 2025 10:57PM UTC coverage: 66.151% (-0.5%) from 66.637%
17871584347

Pull #9489

github

web-flow
Merge 477dc5159 into b34fc964b
Pull Request #9489: multi: add BuildOnion, SendOnion, and TrackOnion RPCs

460 of 616 new or added lines in 14 files covered. (74.68%)

52 existing lines in 18 files now uncovered.

136779 of 206767 relevant lines covered (66.15%)

21206.67 hits per line

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

87.56
/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/lntest/channels"
27
        "github.com/lightningnetwork/lnd/lntest/mock"
28
        "github.com/lightningnetwork/lnd/lntypes"
29
        "github.com/lightningnetwork/lnd/lnwallet"
30
        "github.com/lightningnetwork/lnd/lnwallet/chainfee"
31
        "github.com/lightningnetwork/lnd/lnwire"
32
        "github.com/lightningnetwork/lnd/netann"
33
        "github.com/lightningnetwork/lnd/pool"
34
        "github.com/lightningnetwork/lnd/queue"
35
        "github.com/lightningnetwork/lnd/shachain"
36
        "github.com/stretchr/testify/require"
37
)
38

39
const (
40
        broadcastHeight = 100
41

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

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

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

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

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

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

14✔
80
        params := createTestPeer(t)
14✔
81

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

14✔
92
        err := chanStatusMgr.Start()
14✔
93
        require.NoError(t, err)
14✔
94
        t.Cleanup(func() {
28✔
95
                require.NoError(t, chanStatusMgr.Stop())
14✔
96
        })
14✔
97

98
        aliceKeyPub := alicePeer.IdentityKey()
14✔
99
        estimator := alicePeer.cfg.FeeEstimator
14✔
100

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

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

14✔
115
        bobKeyPriv, bobKeyPub := btcec.PrivKeyFromBytes(
14✔
116
                channels.BobsPrivKey,
14✔
117
        )
14✔
118

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

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

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

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

205
        dbBob := channeldb.OpenForTesting(t, t.TempDir())
14✔
206

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

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

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

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

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

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

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

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

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

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

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

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

332
        alicePeer.remoteFeatures = lnwire.NewFeatureVector(
14✔
333
                nil, lnwire.Features,
14✔
334
        )
14✔
335

14✔
336
        chanID := lnwire.NewChanIDFromOutPoint(channelAlice.ChannelPoint())
14✔
337
        alicePeer.activeChannels.Store(chanID, channelAlice)
14✔
338

14✔
339
        alicePeer.cg.WgAdd(1)
14✔
340
        go alicePeer.channelManager()
14✔
341

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

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

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

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

368
// RemoveLink currently does nothing.
369
func (m *mockMessageSwitch) RemoveLink(cid lnwire.ChannelID) {}
8✔
370

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

×
375
        return nil
×
376
}
×
377

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

19✔
382
        return m.links, nil
19✔
383
}
19✔
384

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

453
func (m *mockUpdateHandler) DisableAdds(dir htlcswitch.LinkDirection) bool {
12✔
454
        if dir == htlcswitch.Outgoing {
20✔
455
                return !m.isOutgoingAddBlocked.Swap(true)
8✔
456
        }
8✔
457

458
        return !m.isIncomingAddBlocked.Swap(true)
4✔
459
}
460

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

469
        return false
×
470
}
471

472
func (m *mockUpdateHandler) OnFlushedOnce(hook func()) {
4✔
473
        hook()
4✔
474
}
4✔
475
func (m *mockUpdateHandler) OnCommitOnce(
476
        _ htlcswitch.LinkDirection, hook func(),
477
) {
8✔
478

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

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

×
487
        return c
×
488
}
×
489

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

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

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

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

13✔
515
        msgCopy := make([]byte, len(msg))
13✔
516
        copy(msgCopy, msg)
13✔
517

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

524
        return nil
13✔
525
}
526

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

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

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

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

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

555
func (m *mockMessageConn) RemoteAddr() net.Addr {
22✔
556
        return nil
22✔
557
}
22✔
558

559
func (m *mockMessageConn) LocalAddr() net.Addr {
3✔
560
        return nil
3✔
561
}
3✔
562

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

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

19✔
575
        aliceKeyPriv, aliceKeyPub := btcec.PrivKeyFromBytes(
19✔
576
                channels.AlicesPrivKey,
19✔
577
        )
19✔
578

19✔
579
        aliceKeySigner := keychain.NewPrivKeyMessageSigner(
19✔
580
                aliceKeyPriv, nodeKeyLocator,
19✔
581
        )
19✔
582

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

19✔
593
        errBuffer, err := queue.NewCircularBuffer(ErrorBufferSize)
19✔
594
        require.NoError(t, err)
19✔
595

19✔
596
        chainIO := &mock.ChainIO{
19✔
597
                BestHeight: broadcastHeight,
19✔
598
        }
19✔
599

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

19✔
608
        const chanActiveTimeout = time.Minute
19✔
609

19✔
610
        dbAliceGraph := graphdb.MakeTestGraph(t)
19✔
611
        require.NoError(t, dbAliceGraph.Start())
19✔
612
        t.Cleanup(func() {
38✔
613
                require.NoError(t, dbAliceGraph.Stop())
19✔
614
        })
19✔
615

616
        dbAliceChannel := channeldb.OpenForTesting(t, t.TempDir())
19✔
617

19✔
618
        nodeSignerAlice := netann.NewNodeSigner(aliceKeySigner)
19✔
619

19✔
620
        chanStatusMgr, err := netann.NewChanStatusManager(&netann.
19✔
621
                ChanStatusConfig{
19✔
622
                ChanStatusSampleInterval: 30 * time.Second,
19✔
623
                ChanEnableTimeout:        chanActiveTimeout,
19✔
624
                ChanDisableTimeout:       2 * time.Minute,
19✔
625
                DB:                       dbAliceChannel.ChannelStateDB(),
19✔
626
                Graph:                    dbAliceGraph,
19✔
627
                MessageSigner:            nodeSignerAlice,
19✔
628
                OurPubKey:                aliceKeyPub,
19✔
629
                OurKeyLoc:                testKeyLoc,
19✔
630
                IsChannelActive: func(lnwire.ChannelID) bool {
19✔
631
                        return true
×
632
                },
×
633
                ApplyChannelUpdate: func(*lnwire.ChannelUpdate1,
634
                        *wire.OutPoint, bool) error {
×
635

×
636
                        return nil
×
637
                },
×
638
        })
639
        require.NoError(t, err)
19✔
640

19✔
641
        interceptableSwitchNotifier := &mock.ChainNotifier{
19✔
642
                EpochChan: make(chan *chainntnfs.BlockEpoch, 1),
19✔
643
        }
19✔
644
        interceptableSwitchNotifier.EpochChan <- &chainntnfs.BlockEpoch{
19✔
645
                Height: 1,
19✔
646
        }
19✔
647

19✔
648
        interceptableSwitch, err := htlcswitch.NewInterceptableSwitch(
19✔
649
                &htlcswitch.InterceptableSwitchConfig{
19✔
650
                        CltvRejectDelta:    testCltvRejectDelta,
19✔
651
                        CltvInterceptDelta: testCltvRejectDelta + 3,
19✔
652
                        Notifier:           interceptableSwitchNotifier,
19✔
653
                },
19✔
654
        )
19✔
655
        require.NoError(t, err)
19✔
656

19✔
657
        // TODO(yy): create interface for lnwallet.LightningChannel so we can
19✔
658
        // easily mock it without the following setups.
19✔
659
        notifier := &mock.ChainNotifier{
19✔
660
                SpendChan: make(chan *chainntnfs.SpendDetail),
19✔
661
                EpochChan: make(chan *chainntnfs.BlockEpoch),
19✔
662
                ConfChan:  make(chan *chainntnfs.TxConfirmation),
19✔
663
        }
19✔
664

19✔
665
        mockSwitch := &mockMessageSwitch{}
19✔
666

19✔
667
        // TODO(yy): change ChannelNotifier to be an interface.
19✔
668
        channelNotifier := channelnotifier.New(dbAliceChannel.ChannelStateDB())
19✔
669
        require.NoError(t, channelNotifier.Start())
19✔
670
        t.Cleanup(func() {
38✔
671
                require.NoError(t, channelNotifier.Stop(),
19✔
672
                        "stop channel notifier failed")
19✔
673
        })
19✔
674

675
        writeBufferPool := pool.NewWriteBuffer(
19✔
676
                pool.DefaultWriteBufferGCInterval,
19✔
677
                pool.DefaultWriteBufferExpiryInterval,
19✔
678
        )
19✔
679

19✔
680
        writePool := pool.NewWrite(
19✔
681
                writeBufferPool, 1, timeout,
19✔
682
        )
19✔
683
        require.NoError(t, writePool.Start())
19✔
684

19✔
685
        readBufferPool := pool.NewReadBuffer(
19✔
686
                pool.DefaultReadBufferGCInterval,
19✔
687
                pool.DefaultReadBufferExpiryInterval,
19✔
688
        )
19✔
689

19✔
690
        readPool := pool.NewRead(
19✔
691
                readBufferPool, 1, timeout,
19✔
692
        )
19✔
693
        require.NoError(t, readPool.Start())
19✔
694

19✔
695
        mockConn := newMockConn(t, 1)
19✔
696

19✔
697
        receivedCustomChan := make(chan *customMsg)
19✔
698

19✔
699
        var pubKey [33]byte
19✔
700
        copy(pubKey[:], aliceKeyPub.SerializeCompressed())
19✔
701

19✔
702
        estimator := chainfee.NewStaticEstimator(12500, 0)
19✔
703

19✔
704
        cfg := &Config{
19✔
705
                Addr:              cfgAddr,
19✔
706
                PubKeyBytes:       pubKey,
19✔
707
                ErrorBuffer:       errBuffer,
19✔
708
                ChainIO:           chainIO,
19✔
709
                Switch:            mockSwitch,
19✔
710
                ChanActiveTimeout: chanActiveTimeout,
19✔
711
                InterceptSwitch:   interceptableSwitch,
19✔
712
                ChannelDB:         dbAliceChannel.ChannelStateDB(),
19✔
713
                FeeEstimator:      estimator,
19✔
714
                Wallet:            wallet,
19✔
715
                ChainNotifier:     notifier,
19✔
716
                ChanStatusMgr:     chanStatusMgr,
19✔
717
                Features: lnwire.NewFeatureVector(
19✔
718
                        nil, lnwire.Features,
19✔
719
                ),
19✔
720
                DisconnectPeer: func(b *btcec.PublicKey) error {
19✔
721
                        return nil
×
722
                },
×
723
                ChannelNotifier:               channelNotifier,
724
                PrunePersistentPeerConnection: func([33]byte) {},
1✔
725
                LegacyFeatures:                lnwire.EmptyFeatureVector(),
726
                WritePool:                     writePool,
727
                ReadPool:                      readPool,
728
                Conn:                          mockConn,
729
                HandleCustomMessage: func(
730
                        peer [33]byte, msg *lnwire.Custom) error {
1✔
731

1✔
732
                        receivedCustomChan <- &customMsg{
1✔
733
                                peer: peer,
1✔
734
                                msg:  *msg,
1✔
735
                        }
1✔
736

1✔
737
                        return nil
1✔
738
                },
1✔
739
                PongBuf: make([]byte, lnwire.MaxPongBytes),
740
                FetchLastChanUpdate: func(chanID lnwire.ShortChannelID,
741
                ) (*lnwire.ChannelUpdate1, error) {
2✔
742

2✔
743
                        return &lnwire.ChannelUpdate1{}, nil
2✔
744
                },
2✔
745
        }
746

747
        alicePeer := NewBrontide(*cfg)
19✔
748

19✔
749
        return &peerTestCtx{
19✔
750
                publishTx:     publishTx,
19✔
751
                mockSwitch:    mockSwitch,
19✔
752
                peer:          alicePeer,
19✔
753
                notifier:      notifier,
19✔
754
                db:            dbAliceChannel,
19✔
755
                privKey:       aliceKeyPriv,
19✔
756
                mockConn:      mockConn,
19✔
757
                customChan:    receivedCustomChan,
19✔
758
                chanStatusMgr: chanStatusMgr,
19✔
759
        }
19✔
760
}
761

762
// startPeer invokes the `Start` method on the specified peer and handles any
763
// initial startup messages for testing.
764
func startPeer(t *testing.T, mockConn *mockMessageConn,
765
        peer *Brontide) <-chan struct{} {
3✔
766

3✔
767
        // Start the peer in a goroutine so that we can handle and test for
3✔
768
        // startup messages. Successfully sending and receiving init message,
3✔
769
        // indicates a successful startup.
3✔
770
        done := make(chan struct{})
3✔
771
        go func() {
6✔
772
                require.NoError(t, peer.Start())
3✔
773
                close(done)
3✔
774
        }()
3✔
775

776
        // Receive the init message that should be the first message received on
777
        // startup.
778
        rawMsg, err := fn.RecvOrTimeout[[]byte](
3✔
779
                mockConn.writtenMessages, timeout,
3✔
780
        )
3✔
781
        require.NoError(t, err)
3✔
782

3✔
783
        msgReader := bytes.NewReader(rawMsg)
3✔
784
        nextMsg, err := lnwire.ReadMessage(msgReader, 0)
3✔
785
        require.NoError(t, err)
3✔
786

3✔
787
        _, ok := nextMsg.(*lnwire.Init)
3✔
788
        require.True(t, ok)
3✔
789

3✔
790
        // Write the reply for the init message to complete the startup.
3✔
791
        initReplyMsg := lnwire.NewInitMessage(
3✔
792
                lnwire.NewRawFeatureVector(
3✔
793
                        lnwire.DataLossProtectRequired,
3✔
794
                        lnwire.GossipQueriesOptional,
3✔
795
                ),
3✔
796
                lnwire.NewRawFeatureVector(),
3✔
797
        )
3✔
798

3✔
799
        var b bytes.Buffer
3✔
800
        _, err = lnwire.WriteMessage(&b, initReplyMsg, 0)
3✔
801
        require.NoError(t, err)
3✔
802

3✔
803
        ok = fn.SendOrQuit[[]byte, struct{}](
3✔
804
                mockConn.readMessages, b.Bytes(), make(chan struct{}),
3✔
805
        )
3✔
806
        require.True(t, ok)
3✔
807

3✔
808
        return done
3✔
809
}
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