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

lightningnetwork / lnd / 13725358077

07 Mar 2025 04:51PM UTC coverage: 58.224% (-10.4%) from 68.615%
13725358077

Pull #9458

github

web-flow
Merge bf4c6625f into ab2dc09eb
Pull Request #9458: multi+server.go: add initial permissions for some peers

346 of 549 new or added lines in 10 files covered. (63.02%)

27466 existing lines in 443 files now uncovered.

94609 of 162492 relevant lines covered (58.22%)

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

40
const (
41
        broadcastHeight = 100
42

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
UNCOV
340
        alicePeer.wg.Add(1)
×
UNCOV
341
        go alicePeer.channelManager()
×
UNCOV
342

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

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

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

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

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

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

×
376
        return nil
×
377
}
×
378

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

465
        return false
×
466
}
467

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

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

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

×
483
        return c
×
484
}
×
485

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

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

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

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

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

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

UNCOV
520
        return nil
×
521
}
522

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
UNCOV
606
        dbPath := t.TempDir()
×
UNCOV
607

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

×
UNCOV
618
        dbAliceGraph, err := graphdb.NewChannelGraph(graphBackend)
×
UNCOV
619
        require.NoError(t, err)
×
UNCOV
620

×
UNCOV
621
        dbAliceChannel := channeldb.OpenForTesting(t, dbPath)
×
UNCOV
622

×
UNCOV
623
        nodeSignerAlice := netann.NewNodeSigner(aliceKeySigner)
×
UNCOV
624

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

×
641
                        return nil
×
642
                },
×
643
        })
UNCOV
644
        require.NoError(t, err)
×
UNCOV
645

×
UNCOV
646
        interceptableSwitchNotifier := &mock.ChainNotifier{
×
UNCOV
647
                EpochChan: make(chan *chainntnfs.BlockEpoch, 1),
×
UNCOV
648
        }
×
UNCOV
649
        interceptableSwitchNotifier.EpochChan <- &chainntnfs.BlockEpoch{
×
UNCOV
650
                Height: 1,
×
UNCOV
651
        }
×
UNCOV
652

×
UNCOV
653
        interceptableSwitch, err := htlcswitch.NewInterceptableSwitch(
×
UNCOV
654
                &htlcswitch.InterceptableSwitchConfig{
×
UNCOV
655
                        CltvRejectDelta:    testCltvRejectDelta,
×
UNCOV
656
                        CltvInterceptDelta: testCltvRejectDelta + 3,
×
UNCOV
657
                        Notifier:           interceptableSwitchNotifier,
×
UNCOV
658
                },
×
UNCOV
659
        )
×
UNCOV
660
        require.NoError(t, err)
×
UNCOV
661

×
UNCOV
662
        // TODO(yy): create interface for lnwallet.LightningChannel so we can
×
UNCOV
663
        // easily mock it without the following setups.
×
UNCOV
664
        notifier := &mock.ChainNotifier{
×
UNCOV
665
                SpendChan: make(chan *chainntnfs.SpendDetail),
×
UNCOV
666
                EpochChan: make(chan *chainntnfs.BlockEpoch),
×
UNCOV
667
                ConfChan:  make(chan *chainntnfs.TxConfirmation),
×
UNCOV
668
        }
×
UNCOV
669

×
UNCOV
670
        mockSwitch := &mockMessageSwitch{}
×
UNCOV
671

×
UNCOV
672
        // TODO(yy): change ChannelNotifier to be an interface.
×
UNCOV
673
        channelNotifier := channelnotifier.New(dbAliceChannel.ChannelStateDB())
×
UNCOV
674
        require.NoError(t, channelNotifier.Start())
×
UNCOV
675
        t.Cleanup(func() {
×
UNCOV
676
                require.NoError(t, channelNotifier.Stop(),
×
UNCOV
677
                        "stop channel notifier failed")
×
UNCOV
678
        })
×
679

UNCOV
680
        writeBufferPool := pool.NewWriteBuffer(
×
UNCOV
681
                pool.DefaultWriteBufferGCInterval,
×
UNCOV
682
                pool.DefaultWriteBufferExpiryInterval,
×
UNCOV
683
        )
×
UNCOV
684

×
UNCOV
685
        writePool := pool.NewWrite(
×
UNCOV
686
                writeBufferPool, 1, timeout,
×
UNCOV
687
        )
×
UNCOV
688
        require.NoError(t, writePool.Start())
×
UNCOV
689

×
UNCOV
690
        readBufferPool := pool.NewReadBuffer(
×
UNCOV
691
                pool.DefaultReadBufferGCInterval,
×
UNCOV
692
                pool.DefaultReadBufferExpiryInterval,
×
UNCOV
693
        )
×
UNCOV
694

