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

lightningnetwork / lnd / 13035292482

29 Jan 2025 03:59PM UTC coverage: 49.3% (-9.5%) from 58.777%
13035292482

Pull #9456

github

mohamedawnallah
docs: update release-notes-0.19.0.md

In this commit, we warn users about the removal
of RPCs `SendToRoute`, `SendToRouteSync`, `SendPayment`,
and `SendPaymentSync` in the next release 0.20.
Pull Request #9456: lnrpc+docs: deprecate warning `SendToRoute`, `SendToRouteSync`, `SendPayment`, and `SendPaymentSync` in Release 0.19

100634 of 204126 relevant lines covered (49.3%)

1.54 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.
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,
79
        b *channeldb.OpenChannel)) (*peerTestCtx, error) {
×
80

×
81
        params := createTestPeer(t)
×
82

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

404
// ChanID returns the mockUpdateHandler's cid.
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

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

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

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

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

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

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

500
// Flush mocks a message conn flush.
501
func (m *mockMessageConn) Flush() (int, error) {
×
502
        m.writeRaceDetectingCounter++
×
503
        return 0, nil
×
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.
508
func (m *mockMessageConn) WriteMessage(msg []byte) error {
×
509
        m.writeRaceDetectingCounter++
×
510

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

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

520
        return nil
×
521
}
522

523
// assertWrite asserts that our mock as had WriteMessage called with the byte
524
// slice we expect.
525
func (m *mockMessageConn) assertWrite(expected []byte) {
×
526
        select {
×
527
        case actual := <-m.writtenMessages:
×
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

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

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

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

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

555
func (m *mockMessageConn) LocalAddr() net.Addr {
×
556
        return nil
×
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.
566
func createTestPeer(t *testing.T) *peerTestCtx {
×
567
        nodeKeyLocator := keychain.KeyLocator{
×
568
                Family: keychain.KeyFamilyNodeKey,
×
569
        }
×
570

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

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

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

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

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

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

×
604
        const chanActiveTimeout = time.Minute
×
605

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

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

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

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

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

×
625
        chanStatusMgr, err := netann.NewChanStatusManager(&netann.
×
626
                ChanStatusConfig{
×
627
                ChanStatusSampleInterval: 30 * time.Second,
×
628
                ChanEnableTimeout:        chanActiveTimeout,
×
629
                ChanDisableTimeout:       2 * time.Minute,
×
630
                DB:                       dbAliceChannel.ChannelStateDB(),
×
631
                Graph:                    dbAliceGraph,
×
632
                MessageSigner:            nodeSignerAlice,
×
633
                OurPubKey:                aliceKeyPub,
×
634
                OurKeyLoc:                testKeyLoc,
×
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
        })
644
        require.NoError(t, err)
×
645

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

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

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

×
670
        mockSwitch := &mockMessageSwitch{}
×
671

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

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

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

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

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

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

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

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

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

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

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

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

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

752
        alicePeer := NewBrontide(*cfg)
×
753

×
754
        return &peerTestCtx{
×
755
                publishTx:     publishTx,
×
756
                mockSwitch:    mockSwitch,
×
757
                peer:          alicePeer,
×
758
                notifier:      notifier,
×
759
                db:            dbAliceChannel,
×
760
                privKey:       aliceKeyPriv,
×
761
                mockConn:      mockConn,
×
762
                customChan:    receivedCustomChan,
×
763
                chanStatusMgr: chanStatusMgr,
×
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,
770
        peer *Brontide) <-chan struct{} {
×
771

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

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

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

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

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

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

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

×
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