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

lightningnetwork / lnd / 16990665124

15 Aug 2025 01:10PM UTC coverage: 66.74% (-0.03%) from 66.765%
16990665124

Pull #9455

github

web-flow
Merge 035fac41d into fb1adfc21
Pull Request #9455: [1/2] discovery+lnwire: add support for DNS host name in NodeAnnouncement msg

116 of 188 new or added lines in 8 files covered. (61.7%)

110 existing lines in 23 files now uncovered.

136011 of 203791 relevant lines covered (66.74%)

21482.89 hits per line

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

88.01
/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
// Bandwidth currently returns a dummy value.
407
func (m *mockUpdateHandler) Bandwidth() lnwire.MilliSatoshi { return 0 }
×
408

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

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

415
type mockMessageConn struct {
416
        t *testing.T
417

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

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

426
        readMessages   chan []byte
427
        curReadMessage []byte
428

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

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

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

445
        return m.isIncomingAddBlocked.Swap(false)
×
446
}
447

448
func (m *mockUpdateHandler) DisableAdds(dir htlcswitch.LinkDirection) bool {
12✔
449
        if dir == htlcswitch.Outgoing {
20✔
450
                return !m.isOutgoingAddBlocked.Swap(true)
8✔
451
        }
8✔
452

453
        return !m.isIncomingAddBlocked.Swap(true)
4✔
454
}
455

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

464
        return false
×
465
}
466

467
func (m *mockUpdateHandler) OnFlushedOnce(hook func()) {
4✔
468
        hook()
4✔
469
}
4✔
470
func (m *mockUpdateHandler) OnCommitOnce(
471
        _ htlcswitch.LinkDirection, hook func(),
472
) {
8✔
473

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

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

×
482
        return c
×
483
}
×
484

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

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

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

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

13✔
510
        msgCopy := make([]byte, len(msg))
13✔
511
        copy(msgCopy, msg)
13✔
512

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

519
        return nil
13✔
520
}
521

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

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

534
func (m *mockMessageConn) SetReadDeadline(t time.Time) error {
11✔
535
        m.readRaceDetectingCounter++
11✔
536
        return nil
11✔
537
}
11✔
538

539
func (m *mockMessageConn) ReadNextHeader() (uint32, error) {
7✔
540
        m.readRaceDetectingCounter++
7✔
541
        m.curReadMessage = <-m.readMessages
7✔
542
        return uint32(len(m.curReadMessage)), nil
7✔
543
}
7✔
544

545
func (m *mockMessageConn) ReadNextBody(buf []byte) ([]byte, error) {
4✔
546
        m.readRaceDetectingCounter++
4✔
547
        return m.curReadMessage, nil
4✔
548
}
4✔
549

550
func (m *mockMessageConn) RemoteAddr() net.Addr {
22✔
551
        return nil
22✔
552
}
22✔
553

554
func (m *mockMessageConn) LocalAddr() net.Addr {
3✔
555
        return nil
3✔
556
}
3✔
557

UNCOV
558
func (m *mockMessageConn) Close() error {
×
UNCOV
559
        return nil
×
UNCOV
560
}
×
561

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

19✔
570
        aliceKeyPriv, aliceKeyPub := btcec.PrivKeyFromBytes(
19✔
571
                channels.AlicesPrivKey,
19✔
572
        )
19✔
573

19✔
574
        aliceKeySigner := keychain.NewPrivKeyMessageSigner(
19✔
575
                aliceKeyPriv, nodeKeyLocator,
19✔
576
        )
19✔
577

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

19✔
588
        errBuffer, err := queue.NewCircularBuffer(ErrorBufferSize)
19✔
589
        require.NoError(t, err)
19✔
590

19✔
591
        chainIO := &mock.ChainIO{
19✔
592
                BestHeight: broadcastHeight,
19✔
593
        }
19✔
594

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

19✔
603
        const chanActiveTimeout = time.Minute
19✔
604

19✔
605
        dbAliceGraph := graphdb.MakeTestGraph(t)
19✔
606
        require.NoError(t, dbAliceGraph.Start())
19✔
607
        t.Cleanup(func() {
38✔
608
                require.NoError(t, dbAliceGraph.Stop())
19✔
609
        })
19✔
610

611
        dbAliceChannel := channeldb.OpenForTesting(t, t.TempDir())
19✔
612

19✔
613
        nodeSignerAlice := netann.NewNodeSigner(aliceKeySigner)
19✔
614

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

×
631
                        return nil
×
632
                },
×
633
        })
634
        require.NoError(t, err)
19✔
635

19✔
636
        interceptableSwitchNotifier := &mock.ChainNotifier{
19✔
637
                EpochChan: make(chan *chainntnfs.BlockEpoch, 1),
19✔
638
        }
19✔
639
        interceptableSwitchNotifier.EpochChan <- &chainntnfs.BlockEpoch{
19✔
640
                Height: 1,
19✔
641
        }
19✔
642

