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

lightningnetwork / lnd / 11216766535

07 Oct 2024 01:37PM UTC coverage: 57.817% (-1.0%) from 58.817%
11216766535

Pull #9148

github

ProofOfKeags
lnwire: remove kickoff feerate from propose/commit
Pull Request #9148: DynComms [2/n]: lnwire: add authenticated wire messages for Dyn*

571 of 879 new or added lines in 16 files covered. (64.96%)

23253 existing lines in 251 files now uncovered.

99022 of 171268 relevant lines covered (57.82%)

38420.67 hits per line

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

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

38
const (
39
        broadcastHeight = 100
40

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

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

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

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

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

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

14✔
79
        params := createTestPeer(t)
14✔
80

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

14✔
91
        err := chanStatusMgr.Start()
14✔
92
        require.NoError(t, err)
14✔
93
        t.Cleanup(func() {
28✔
94
                require.NoError(t, chanStatusMgr.Stop())
14✔
95
        })
14✔
96

97
        aliceKeyPub := alicePeer.IdentityKey()
14✔
98
        estimator := alicePeer.cfg.FeeEstimator
14✔
99

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

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

14✔
114
        bobKeyPriv, bobKeyPub := btcec.PrivKeyFromBytes(
14✔
115
                channels.BobsPrivKey,
14✔
116
        )
14✔
117

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

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

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

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

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

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

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

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

242
        shortChanID := lnwire.NewShortChanIDFromInt(
14✔
243
                binary.BigEndian.Uint64(chanIDBytes[:]),
14✔
244
        )
14✔
245

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

14✔
281
        // Set custom values on the channel states.
14✔
282
        updateChan(aliceChannelState, bobChannelState)
14✔
283

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

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

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

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

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

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

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

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

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

14✔
343
        return &peerTestCtx{
14✔
344
                peer:       alicePeer,
14✔
345
                channel:    channelBob,
14✔
346
                notifier:   notifier,
14✔
347
                publishTx:  publishTx,
14✔
348
                mockSwitch: mockSwitch,
14✔
349
                mockConn:   params.mockConn,
14✔
350
        }, nil
14✔
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) {}
8✔
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) {
19✔
382

19✔
383
        return m.links, nil
19✔
384
}
19✔
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 {
9✔
396
        return &mockUpdateHandler{
9✔
397
                cid: cid,
9✔
398
        }
9✔
399
}
9✔
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 }
18✔
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 {
12✔
450
        if dir == htlcswitch.Outgoing {
20✔
451
                return !m.isOutgoingAddBlocked.Swap(true)
8✔
452
        }
8✔
453

454
        return !m.isIncomingAddBlocked.Swap(true)
4✔
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()) {
4✔
469
        hook()
4✔
470
}
4✔
471
func (m *mockUpdateHandler) OnCommitOnce(
472
        _ htlcswitch.LinkDirection, hook func(),
473
) {
8✔
474

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

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

×
NEW
483
        return c
×
NEW
484
}
×
485

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

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

500
// Flush mocks a message conn flush.
501
func (m *mockMessageConn) Flush() (int, error) {
13✔
502
        m.writeRaceDetectingCounter++
13✔
503
        return 0, nil
13✔
504
}
13✔
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 {
13✔
509
        m.writeRaceDetectingCounter++
13✔
510

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

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

520
        return nil
13✔
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) {
4✔
526
        select {
4✔
527
        case actual := <-m.writtenMessages:
4✔
528
                require.Equal(m.t, expected, actual)
4✔
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 {
11✔
536
        m.readRaceDetectingCounter++
11✔
537
        return nil
11✔
538
}
11✔
539

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

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

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

555
func (m *mockMessageConn) LocalAddr() net.Addr {
3✔
556
        return nil
3✔
557
}
3✔
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 {
19✔
567
        nodeKeyLocator := keychain.KeyLocator{
19✔
568
                Family: keychain.KeyFamilyNodeKey,
19✔
569
        }
19✔
570

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

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

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

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

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

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

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

19✔
606
        dbAlice, err := channeldb.Open(t.TempDir())
19✔
607
        require.NoError(t, err)
19✔
608
        t.Cleanup(func() {
38✔
609
                require.NoError(t, dbAlice.Close())
19✔
610
        })
19✔
611

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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