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

lightningnetwork / lnd / 15736109134

18 Jun 2025 02:46PM UTC coverage: 58.197% (-10.1%) from 68.248%
15736109134

Pull #9752

github

web-flow
Merge d2634a68c into 31c74f20f
Pull Request #9752: routerrpc: reject payment to invoice that don't have payment secret or blinded paths

6 of 13 new or added lines in 2 files covered. (46.15%)

28331 existing lines in 455 files now uncovered.

97860 of 168153 relevant lines covered (58.2%)

1.81 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/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.
UNCOV
58
var noUpdate = func(a, b *channeldb.OpenChannel) {}
×
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,
UNCOV
78
        b *channeldb.OpenChannel)) (*peerTestCtx, error) {
×
UNCOV
79

×
UNCOV
80
        params := createTestPeer(t)
×
UNCOV
81

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
UNCOV
342
        return &peerTestCtx{
×
UNCOV
343
                peer:       alicePeer,
×
UNCOV
344
                channel:    channelBob,
×
UNCOV
345
                notifier:   notifier,
×
UNCOV
346
                publishTx:  publishTx,
×
UNCOV
347
                mockSwitch: mockSwitch,
×
UNCOV
348
                mockConn:   params.mockConn,
×
UNCOV
349
        }, nil
×
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.
UNCOV
369
func (m *mockMessageSwitch) RemoveLink(cid lnwire.ChannelID) {}
×
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) (
UNCOV
380
        []htlcswitch.ChannelUpdateHandler, error) {
×
UNCOV
381

×
UNCOV
382
        return m.links, nil
×
UNCOV
383
}
×
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.
UNCOV
394
func newMockUpdateHandler(cid lnwire.ChannelID) *mockUpdateHandler {
×
UNCOV
395
        return &mockUpdateHandler{
×
UNCOV
396
                cid: cid,
×
UNCOV
397
        }
×
UNCOV
398
}
×
399

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

403
// ChanID returns the mockUpdateHandler's cid.
UNCOV
404
func (m *mockUpdateHandler) ChanID() lnwire.ChannelID { return m.cid }
×
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

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

UNCOV
453
        return !m.isIncomingAddBlocked.Swap(true)
×
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

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

×
UNCOV
474
        hook()
×
UNCOV
475
}
×
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

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

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

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

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

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

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

UNCOV
519
        return nil
×
520
}
521

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

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

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

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

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

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

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

558
func (m *mockMessageConn) Close() error {
×
559
        return nil
×
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.
UNCOV
565
func createTestPeer(t *testing.T) *peerTestCtx {
×
UNCOV
566
        nodeKeyLocator := keychain.KeyLocator{
×
UNCOV
567
                Family: keychain.KeyFamilyNodeKey,
×
UNCOV
568
        }
×
UNCOV
569

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

×
UNCOV
574
        aliceKeySigner := keychain.NewPrivKeyMessageSigner(
×
UNCOV
575
                aliceKeyPriv, nodeKeyLocator,
×
UNCOV
576
        )
×
UNCOV
577

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

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

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

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

×
UNCOV
603
        const chanActiveTimeout = time.Minute
×
UNCOV
604

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

UNCOV
611
        dbAliceChannel := channeldb.OpenForTesting(t, t.TempDir())
×
UNCOV
612

×
UNCOV
613
        nodeSignerAlice := netann.NewNodeSigner(aliceKeySigner)
×
UNCOV
614

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

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

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

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

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

×
UNCOV
660
        mockSwitch := &mockMessageSwitch{}
×
UNCOV
661

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

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

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

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

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

×
UNCOV
690
        mockConn := newMockConn(t, 1)
×
UNCOV
691

×
UNCOV
692
        receivedCustomChan := make(chan *customMsg)
×
UNCOV
693

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

×
UNCOV
697
        estimator := chainfee.NewStaticEstimator(12500, 0)
×
UNCOV
698

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

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

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

×
UNCOV
738
                        return &lnwire.ChannelUpdate1{}, nil
×
UNCOV
739
                },
×
740
        }
741

UNCOV
742
        alicePeer := NewBrontide(*cfg)
×
UNCOV
743

×
UNCOV
744
        return &peerTestCtx{
×
UNCOV
745
                publishTx:     publishTx,
×
UNCOV
746
                mockSwitch:    mockSwitch,
×
UNCOV
747
                peer:          alicePeer,
×
UNCOV
748
                notifier:      notifier,
×
UNCOV
749
                db:            dbAliceChannel,
×
UNCOV
750
                privKey:       aliceKeyPriv,
×
UNCOV
751
                mockConn:      mockConn,
×
UNCOV
752
                customChan:    receivedCustomChan,
×
UNCOV
753
                chanStatusMgr: chanStatusMgr,
×
UNCOV
754
        }
×
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,
UNCOV
760
        peer *Brontide) <-chan struct{} {
×
UNCOV
761

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

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

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

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

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

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

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

×
UNCOV
803
        return done
×
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