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

lightningnetwork / lnd / 11292787765

11 Oct 2024 12:58PM UTC coverage: 49.179% (-9.5%) from 58.716%
11292787765

push

github

web-flow
Merge pull request #9168 from feelancer21/fix-lncli-wallet-proto

lnrpc: fix lncli documentation tags in walletkit.proto

97369 of 197987 relevant lines covered (49.18%)

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

37
const (
38
        broadcastHeight = 100
39

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

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

49
var (
50
        testKeyLoc = keychain.KeyLocator{Family: keychain.KeyFamilyNodeKey}
51
)
52

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

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

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

×
78
        params := createTestPeer(t)
×
79

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

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

96
        aliceKeyPub := alicePeer.IdentityKey()
×
97
        estimator := alicePeer.cfg.FeeEstimator
×
98

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

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

×
113
        bobKeyPriv, bobKeyPub := btcec.PrivKeyFromBytes(
×
114
                channels.BobsPrivKey,
×
115
        )
×
116

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

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

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

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

203
        dbBob, err := channeldb.Open(t.TempDir())
×
204
        if err != nil {
×
205
                return nil, err
×
206
        }
×
207
        t.Cleanup(func() {
×
208
                require.NoError(t, dbBob.Close())
×
209
        })
×
210

211
        feePerKw, err := estimator.EstimateFeePerKW(1)
×
212
        if err != nil {
×
213
                return nil, err
×
214
        }
×
215

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

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

241
        shortChanID := lnwire.NewShortChanIDFromInt(
×
242
                binary.BigEndian.Uint64(chanIDBytes[:]),
×
243
        )
×
244

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

×
280
        // Set custom values on the channel states.
×
281
        updateChan(aliceChannelState, bobChannelState)
×
282

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

288
        bobAddr := &net.TCPAddr{
×
289
                IP:   net.ParseIP("127.0.0.1"),
×
290
                Port: 18556,
×
291
        }
×
292

×
293
        if err := bobChannelState.SyncPending(bobAddr, 0); err != nil {
×
294
                return nil, err
×
295
        }
×
296

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

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

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

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

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

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

×
342
        return &peerTestCtx{
×
343
                peer:       alicePeer,
×
344
                channel:    channelBob,
×
345
                notifier:   notifier,
×
346
                publishTx:  publishTx,
×
347
                mockSwitch: mockSwitch,
×
348
                mockConn:   params.mockConn,
×
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.
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) (
380
        []htlcswitch.ChannelUpdateHandler, error) {
×
381

×
382
        return m.links, nil
×
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.
394
func newMockUpdateHandler(cid lnwire.ChannelID) *mockUpdateHandler {
×
395
        return &mockUpdateHandler{
×
396
                cid: cid,
×
397
        }
×
398
}
×
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 }
×
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 {
×
449
        if dir == htlcswitch.Outgoing {
×
450
                return !m.isOutgoingAddBlocked.Swap(true)
×
451
        }
×
452

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

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

×
474
        hook()
×
475
}
×
476

477
func newMockConn(t *testing.T, expectedMessages int) *mockMessageConn {
×
478
        return &mockMessageConn{
×
479
                t:               t,
×
480
                writtenMessages: make(chan []byte, expectedMessages),
×
481
                readMessages:    make(chan []byte, 1),
×
482
        }
×
483
}
×
484

485
// SetWriteDeadline mocks setting write deadline for our conn.
486
func (m *mockMessageConn) SetWriteDeadline(time.Time) error {
×
487
        m.writeRaceDetectingCounter++
×
488
        return nil
×
489
}
×
490

491
// Flush mocks a message conn flush.
492
func (m *mockMessageConn) Flush() (int, error) {
×
493
        m.writeRaceDetectingCounter++
×
494
        return 0, nil
×
495
}
×
496

497
// WriteMessage mocks sending of a message on our connection. It will push
498
// the bytes sent into the mock's writtenMessages channel.
499
func (m *mockMessageConn) WriteMessage(msg []byte) error {
×
500
        m.writeRaceDetectingCounter++
×
501

×
502
        msgCopy := make([]byte, len(msg))
×
503
        copy(msgCopy, msg)
×
504

×
505
        select {
×
506
        case m.writtenMessages <- msgCopy:
×
507
        case <-time.After(timeout):
×
508
                m.t.Fatalf("timeout sending message: %v", msgCopy)
×
509
        }
510

511
        return nil
×
512
}
513

514
// assertWrite asserts that our mock as had WriteMessage called with the byte
515
// slice we expect.
516
func (m *mockMessageConn) assertWrite(expected []byte) {
×
517
        select {
×
518
        case actual := <-m.writtenMessages:
×
519
                require.Equal(m.t, expected, actual)
×
520

521
        case <-time.After(timeout):
×
522
                m.t.Fatalf("timeout waiting for write: %v", expected)
×
523
        }
524
}
525

526
func (m *mockMessageConn) SetReadDeadline(t time.Time) error {
×
527
        m.readRaceDetectingCounter++
×
528
        return nil
×
529
}
×
530

531
func (m *mockMessageConn) ReadNextHeader() (uint32, error) {
×
532
        m.readRaceDetectingCounter++
×
533
        m.curReadMessage = <-m.readMessages
×
534
        return uint32(len(m.curReadMessage)), nil
×
535
}
×
536

537
func (m *mockMessageConn) ReadNextBody(buf []byte) ([]byte, error) {
×
538
        m.readRaceDetectingCounter++
×
539
        return m.curReadMessage, nil
×
540
}
×
541

542
func (m *mockMessageConn) RemoteAddr() net.Addr {
×
543
        return nil
×
544
}
×
545

546
func (m *mockMessageConn) LocalAddr() net.Addr {
×
547
        return nil
×
548
}
×
549

550
func (m *mockMessageConn) Close() error {
×
551
        return nil
×
552
}
×
553

554
// createTestPeer creates a new peer for testing and returns a context struct
555
// containing necessary handles and mock objects for conducting tests on peer
556
// functionalities.
557
func createTestPeer(t *testing.T) *peerTestCtx {
×
558
        nodeKeyLocator := keychain.KeyLocator{
×
559
                Family: keychain.KeyFamilyNodeKey,
×
560
        }
×
561

×
562
        aliceKeyPriv, aliceKeyPub := btcec.PrivKeyFromBytes(
×
563
                channels.AlicesPrivKey,
×
564
        )
×
565

×
566
        aliceKeySigner := keychain.NewPrivKeyMessageSigner(
×
567
                aliceKeyPriv, nodeKeyLocator,
×
568
        )
×
569

×
570
        aliceAddr := &net.TCPAddr{
×
571
                IP:   net.ParseIP("127.0.0.1"),
×
572
                Port: 18555,
×
573
        }
×
574
        cfgAddr := &lnwire.NetAddress{
×
575
                IdentityKey: aliceKeyPub,
×
576
                Address:     aliceAddr,
×
577
                ChainNet:    wire.SimNet,
×
578
        }
×
579

×
580
        errBuffer, err := queue.NewCircularBuffer(ErrorBufferSize)
×
581
        require.NoError(t, err)
×
582

×
583
        chainIO := &mock.ChainIO{
×
584
                BestHeight: broadcastHeight,
×
585
        }
×
586

×
587
        publishTx := make(chan *wire.MsgTx)
×
588
        wallet := &lnwallet.LightningWallet{
×
589
                WalletController: &mock.WalletController{
×
590
                        RootKey:               aliceKeyPriv,
×
591
                        PublishedTransactions: publishTx,
×
592
                },
×
593
        }
×
594

×
595
        const chanActiveTimeout = time.Minute
×
596

×
597
        dbAlice, err := channeldb.Open(t.TempDir())
×
598
        require.NoError(t, err)
×
599
        t.Cleanup(func() {
×
600
                require.NoError(t, dbAlice.Close())
×
601
        })
×
602

603
        nodeSignerAlice := netann.NewNodeSigner(aliceKeySigner)
×
604

×
605
        chanStatusMgr, err := netann.NewChanStatusManager(&netann.
×
606
                ChanStatusConfig{
×
607
                ChanStatusSampleInterval: 30 * time.Second,
×
608
                ChanEnableTimeout:        chanActiveTimeout,
×
609
                ChanDisableTimeout:       2 * time.Minute,
×
610
                DB:                       dbAlice.ChannelStateDB(),
×
611
                Graph:                    dbAlice.ChannelGraph(),
×
612
                MessageSigner:            nodeSignerAlice,
×
613
                OurPubKey:                aliceKeyPub,
×
614
                OurKeyLoc:                testKeyLoc,
×
615
                IsChannelActive: func(lnwire.ChannelID) bool {
×
616
                        return true
×
617
                },
×
618
                ApplyChannelUpdate: func(*lnwire.ChannelUpdate1,
619
                        *wire.OutPoint, bool) error {
×
620

×
621
                        return nil
×
622
                },
×
623
        })
624
        require.NoError(t, err)
×
625

×
626
        interceptableSwitchNotifier := &mock.ChainNotifier{
×
627
                EpochChan: make(chan *chainntnfs.BlockEpoch, 1),
×
628
        }
×
629
        interceptableSwitchNotifier.EpochChan <- &chainntnfs.BlockEpoch{
×
630
                Height: 1,
×
631
        }
×
632

×
633
        interceptableSwitch, err := htlcswitch.NewInterceptableSwitch(
×
634
                &htlcswitch.InterceptableSwitchConfig{
×
635
                        CltvRejectDelta:    testCltvRejectDelta,
×
636
                        CltvInterceptDelta: testCltvRejectDelta + 3,
×
637
                        Notifier:           interceptableSwitchNotifier,
×
638
                },
×
639
        )
×
640
        require.NoError(t, err)
×
641

×
642
        // TODO(yy): create interface for lnwallet.LightningChannel so we can
×
643
        // easily mock it without the following setups.
×
644
        notifier := &mock.ChainNotifier{
×
645
                SpendChan: make(chan *chainntnfs.SpendDetail),
×
646
                EpochChan: make(chan *chainntnfs.BlockEpoch),
×
647
                ConfChan:  make(chan *chainntnfs.TxConfirmation),
×
648
        }
×
649

×
650
        mockSwitch := &mockMessageSwitch{}
×
651

×
652
        // TODO(yy): change ChannelNotifier to be an interface.
×
653
        channelNotifier := channelnotifier.New(dbAlice.ChannelStateDB())
×
654
        require.NoError(t, channelNotifier.Start())
×
655
        t.Cleanup(func() {
×
656
                require.NoError(t, channelNotifier.Stop(),
×
657
                        "stop channel notifier failed")
×
658
        })
×
659

660
        writeBufferPool := pool.NewWriteBuffer(
×
661
                pool.DefaultWriteBufferGCInterval,
×
662
                pool.DefaultWriteBufferExpiryInterval,
×
663
        )
×
664

×
665
        writePool := pool.NewWrite(
×
666
                writeBufferPool, 1, timeout,
×
667
        )
×
668
        require.NoError(t, writePool.Start())
×
669

×
670
        readBufferPool := pool.NewReadBuffer(
×
671
                pool.DefaultReadBufferGCInterval,
×
672
                pool.DefaultReadBufferExpiryInterval,
×
673
        )
×
674

×
675
        readPool := pool.NewRead(
×
676
                readBufferPool, 1, timeout,
×
677
        )
×
678
        require.NoError(t, readPool.Start())
×
679

×
680
        mockConn := newMockConn(t, 1)
×
681

×
682
        receivedCustomChan := make(chan *customMsg)
×
683

×
684
        var pubKey [33]byte
×
685
        copy(pubKey[:], aliceKeyPub.SerializeCompressed())
×
686

×
687
        estimator := chainfee.NewStaticEstimator(12500, 0)
×
688

×
689
        cfg := &Config{
×
690
                Addr:              cfgAddr,
×
691
                PubKeyBytes:       pubKey,
×
692
                ErrorBuffer:       errBuffer,
×
693
                ChainIO:           chainIO,
×
694
                Switch:            mockSwitch,
×
695
                ChanActiveTimeout: chanActiveTimeout,
×
696
                InterceptSwitch:   interceptableSwitch,
×
697
                ChannelDB:         dbAlice.ChannelStateDB(),
×
698
                FeeEstimator:      estimator,
×
699
                Wallet:            wallet,
×
700
                ChainNotifier:     notifier,
×
701
                ChanStatusMgr:     chanStatusMgr,
×
702
                Features: lnwire.NewFeatureVector(
×
703
                        nil, lnwire.Features,
×
704
                ),
×
705
                DisconnectPeer: func(b *btcec.PublicKey) error {
×
706
                        return nil
×
707
                },
×
708
                ChannelNotifier:               channelNotifier,
709
                PrunePersistentPeerConnection: func([33]byte) {},
×
710
                LegacyFeatures:                lnwire.EmptyFeatureVector(),
711
                WritePool:                     writePool,
712
                ReadPool:                      readPool,
713
                Conn:                          mockConn,
714
                HandleCustomMessage: func(
715
                        peer [33]byte, msg *lnwire.Custom) error {
×
716

×
717
                        receivedCustomChan <- &customMsg{
×
718
                                peer: peer,
×
719
                                msg:  *msg,
×
720
                        }
×
721

×
722
                        return nil
×
723
                },
×
724
                PongBuf: make([]byte, lnwire.MaxPongBytes),
725
                FetchLastChanUpdate: func(chanID lnwire.ShortChannelID,
726
                ) (*lnwire.ChannelUpdate1, error) {
×
727

×
728
                        return &lnwire.ChannelUpdate1{}, nil
×
729
                },
×
730
        }
731

732
        alicePeer := NewBrontide(*cfg)
×
733

×
734
        return &peerTestCtx{
×
735
                publishTx:     publishTx,
×
736
                mockSwitch:    mockSwitch,
×
737
                peer:          alicePeer,
×
738
                notifier:      notifier,
×
739
                db:            dbAlice,
×
740
                privKey:       aliceKeyPriv,
×
741
                mockConn:      mockConn,
×
742
                customChan:    receivedCustomChan,
×
743
                chanStatusMgr: chanStatusMgr,
×
744
        }
×
745
}
746

747
// startPeer invokes the `Start` method on the specified peer and handles any
748
// initial startup messages for testing.
749
func startPeer(t *testing.T, mockConn *mockMessageConn,
750
        peer *Brontide) <-chan struct{} {
×
751

×
752
        // Start the peer in a goroutine so that we can handle and test for
×
753
        // startup messages. Successfully sending and receiving init message,
×
754
        // indicates a successful startup.
×
755
        done := make(chan struct{})
×
756
        go func() {
×
757
                require.NoError(t, peer.Start())
×
758
                close(done)
×
759
        }()
×
760

761
        // Receive the init message that should be the first message received on
762
        // startup.
763
        rawMsg, err := fn.RecvOrTimeout[[]byte](
×
764
                mockConn.writtenMessages, timeout,
×
765
        )
×
766
        require.NoError(t, err)
×
767

×
768
        msgReader := bytes.NewReader(rawMsg)
×
769
        nextMsg, err := lnwire.ReadMessage(msgReader, 0)
×
770
        require.NoError(t, err)
×
771

×
772
        _, ok := nextMsg.(*lnwire.Init)
×
773
        require.True(t, ok)
×
774

×
775
        // Write the reply for the init message to complete the startup.
×
776
        initReplyMsg := lnwire.NewInitMessage(
×
777
                lnwire.NewRawFeatureVector(
×
778
                        lnwire.DataLossProtectRequired,
×
779
                        lnwire.GossipQueriesOptional,
×
780
                ),
×
781
                lnwire.NewRawFeatureVector(),
×
782
        )
×
783

×
784
        var b bytes.Buffer
×
785
        _, err = lnwire.WriteMessage(&b, initReplyMsg, 0)
×
786
        require.NoError(t, err)
×
787

×
788
        ok = fn.SendOrQuit[[]byte, struct{}](
×
789
                mockConn.readMessages, b.Bytes(), make(chan struct{}),
×
790
        )
×
791
        require.True(t, ok)
×
792

×
793
        return done
×
794
}
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