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

lightningnetwork / lnd / 12065491531

28 Nov 2024 08:42AM UTC coverage: 58.891% (-0.05%) from 58.939%
12065491531

Pull #9318

github

guggero
make: remove exotic build targets from release list

With this commit we remove build targets from our list of release build
OS/architecture pairs to reduce the overhead of building for them with
every pull request and every release.

According to https://tooomm.github.io/github-release-stats/?username=lightningnetwork&repository=lnd
those targets are rarely used, compared to the most popular ones:

| Release File                          | Absolute DL | Relative DL |
|---------------------------------------|-------------|-------------|
| lnd-darwin-amd64-v0.18.3-beta.tar.gz  | 1,930       | 72          |
| lnd-darwin-arm64-v0.18.3-beta.tar.gz  | 2,020       | 162         |
| lnd-freebsd-386-v0.18.3-beta.tar.gz   | 1,864       | 6           |
| lnd-freebsd-amd64-v0.18.3-beta.tar.gz | 1,874       | 16          |
| lnd-freebsd-arm-v0.18.3-beta.tar.gz   | 1,865       | 7           |
| lnd-linux-386-v0.18.3-beta.tar.gz     | 1,873       | 15          |
| lnd-linux-amd64-v0.18.3-beta.tar.gz   | 3,355       | 1,497       |
| lnd-linux-arm64-v0.18.3-beta.tar.gz   | 3,053       | 1,195       |
| lnd-linux-armv6-v0.18.3-beta.tar.gz   | 1,868       | 10          |
| lnd-linux-armv7-v0.18.3-beta.tar.gz   | 1,893       | 35          |
| lnd-linux-mips-v0.18.3-beta.tar.gz    | 1,859       | 1           |
| lnd-linux-mips64-v0.18.3-beta.tar.gz  | 1,860       | 2           |
| lnd-linux-mipsle-v0.18.3-beta.tar.gz  | 1,859       | 1           |
| lnd-linux-ppc64-v0.18.3-beta.tar.gz   | 1,858       | 0           |
| lnd-linux-ppc64le-v0.18.3-beta.tar.gz | 1,859       | 1           |
| lnd-linux-s390x-v0.18.3-beta.tar.gz   | 1,859       | 1           |
| lnd-netbsd-amd64-v0.18.3-beta.tar.gz  | 1,859       | 1           |
| lnd-openbsd-amd64-v0.18.3-beta.tar.gz | 1,861       | 3           |
| lnd-source-v0.18.3-beta.tar.gz        | 1,863       | 5           |
| lnd-windows-386-v0.18.3-beta.zip      | 1,895       | 37          |
| lnd-windows-amd64-v0.18.3-beta.zip    | ... (continued)
Pull Request #9318: make: remove exotic build targets from release list

133304 of 226358 relevant lines covered (58.89%)

19531.56 hits per line

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

87.73
/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.NewAuxSignerMock(
14✔
310
                        lnwallet.EmptyMockJobHandler,
14✔
311
                )),
14✔
312
        )
14✔
313
        if err != nil {
14✔
314
                return nil, err
×
315
        }
×
316
        _ = alicePool.Start()
14✔
317
        t.Cleanup(func() {
28✔
318
                require.NoError(t, alicePool.Stop())
14✔
319
        })
14✔
320

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

337
        alicePeer.remoteFeatures = lnwire.NewFeatureVector(
14✔
338
                nil, lnwire.Features,
14✔
339
        )
14✔
340

14✔
341
        chanID := lnwire.NewChanIDFromOutPoint(channelAlice.ChannelPoint())
14✔
342
        alicePeer.activeChannels.Store(chanID, channelAlice)
14✔
343

14✔
344
        alicePeer.wg.Add(1)
14✔
345
        go alicePeer.channelManager()
14✔
346

14✔
347
        return &peerTestCtx{
14✔
348
                peer:       alicePeer,
14✔
349
                channel:    channelBob,
14✔
350
                notifier:   notifier,
14✔
351
                publishTx:  publishTx,
14✔
352
                mockSwitch: mockSwitch,
14✔
353
                mockConn:   params.mockConn,
14✔
354
        }, nil
14✔
355
}
356

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

363
// BestHeight currently returns a dummy value.
364
func (m *mockMessageSwitch) BestHeight() uint32 {
×
365
        return 0
×
366
}
×
367

368
// CircuitModifier currently returns a dummy value.
369
func (m *mockMessageSwitch) CircuitModifier() htlcswitch.CircuitModifier {
×
370
        return nil
×
371
}
×
372

373
// RemoveLink currently does nothing.
374
func (m *mockMessageSwitch) RemoveLink(cid lnwire.ChannelID) {}
8✔
375