×
UNCOV
695
        readPool := pool.NewRead(
×
UNCOV
696
                readBufferPool, 1, timeout,
×
UNCOV
697
        )
×
UNCOV
698
        require.NoError(t, readPool.Start())
×
UNCOV
699

×
UNCOV
700
        mockConn := newMockConn(t, 1)
×
UNCOV
701

×
UNCOV
702
        receivedCustomChan := make(chan *customMsg)
×
UNCOV
703

×
UNCOV
704
        var pubKey [33]byte
×
UNCOV
705
        copy(pubKey[:], aliceKeyPub.SerializeCompressed())
×
UNCOV
706

×
UNCOV
707
        estimator := chainfee.NewStaticEstimator(12500, 0)
×
UNCOV
708

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

×
UNCOV
737
                        receivedCustomChan <- &customMsg{
×
UNCOV
738
                                peer: peer,
×
UNCOV
739
                                msg:  *msg,
×
UNCOV
740
                        }
×
UNCOV
741

×
UNCOV
742
                        return nil
×
UNCOV
743
                },
×
744
                PongBuf: make([]byte, lnwire.MaxPongBytes),
745
                FetchLastChanUpdate: func(chanID lnwire.ShortChannelID,
UNCOV
746
                ) (*lnwire.ChannelUpdate1, error) {
×
UNCOV
747

×
UNCOV
748
                        return &lnwire.ChannelUpdate1{}, nil
×
UNCOV
749
                },
×
750
        }
751

UNCOV
752
        alicePeer := NewBrontide(*cfg)
×
UNCOV
753

×
UNCOV
754
        return &peerTestCtx{
×
UNCOV
755
                publishTx:     publishTx,
×
UNCOV
756
                mockSwitch:    mockSwitch,
×
UNCOV
757
                peer:          alicePeer,
×
UNCOV
758
                notifier:      notifier,
×
UNCOV
759
                db:            dbAliceChannel,
×
UNCOV
760
                privKey:       aliceKeyPriv,
×
UNCOV
761
                mockConn:      mockConn,
×
UNCOV
762
                customChan:    receivedCustomChan,
×
UNCOV
763
                chanStatusMgr: chanStatusMgr,
×
UNCOV
764
        }
×
765
}
766

767
// startPeer invokes the `Start` method on the specified peer and handles any
768
// initial startup messages for testing.
769
func startPeer(t *testing.T, mockConn *mockMessageConn,
UNCOV
770
        peer *Brontide) <-chan struct{} {
×
UNCOV
771

×
UNCOV
772
        // Start the peer in a goroutine so that we can handle and test for
×
UNCOV
773
        // startup messages. Successfully sending and receiving init message,
×
UNCOV
774
        // indicates a successful startup.
×
UNCOV
775
        done := make(chan struct{})
×
UNCOV
776
        go func() {
×
UNCOV
777
                require.NoError(t, peer.Start())
×
UNCOV
778
                close(done)
×
UNCOV
779
        }()
×
780

781
        // Receive the init message that should be the first message received on
782
        // startup.
UNCOV
783
        rawMsg, err := fn.RecvOrTimeout[[]byte](
×
UNCOV
784
                mockConn.writtenMessages, timeout,
×
UNCOV
785
        )
×
UNCOV
786
        require.NoError(t, err)
×
UNCOV
787

×
UNCOV
788
        msgReader := bytes.NewReader(rawMsg)
×
UNCOV
789
        nextMsg, err := lnwire.ReadMessage(msgReader, 0)
×
UNCOV
790
        require.NoError(t, err)
×
UNCOV
791

×
UNCOV
792
        _, ok := nextMsg.(*lnwire.Init)
×
UNCOV
793
        require.True(t, ok)
×
UNCOV
794

×
UNCOV
795
        // Write the reply for the init message to complete the startup.
×
UNCOV
796
        initReplyMsg := lnwire.NewInitMessage(
×
UNCOV
797
                lnwire.NewRawFeatureVector(
×
UNCOV
798
                        lnwire.DataLossProtectRequired,
×
UNCOV
799
                        lnwire.GossipQueriesOptional,
×
UNCOV
800
                ),
×
UNCOV
801
                lnwire.NewRawFeatureVector(),
×
UNCOV
802
        )
×
UNCOV
803

×
UNCOV
804
        var b bytes.Buffer
×
UNCOV
805
        _, err = lnwire.WriteMessage(&b, initReplyMsg, 0)
×
UNCOV
806
        require.NoError(t, err)
×
UNCOV
807

×
UNCOV
808
        ok = fn.SendOrQuit[[]byte, struct{}](
×
UNCOV
809
                mockConn.readMessages, b.Bytes(), make(chan struct{}),
×
UNCOV
810
        )
×
UNCOV
811
        require.True(t, ok)
×
UNCOV
812

×
UNCOV
813
        return done
×
814
}
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