19✔
643
        interceptableSwitch, err := htlcswitch.NewInterceptableSwitch(
19✔
644
                &htlcswitch.InterceptableSwitchConfig{
19✔
645
                        CltvRejectDelta:    testCltvRejectDelta,
19✔
646
                        CltvInterceptDelta: testCltvRejectDelta + 3,
19✔
647
                        Notifier:           interceptableSwitchNotifier,
19✔
648
                },
19✔
649
        )
19✔
650
        require.NoError(t, err)
19✔
651

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

19✔
660
        mockSwitch := &mockMessageSwitch{}
19✔
661

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

670
        writeBufferPool := pool.NewWriteBuffer(
19✔
671
                pool.DefaultWriteBufferGCInterval,
19✔
672
                pool.DefaultWriteBufferExpiryInterval,
19✔
673
        )
19✔
674

19✔
675
        writePool := pool.NewWrite(
19✔
676
                writeBufferPool, 1, timeout,
19✔
677
        )
19✔
678
        require.NoError(t, writePool.Start())
19✔
679

19✔
680
        readBufferPool := pool.NewReadBuffer(
19✔
681
                pool.DefaultReadBufferGCInterval,
19✔
682
                pool.DefaultReadBufferExpiryInterval,
19✔
683
        )
19✔
684

19✔
685
        readPool := pool.NewRead(
19✔
686
                readBufferPool, 1, timeout,
19✔
687
        )
19✔
688
        require.NoError(t, readPool.Start())
19✔
689

19✔
690
        mockConn := newMockConn(t, 1)
19✔
691

19✔
692
        receivedCustomChan := make(chan *customMsg)
19✔
693

19✔
694
        var pubKey [33]byte
19✔
695
        copy(pubKey[:], aliceKeyPub.SerializeCompressed())
19✔
696

19✔
697
        estimator := chainfee.NewStaticEstimator(12500, 0)
19✔
698

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

1✔
727
                        receivedCustomChan <- &customMsg{
1✔
728
                                peer: peer,
1✔
729
                                msg:  *msg,
1✔
730
                        }
1✔
731

1✔
732
                        return nil
1✔
733
                },
1✔
734
                PongBuf: make([]byte, lnwire.MaxPongBytes),
735
                FetchLastChanUpdate: func(chanID lnwire.ShortChannelID,
736
                ) (*lnwire.ChannelUpdate1, error) {
2✔
737

2✔
738
                        return &lnwire.ChannelUpdate1{}, nil
2✔
739
                },
2✔
740
        }
741

742
        alicePeer := NewBrontide(*cfg)
19✔
743

19✔
744
        return &peerTestCtx{
19✔
745
                publishTx:     publishTx,
19✔
746
                mockSwitch:    mockSwitch,
19✔
747
                peer:          alicePeer,
19✔
748
                notifier:      notifier,
19✔
749
                db:            dbAliceChannel,
19✔
750
                privKey:       aliceKeyPriv,
19✔
751
                mockConn:      mockConn,
19✔
752
                customChan:    receivedCustomChan,
19✔
753
                chanStatusMgr: chanStatusMgr,
19✔
754
        }
19✔
755
}
756

757
// startPeer invokes the `Start` method on the specified peer and handles any
758
// initial startup messages for testing.
759
func startPeer(t *testing.T, mockConn *mockMessageConn,
760
        peer *Brontide) <-chan struct{} {
3✔
761

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

771
        // Receive the init message that should be the first message received on
772
        // startup.
773
        rawMsg, err := fn.RecvOrTimeout[[]byte](
3✔
774
                mockConn.writtenMessages, timeout,
3✔
775
        )
3✔
776
        require.NoError(t, err)
3✔
777

3✔
778
        msgReader := bytes.NewReader(rawMsg)
3✔
779
        nextMsg, err := lnwire.ReadMessage(msgReader, 0)
3✔
780
        require.NoError(t, err)
3✔
781

3✔
782
        _, ok := nextMsg.(*lnwire.Init)
3✔
783
        require.True(t, ok)
3✔
784

3✔
785
        // Write the reply for the init message to complete the startup.
3✔
786
        initReplyMsg := lnwire.NewInitMessage(
3✔
787
                lnwire.NewRawFeatureVector(
3✔
788
                        lnwire.DataLossProtectRequired,
3✔
789
                        lnwire.GossipQueriesOptional,
3✔
790
                ),
3✔
791
                lnwire.NewRawFeatureVector(),
3✔
792
        )
3✔
793

3✔
794
        var b bytes.Buffer
3✔
795
        _, err = lnwire.WriteMessage(&b, initReplyMsg, 0)
3✔
796
        require.NoError(t, err)
3✔
797

3✔
798
        ok = fn.SendOrQuit[[]byte, struct{}](
3✔
799
                mockConn.readMessages, b.Bytes(), make(chan struct{}),
3✔
800
        )
3✔
801
        require.True(t, ok)
3✔
802

3✔
803
        return done
3✔
804
}
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