376
// CreateAndAddLink currently returns a dummy value.
377
func (m *mockMessageSwitch) CreateAndAddLink(cfg htlcswitch.ChannelLinkConfig,
378
        lnChan *lnwallet.LightningChannel) error {
×
379

×
380
        return nil
×
381
}
×
382

383
// GetLinksByInterface returns the active links.
384
func (m *mockMessageSwitch) GetLinksByInterface(pub [33]byte) (
385
        []htlcswitch.ChannelUpdateHandler, error) {
19✔
386

19✔
387
        return m.links, nil
19✔
388
}
19✔
389

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

398
// newMockUpdateHandler creates a new mockUpdateHandler.
399
func newMockUpdateHandler(cid lnwire.ChannelID) *mockUpdateHandler {
9✔
400
        return &mockUpdateHandler{
9✔
401
                cid: cid,
9✔
402
        }
9✔
403
}
9✔
404

405
// HandleChannelUpdate currently does nothing.
406
func (m *mockUpdateHandler) HandleChannelUpdate(msg lnwire.Message) {}
×
407

408
// ChanID returns the mockUpdateHandler's cid.
409
func (m *mockUpdateHandler) ChanID() lnwire.ChannelID { return m.cid }
18✔
410

411
// Bandwidth currently returns a dummy value.
412
func (m *mockUpdateHandler) Bandwidth() lnwire.MilliSatoshi { return 0 }
×
413

414
// EligibleToForward currently returns a dummy value.
415
func (m *mockUpdateHandler) EligibleToForward() bool { return false }
×
416

417
// MayAddOutgoingHtlc currently returns nil.
418
func (m *mockUpdateHandler) MayAddOutgoingHtlc(lnwire.MilliSatoshi) error { return nil }
×
419

420
type mockMessageConn struct {
421
        t *testing.T
422

423
        // MessageConn embeds our interface so that the mock does not need to
424
        // implement every function. The mock will panic if an unspecified function
425
        // is called.
426
        MessageConn
427

428
        // writtenMessages is a channel that our mock pushes written messages into.
429
        writtenMessages chan []byte
430

431
        readMessages   chan []byte
432
        curReadMessage []byte
433

434
        // writeRaceDetectingCounter is incremented on any function call
435
        // associated with writing to the connection. The race detector will
436
        // trigger on this counter if a data race exists.
437
        writeRaceDetectingCounter int
438

439
        // readRaceDetectingCounter is incremented on any function call
440
        // associated with reading from the connection. The race detector will
441
        // trigger on this counter if a data race exists.
442
        readRaceDetectingCounter int
443
}
444

445
func (m *mockUpdateHandler) EnableAdds(dir htlcswitch.LinkDirection) bool {
×
446
        if dir == htlcswitch.Outgoing {
×
447
                return m.isOutgoingAddBlocked.Swap(false)
×
448
        }
×
449

450
        return m.isIncomingAddBlocked.Swap(false)
×
451
}
452

453
func (m *mockUpdateHandler) DisableAdds(dir htlcswitch.LinkDirection) bool {
12✔
454
        if dir == htlcswitch.Outgoing {
20✔
455
                return !m.isOutgoingAddBlocked.Swap(true)
8✔
456
        }
8✔
457

458
        return !m.isIncomingAddBlocked.Swap(true)
4✔
459
}
460

461
func (m *mockUpdateHandler) IsFlushing(dir htlcswitch.LinkDirection) bool {
×
462
        switch dir {
×
463
        case htlcswitch.Outgoing:
×
464
                return m.isOutgoingAddBlocked.Load()
×
465
        case htlcswitch.Incoming:
×
466
                return m.isIncomingAddBlocked.Load()
×
467
        }
468

469
        return false
×
470
}
471

472
func (m *mockUpdateHandler) OnFlushedOnce(hook func()) {
4✔
473
        hook()
4✔
474
}
4✔
475
func (m *mockUpdateHandler) OnCommitOnce(
476
        _ htlcswitch.LinkDirection, hook func(),
477
) {
8✔
478

8✔
479
        hook()
8✔
480
}
8✔
481
func (m *mockUpdateHandler) InitStfu() <-chan fn.Result[lntypes.ChannelParty] {
×
482
        // TODO(proofofkeags): Implement
×
483
        c := make(chan fn.Result[lntypes.ChannelParty], 1)
×
484

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

×
487
        return c
×
488
}
×
489

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

498
// SetWriteDeadline mocks setting write deadline for our conn.
499
func (m *mockMessageConn) SetWriteDeadline(time.Time) error {
13✔
500
        m.writeRaceDetectingCounter++
13✔
501
        return nil
13✔
502
}
13✔
503

504
// Flush mocks a message conn flush.
505
func (m *mockMessageConn) Flush() (int, error) {
13✔
506
        m.writeRaceDetectingCounter++
13✔
507
        return 0, nil
13✔
508
}
13✔
509

510
// WriteMessage mocks sending of a message on our connection. It will push
511
// the bytes sent into the mock's writtenMessages channel.
512
func (m *mockMessageConn) WriteMessage(msg []byte) error {
13✔
513
        m.writeRaceDetectingCounter++
13✔
514

13✔
515
        msgCopy := make([]byte, len(msg))
13✔
516
        copy(msgCopy, msg)
13✔
517

13✔
518
        select {
13✔
519
        case m.writtenMessages <- msgCopy:
13✔
520
        case <-time.After(timeout):
×
521
                m.t.Fatalf("timeout sending message: %v", msgCopy)
×
522
        }
523

524
        return nil
13✔
525
}
526

527
// assertWrite asserts that our mock as had WriteMessage called with the byte
528
// slice we expect.
529
func (m *mockMessageConn) assertWrite(expected []byte) {
4✔
530
        select {
4✔
531
        case actual := <-m.writtenMessages:
4✔
532
                require.Equal(m.t, expected, actual)
4✔
533

534
        case <-time.After(timeout):
×
535
                m.t.Fatalf("timeout waiting for write: %v", expected)
×
536
        }
537
}
538

539
func (m *mockMessageConn) SetReadDeadline(t time.Time) error {
11✔
540
        m.readRaceDetectingCounter++
11✔
541
        return nil
11✔
542
}
11✔
543

544
func (m *mockMessageConn) ReadNextHeader() (uint32, error) {
7✔
545
        m.readRaceDetectingCounter++
7✔
546
        m.curReadMessage = <-m.readMessages
7✔
547
        return uint32(len(m.curReadMessage)), nil
7✔
548
}
7✔
549

550
func (m *mockMessageConn) ReadNextBody(buf []byte) ([]byte, error) {
4✔
551
        m.readRaceDetectingCounter++
4✔
552
        return m.curReadMessage, nil
4✔
553
}
4✔
554

555
func (m *mockMessageConn) RemoteAddr() net.Addr {
22✔
556
        return nil
22✔
557
}
22✔
558

559
func (m *mockMessageConn) LocalAddr() net.Addr {
3✔
560
        return nil
3✔
561
}
3✔
562

563
func (m *mockMessageConn) Close() error {
×
564
        return nil
×
565
}
×
566

567
// createTestPeer creates a new peer for testing and returns a context struct
568
// containing necessary handles and mock objects for conducting tests on peer
569
// functionalities.
570
func createTestPeer(t *testing.T) *peerTestCtx {
19✔
571
        nodeKeyLocator := keychain.KeyLocator{
19✔
572
                Family: keychain.KeyFamilyNodeKey,
19✔
573
        }
19✔
574

19✔
575
        aliceKeyPriv, aliceKeyPub := btcec.PrivKeyFromBytes(
19✔
576
                channels.AlicesPrivKey,
19✔
577
        )
19✔
578

19✔
579
        aliceKeySigner := keychain.NewPrivKeyMessageSigner(
19✔
580
                aliceKeyPriv, nodeKeyLocator,
19✔
581
        )
19✔
582

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

19✔
593
        errBuffer, err := queue.NewCircularBuffer(ErrorBufferSize)
19✔
594
        require.NoError(t, err)
19✔
595

19✔
596
        chainIO := &mock.ChainIO{
19✔
597
                BestHeight: broadcastHeight,
19✔
598
        }
19✔
599

19✔
600
        publishTx := make(chan *wire.MsgTx)
19✔
601
        wallet := &lnwallet.LightningWallet{
19✔
602
                WalletController: &mock.WalletController{
19✔
603
                        RootKey:               aliceKeyPriv,
19✔
604
                        PublishedTransactions: publishTx,
19✔
605
                },
19✔
606
        }
19✔
607

19✔
608
        const chanActiveTimeout = time.Minute
19✔
609

19✔
610
        dbAlice, err := channeldb.Open(t.TempDir())
19✔
611
        require.NoError(t, err)
19✔
612
        t.Cleanup(func() {
38✔
613
                require.NoError(t, dbAlice.Close())
19✔
614
        })
19✔
615

616
        nodeSignerAlice := netann.NewNodeSigner(aliceKeySigner)
19✔
617

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

×
634
                        return nil
×
635
                },
×
636
        })
637
        require.NoError(t, err)
19✔
638

19✔
639
        interceptableSwitchNotifier := &mock.ChainNotifier{
19✔
640
                EpochChan: make(chan *chainntnfs.BlockEpoch, 1),
19✔
641
        }
19✔
642
        interceptableSwitchNotifier.EpochChan <- &chainntnfs.BlockEpoch{
19✔
643
                Height: 1,
19✔
644
        }
19✔
645

19✔
646
        interceptableSwitch, err := htlcswitch.NewInterceptableSwitch(
19✔
647
                &htlcswitch.InterceptableSwitchConfig{
19✔
648
                        CltvRejectDelta:    testCltvRejectDelta,
19✔
649
                        CltvInterceptDelta: testCltvRejectDelta + 3,
19✔
650
                        Notifier:           interceptableSwitchNotifier,
19✔
651
                },
19✔
652
        )
19✔
653
        require.NoError(t, err)
19✔
654

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

19✔
663
        mockSwitch := &mockMessageSwitch{}
19✔
664

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

673
        writeBufferPool := pool.NewWriteBuffer(
19✔
674
                pool.DefaultWriteBufferGCInterval,
19✔
675
                pool.DefaultWriteBufferExpiryInterval,
19✔
676
        )
19✔
677

19✔
678
        writePool := pool.NewWrite(
19✔
679
                writeBufferPool, 1, timeout,
19✔
680
        )
19✔
681
        require.NoError(t, writePool.Start())
19✔
682

19✔
683
        readBufferPool := pool.NewReadBuffer(
19✔
684
                pool.DefaultReadBufferGCInterval,
19✔
685
                pool.DefaultReadBufferExpiryInterval,
19✔
686
        )
19✔
687

19✔
688
        readPool := pool.NewRead(
19✔
689
                readBufferPool, 1, timeout,
19✔
690
        )
19✔
691
        require.NoError(t, readPool.Start())
19✔
692

19✔
693
        mockConn := newMockConn(t, 1)
19✔
694

19✔
695
        receivedCustomChan := make(chan *customMsg)
19✔
696

19✔
697
        var pubKey [33]byte
19✔
698
        copy(pubKey[:], aliceKeyPub.SerializeCompressed())
19✔
699

19✔
700
        estimator := chainfee.NewStaticEstimator(12500, 0)
19✔
701

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

1✔
730
                        receivedCustomChan <- &customMsg{
1✔
731
                                peer: peer,
1✔
732
                                msg:  *msg,
1✔
733
                        }
1✔
734

1✔
735
                        return nil
1✔
736
                },
1✔
737
                PongBuf: make([]byte, lnwire.MaxPongBytes),
738
                FetchLastChanUpdate: func(chanID lnwire.ShortChannelID,
739
                ) (*lnwire.ChannelUpdate1, error) {
2✔
740

2✔
741
                        return &lnwire.ChannelUpdate1{}, nil
2✔
742
                },
2✔
743
        }
744

745
        alicePeer := NewBrontide(*cfg)
19✔
746

19✔
747
        return &peerTestCtx{
19✔
748
                publishTx:     publishTx,
19✔
749
                mockSwitch:    mockSwitch,
19✔
750
                peer:          alicePeer,
19✔
751
                notifier:      notifier,
19✔
752
                db:            dbAlice,
19✔
753
                privKey:       aliceKeyPriv,
19✔
754
                mockConn:      mockConn,
19✔
755
                customChan:    receivedCustomChan,
19✔
756
                chanStatusMgr: chanStatusMgr,
19✔
757
        }
19✔
758
}
759

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

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

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

3✔
781
        msgReader := bytes.NewReader(rawMsg)
3✔
782
        nextMsg, err := lnwire.ReadMessage(msgReader, 0)
3✔
783
        require.NoError(t, err)
3✔
784

3✔
785
        _, ok := nextMsg.(*lnwire.Init)
3✔
786
        require.True(t, ok)
3✔
787

3✔
788
        // Write the reply for the init message to complete the startup.
3✔
789
        initReplyMsg := lnwire.NewInitMessage(
3✔
790
                lnwire.NewRawFeatureVector(
3✔
791
                        lnwire.DataLossProtectRequired,
3✔
792
                        lnwire.GossipQueriesOptional,
3✔
793
                ),
3✔
794
                lnwire.NewRawFeatureVector(),
3✔
795
        )
3✔
796

3✔
797
        var b bytes.Buffer
3✔
798
        _, err = lnwire.WriteMessage(&b, initReplyMsg, 0)
3✔
799
        require.NoError(t, err)
3✔
800

3✔
801
        ok = fn.SendOrQuit[[]byte, struct{}](
3✔
802
                mockConn.readMessages, b.Bytes(), make(chan struct{}),
3✔
803
        )
3✔
804
        require.True(t, ok)
3✔
805

3✔
806
        return done
3✔
807
}
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