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

lightningnetwork / lnd / 13558005087

27 Feb 2025 03:04AM UTC coverage: 58.834% (-0.001%) from 58.835%
13558005087

Pull #8453

github

Roasbeef
lnwallet/chancloser: increase test coverage of state machine
Pull Request #8453: [4/4] - multi: integrate new rbf coop close FSM into the existing peer flow

1079 of 1370 new or added lines in 23 files covered. (78.76%)

578 existing lines in 40 files now uncovered.

137063 of 232965 relevant lines covered (58.83%)

19205.84 hits per line

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

0.0
/lntest/harness.go
1
package lntest
2

3
import (
4
        "context"
5
        "encoding/hex"
6
        "fmt"
7
        "strings"
8
        "testing"
9
        "time"
10

11
        "github.com/btcsuite/btcd/blockchain"
12
        "github.com/btcsuite/btcd/btcec/v2"
13
        "github.com/btcsuite/btcd/btcutil"
14
        "github.com/btcsuite/btcd/chaincfg/chainhash"
15
        "github.com/btcsuite/btcd/txscript"
16
        "github.com/btcsuite/btcd/wire"
17
        "github.com/go-errors/errors"
18
        "github.com/lightningnetwork/lnd/fn/v2"
19
        "github.com/lightningnetwork/lnd/input"
20
        "github.com/lightningnetwork/lnd/kvdb/etcd"
21
        "github.com/lightningnetwork/lnd/lnrpc"
22
        "github.com/lightningnetwork/lnd/lnrpc/invoicesrpc"
23
        "github.com/lightningnetwork/lnd/lnrpc/routerrpc"
24
        "github.com/lightningnetwork/lnd/lnrpc/signrpc"
25
        "github.com/lightningnetwork/lnd/lnrpc/walletrpc"
26
        "github.com/lightningnetwork/lnd/lntest/miner"
27
        "github.com/lightningnetwork/lnd/lntest/node"
28
        "github.com/lightningnetwork/lnd/lntest/rpc"
29
        "github.com/lightningnetwork/lnd/lntest/wait"
30
        "github.com/lightningnetwork/lnd/lntypes"
31
        "github.com/lightningnetwork/lnd/lnwallet/chainfee"
32
        "github.com/lightningnetwork/lnd/lnwire"
33
        "github.com/lightningnetwork/lnd/routing"
34
        "github.com/stretchr/testify/require"
35
)
36

37
const (
38
        // defaultMinerFeeRate specifies the fee rate in sats when sending
39
        // outputs from the miner.
40
        defaultMinerFeeRate = 7500
41

42
        // numBlocksSendOutput specifies the number of blocks to mine after
43
        // sending outputs from the miner.
44
        numBlocksSendOutput = 2
45

46
        // numBlocksOpenChannel specifies the number of blocks mined when
47
        // opening a channel.
48
        numBlocksOpenChannel = 6
49

50
        // lndErrorChanSize specifies the buffer size used to receive errors
51
        // from lnd process.
52
        lndErrorChanSize = 10
53

54
        // maxBlocksAllowed specifies the max allowed value to be used when
55
        // mining blocks.
56
        maxBlocksAllowed = 100
57

58
        finalCltvDelta  = routing.MinCLTVDelta // 18.
59
        thawHeightDelta = finalCltvDelta * 2   // 36.
60
)
61

62
// TestCase defines a test case that's been used in the integration test.
63
type TestCase struct {
64
        // Name specifies the test name.
65
        Name string
66

67
        // TestFunc is the test case wrapped in a function.
68
        TestFunc func(t *HarnessTest)
69
}
70

71
// HarnessTest builds on top of a testing.T with enhanced error detection. It
72
// is responsible for managing the interactions among different nodes, and
73
// providing easy-to-use assertions.
74
type HarnessTest struct {
75
        *testing.T
76

77
        // miner is a reference to a running full node that can be used to
78
        // create new blocks on the network.
79
        miner *miner.HarnessMiner
80

81
        // manager handles the start and stop of a given node.
82
        manager *nodeManager
83

84
        // feeService is a web service that provides external fee estimates to
85
        // lnd.
86
        feeService WebFeeService
87

88
        // Channel for transmitting stderr output from failed lightning node
89
        // to main process.
90
        lndErrorChan chan error
91

92
        // runCtx is a context with cancel method. It's used to signal when the
93
        // node needs to quit, and used as the parent context when spawning
94
        // children contexts for RPC requests.
95
        runCtx context.Context //nolint:containedctx
96
        cancel context.CancelFunc
97

98
        // stopChainBackend points to the cleanup function returned by the
99
        // chainBackend.
100
        stopChainBackend func()
101

102
        // cleaned specifies whether the cleanup has been applied for the
103
        // current HarnessTest.
104
        cleaned bool
105

106
        // currentHeight is the current height of the chain backend.
107
        currentHeight uint32
108
}
109

110
// harnessOpts contains functional option to modify the behavior of the various
111
// harness calls.
112
type harnessOpts struct {
113
        useAMP bool
114
}
115

116
// defaultHarnessOpts returns a new instance of the harnessOpts with default
117
// values specified.
118
func defaultHarnessOpts() harnessOpts {
×
119
        return harnessOpts{
×
120
                useAMP: false,
×
121
        }
×
122
}
×
123

124
// HarnessOpt is a functional option that can be used to modify the behavior of
125
// harness functionality.
126
type HarnessOpt func(*harnessOpts)
127

128
// WithAMP is a functional option that can be used to enable the AMP feature
129
// for sending payments.
130
func WithAMP() HarnessOpt {
×
131
        return func(h *harnessOpts) {
×
132
                h.useAMP = true
×
133
        }
×
134
}
135

136
// NewHarnessTest creates a new instance of a harnessTest from a regular
137
// testing.T instance.
138
func NewHarnessTest(t *testing.T, lndBinary string, feeService WebFeeService,
139
        dbBackend node.DatabaseBackend, nativeSQL bool) *HarnessTest {
×
140

×
141
        t.Helper()
×
142

×
143
        // Create the run context.
×
144
        ctxt, cancel := context.WithCancel(context.Background())
×
145

×
146
        manager := newNodeManager(lndBinary, dbBackend, nativeSQL)
×
147

×
148
        return &HarnessTest{
×
149
                T:          t,
×
150
                manager:    manager,
×
151
                feeService: feeService,
×
152
                runCtx:     ctxt,
×
153
                cancel:     cancel,
×
154
                // We need to use buffered channel here as we don't want to
×
155
                // block sending errors.
×
156
                lndErrorChan: make(chan error, lndErrorChanSize),
×
157
        }
×
158
}
×
159

160
// Start will assemble the chain backend and the miner for the HarnessTest. It
161
// also starts the fee service and watches lnd process error.
162
func (h *HarnessTest) Start(chain node.BackendConfig,
163
        miner *miner.HarnessMiner) {
×
164

×
165
        // Spawn a new goroutine to watch for any fatal errors that any of the
×
166
        // running lnd processes encounter. If an error occurs, then the test
×
167
        // case should naturally as a result and we log the server error here
×
168
        // to help debug.
×
169
        go func() {
×
170
                select {
×
171
                case err, more := <-h.lndErrorChan:
×
172
                        if !more {
×
173
                                return
×
174
                        }
×
175
                        h.Logf("lnd finished with error (stderr):\n%v", err)
×
176

177
                case <-h.runCtx.Done():
×
178
                        return
×
179
                }
180
        }()
181

182
        // Start the fee service.
183
        err := h.feeService.Start()
×
184
        require.NoError(h, err, "failed to start fee service")
×
185

×
186
        // Assemble the node manager with chainBackend and feeServiceURL.
×
187
        h.manager.chainBackend = chain
×
188
        h.manager.feeServiceURL = h.feeService.URL()
×
189

×
190
        // Assemble the miner.
×
191
        h.miner = miner
×
192

×
193
        // Update block height.
×
194
        h.updateCurrentHeight()
×
195
}
196

197
// ChainBackendName returns the chain backend name used in the test.
198
func (h *HarnessTest) ChainBackendName() string {
×
199
        return h.manager.chainBackend.Name()
×
200
}
×
201

202
// Context returns the run context used in this test. Usaually it should be
203
// managed by the test itself otherwise undefined behaviors will occur. It can
204
// be used, however, when a test needs to have its own context being managed
205
// differently. In that case, instead of using a background context, the run
206
// context should be used such that the test context scope can be fully
207
// controlled.
208
func (h *HarnessTest) Context() context.Context {
×
209
        return h.runCtx
×
210
}
×
211

212
// setupWatchOnlyNode initializes a node with the watch-only accounts of an
213
// associated remote signing instance.
214
func (h *HarnessTest) setupWatchOnlyNode(name string,
215
        signerNode *node.HarnessNode, password []byte) *node.HarnessNode {
×
216

×
217
        // Prepare arguments for watch-only node connected to the remote signer.
×
218
        remoteSignerArgs := []string{
×
219
                "--remotesigner.enable",
×
220
                fmt.Sprintf("--remotesigner.rpchost=localhost:%d",
×
221
                        signerNode.Cfg.RPCPort),
×
222
                fmt.Sprintf("--remotesigner.tlscertpath=%s",
×
223
                        signerNode.Cfg.TLSCertPath),
×
224
                fmt.Sprintf("--remotesigner.macaroonpath=%s",
×
225
                        signerNode.Cfg.AdminMacPath),
×
226
        }
×
227

×
228
        // Fetch watch-only accounts from the signer node.
×
229
        resp := signerNode.RPC.ListAccounts(&walletrpc.ListAccountsRequest{})
×
230
        watchOnlyAccounts, err := walletrpc.AccountsToWatchOnly(resp.Accounts)
×
231
        require.NoErrorf(h, err, "unable to find watch only accounts for %s",
×
232
                name)
×
233

×
234
        // Create a new watch-only node with remote signer configuration.
×
235
        return h.NewNodeRemoteSigner(
×
236
                name, remoteSignerArgs, password,
×
237
                &lnrpc.WatchOnly{
×
238
                        MasterKeyBirthdayTimestamp: 0,
×
239
                        MasterKeyFingerprint:       nil,
×
240
                        Accounts:                   watchOnlyAccounts,
×
241
                },
×
242
        )
×
243
}
×
244

245
// createAndSendOutput send amt satoshis from the internal mining node to the
246
// targeted lightning node using a P2WKH address. No blocks are mined so
247
// transactions will sit unconfirmed in mempool.
248
func (h *HarnessTest) createAndSendOutput(target *node.HarnessNode,
249
        amt btcutil.Amount, addrType lnrpc.AddressType) {
×
250

×
251
        req := &lnrpc.NewAddressRequest{Type: addrType}
×
252
        resp := target.RPC.NewAddress(req)
×
253
        addr := h.DecodeAddress(resp.Address)
×
254
        addrScript := h.PayToAddrScript(addr)
×
255

×
256
        output := &wire.TxOut{
×
257
                PkScript: addrScript,
×
258
                Value:    int64(amt),
×
259
        }
×
260
        h.miner.SendOutput(output, defaultMinerFeeRate)
×
261
}
×
262

263
// Stop stops the test harness.
264
func (h *HarnessTest) Stop() {
×
265
        // Do nothing if it's not started.
×
266
        if h.runCtx == nil {
×
267
                h.Log("HarnessTest is not started")
×
268
                return
×
269
        }
×
270

271
        h.shutdownAllNodes()
×
272

×
273
        close(h.lndErrorChan)
×
274

×
275
        // Stop the fee service.
×
276
        err := h.feeService.Stop()
×
277
        require.NoError(h, err, "failed to stop fee service")
×
278

×
279
        // Stop the chainBackend.
×
280
        h.stopChainBackend()
×
281

×
282
        // Stop the miner.
×
283
        h.miner.Stop()
×
284
}
285

286
// RunTestCase executes a harness test case. Any errors or panics will be
287
// represented as fatal.
288
func (h *HarnessTest) RunTestCase(testCase *TestCase) {
×
289
        defer func() {
×
290
                if err := recover(); err != nil {
×
291
                        description := errors.Wrap(err, 2).ErrorStack()
×
292
                        h.Fatalf("Failed: (%v) panic with: \n%v",
×
293
                                testCase.Name, description)
×
294
                }
×
295
        }()
296

297
        testCase.TestFunc(h)
×
298
}
299

300
// Subtest creates a child HarnessTest, which inherits the harness net and
301
// stand by nodes created by the parent test. It will return a cleanup function
302
// which resets  all the standby nodes' configs back to its original state and
303
// create snapshots of each nodes' internal state.
304
func (h *HarnessTest) Subtest(t *testing.T) *HarnessTest {
×
305
        t.Helper()
×
306

×
307
        st := &HarnessTest{
×
308
                T:            t,
×
309
                manager:      h.manager,
×
310
                miner:        h.miner,
×
311
                feeService:   h.feeService,
×
312
                lndErrorChan: make(chan error, lndErrorChanSize),
×
313
        }
×
314

×
315
        // Inherit context from the main test.
×
316
        st.runCtx, st.cancel = context.WithCancel(h.runCtx)
×
317

×
318
        // Inherit the subtest for the miner.
×
319
        st.miner.T = st.T
×
320

×
321
        // Reset fee estimator.
×
322
        st.feeService.Reset()
×
323

×
324
        // Record block height.
×
325
        h.updateCurrentHeight()
×
326
        startHeight := int32(h.CurrentHeight())
×
327

×
328
        st.Cleanup(func() {
×
329
                // Make sure the test is not consuming too many blocks.
×
330
                st.checkAndLimitBlocksMined(startHeight)
×
331

×
332
                // Don't bother run the cleanups if the test is failed.
×
333
                if st.Failed() {
×
334
                        st.Log("test failed, skipped cleanup")
×
335
                        st.shutdownNodesNoAssert()
×
336
                        return
×
337
                }
×
338

339
                // Don't run cleanup if it's already done. This can happen if
340
                // we have multiple level inheritance of the parent harness
341
                // test. For instance, a `Subtest(st)`.
342
                if st.cleaned {
×
343
                        st.Log("test already cleaned, skipped cleanup")
×
344
                        return
×
345
                }
×
346

347
                // If found running nodes, shut them down.
348
                st.shutdownAllNodes()
×
349

×
350
                // We require the mempool to be cleaned from the test.
×
351
                require.Empty(st, st.miner.GetRawMempool(), "mempool not "+
×
352
                        "cleaned, please mine blocks to clean them all.")
×
353

×
354
                // Finally, cancel the run context. We have to do it here
×
355
                // because we need to keep the context alive for the above
×
356
                // assertions used in cleanup.
×
357
                st.cancel()
×
358

×
359
                // We now want to mark the parent harness as cleaned to avoid
×
360
                // running cleanup again since its internal state has been
×
361
                // cleaned up by its child harness tests.
×
362
                h.cleaned = true
×
363
        })
364

365
        return st
×
366
}
367

368
// checkAndLimitBlocksMined asserts that the blocks mined in a single test
369
// doesn't exceed 50, which implicitly discourage table-drive tests, which are
370
// hard to maintain and take a long time to run.
371
func (h *HarnessTest) checkAndLimitBlocksMined(startHeight int32) {
×
372
        _, endHeight := h.GetBestBlock()
×
373
        blocksMined := endHeight - startHeight
×
374

×
375
        h.Logf("finished test: %s, start height=%d, end height=%d, mined "+
×
376
                "blocks=%d", h.manager.currentTestCase, startHeight, endHeight,
×
377
                blocksMined)
×
378

×
379
        // If the number of blocks is less than 40, we consider the test
×
380
        // healthy.
×
381
        if blocksMined < 40 {
×
382
                return
×
383
        }
×
384

385
        // Otherwise log a warning if it's mining more than 40 blocks.
386
        desc := "!============================================!\n"
×
387

×
388
        desc += fmt.Sprintf("Too many blocks (%v) mined in one test! Tips:\n",
×
389
                blocksMined)
×
390

×
391
        desc += "1. break test into smaller individual tests, especially if " +
×
392
                "this is a table-drive test.\n" +
×
393
                "2. use smaller CSV via `--bitcoin.defaultremotedelay=1.`\n" +
×
394
                "3. use smaller CLTV via `--bitcoin.timelockdelta=18.`\n" +
×
395
                "4. remove unnecessary CloseChannel when test ends.\n" +
×
396
                "5. use `CreateSimpleNetwork` for efficient channel creation.\n"
×
397
        h.Log(desc)
×
398

×
399
        // We enforce that the test should not mine more than 50 blocks, which
×
400
        // is more than enough to test a multi hop force close scenario.
×
401
        require.LessOrEqual(h, int(blocksMined), 50, "cannot mine more than "+
×
402
                "50 blocks in one test")
×
403
}
404

405
// shutdownNodesNoAssert will shutdown all running nodes without assertions.
406
// This is used when the test has already failed, we don't want to log more
407
// errors but focusing on the original error.
408
func (h *HarnessTest) shutdownNodesNoAssert() {
×
409
        for _, node := range h.manager.activeNodes {
×
410
                _ = h.manager.shutdownNode(node)
×
411
        }
×
412
}
413

414
// shutdownAllNodes will shutdown all running nodes.
415
func (h *HarnessTest) shutdownAllNodes() {
×
416
        var err error
×
417
        for _, node := range h.manager.activeNodes {
×
418
                err = h.manager.shutdownNode(node)
×
419
                if err == nil {
×
420
                        continue
×
421
                }
422

423
                // Instead of returning the error, we will log it instead. This
424
                // is needed so other nodes can continue their shutdown
425
                // processes.
426
                h.Logf("unable to shutdown %s, got err: %v", node.Name(), err)
×
427
        }
428

429
        require.NoError(h, err, "failed to shutdown all nodes")
×
430
}
431

432
// cleanupStandbyNode is a function should be called with defer whenever a
433
// subtest is created. It will reset the standby nodes configs, snapshot the
434
// states, and validate the node has a clean state.
435
func (h *HarnessTest) cleanupStandbyNode(hn *node.HarnessNode) {
×
436
        // Remove connections made from this test.
×
437
        h.removeConnectionns(hn)
×
438

×
439
        // Delete all payments made from this test.
×
440
        hn.RPC.DeleteAllPayments()
×
441

×
442
        // Check the node's current state with timeout.
×
443
        //
×
444
        // NOTE: we need to do this in a `wait` because it takes some time for
×
445
        // the node to update its internal state. Once the RPCs are synced we
×
446
        // can then remove this wait.
×
447
        err := wait.NoError(func() error {
×
448
                // Update the node's internal state.
×
449
                hn.UpdateState()
×
450

×
451
                // Check the node is in a clean state for the following tests.
×
452
                return h.validateNodeState(hn)
×
453
        }, wait.DefaultTimeout)
×
454
        require.NoError(h, err, "timeout checking node's state")
×
455
}
456

457
// removeConnectionns will remove all connections made on the standby nodes
458
// expect the connections between Alice and Bob.
459
func (h *HarnessTest) removeConnectionns(hn *node.HarnessNode) {
×
460
        resp := hn.RPC.ListPeers()
×
461
        for _, peer := range resp.Peers {
×
462
                hn.RPC.DisconnectPeer(peer.PubKey)
×
463
        }
×
464
}
465

466
// SetTestName set the test case name.
467
func (h *HarnessTest) SetTestName(name string) {
×
468
        cleanTestCaseName := strings.ReplaceAll(name, " ", "_")
×
469
        h.manager.currentTestCase = cleanTestCaseName
×
470
}
×
471

472
// NewNode creates a new node and asserts its creation. The node is guaranteed
473
// to have finished its initialization and all its subservers are started.
474
func (h *HarnessTest) NewNode(name string,
475
        extraArgs []string) *node.HarnessNode {
×
476

×
477
        node, err := h.manager.newNode(h.T, name, extraArgs, nil, false)
×
478
        require.NoErrorf(h, err, "unable to create new node for %s", name)
×
479

×
480
        // Start the node.
×
481
        err = node.Start(h.runCtx)
×
482
        require.NoError(h, err, "failed to start node %s", node.Name())
×
483

×
484
        // Get the miner's best block hash.
×
485
        bestBlock, err := h.miner.Client.GetBestBlockHash()
×
486
        require.NoError(h, err, "unable to get best block hash")
×
487

×
488
        // Wait until the node's chain backend is synced to the miner's best
×
489
        // block.
×
490
        h.WaitForBlockchainSyncTo(node, *bestBlock)
×
491

×
492
        return node
×
493
}
×
494

495
// NewNodeWithCoins creates a new node and asserts its creation. The node is
496
// guaranteed to have finished its initialization and all its subservers are
497
// started. In addition, 5 UTXO of 1 BTC each are sent to the node.
498
func (h *HarnessTest) NewNodeWithCoins(name string,
499
        extraArgs []string) *node.HarnessNode {
×
500

×
501
        node := h.NewNode(name, extraArgs)
×
502

×
503
        // Load up the wallets of the node with 5 outputs of 1 BTC each.
×
504
        const (
×
505
                numOutputs  = 5
×
506
                fundAmount  = 1 * btcutil.SatoshiPerBitcoin
×
507
                totalAmount = fundAmount * numOutputs
×
508
        )
×
509

×
510
        for i := 0; i < numOutputs; i++ {
×
511
                h.createAndSendOutput(
×
512
                        node, fundAmount,
×
513
                        lnrpc.AddressType_WITNESS_PUBKEY_HASH,
×
514
                )
×
515
        }
×
516

517
        // Mine a block to confirm the transactions.
518
        h.MineBlocksAndAssertNumTxes(1, numOutputs)
×
519

×
520
        // Now block until the wallet have fully synced up.
×
521
        h.WaitForBalanceConfirmed(node, totalAmount)
×
522

×
523
        return node
×
524
}
525

526
// Shutdown shuts down the given node and asserts that no errors occur.
527
func (h *HarnessTest) Shutdown(node *node.HarnessNode) {
×
528
        err := h.manager.shutdownNode(node)
×
529
        require.NoErrorf(h, err, "unable to shutdown %v in %v", node.Name(),
×
530
                h.manager.currentTestCase)
×
531
}
×
532

533
// SuspendNode stops the given node and returns a callback that can be used to
534
// start it again.
535
func (h *HarnessTest) SuspendNode(node *node.HarnessNode) func() error {
×
536
        err := node.Stop()
×
537
        require.NoErrorf(h, err, "failed to stop %s", node.Name())
×
538

×
539
        // Remove the node from active nodes.
×
540
        delete(h.manager.activeNodes, node.Cfg.NodeID)
×
541

×
542
        return func() error {
×
543
                h.manager.registerNode(node)
×
544

×
545
                if err := node.Start(h.runCtx); err != nil {
×
546
                        return err
×
547
                }
×
548
                h.WaitForBlockchainSync(node)
×
549

×
550
                return nil
×
551
        }
552
}
553

554
// RestartNode restarts a given node, unlocks it and asserts it's successfully
555
// started.
556
func (h *HarnessTest) RestartNode(hn *node.HarnessNode) {
×
557
        err := h.manager.restartNode(h.runCtx, hn, nil)
×
558
        require.NoErrorf(h, err, "failed to restart node %s", hn.Name())
×
559

×
560
        err = h.manager.unlockNode(hn)
×
561
        require.NoErrorf(h, err, "failed to unlock node %s", hn.Name())
×
562

×
563
        if !hn.Cfg.SkipUnlock {
×
564
                // Give the node some time to catch up with the chain before we
×
565
                // continue with the tests.
×
566
                h.WaitForBlockchainSync(hn)
×
567
        }
×
568
}
569

570
// RestartNodeNoUnlock restarts a given node without unlocking its wallet.
571
func (h *HarnessTest) RestartNodeNoUnlock(hn *node.HarnessNode) {
×
572
        err := h.manager.restartNode(h.runCtx, hn, nil)
×
573
        require.NoErrorf(h, err, "failed to restart node %s", hn.Name())
×
574
}
×
575

576
// RestartNodeWithChanBackups restarts a given node with the specified channel
577
// backups.
578
func (h *HarnessTest) RestartNodeWithChanBackups(hn *node.HarnessNode,
579
        chanBackups ...*lnrpc.ChanBackupSnapshot) {
×
580

×
581
        err := h.manager.restartNode(h.runCtx, hn, nil)
×
582
        require.NoErrorf(h, err, "failed to restart node %s", hn.Name())
×
583

×
584
        err = h.manager.unlockNode(hn, chanBackups...)
×
585
        require.NoErrorf(h, err, "failed to unlock node %s", hn.Name())
×
586

×
587
        // Give the node some time to catch up with the chain before we
×
588
        // continue with the tests.
×
589
        h.WaitForBlockchainSync(hn)
×
590
}
×
591

592
// RestartNodeWithExtraArgs updates the node's config and restarts it.
593
func (h *HarnessTest) RestartNodeWithExtraArgs(hn *node.HarnessNode,
594
        extraArgs []string) {
×
595

×
596
        hn.SetExtraArgs(extraArgs)
×
597
        h.RestartNode(hn)
×
598
}
×
599

600
// NewNodeWithSeed fully initializes a new HarnessNode after creating a fresh
601
// aezeed. The provided password is used as both the aezeed password and the
602
// wallet password. The generated mnemonic is returned along with the
603
// initialized harness node.
604
func (h *HarnessTest) NewNodeWithSeed(name string,
605
        extraArgs []string, password []byte,
606
        statelessInit bool) (*node.HarnessNode, []string, []byte) {
×
607

×
608
        // Create a request to generate a new aezeed. The new seed will have
×
609
        // the same password as the internal wallet.
×
610
        req := &lnrpc.GenSeedRequest{
×
611
                AezeedPassphrase: password,
×
612
                SeedEntropy:      nil,
×
613
        }
×
614

×
615
        return h.newNodeWithSeed(name, extraArgs, req, statelessInit)
×
616
}
×
617

618
// newNodeWithSeed creates and initializes a new HarnessNode such that it'll be
619
// ready to accept RPC calls. A `GenSeedRequest` is needed to generate the
620
// seed.
621
func (h *HarnessTest) newNodeWithSeed(name string,
622
        extraArgs []string, req *lnrpc.GenSeedRequest,
623
        statelessInit bool) (*node.HarnessNode, []string, []byte) {
×
624

×
625
        node, err := h.manager.newNode(
×
626
                h.T, name, extraArgs, req.AezeedPassphrase, true,
×
627
        )
×
628
        require.NoErrorf(h, err, "unable to create new node for %s", name)
×
629

×
630
        // Start the node with seed only, which will only create the `State`
×
631
        // and `WalletUnlocker` clients.
×
632
        err = node.StartWithNoAuth(h.runCtx)
×
633
        require.NoErrorf(h, err, "failed to start node %s", node.Name())
×
634

×
635
        // Generate a new seed.
×
636
        genSeedResp := node.RPC.GenSeed(req)
×
637

×
638
        // With the seed created, construct the init request to the node,
×
639
        // including the newly generated seed.
×
640
        initReq := &lnrpc.InitWalletRequest{
×
641
                WalletPassword:     req.AezeedPassphrase,
×
642
                CipherSeedMnemonic: genSeedResp.CipherSeedMnemonic,
×
643
                AezeedPassphrase:   req.AezeedPassphrase,
×
644
                StatelessInit:      statelessInit,
×
645
        }
×
646

×
647
        // Pass the init request via rpc to finish unlocking the node. This
×
648
        // will also initialize the macaroon-authenticated LightningClient.
×
649
        adminMac, err := h.manager.initWalletAndNode(node, initReq)
×
650
        require.NoErrorf(h, err, "failed to unlock and init node %s",
×
651
                node.Name())
×
652

×
653
        // In stateless initialization mode we get a macaroon back that we have
×
654
        // to return to the test, otherwise gRPC calls won't be possible since
×
655
        // there are no macaroon files created in that mode.
×
656
        // In stateful init the admin macaroon will just be nil.
×
657
        return node, genSeedResp.CipherSeedMnemonic, adminMac
×
658
}
×
659

660
// RestoreNodeWithSeed fully initializes a HarnessNode using a chosen mnemonic,
661
// password, recovery window, and optionally a set of static channel backups.
662
// After providing the initialization request to unlock the node, this method
663
// will finish initializing the LightningClient such that the HarnessNode can
664
// be used for regular rpc operations.
665
func (h *HarnessTest) RestoreNodeWithSeed(name string, extraArgs []string,
666
        password []byte, mnemonic []string, rootKey string,
667
        recoveryWindow int32,
668
        chanBackups *lnrpc.ChanBackupSnapshot) *node.HarnessNode {
×
669

×
670
        n, err := h.manager.newNode(h.T, name, extraArgs, password, true)
×
671
        require.NoErrorf(h, err, "unable to create new node for %s", name)
×
672

×
673
        // Start the node with seed only, which will only create the `State`
×
674
        // and `WalletUnlocker` clients.
×
675
        err = n.StartWithNoAuth(h.runCtx)
×
676
        require.NoErrorf(h, err, "failed to start node %s", n.Name())
×
677

×
678
        // Create the wallet.
×
679
        initReq := &lnrpc.InitWalletRequest{
×
680
                WalletPassword:     password,
×
681
                CipherSeedMnemonic: mnemonic,
×
682
                AezeedPassphrase:   password,
×
683
                ExtendedMasterKey:  rootKey,
×
684
                RecoveryWindow:     recoveryWindow,
×
685
                ChannelBackups:     chanBackups,
×
686
        }
×
687
        _, err = h.manager.initWalletAndNode(n, initReq)
×
688
        require.NoErrorf(h, err, "failed to unlock and init node %s",
×
689
                n.Name())
×
690

×
691
        return n
×
692
}
×
693

694
// NewNodeEtcd starts a new node with seed that'll use an external etcd
695
// database as its storage. The passed cluster flag indicates that we'd like
696
// the node to join the cluster leader election. We won't wait until RPC is
697
// available (this is useful when the node is not expected to become the leader
698
// right away).
699
func (h *HarnessTest) NewNodeEtcd(name string, etcdCfg *etcd.Config,
700
        password []byte, cluster bool,
701
        leaderSessionTTL int) *node.HarnessNode {
×
702

×
703
        // We don't want to use the embedded etcd instance.
×
704
        h.manager.dbBackend = node.BackendBbolt
×
705

×
706
        extraArgs := node.ExtraArgsEtcd(
×
707
                etcdCfg, name, cluster, leaderSessionTTL,
×
708
        )
×
709
        node, err := h.manager.newNode(h.T, name, extraArgs, password, true)
×
710
        require.NoError(h, err, "failed to create new node with etcd")
×
711

×
712
        // Start the node daemon only.
×
713
        err = node.StartLndCmd(h.runCtx)
×
714
        require.NoError(h, err, "failed to start node %s", node.Name())
×
715

×
716
        return node
×
717
}
×
718

719
// NewNodeWithSeedEtcd starts a new node with seed that'll use an external etcd
720
// database as its storage. The passed cluster flag indicates that we'd like
721
// the node to join the cluster leader election.
722
func (h *HarnessTest) NewNodeWithSeedEtcd(name string, etcdCfg *etcd.Config,
723
        password []byte, statelessInit, cluster bool,
724
        leaderSessionTTL int) (*node.HarnessNode, []string, []byte) {
×
725

×
726
        // We don't want to use the embedded etcd instance.
×
727
        h.manager.dbBackend = node.BackendBbolt
×
728

×
729
        // Create a request to generate a new aezeed. The new seed will have
×
730
        // the same password as the internal wallet.
×
731
        req := &lnrpc.GenSeedRequest{
×
732
                AezeedPassphrase: password,
×
733
                SeedEntropy:      nil,
×
734
        }
×
735

×
736
        extraArgs := node.ExtraArgsEtcd(
×
737
                etcdCfg, name, cluster, leaderSessionTTL,
×
738
        )
×
739

×
740
        return h.newNodeWithSeed(name, extraArgs, req, statelessInit)
×
741
}
×
742

743
// NewNodeRemoteSigner creates a new remote signer node and asserts its
744
// creation.
745
func (h *HarnessTest) NewNodeRemoteSigner(name string, extraArgs []string,
746
        password []byte, watchOnly *lnrpc.WatchOnly) *node.HarnessNode {
×
747

×
748
        hn, err := h.manager.newNode(h.T, name, extraArgs, password, true)
×
749
        require.NoErrorf(h, err, "unable to create new node for %s", name)
×
750

×
751
        err = hn.StartWithNoAuth(h.runCtx)
×
752
        require.NoError(h, err, "failed to start node %s", name)
×
753

×
754
        // With the seed created, construct the init request to the node,
×
755
        // including the newly generated seed.
×
756
        initReq := &lnrpc.InitWalletRequest{
×
757
                WalletPassword: password,
×
758
                WatchOnly:      watchOnly,
×
759
        }
×
760

×
761
        // Pass the init request via rpc to finish unlocking the node. This
×
762
        // will also initialize the macaroon-authenticated LightningClient.
×
763
        _, err = h.manager.initWalletAndNode(hn, initReq)
×
764
        require.NoErrorf(h, err, "failed to init node %s", name)
×
765

×
766
        return hn
×
767
}
×
768

769
// KillNode kills the node and waits for the node process to stop.
770
func (h *HarnessTest) KillNode(hn *node.HarnessNode) {
×
771
        delete(h.manager.activeNodes, hn.Cfg.NodeID)
×
772

×
773
        h.Logf("Manually killing the node %s", hn.Name())
×
774
        require.NoErrorf(h, hn.KillAndWait(), "%s: kill got error", hn.Name())
×
775
}
×
776

777
// SetFeeEstimate sets a fee rate to be returned from fee estimator.
778
//
779
// NOTE: this method will set the fee rate for a conf target of 1, which is the
780
// fallback fee rate for a `WebAPIEstimator` if a higher conf target's fee rate
781
// is not set. This means if the fee rate for conf target 6 is set, the fee
782
// estimator will use that value instead.
783
func (h *HarnessTest) SetFeeEstimate(fee chainfee.SatPerKWeight) {
×
784
        h.feeService.SetFeeRate(fee, 1)
×
785
}
×
786

787
// SetFeeEstimateWithConf sets a fee rate of a specified conf target to be
788
// returned from fee estimator.
789
func (h *HarnessTest) SetFeeEstimateWithConf(
790
        fee chainfee.SatPerKWeight, conf uint32) {
×
791

×
792
        h.feeService.SetFeeRate(fee, conf)
×
793
}
×
794

795
// SetMinRelayFeerate sets a min relay fee rate to be returned from fee
796
// estimator.
797
func (h *HarnessTest) SetMinRelayFeerate(fee chainfee.SatPerKVByte) {
×
798
        h.feeService.SetMinRelayFeerate(fee)
×
799
}
×
800

801
// validateNodeState checks that the node doesn't have any uncleaned states
802
// which will affect its following tests.
803
func (h *HarnessTest) validateNodeState(hn *node.HarnessNode) error {
×
804
        errStr := func(subject string) error {
×
805
                return fmt.Errorf("%s: found %s channels, please close "+
×
806
                        "them properly", hn.Name(), subject)
×
807
        }
×
808
        // If the node still has open channels, it's most likely that the
809
        // current test didn't close it properly.
810
        if hn.State.OpenChannel.Active != 0 {
×
811
                return errStr("active")
×
812
        }
×
813
        if hn.State.OpenChannel.Public != 0 {
×
814
                return errStr("public")
×
815
        }
×
816
        if hn.State.OpenChannel.Private != 0 {
×
817
                return errStr("private")
×
818
        }
×
819
        if hn.State.OpenChannel.Pending != 0 {
×
820
                return errStr("pending open")
×
821
        }
×
822

823
        // The number of pending force close channels should be zero.
824
        if hn.State.CloseChannel.PendingForceClose != 0 {
×
825
                return errStr("pending force")
×
826
        }
×
827

828
        // The number of waiting close channels should be zero.
829
        if hn.State.CloseChannel.WaitingClose != 0 {
×
830
                return errStr("waiting close")
×
831
        }
×
832

833
        // Ths number of payments should be zero.
834
        if hn.State.Payment.Total != 0 {
×
835
                return fmt.Errorf("%s: found uncleaned payments, please "+
×
836
                        "delete all of them properly", hn.Name())
×
837
        }
×
838

839
        // The number of public edges should be zero.
840
        if hn.State.Edge.Public != 0 {
×
841
                return fmt.Errorf("%s: found active public egdes, please "+
×
842
                        "clean them properly", hn.Name())
×
843
        }
×
844

845
        // The number of edges should be zero.
846
        if hn.State.Edge.Total != 0 {
×
847
                return fmt.Errorf("%s: found active edges, please "+
×
848
                        "clean them properly", hn.Name())
×
849
        }
×
850

851
        return nil
×
852
}
853

854
// GetChanPointFundingTxid takes a channel point and converts it into a chain
855
// hash.
856
func (h *HarnessTest) GetChanPointFundingTxid(
857
        cp *lnrpc.ChannelPoint) chainhash.Hash {
×
858

×
859
        txid, err := lnrpc.GetChanPointFundingTxid(cp)
×
860
        require.NoError(h, err, "unable to get txid")
×
861

×
862
        return *txid
×
863
}
×
864

865
// OutPointFromChannelPoint creates an outpoint from a given channel point.
866
func (h *HarnessTest) OutPointFromChannelPoint(
867
        cp *lnrpc.ChannelPoint) wire.OutPoint {
×
868

×
869
        txid := h.GetChanPointFundingTxid(cp)
×
870
        return wire.OutPoint{
×
871
                Hash:  txid,
×
872
                Index: cp.OutputIndex,
×
873
        }
×
874
}
×
875

876
// OpenChannelParams houses the params to specify when opening a new channel.
877
type OpenChannelParams struct {
878
        // Amt is the local amount being put into the channel.
879
        Amt btcutil.Amount
880

881
        // PushAmt is the amount that should be pushed to the remote when the
882
        // channel is opened.
883
        PushAmt btcutil.Amount
884

885
        // Private is a boolan indicating whether the opened channel should be
886
        // private.
887
        Private bool
888

889
        // SpendUnconfirmed is a boolean indicating whether we can utilize
890
        // unconfirmed outputs to fund the channel.
891
        SpendUnconfirmed bool
892

893
        // MinHtlc is the htlc_minimum_msat value set when opening the channel.
894
        MinHtlc lnwire.MilliSatoshi
895

896
        // RemoteMaxHtlcs is the remote_max_htlcs value set when opening the
897
        // channel, restricting the number of concurrent HTLCs the remote party
898
        // can add to a commitment.
899
        RemoteMaxHtlcs uint16
900

901
        // FundingShim is an optional funding shim that the caller can specify
902
        // in order to modify the channel funding workflow.
903
        FundingShim *lnrpc.FundingShim
904

905
        // SatPerVByte is the amount of satoshis to spend in chain fees per
906
        // virtual byte of the transaction.
907
        SatPerVByte btcutil.Amount
908

909
        // ConfTarget is the number of blocks that the funding transaction
910
        // should be confirmed in.
911
        ConfTarget fn.Option[int32]
912

913
        // CommitmentType is the commitment type that should be used for the
914
        // channel to be opened.
915
        CommitmentType lnrpc.CommitmentType
916

917
        // ZeroConf is used to determine if the channel will be a zero-conf
918
        // channel. This only works if the explicit negotiation is used with
919
        // anchors or script enforced leases.
920
        ZeroConf bool
921

922
        // ScidAlias denotes whether the channel will be an option-scid-alias
923
        // channel type negotiation.
924
        ScidAlias bool
925

926
        // BaseFee is the channel base fee applied during the channel
927
        // announcement phase.
928
        BaseFee uint64
929

930
        // FeeRate is the channel fee rate in ppm applied during the channel
931
        // announcement phase.
932
        FeeRate uint64
933

934
        // UseBaseFee, if set, instructs the downstream logic to apply the
935
        // user-specified channel base fee to the channel update announcement.
936
        // If set to false it avoids applying a base fee of 0 and instead
937
        // activates the default configured base fee.
938
        UseBaseFee bool
939

940
        // UseFeeRate, if set, instructs the downstream logic to apply the
941
        // user-specified channel fee rate to the channel update announcement.
942
        // If set to false it avoids applying a fee rate of 0 and instead
943
        // activates the default configured fee rate.
944
        UseFeeRate bool
945

946
        // FundMax is a boolean indicating whether the channel should be funded
947
        // with the maximum possible amount from the wallet.
948
        FundMax bool
949

950
        // An optional note-to-self containing some useful information about the
951
        // channel. This is stored locally only, and is purely for reference. It
952
        // has no bearing on the channel's operation. Max allowed length is 500
953
        // characters.
954
        Memo string
955

956
        // Outpoints is a list of client-selected outpoints that should be used
957
        // for funding a channel. If Amt is specified then this amount is
958
        // allocated from the sum of outpoints towards funding. If the
959
        // FundMax flag is specified the entirety of selected funds is
960
        // allocated towards channel funding.
961
        Outpoints []*lnrpc.OutPoint
962

963
        // CloseAddress sets the upfront_shutdown_script parameter during
964
        // channel open. It is expected to be encoded as a bitcoin address.
965
        CloseAddress string
966
}
967

968
// prepareOpenChannel waits for both nodes to be synced to chain and returns an
969
// OpenChannelRequest.
970
func (h *HarnessTest) prepareOpenChannel(srcNode, destNode *node.HarnessNode,
971
        p OpenChannelParams) *lnrpc.OpenChannelRequest {
×
972

×
973
        // Wait until srcNode and destNode have the latest chain synced.
×
974
        // Otherwise, we may run into a check within the funding manager that
×
975
        // prevents any funding workflows from being kicked off if the chain
×
976
        // isn't yet synced.
×
977
        h.WaitForBlockchainSync(srcNode)
×
978
        h.WaitForBlockchainSync(destNode)
×
979

×
980
        // Specify the minimal confirmations of the UTXOs used for channel
×
981
        // funding.
×
982
        minConfs := int32(1)
×
983
        if p.SpendUnconfirmed {
×
984
                minConfs = 0
×
985
        }
×
986

987
        // Get the requested conf target. If not set, default to 6.
988
        confTarget := p.ConfTarget.UnwrapOr(6)
×
989

×
990
        // If there's fee rate set, unset the conf target.
×
991
        if p.SatPerVByte != 0 {
×
992
                confTarget = 0
×
993
        }
×
994

995
        // Prepare the request.
996
        return &lnrpc.OpenChannelRequest{
×
997
                NodePubkey:         destNode.PubKey[:],
×
998
                LocalFundingAmount: int64(p.Amt),
×
999
                PushSat:            int64(p.PushAmt),
×
1000
                Private:            p.Private,
×
1001
                TargetConf:         confTarget,
×
1002
                MinConfs:           minConfs,
×
1003
                SpendUnconfirmed:   p.SpendUnconfirmed,
×
1004
                MinHtlcMsat:        int64(p.MinHtlc),
×
1005
                RemoteMaxHtlcs:     uint32(p.RemoteMaxHtlcs),
×
1006
                FundingShim:        p.FundingShim,
×
1007
                SatPerVbyte:        uint64(p.SatPerVByte),
×
1008
                CommitmentType:     p.CommitmentType,
×
1009
                ZeroConf:           p.ZeroConf,
×
1010
                ScidAlias:          p.ScidAlias,
×
1011
                BaseFee:            p.BaseFee,
×
1012
                FeeRate:            p.FeeRate,
×
1013
                UseBaseFee:         p.UseBaseFee,
×
1014
                UseFeeRate:         p.UseFeeRate,
×
1015
                FundMax:            p.FundMax,
×
1016
                Memo:               p.Memo,
×
1017
                Outpoints:          p.Outpoints,
×
1018
                CloseAddress:       p.CloseAddress,
×
1019
        }
×
1020
}
1021

1022
// OpenChannelAssertPending attempts to open a channel between srcNode and
1023
// destNode with the passed channel funding parameters. Once the `OpenChannel`
1024
// is called, it will consume the first event it receives from the open channel
1025
// client and asserts it's a channel pending event.
1026
func (h *HarnessTest) openChannelAssertPending(srcNode,
1027
        destNode *node.HarnessNode,
1028
        p OpenChannelParams) (*lnrpc.PendingUpdate, rpc.OpenChanClient) {
×
1029

×
1030
        // Prepare the request and open the channel.
×
1031
        openReq := h.prepareOpenChannel(srcNode, destNode, p)
×
1032
        respStream := srcNode.RPC.OpenChannel(openReq)
×
1033

×
1034
        // Consume the "channel pending" update. This waits until the node
×
1035
        // notifies us that the final message in the channel funding workflow
×
1036
        // has been sent to the remote node.
×
1037
        resp := h.ReceiveOpenChannelUpdate(respStream)
×
1038

×
1039
        // Check that the update is channel pending.
×
1040
        update, ok := resp.Update.(*lnrpc.OpenStatusUpdate_ChanPending)
×
1041
        require.Truef(h, ok, "expected channel pending: update, instead got %v",
×
1042
                resp)
×
1043

×
1044
        return update.ChanPending, respStream
×
1045
}
×
1046

1047
// OpenChannelAssertPending attempts to open a channel between srcNode and
1048
// destNode with the passed channel funding parameters. Once the `OpenChannel`
1049
// is called, it will consume the first event it receives from the open channel
1050
// client and asserts it's a channel pending event. It returns the
1051
// `PendingUpdate`.
1052
func (h *HarnessTest) OpenChannelAssertPending(srcNode,
1053
        destNode *node.HarnessNode, p OpenChannelParams) *lnrpc.PendingUpdate {
×
1054

×
1055
        resp, _ := h.openChannelAssertPending(srcNode, destNode, p)
×
1056
        return resp
×
1057
}
×
1058

1059
// OpenChannelAssertStream attempts to open a channel between srcNode and
1060
// destNode with the passed channel funding parameters. Once the `OpenChannel`
1061
// is called, it will consume the first event it receives from the open channel
1062
// client and asserts it's a channel pending event. It returns the open channel
1063
// stream.
1064
func (h *HarnessTest) OpenChannelAssertStream(srcNode,
1065
        destNode *node.HarnessNode, p OpenChannelParams) rpc.OpenChanClient {
×
1066

×
1067
        _, stream := h.openChannelAssertPending(srcNode, destNode, p)
×
1068
        return stream
×
1069
}
×
1070

1071
// OpenChannel attempts to open a channel with the specified parameters
1072
// extended from Alice to Bob. Additionally, for public channels, it will mine
1073
// extra blocks so they are announced to the network. In specific, the
1074
// following items are asserted,
1075
//   - for non-zero conf channel, 1 blocks will be mined to confirm the funding
1076
//     tx.
1077
//   - both nodes should see the channel edge update in their network graph.
1078
//   - both nodes can report the status of the new channel from ListChannels.
1079
//   - extra blocks are mined if it's a public channel.
1080
func (h *HarnessTest) OpenChannel(alice, bob *node.HarnessNode,
1081
        p OpenChannelParams) *lnrpc.ChannelPoint {
×
1082

×
1083
        // First, open the channel without announcing it.
×
1084
        cp := h.OpenChannelNoAnnounce(alice, bob, p)
×
1085

×
1086
        // If this is a private channel, there's no need to mine extra blocks
×
1087
        // since it will never be announced to the network.
×
1088
        if p.Private {
×
1089
                return cp
×
1090
        }
×
1091

1092
        // Mine extra blocks to announce the channel.
1093
        if p.ZeroConf {
×
1094
                // For a zero-conf channel, no blocks have been mined so we
×
1095
                // need to mine 6 blocks.
×
1096
                //
×
1097
                // Mine 1 block to confirm the funding transaction.
×
1098
                h.MineBlocksAndAssertNumTxes(numBlocksOpenChannel, 1)
×
1099
        } else {
×
1100
                // For a regular channel, 1 block has already been mined to
×
1101
                // confirm the funding transaction, so we mine 5 blocks.
×
1102
                h.MineBlocks(numBlocksOpenChannel - 1)
×
1103
        }
×
1104

1105
        return cp
×
1106
}
1107

1108
// OpenChannelNoAnnounce attempts to open a channel with the specified
1109
// parameters extended from Alice to Bob without mining the necessary blocks to
1110
// announce the channel. Additionally, the following items are asserted,
1111
//   - for non-zero conf channel, 1 blocks will be mined to confirm the funding
1112
//     tx.
1113
//   - both nodes should see the channel edge update in their network graph.
1114
//   - both nodes can report the status of the new channel from ListChannels.
1115
func (h *HarnessTest) OpenChannelNoAnnounce(alice, bob *node.HarnessNode,
1116
        p OpenChannelParams) *lnrpc.ChannelPoint {
×
1117

×
1118
        chanOpenUpdate := h.OpenChannelAssertStream(alice, bob, p)
×
1119

×
1120
        // Open a zero conf channel.
×
1121
        if p.ZeroConf {
×
1122
                return h.openChannelZeroConf(alice, bob, chanOpenUpdate)
×
1123
        }
×
1124

1125
        // Open a non-zero conf channel.
1126
        return h.openChannel(alice, bob, chanOpenUpdate)
×
1127
}
1128

1129
// openChannel attempts to open a channel with the specified parameters
1130
// extended from Alice to Bob. Additionally, the following items are asserted,
1131
//   - 1 block is mined and the funding transaction should be found in it.
1132
//   - both nodes should see the channel edge update in their network graph.
1133
//   - both nodes can report the status of the new channel from ListChannels.
1134
func (h *HarnessTest) openChannel(alice, bob *node.HarnessNode,
1135
        stream rpc.OpenChanClient) *lnrpc.ChannelPoint {
×
1136

×
1137
        // Mine 1 block to confirm the funding transaction.
×
1138
        block := h.MineBlocksAndAssertNumTxes(1, 1)[0]
×
1139

×
1140
        // Wait for the channel open event.
×
1141
        fundingChanPoint := h.WaitForChannelOpenEvent(stream)
×
1142

×
1143
        // Check that the funding tx is found in the first block.
×
1144
        fundingTxID := h.GetChanPointFundingTxid(fundingChanPoint)
×
1145
        h.AssertTxInBlock(block, fundingTxID)
×
1146

×
1147
        // Check that both alice and bob have seen the channel from their
×
1148
        // network topology.
×
1149
        h.AssertChannelInGraph(alice, fundingChanPoint)
×
1150
        h.AssertChannelInGraph(bob, fundingChanPoint)
×
1151

×
1152
        // Check that the channel can be seen in their ListChannels.
×
1153
        h.AssertChannelExists(alice, fundingChanPoint)
×
1154
        h.AssertChannelExists(bob, fundingChanPoint)
×
1155

×
1156
        return fundingChanPoint
×
1157
}
×
1158

1159
// openChannelZeroConf attempts to open a channel with the specified parameters
1160
// extended from Alice to Bob. Additionally, the following items are asserted,
1161
//   - both nodes should see the channel edge update in their network graph.
1162
//   - both nodes can report the status of the new channel from ListChannels.
1163
func (h *HarnessTest) openChannelZeroConf(alice, bob *node.HarnessNode,
1164
        stream rpc.OpenChanClient) *lnrpc.ChannelPoint {
×
1165

×
1166
        // Wait for the channel open event.
×
1167
        fundingChanPoint := h.WaitForChannelOpenEvent(stream)
×
1168

×
1169
        // Check that both alice and bob have seen the channel from their
×
1170
        // network topology.
×
1171
        h.AssertChannelInGraph(alice, fundingChanPoint)
×
1172
        h.AssertChannelInGraph(bob, fundingChanPoint)
×
1173

×
1174
        // Finally, check that the channel can be seen in their ListChannels.
×
1175
        h.AssertChannelExists(alice, fundingChanPoint)
×
1176
        h.AssertChannelExists(bob, fundingChanPoint)
×
1177

×
1178
        return fundingChanPoint
×
1179
}
×
1180

1181
// OpenChannelAssertErr opens a channel between node srcNode and destNode,
1182
// asserts that the expected error is returned from the channel opening.
1183
func (h *HarnessTest) OpenChannelAssertErr(srcNode, destNode *node.HarnessNode,
1184
        p OpenChannelParams, expectedErr error) {
×
1185

×
1186
        // Prepare the request and open the channel.
×
1187
        openReq := h.prepareOpenChannel(srcNode, destNode, p)
×
1188
        respStream := srcNode.RPC.OpenChannel(openReq)
×
1189

×
1190
        // Receive an error to be sent from the stream.
×
1191
        _, err := h.receiveOpenChannelUpdate(respStream)
×
1192
        require.NotNil(h, err, "expected channel opening to fail")
×
1193

×
1194
        // Use string comparison here as we haven't codified all the RPC errors
×
1195
        // yet.
×
1196
        require.Containsf(h, err.Error(), expectedErr.Error(), "unexpected "+
×
1197
                "error returned, want %v, got %v", expectedErr, err)
×
1198
}
×
1199

1200
// closeChannelOpts holds the options for closing a channel.
1201
type closeChannelOpts struct {
1202
        feeRate fn.Option[chainfee.SatPerVByte]
1203

1204
        // localTxOnly is a boolean indicating if we should only attempt to
1205
        // consume close pending notifications for the local transaction.
1206
        localTxOnly bool
1207

1208
        // skipMempoolCheck is a boolean indicating if we should skip the normal
1209
        // mempool check after a coop close.
1210
        skipMempoolCheck bool
1211

1212
        // errString is an expected error. If this is non-blank, then we'll
1213
        // assert that the coop close wasn't possible, and returns an error that
1214
        // contains this err string.
1215
        errString string
1216
}
1217

1218
// CloseChanOpt is a functional option to modify the way we close a channel.
1219
type CloseChanOpt func(*closeChannelOpts)
1220

1221
// WithCoopCloseFeeRate is a functional option to set the fee rate for a coop
1222
// close attempt.
NEW
1223
func WithCoopCloseFeeRate(rate chainfee.SatPerVByte) CloseChanOpt {
×
NEW
1224
        return func(o *closeChannelOpts) {
×
NEW
1225
                o.feeRate = fn.Some(rate)
×
NEW
1226
        }
×
1227
}
1228

1229
// WithLocalTxNotify is a functional option to indicate that we should only
1230
// notify for the local txn. This is useful for the RBF coop close type, as
1231
// it'll notify for both local and remote txns.
NEW
1232
func WithLocalTxNotify() CloseChanOpt {
×
NEW
1233
        return func(o *closeChannelOpts) {
×
NEW
1234
                o.localTxOnly = true
×
NEW
1235
        }
×
1236
}
1237

1238
// WithSkipMempoolCheck is a functional option to indicate that we should skip
1239
// the mempool check. This can be used when a coop close iteration may not
1240
// result in a newly broadcast transaction.
NEW
1241
func WithSkipMempoolCheck() CloseChanOpt {
×
NEW
1242
        return func(o *closeChannelOpts) {
×
NEW
1243
                o.skipMempoolCheck = true
×
NEW
1244
        }
×
1245
}
1246

1247
// WithExpectedErrString is a functional option that can be used to assert that
1248
// an error occurs during the coop close process.
NEW
1249
func WithExpectedErrString(errString string) CloseChanOpt {
×
NEW
1250
        return func(o *closeChannelOpts) {
×
NEW
1251
                o.errString = errString
×
NEW
1252
        }
×
1253
}
1254

1255
// defaultCloseOpts returns the set of default close options.
NEW
1256
func defaultCloseOpts() *closeChannelOpts {
×
NEW
1257
        return &closeChannelOpts{}
×
NEW
1258
}
×
1259

1260
// CloseChannelAssertPending attempts to close the channel indicated by the
1261
// passed channel point, initiated by the passed node. Once the CloseChannel
1262
// rpc is called, it will consume one event and assert it's a close pending
1263
// event. In addition, it will check that the closing tx can be found in the
1264
// mempool.
1265
func (h *HarnessTest) CloseChannelAssertPending(hn *node.HarnessNode,
1266
        cp *lnrpc.ChannelPoint, force bool,
NEW
1267
        opts ...CloseChanOpt) (rpc.CloseChanClient, *lnrpc.CloseStatusUpdate) {
×
NEW
1268

×
NEW
1269
        closeOpts := defaultCloseOpts()
×
NEW
1270
        for _, optFunc := range opts {
×
NEW
1271
                optFunc(closeOpts)
×
NEW
1272
        }
×
1273

1274
        // Calls the rpc to close the channel.
1275
        closeReq := &lnrpc.CloseChannelRequest{
×
1276
                ChannelPoint: cp,
×
1277
                Force:        force,
×
1278
                NoWait:       true,
×
1279
        }
×
1280

×
NEW
1281
        closeOpts.feeRate.WhenSome(func(feeRate chainfee.SatPerVByte) {
×
NEW
1282
                closeReq.SatPerVbyte = uint64(feeRate)
×
NEW
1283
        })
×
1284

1285
        var (
×
1286
                stream rpc.CloseChanClient
×
1287
                event  *lnrpc.CloseStatusUpdate
×
1288
                err    error
×
1289
        )
×
1290

×
1291
        // Consume the "channel close" update in order to wait for the closing
×
1292
        // transaction to be broadcast, then wait for the closing tx to be seen
×
1293
        // within the network.
×
1294
        stream = hn.RPC.CloseChannel(closeReq)
×
1295
        _, err = h.ReceiveCloseChannelUpdate(stream)
×
1296
        require.NoError(h, err, "close channel update got error: %v", err)
×
1297

×
NEW
1298
        var closeTxid *chainhash.Hash
×
NEW
1299
        for {
×
NEW
1300
                event, err = h.ReceiveCloseChannelUpdate(stream)
×
NEW
1301
                if err != nil {
×
NEW
1302
                        h.Logf("Test: %s, close channel got error: %v",
×
NEW
1303
                                h.manager.currentTestCase, err)
×
NEW
1304
                }
×
NEW
1305
                if err != nil && closeOpts.errString == "" {
×
NEW
1306
                        require.NoError(h, err, "retry closing channel failed")
×
NEW
1307
                } else if err != nil && closeOpts.errString != "" {
×
NEW
1308
                        require.ErrorContains(h, err, closeOpts.errString)
×
NEW
1309
                        return nil, nil
×
NEW
1310
                }
×
1311

NEW
1312
                pendingClose, ok := event.Update.(*lnrpc.CloseStatusUpdate_ClosePending) //nolint:ll
×
NEW
1313
                require.Truef(h, ok, "expected channel close "+
×
NEW
1314
                        "update, instead got %v", pendingClose)
×
1315

×
NEW
1316
                if !pendingClose.ClosePending.LocalCloseTx &&
×
NEW
1317
                        closeOpts.localTxOnly {
×
1318

×
NEW
1319
                        continue
×
1320
                }
1321

NEW
1322
                closeTxid, err = chainhash.NewHash(
×
NEW
1323
                        pendingClose.ClosePending.Txid,
×
NEW
1324
                )
×
NEW
1325
                require.NoErrorf(h, err, "unable to decode closeTxid: %v",
×
NEW
1326
                        pendingClose.ClosePending.Txid)
×
NEW
1327

×
NEW
1328
                break
×
1329
        }
1330

NEW
1331
        if !closeOpts.skipMempoolCheck {
×
NEW
1332
                // Assert the closing tx is in the mempool.
×
NEW
1333
                h.miner.AssertTxInMempool(*closeTxid)
×
NEW
1334
        }
×
1335

NEW
1336
        return stream, event
×
1337
}
1338

1339
// CloseChannel attempts to coop close a non-anchored channel identified by the
1340
// passed channel point owned by the passed harness node. The following items
1341
// are asserted,
1342
//  1. a close pending event is sent from the close channel client.
1343
//  2. the closing tx is found in the mempool.
1344
//  3. the node reports the channel being waiting to close.
1345
//  4. a block is mined and the closing tx should be found in it.
1346
//  5. the node reports zero waiting close channels.
1347
//  6. the node receives a topology update regarding the channel close.
1348
func (h *HarnessTest) CloseChannel(hn *node.HarnessNode,
1349
        cp *lnrpc.ChannelPoint) chainhash.Hash {
×
1350

×
1351
        stream, _ := h.CloseChannelAssertPending(hn, cp, false)
×
1352

×
1353
        return h.AssertStreamChannelCoopClosed(hn, cp, false, stream)
×
1354
}
×
1355

1356
// ForceCloseChannel attempts to force close a non-anchored channel identified
1357
// by the passed channel point owned by the passed harness node. The following
1358
// items are asserted,
1359
//  1. a close pending event is sent from the close channel client.
1360
//  2. the closing tx is found in the mempool.
1361
//  3. the node reports the channel being waiting to close.
1362
//  4. a block is mined and the closing tx should be found in it.
1363
//  5. the node reports zero waiting close channels.
1364
//  6. the node receives a topology update regarding the channel close.
1365
//  7. mine DefaultCSV-1 blocks.
1366
//  8. the node reports zero pending force close channels.
1367
func (h *HarnessTest) ForceCloseChannel(hn *node.HarnessNode,
1368
        cp *lnrpc.ChannelPoint) chainhash.Hash {
×
1369

×
1370
        stream, _ := h.CloseChannelAssertPending(hn, cp, true)
×
1371

×
1372
        closingTxid := h.AssertStreamChannelForceClosed(hn, cp, false, stream)
×
1373

×
1374
        // Cleanup the force close.
×
1375
        h.CleanupForceClose(hn)
×
1376

×
1377
        return closingTxid
×
1378
}
×
1379

1380
// CloseChannelAssertErr closes the given channel and asserts an error
1381
// returned.
1382
func (h *HarnessTest) CloseChannelAssertErr(hn *node.HarnessNode,
1383
        req *lnrpc.CloseChannelRequest) error {
×
1384

×
1385
        // Calls the rpc to close the channel.
×
1386
        stream := hn.RPC.CloseChannel(req)
×
1387

×
1388
        // Consume the "channel close" update in order to wait for the closing
×
1389
        // transaction to be broadcast, then wait for the closing tx to be seen
×
1390
        // within the network.
×
1391
        _, err := h.ReceiveCloseChannelUpdate(stream)
×
1392
        require.Errorf(h, err, "%s: expect close channel to return an error",
×
1393
                hn.Name())
×
1394

×
1395
        return err
×
1396
}
×
1397

1398
// IsNeutrinoBackend returns a bool indicating whether the node is using a
1399
// neutrino as its backend. This is useful when we want to skip certain tests
1400
// which cannot be done with a neutrino backend.
1401
func (h *HarnessTest) IsNeutrinoBackend() bool {
×
1402
        return h.manager.chainBackend.Name() == NeutrinoBackendName
×
1403
}
×
1404

1405
// fundCoins attempts to send amt satoshis from the internal mining node to the
1406
// targeted lightning node. The confirmed boolean indicates whether the
1407
// transaction that pays to the target should confirm. For neutrino backend,
1408
// the `confirmed` param is ignored.
1409
func (h *HarnessTest) fundCoins(amt btcutil.Amount, target *node.HarnessNode,
1410
        addrType lnrpc.AddressType, confirmed bool) {
×
1411

×
1412
        initialBalance := target.RPC.WalletBalance()
×
1413

×
1414
        // First, obtain an address from the target lightning node, preferring
×
1415
        // to receive a p2wkh address s.t the output can immediately be used as
×
1416
        // an input to a funding transaction.
×
1417
        req := &lnrpc.NewAddressRequest{Type: addrType}
×
1418
        resp := target.RPC.NewAddress(req)
×
1419
        addr := h.DecodeAddress(resp.Address)
×
1420
        addrScript := h.PayToAddrScript(addr)
×
1421

×
1422
        // Generate a transaction which creates an output to the target
×
1423
        // pkScript of the desired amount.
×
1424
        output := &wire.TxOut{
×
1425
                PkScript: addrScript,
×
1426
                Value:    int64(amt),
×
1427
        }
×
1428
        h.miner.SendOutput(output, defaultMinerFeeRate)
×
1429

×
1430
        // Encode the pkScript in hex as this the format that it will be
×
1431
        // returned via rpc.
×
1432
        expPkScriptStr := hex.EncodeToString(addrScript)
×
1433

×
1434
        // Now, wait for ListUnspent to show the unconfirmed transaction
×
1435
        // containing the correct pkscript.
×
1436
        //
×
1437
        // Since neutrino doesn't support unconfirmed outputs, skip this check.
×
1438
        if !h.IsNeutrinoBackend() {
×
1439
                utxos := h.AssertNumUTXOsUnconfirmed(target, 1)
×
1440

×
1441
                // Assert that the lone unconfirmed utxo contains the same
×
1442
                // pkscript as the output generated above.
×
1443
                pkScriptStr := utxos[0].PkScript
×
1444
                require.Equal(h, pkScriptStr, expPkScriptStr,
×
1445
                        "pkscript mismatch")
×
1446

×
1447
                expectedBalance := btcutil.Amount(
×
1448
                        initialBalance.UnconfirmedBalance,
×
1449
                ) + amt
×
1450
                h.WaitForBalanceUnconfirmed(target, expectedBalance)
×
1451
        }
×
1452

1453
        // If the transaction should remain unconfirmed, then we'll wait until
1454
        // the target node's unconfirmed balance reflects the expected balance
1455
        // and exit.
1456
        if !confirmed {
×
1457
                return
×
1458
        }
×
1459

1460
        // Otherwise, we'll generate 1 new blocks to ensure the output gains a
1461
        // sufficient number of confirmations and wait for the balance to
1462
        // reflect what's expected.
1463
        h.MineBlocksAndAssertNumTxes(1, 1)
×
1464

×
1465
        expectedBalance := btcutil.Amount(initialBalance.ConfirmedBalance) + amt
×
1466
        h.WaitForBalanceConfirmed(target, expectedBalance)
×
1467
}
1468

1469
// FundCoins attempts to send amt satoshis from the internal mining node to the
1470
// targeted lightning node using a P2WKH address. 1 blocks are mined after in
1471
// order to confirm the transaction.
1472
func (h *HarnessTest) FundCoins(amt btcutil.Amount, hn *node.HarnessNode) {
×
1473
        h.fundCoins(amt, hn, lnrpc.AddressType_WITNESS_PUBKEY_HASH, true)
×
1474
}
×
1475

1476
// FundCoinsUnconfirmed attempts to send amt satoshis from the internal mining
1477
// node to the targeted lightning node using a P2WKH address. No blocks are
1478
// mined after and the UTXOs are unconfirmed.
1479
func (h *HarnessTest) FundCoinsUnconfirmed(amt btcutil.Amount,
1480
        hn *node.HarnessNode) {
×
1481

×
1482
        h.fundCoins(amt, hn, lnrpc.AddressType_WITNESS_PUBKEY_HASH, false)
×
1483
}
×
1484

1485
// FundCoinsNP2WKH attempts to send amt satoshis from the internal mining node
1486
// to the targeted lightning node using a NP2WKH address.
1487
func (h *HarnessTest) FundCoinsNP2WKH(amt btcutil.Amount,
1488
        target *node.HarnessNode) {
×
1489

×
1490
        h.fundCoins(amt, target, lnrpc.AddressType_NESTED_PUBKEY_HASH, true)
×
1491
}
×
1492

1493
// FundCoinsP2TR attempts to send amt satoshis from the internal mining node to
1494
// the targeted lightning node using a P2TR address.
1495
func (h *HarnessTest) FundCoinsP2TR(amt btcutil.Amount,
1496
        target *node.HarnessNode) {
×
1497

×
1498
        h.fundCoins(amt, target, lnrpc.AddressType_TAPROOT_PUBKEY, true)
×
1499
}
×
1500

1501
// FundNumCoins attempts to send the given number of UTXOs from the internal
1502
// mining node to the targeted lightning node using a P2WKH address. Each UTXO
1503
// has an amount of 1 BTC. 1 blocks are mined to confirm the tx.
1504
func (h *HarnessTest) FundNumCoins(hn *node.HarnessNode, num int) {
×
1505
        // Get the initial balance first.
×
1506
        resp := hn.RPC.WalletBalance()
×
1507
        initialBalance := btcutil.Amount(resp.ConfirmedBalance)
×
1508

×
1509
        const fundAmount = 1 * btcutil.SatoshiPerBitcoin
×
1510

×
1511
        // Send out the outputs from the miner.
×
1512
        for i := 0; i < num; i++ {
×
1513
                h.createAndSendOutput(
×
1514
                        hn, fundAmount, lnrpc.AddressType_WITNESS_PUBKEY_HASH,
×
1515
                )
×
1516
        }
×
1517

1518
        // Wait for ListUnspent to show the correct number of unconfirmed
1519
        // UTXOs.
1520
        //
1521
        // Since neutrino doesn't support unconfirmed outputs, skip this check.
1522
        if !h.IsNeutrinoBackend() {
×
1523
                h.AssertNumUTXOsUnconfirmed(hn, num)
×
1524
        }
×
1525

1526
        // Mine a block to confirm the transactions.
1527
        h.MineBlocksAndAssertNumTxes(1, num)
×
1528

×
1529
        // Now block until the wallet have fully synced up.
×
1530
        totalAmount := btcutil.Amount(fundAmount * num)
×
1531
        expectedBalance := initialBalance + totalAmount
×
1532
        h.WaitForBalanceConfirmed(hn, expectedBalance)
×
1533
}
1534

1535
// completePaymentRequestsAssertStatus sends payments from a node to complete
1536
// all payment requests. This function does not return until all payments
1537
// have reached the specified status.
1538
func (h *HarnessTest) completePaymentRequestsAssertStatus(hn *node.HarnessNode,
1539
        paymentRequests []string, status lnrpc.Payment_PaymentStatus,
1540
        opts ...HarnessOpt) {
×
1541

×
1542
        payOpts := defaultHarnessOpts()
×
1543
        for _, opt := range opts {
×
1544
                opt(&payOpts)
×
1545
        }
×
1546

1547
        // Create a buffered chan to signal the results.
1548
        results := make(chan rpc.PaymentClient, len(paymentRequests))
×
1549

×
1550
        // send sends a payment and asserts if it doesn't succeeded.
×
1551
        send := func(payReq string) {
×
1552
                req := &routerrpc.SendPaymentRequest{
×
1553
                        PaymentRequest: payReq,
×
1554
                        TimeoutSeconds: int32(wait.PaymentTimeout.Seconds()),
×
1555
                        FeeLimitMsat:   noFeeLimitMsat,
×
1556
                        Amp:            payOpts.useAMP,
×
1557
                }
×
1558
                stream := hn.RPC.SendPayment(req)
×
1559

×
1560
                // Signal sent succeeded.
×
1561
                results <- stream
×
1562
        }
×
1563

1564
        // Launch all payments simultaneously.
1565
        for _, payReq := range paymentRequests {
×
1566
                payReqCopy := payReq
×
1567
                go send(payReqCopy)
×
1568
        }
×
1569

1570
        // Wait for all payments to report the expected status.
1571
        timer := time.After(wait.PaymentTimeout)
×
1572
        select {
×
1573
        case stream := <-results:
×
1574
                h.AssertPaymentStatusFromStream(stream, status)
×
1575

1576
        case <-timer:
×
1577
                require.Fail(h, "timeout", "waiting payment results timeout")
×
1578
        }
1579
}
1580

1581
// CompletePaymentRequests sends payments from a node to complete all payment
1582
// requests. This function does not return until all payments successfully
1583
// complete without errors.
1584
func (h *HarnessTest) CompletePaymentRequests(hn *node.HarnessNode,
1585
        paymentRequests []string, opts ...HarnessOpt) {
×
1586

×
1587
        h.completePaymentRequestsAssertStatus(
×
1588
                hn, paymentRequests, lnrpc.Payment_SUCCEEDED, opts...,
×
1589
        )
×
1590
}
×
1591

1592
// CompletePaymentRequestsNoWait sends payments from a node to complete all
1593
// payment requests without waiting for the results. Instead, it checks the
1594
// number of updates in the specified channel has increased.
1595
func (h *HarnessTest) CompletePaymentRequestsNoWait(hn *node.HarnessNode,
1596
        paymentRequests []string, chanPoint *lnrpc.ChannelPoint) {
×
1597

×
1598
        // We start by getting the current state of the client's channels. This
×
1599
        // is needed to ensure the payments actually have been committed before
×
1600
        // we return.
×
1601
        oldResp := h.GetChannelByChanPoint(hn, chanPoint)
×
1602

×
1603
        // Send payments and assert they are in-flight.
×
1604
        h.completePaymentRequestsAssertStatus(
×
1605
                hn, paymentRequests, lnrpc.Payment_IN_FLIGHT,
×
1606
        )
×
1607

×
1608
        // We are not waiting for feedback in the form of a response, but we
×
1609
        // should still wait long enough for the server to receive and handle
×
1610
        // the send before cancelling the request. We wait for the number of
×
1611
        // updates to one of our channels has increased before we return.
×
1612
        err := wait.NoError(func() error {
×
1613
                newResp := h.GetChannelByChanPoint(hn, chanPoint)
×
1614

×
1615
                // If this channel has an increased number of updates, we
×
1616
                // assume the payments are committed, and we can return.
×
1617
                if newResp.NumUpdates > oldResp.NumUpdates {
×
1618
                        return nil
×
1619
                }
×
1620

1621
                // Otherwise return an error as the NumUpdates are not
1622
                // increased.
1623
                return fmt.Errorf("%s: channel:%v not updated after sending "+
×
1624
                        "payments, old updates: %v, new updates: %v", hn.Name(),
×
1625
                        chanPoint, oldResp.NumUpdates, newResp.NumUpdates)
×
1626
        }, DefaultTimeout)
1627
        require.NoError(h, err, "timeout while checking for channel updates")
×
1628
}
1629

1630
// OpenChannelPsbt attempts to open a channel between srcNode and destNode with
1631
// the passed channel funding parameters. It will assert if the expected step
1632
// of funding the PSBT is not received from the source node.
1633
func (h *HarnessTest) OpenChannelPsbt(srcNode, destNode *node.HarnessNode,
1634
        p OpenChannelParams) (rpc.OpenChanClient, []byte) {
×
1635

×
1636
        // Wait until srcNode and destNode have the latest chain synced.
×
1637
        // Otherwise, we may run into a check within the funding manager that
×
1638
        // prevents any funding workflows from being kicked off if the chain
×
1639
        // isn't yet synced.
×
1640
        h.WaitForBlockchainSync(srcNode)
×
1641
        h.WaitForBlockchainSync(destNode)
×
1642

×
1643
        // Send the request to open a channel to the source node now. This will
×
1644
        // open a long-lived stream where we'll receive status updates about
×
1645
        // the progress of the channel.
×
1646
        // respStream := h.OpenChannelStreamAndAssert(srcNode, destNode, p)
×
1647
        req := &lnrpc.OpenChannelRequest{
×
1648
                NodePubkey:         destNode.PubKey[:],
×
1649
                LocalFundingAmount: int64(p.Amt),
×
1650
                PushSat:            int64(p.PushAmt),
×
1651
                Private:            p.Private,
×
1652
                SpendUnconfirmed:   p.SpendUnconfirmed,
×
1653
                MinHtlcMsat:        int64(p.MinHtlc),
×
1654
                FundingShim:        p.FundingShim,
×
1655
                CommitmentType:     p.CommitmentType,
×
1656
        }
×
1657
        respStream := srcNode.RPC.OpenChannel(req)
×
1658

×
1659
        // Consume the "PSBT funding ready" update. This waits until the node
×
1660
        // notifies us that the PSBT can now be funded.
×
1661
        resp := h.ReceiveOpenChannelUpdate(respStream)
×
1662
        upd, ok := resp.Update.(*lnrpc.OpenStatusUpdate_PsbtFund)
×
1663
        require.Truef(h, ok, "expected PSBT funding update, got %v", resp)
×
1664

×
1665
        // Make sure the channel funding address has the correct type for the
×
1666
        // given commitment type.
×
1667
        fundingAddr, err := btcutil.DecodeAddress(
×
1668
                upd.PsbtFund.FundingAddress, miner.HarnessNetParams,
×
1669
        )
×
1670
        require.NoError(h, err)
×
1671

×
1672
        switch p.CommitmentType {
×
1673
        case lnrpc.CommitmentType_SIMPLE_TAPROOT:
×
1674
                require.IsType(h, &btcutil.AddressTaproot{}, fundingAddr)
×
1675

1676
        default:
×
1677
                require.IsType(
×
1678
                        h, &btcutil.AddressWitnessScriptHash{}, fundingAddr,
×
1679
                )
×
1680
        }
1681

1682
        return respStream, upd.PsbtFund.Psbt
×
1683
}
1684

1685
// CleanupForceClose mines blocks to clean up the force close process. This is
1686
// used for tests that are not asserting the expected behavior is found during
1687
// the force close process, e.g., num of sweeps, etc. Instead, it provides a
1688
// shortcut to move the test forward with a clean mempool.
1689
func (h *HarnessTest) CleanupForceClose(hn *node.HarnessNode) {
×
1690
        // Wait for the channel to be marked pending force close.
×
1691
        h.AssertNumPendingForceClose(hn, 1)
×
1692

×
1693
        // Mine enough blocks for the node to sweep its funds from the force
×
1694
        // closed channel. The commit sweep resolver is offers the input to the
×
1695
        // sweeper when it's force closed, and broadcast the sweep tx at
×
1696
        // defaulCSV-1.
×
1697
        //
×
1698
        // NOTE: we might empty blocks here as we don't know the exact number
×
1699
        // of blocks to mine. This may end up mining more blocks than needed.
×
1700
        h.MineEmptyBlocks(node.DefaultCSV - 1)
×
1701

×
1702
        // Assert there is one pending sweep.
×
1703
        h.AssertNumPendingSweeps(hn, 1)
×
1704

×
1705
        // The node should now sweep the funds, clean up by mining the sweeping
×
1706
        // tx.
×
1707
        h.MineBlocksAndAssertNumTxes(1, 1)
×
1708

×
1709
        // Mine blocks to get any second level HTLC resolved. If there are no
×
1710
        // HTLCs, this will behave like h.AssertNumPendingCloseChannels.
×
1711
        h.mineTillForceCloseResolved(hn)
×
1712
}
×
1713

1714
// CreatePayReqs is a helper method that will create a slice of payment
1715
// requests for the given node.
1716
func (h *HarnessTest) CreatePayReqs(hn *node.HarnessNode,
1717
        paymentAmt btcutil.Amount, numInvoices int,
1718
        routeHints ...*lnrpc.RouteHint) ([]string, [][]byte, []*lnrpc.Invoice) {
×
1719

×
1720
        payReqs := make([]string, numInvoices)
×
1721
        rHashes := make([][]byte, numInvoices)
×
1722
        invoices := make([]*lnrpc.Invoice, numInvoices)
×
1723
        for i := 0; i < numInvoices; i++ {
×
1724
                preimage := h.Random32Bytes()
×
1725

×
1726
                invoice := &lnrpc.Invoice{
×
1727
                        Memo:       "testing",
×
1728
                        RPreimage:  preimage,
×
1729
                        Value:      int64(paymentAmt),
×
1730
                        RouteHints: routeHints,
×
1731
                }
×
1732
                resp := hn.RPC.AddInvoice(invoice)
×
1733

×
1734
                // Set the payment address in the invoice so the caller can
×
1735
                // properly use it.
×
1736
                invoice.PaymentAddr = resp.PaymentAddr
×
1737

×
1738
                payReqs[i] = resp.PaymentRequest
×
1739
                rHashes[i] = resp.RHash
×
1740
                invoices[i] = invoice
×
1741
        }
×
1742

1743
        return payReqs, rHashes, invoices
×
1744
}
1745

1746
// BackupDB creates a backup of the current database. It will stop the node
1747
// first, copy the database files, and restart the node.
1748
func (h *HarnessTest) BackupDB(hn *node.HarnessNode) {
×
1749
        restart := h.SuspendNode(hn)
×
1750

×
1751
        err := hn.BackupDB()
×
1752
        require.NoErrorf(h, err, "%s: failed to backup db", hn.Name())
×
1753

×
1754
        err = restart()
×
1755
        require.NoErrorf(h, err, "%s: failed to restart", hn.Name())
×
1756
}
×
1757

1758
// RestartNodeAndRestoreDB restarts a given node with a callback to restore the
1759
// db.
1760
func (h *HarnessTest) RestartNodeAndRestoreDB(hn *node.HarnessNode) {
×
1761
        cb := func() error { return hn.RestoreDB() }
×
1762
        err := h.manager.restartNode(h.runCtx, hn, cb)
×
1763
        require.NoErrorf(h, err, "failed to restart node %s", hn.Name())
×
1764

×
1765
        err = h.manager.unlockNode(hn)
×
1766
        require.NoErrorf(h, err, "failed to unlock node %s", hn.Name())
×
1767

×
1768
        // Give the node some time to catch up with the chain before we
×
1769
        // continue with the tests.
×
1770
        h.WaitForBlockchainSync(hn)
×
1771
}
1772

1773
// CleanShutDown is used to quickly end a test by shutting down all non-standby
1774
// nodes and mining blocks to empty the mempool.
1775
//
1776
// NOTE: this method provides a faster exit for a test that involves force
1777
// closures as the caller doesn't need to mine all the blocks to make sure the
1778
// mempool is empty.
1779
func (h *HarnessTest) CleanShutDown() {
×
1780
        // First, shutdown all nodes to prevent new transactions being created
×
1781
        // and fed into the mempool.
×
1782
        h.shutdownAllNodes()
×
1783

×
1784
        // Now mine blocks till the mempool is empty.
×
1785
        h.cleanMempool()
×
1786
}
×
1787

1788
// QueryChannelByChanPoint tries to find a channel matching the channel point
1789
// and asserts. It returns the channel found.
1790
func (h *HarnessTest) QueryChannelByChanPoint(hn *node.HarnessNode,
1791
        chanPoint *lnrpc.ChannelPoint,
1792
        opts ...ListChannelOption) *lnrpc.Channel {
×
1793

×
1794
        channel, err := h.findChannel(hn, chanPoint, opts...)
×
1795
        require.NoError(h, err, "failed to query channel")
×
1796

×
1797
        return channel
×
1798
}
×
1799

1800
// SendPaymentAndAssertStatus sends a payment from the passed node and asserts
1801
// the desired status is reached.
1802
func (h *HarnessTest) SendPaymentAndAssertStatus(hn *node.HarnessNode,
1803
        req *routerrpc.SendPaymentRequest,
1804
        status lnrpc.Payment_PaymentStatus) *lnrpc.Payment {
×
1805

×
1806
        stream := hn.RPC.SendPayment(req)
×
1807
        return h.AssertPaymentStatusFromStream(stream, status)
×
1808
}
×
1809

1810
// SendPaymentAssertFail sends a payment from the passed node and asserts the
1811
// payment is failed with the specified failure reason .
1812
func (h *HarnessTest) SendPaymentAssertFail(hn *node.HarnessNode,
1813
        req *routerrpc.SendPaymentRequest,
1814
        reason lnrpc.PaymentFailureReason) *lnrpc.Payment {
×
1815

×
1816
        payment := h.SendPaymentAndAssertStatus(hn, req, lnrpc.Payment_FAILED)
×
1817
        require.Equal(h, reason, payment.FailureReason,
×
1818
                "payment failureReason not matched")
×
1819

×
1820
        return payment
×
1821
}
×
1822

1823
// SendPaymentAssertSettled sends a payment from the passed node and asserts the
1824
// payment is settled.
1825
func (h *HarnessTest) SendPaymentAssertSettled(hn *node.HarnessNode,
1826
        req *routerrpc.SendPaymentRequest) *lnrpc.Payment {
×
1827

×
1828
        return h.SendPaymentAndAssertStatus(hn, req, lnrpc.Payment_SUCCEEDED)
×
1829
}
×
1830

1831
// SendPaymentAssertInflight sends a payment from the passed node and asserts
1832
// the payment is inflight.
1833
func (h *HarnessTest) SendPaymentAssertInflight(hn *node.HarnessNode,
1834
        req *routerrpc.SendPaymentRequest) *lnrpc.Payment {
×
1835

×
1836
        return h.SendPaymentAndAssertStatus(hn, req, lnrpc.Payment_IN_FLIGHT)
×
1837
}
×
1838

1839
// OpenChannelRequest is used to open a channel using the method
1840
// OpenMultiChannelsAsync.
1841
type OpenChannelRequest struct {
1842
        // Local is the funding node.
1843
        Local *node.HarnessNode
1844

1845
        // Remote is the receiving node.
1846
        Remote *node.HarnessNode
1847

1848
        // Param is the open channel params.
1849
        Param OpenChannelParams
1850

1851
        // stream is the client created after calling OpenChannel RPC.
1852
        stream rpc.OpenChanClient
1853

1854
        // result is a channel used to send the channel point once the funding
1855
        // has succeeded.
1856
        result chan *lnrpc.ChannelPoint
1857
}
1858

1859
// OpenMultiChannelsAsync takes a list of OpenChannelRequest and opens them in
1860
// batch. The channel points are returned in same the order of the requests
1861
// once all of the channel open succeeded.
1862
//
1863
// NOTE: compared to open multiple channel sequentially, this method will be
1864
// faster as it doesn't need to mine 6 blocks for each channel open. However,
1865
// it does make debugging the logs more difficult as messages are intertwined.
1866
func (h *HarnessTest) OpenMultiChannelsAsync(
1867
        reqs []*OpenChannelRequest) []*lnrpc.ChannelPoint {
×
1868

×
1869
        // openChannel opens a channel based on the request.
×
1870
        openChannel := func(req *OpenChannelRequest) {
×
1871
                stream := h.OpenChannelAssertStream(
×
1872
                        req.Local, req.Remote, req.Param,
×
1873
                )
×
1874
                req.stream = stream
×
1875
        }
×
1876

1877
        // assertChannelOpen is a helper closure that asserts a channel is
1878
        // open.
1879
        assertChannelOpen := func(req *OpenChannelRequest) {
×
1880
                // Wait for the channel open event from the stream.
×
1881
                cp := h.WaitForChannelOpenEvent(req.stream)
×
1882

×
1883
                if !req.Param.Private {
×
1884
                        // Check that both alice and bob have seen the channel
×
1885
                        // from their channel watch request.
×
1886
                        h.AssertChannelInGraph(req.Local, cp)
×
1887
                        h.AssertChannelInGraph(req.Remote, cp)
×
1888
                }
×
1889

1890
                // Finally, check that the channel can be seen in their
1891
                // ListChannels.
1892
                h.AssertChannelExists(req.Local, cp)
×
1893
                h.AssertChannelExists(req.Remote, cp)
×
1894

×
1895
                req.result <- cp
×
1896
        }
1897

1898
        // Go through the requests and make the OpenChannel RPC call.
1899
        for _, r := range reqs {
×
1900
                openChannel(r)
×
1901
        }
×
1902

1903
        // Mine one block to confirm all the funding transactions.
1904
        h.MineBlocksAndAssertNumTxes(1, len(reqs))
×
1905

×
1906
        // Mine 5 more blocks so all the public channels are announced to the
×
1907
        // network.
×
1908
        h.MineBlocks(numBlocksOpenChannel - 1)
×
1909

×
1910
        // Once the blocks are mined, we fire goroutines for each of the
×
1911
        // request to watch for the channel openning.
×
1912
        for _, r := range reqs {
×
1913
                r.result = make(chan *lnrpc.ChannelPoint, 1)
×
1914
                go assertChannelOpen(r)
×
1915
        }
×
1916

1917
        // Finally, collect the results.
1918
        channelPoints := make([]*lnrpc.ChannelPoint, 0)
×
1919
        for _, r := range reqs {
×
1920
                select {
×
1921
                case cp := <-r.result:
×
1922
                        channelPoints = append(channelPoints, cp)
×
1923

1924
                case <-time.After(wait.ChannelOpenTimeout):
×
1925
                        require.Failf(h, "timeout", "wait channel point "+
×
1926
                                "timeout for channel %s=>%s", r.Local.Name(),
×
1927
                                r.Remote.Name())
×
1928
                }
1929
        }
1930

1931
        // Assert that we have the expected num of channel points.
1932
        require.Len(h, channelPoints, len(reqs),
×
1933
                "returned channel points not match")
×
1934

×
1935
        return channelPoints
×
1936
}
1937

1938
// ReceiveInvoiceUpdate waits until a message is received on the subscribe
1939
// invoice stream or the timeout is reached.
1940
func (h *HarnessTest) ReceiveInvoiceUpdate(
1941
        stream rpc.InvoiceUpdateClient) *lnrpc.Invoice {
×
1942

×
1943
        chanMsg := make(chan *lnrpc.Invoice)
×
1944
        errChan := make(chan error)
×
1945
        go func() {
×
1946
                // Consume one message. This will block until the message is
×
1947
                // received.
×
1948
                resp, err := stream.Recv()
×
1949
                if err != nil {
×
1950
                        errChan <- err
×
1951
                        return
×
1952
                }
×
1953
                chanMsg <- resp
×
1954
        }()
1955

1956
        select {
×
1957
        case <-time.After(DefaultTimeout):
×
1958
                require.Fail(h, "timeout", "timeout receiving invoice update")
×
1959

1960
        case err := <-errChan:
×
1961
                require.Failf(h, "err from stream",
×
1962
                        "received err from stream: %v", err)
×
1963

1964
        case updateMsg := <-chanMsg:
×
1965
                return updateMsg
×
1966
        }
1967

1968
        return nil
×
1969
}
1970

1971
// CalculateTxFee retrieves parent transactions and reconstructs the fee paid.
1972
func (h *HarnessTest) CalculateTxFee(tx *wire.MsgTx) btcutil.Amount {
×
1973
        var balance btcutil.Amount
×
1974
        for _, in := range tx.TxIn {
×
1975
                parentHash := in.PreviousOutPoint.Hash
×
1976
                rawTx := h.miner.GetRawTransaction(parentHash)
×
1977
                parent := rawTx.MsgTx()
×
1978
                value := parent.TxOut[in.PreviousOutPoint.Index].Value
×
1979

×
1980
                balance += btcutil.Amount(value)
×
1981
        }
×
1982

1983
        for _, out := range tx.TxOut {
×
1984
                balance -= btcutil.Amount(out.Value)
×
1985
        }
×
1986

1987
        return balance
×
1988
}
1989

1990
// CalculateTxWeight calculates the weight for a given tx.
1991
//
1992
// TODO(yy): use weight estimator to get more accurate result.
1993
func (h *HarnessTest) CalculateTxWeight(tx *wire.MsgTx) lntypes.WeightUnit {
×
1994
        utx := btcutil.NewTx(tx)
×
1995
        return lntypes.WeightUnit(blockchain.GetTransactionWeight(utx))
×
1996
}
×
1997

1998
// CalculateTxFeeRate calculates the fee rate for a given tx.
1999
func (h *HarnessTest) CalculateTxFeeRate(
2000
        tx *wire.MsgTx) chainfee.SatPerKWeight {
×
2001

×
2002
        w := h.CalculateTxWeight(tx)
×
2003
        fee := h.CalculateTxFee(tx)
×
2004

×
2005
        return chainfee.NewSatPerKWeight(fee, w)
×
2006
}
×
2007

2008
// CalculateTxesFeeRate takes a list of transactions and estimates the fee rate
2009
// used to sweep them.
2010
//
2011
// NOTE: only used in current test file.
2012
func (h *HarnessTest) CalculateTxesFeeRate(txns []*wire.MsgTx) int64 {
×
2013
        const scale = 1000
×
2014

×
2015
        var totalWeight, totalFee int64
×
2016
        for _, tx := range txns {
×
2017
                utx := btcutil.NewTx(tx)
×
2018
                totalWeight += blockchain.GetTransactionWeight(utx)
×
2019

×
2020
                fee := h.CalculateTxFee(tx)
×
2021
                totalFee += int64(fee)
×
2022
        }
×
2023
        feeRate := totalFee * scale / totalWeight
×
2024

×
2025
        return feeRate
×
2026
}
2027

2028
// AssertSweepFound looks up a sweep in a nodes list of broadcast sweeps and
2029
// asserts it's found.
2030
//
2031
// NOTE: Does not account for node's internal state.
2032
func (h *HarnessTest) AssertSweepFound(hn *node.HarnessNode,
2033
        sweep string, verbose bool, startHeight int32) {
×
2034

×
2035
        err := wait.NoError(func() error {
×
2036
                // List all sweeps that alice's node had broadcast.
×
2037
                sweepResp := hn.RPC.ListSweeps(verbose, startHeight)
×
2038

×
2039
                var found bool
×
2040
                if verbose {
×
2041
                        found = findSweepInDetails(h, sweep, sweepResp)
×
2042
                } else {
×
2043
                        found = findSweepInTxids(h, sweep, sweepResp)
×
2044
                }
×
2045

2046
                if found {
×
2047
                        return nil
×
2048
                }
×
2049

2050
                return fmt.Errorf("sweep tx %v not found in resp %v", sweep,
×
2051
                        sweepResp)
×
2052
        }, wait.DefaultTimeout)
2053
        require.NoError(h, err, "%s: timeout checking sweep tx", hn.Name())
×
2054
}
2055

2056
func findSweepInTxids(ht *HarnessTest, sweepTxid string,
2057
        sweepResp *walletrpc.ListSweepsResponse) bool {
×
2058

×
2059
        sweepTxIDs := sweepResp.GetTransactionIds()
×
2060
        require.NotNil(ht, sweepTxIDs, "expected transaction ids")
×
2061
        require.Nil(ht, sweepResp.GetTransactionDetails())
×
2062

×
2063
        // Check that the sweep tx we have just produced is present.
×
2064
        for _, tx := range sweepTxIDs.TransactionIds {
×
2065
                if tx == sweepTxid {
×
2066
                        return true
×
2067
                }
×
2068
        }
2069

2070
        return false
×
2071
}
2072

2073
func findSweepInDetails(ht *HarnessTest, sweepTxid string,
2074
        sweepResp *walletrpc.ListSweepsResponse) bool {
×
2075

×
2076
        sweepDetails := sweepResp.GetTransactionDetails()
×
2077
        require.NotNil(ht, sweepDetails, "expected transaction details")
×
2078
        require.Nil(ht, sweepResp.GetTransactionIds())
×
2079

×
2080
        for _, tx := range sweepDetails.Transactions {
×
2081
                if tx.TxHash == sweepTxid {
×
2082
                        return true
×
2083
                }
×
2084
        }
2085

2086
        return false
×
2087
}
2088

2089
// QueryRoutesAndRetry attempts to keep querying a route until timeout is
2090
// reached.
2091
//
2092
// NOTE: when a channel is opened, we may need to query multiple times to get
2093
// it in our QueryRoutes RPC. This happens even after we check the channel is
2094
// heard by the node using ht.AssertChannelOpen. Deep down, this is because our
2095
// GraphTopologySubscription and QueryRoutes give different results regarding a
2096
// specific channel, with the formal reporting it being open while the latter
2097
// not, resulting GraphTopologySubscription acting "faster" than QueryRoutes.
2098
// TODO(yy): make sure related subsystems share the same view on a given
2099
// channel.
2100
func (h *HarnessTest) QueryRoutesAndRetry(hn *node.HarnessNode,
2101
        req *lnrpc.QueryRoutesRequest) *lnrpc.QueryRoutesResponse {
×
2102

×
2103
        var routes *lnrpc.QueryRoutesResponse
×
2104
        err := wait.NoError(func() error {
×
2105
                ctxt, cancel := context.WithCancel(h.runCtx)
×
2106
                defer cancel()
×
2107

×
2108
                resp, err := hn.RPC.LN.QueryRoutes(ctxt, req)
×
2109
                if err != nil {
×
2110
                        return fmt.Errorf("%s: failed to query route: %w",
×
2111
                                hn.Name(), err)
×
2112
                }
×
2113

2114
                routes = resp
×
2115

×
2116
                return nil
×
2117
        }, DefaultTimeout)
2118

2119
        require.NoError(h, err, "timeout querying routes")
×
2120

×
2121
        return routes
×
2122
}
2123

2124
// ReceiveHtlcInterceptor waits until a message is received on the htlc
2125
// interceptor stream or the timeout is reached.
2126
func (h *HarnessTest) ReceiveHtlcInterceptor(
2127
        stream rpc.InterceptorClient) *routerrpc.ForwardHtlcInterceptRequest {
×
2128

×
2129
        chanMsg := make(chan *routerrpc.ForwardHtlcInterceptRequest)
×
2130
        errChan := make(chan error)
×
2131
        go func() {
×
2132
                // Consume one message. This will block until the message is
×
2133
                // received.
×
2134
                resp, err := stream.Recv()
×
2135
                if err != nil {
×
2136
                        errChan <- err
×
2137
                        return
×
2138
                }
×
2139
                chanMsg <- resp
×
2140
        }()
2141

2142
        select {
×
2143
        case <-time.After(DefaultTimeout):
×
2144
                require.Fail(h, "timeout", "timeout intercepting htlc")
×
2145

2146
        case err := <-errChan:
×
2147
                require.Failf(h, "err from HTLC interceptor stream",
×
2148
                        "received err from HTLC interceptor stream: %v", err)
×
2149

2150
        case updateMsg := <-chanMsg:
×
2151
                return updateMsg
×
2152
        }
2153

2154
        return nil
×
2155
}
2156

2157
// ReceiveInvoiceHtlcModification waits until a message is received on the
2158
// invoice HTLC modifier stream or the timeout is reached.
2159
func (h *HarnessTest) ReceiveInvoiceHtlcModification(
2160
        stream rpc.InvoiceHtlcModifierClient) *invoicesrpc.HtlcModifyRequest {
×
2161

×
2162
        chanMsg := make(chan *invoicesrpc.HtlcModifyRequest)
×
2163
        errChan := make(chan error)
×
2164
        go func() {
×
2165
                // Consume one message. This will block until the message is
×
2166
                // received.
×
2167
                resp, err := stream.Recv()
×
2168
                if err != nil {
×
2169
                        errChan <- err
×
2170
                        return
×
2171
                }
×
2172
                chanMsg <- resp
×
2173
        }()
2174

2175
        select {
×
2176
        case <-time.After(DefaultTimeout):
×
2177
                require.Fail(h, "timeout", "timeout invoice HTLC modifier")
×
2178

2179
        case err := <-errChan:
×
2180
                require.Failf(h, "err from invoice HTLC modifier stream",
×
2181
                        "received err from invoice HTLC modifier stream: %v",
×
2182
                        err)
×
2183

2184
        case updateMsg := <-chanMsg:
×
2185
                return updateMsg
×
2186
        }
2187

2188
        return nil
×
2189
}
2190

2191
// ReceiveChannelEvent waits until a message is received from the
2192
// ChannelEventsClient stream or the timeout is reached.
2193
func (h *HarnessTest) ReceiveChannelEvent(
2194
        stream rpc.ChannelEventsClient) *lnrpc.ChannelEventUpdate {
×
2195

×
2196
        chanMsg := make(chan *lnrpc.ChannelEventUpdate)
×
2197
        errChan := make(chan error)
×
2198
        go func() {
×
2199
                // Consume one message. This will block until the message is
×
2200
                // received.
×
2201
                resp, err := stream.Recv()
×
2202
                if err != nil {
×
2203
                        errChan <- err
×
2204
                        return
×
2205
                }
×
2206
                chanMsg <- resp
×
2207
        }()
2208

2209
        select {
×
2210
        case <-time.After(DefaultTimeout):
×
2211
                require.Fail(h, "timeout", "timeout intercepting htlc")
×
2212

2213
        case err := <-errChan:
×
2214
                require.Failf(h, "err from stream",
×
2215
                        "received err from stream: %v", err)
×
2216

2217
        case updateMsg := <-chanMsg:
×
2218
                return updateMsg
×
2219
        }
2220

2221
        return nil
×
2222
}
2223

2224
// GetOutputIndex returns the output index of the given address in the given
2225
// transaction.
2226
func (h *HarnessTest) GetOutputIndex(txid chainhash.Hash, addr string) int {
×
2227
        // We'll then extract the raw transaction from the mempool in order to
×
2228
        // determine the index of the p2tr output.
×
2229
        tx := h.miner.GetRawTransaction(txid)
×
2230

×
2231
        p2trOutputIndex := -1
×
2232
        for i, txOut := range tx.MsgTx().TxOut {
×
2233
                _, addrs, _, err := txscript.ExtractPkScriptAddrs(
×
2234
                        txOut.PkScript, h.miner.ActiveNet,
×
2235
                )
×
2236
                require.NoError(h, err)
×
2237

×
2238
                if addrs[0].String() == addr {
×
2239
                        p2trOutputIndex = i
×
2240
                }
×
2241
        }
2242
        require.Greater(h, p2trOutputIndex, -1)
×
2243

×
2244
        return p2trOutputIndex
×
2245
}
2246

2247
// SendCoins sends a coin from node A to node B with the given amount, returns
2248
// the sending tx.
2249
func (h *HarnessTest) SendCoins(a, b *node.HarnessNode,
2250
        amt btcutil.Amount) *wire.MsgTx {
×
2251

×
2252
        // Create an address for Bob receive the coins.
×
2253
        req := &lnrpc.NewAddressRequest{
×
2254
                Type: lnrpc.AddressType_TAPROOT_PUBKEY,
×
2255
        }
×
2256
        resp := b.RPC.NewAddress(req)
×
2257

×
2258
        // Send the coins from Alice to Bob. We should expect a tx to be
×
2259
        // broadcast and seen in the mempool.
×
2260
        sendReq := &lnrpc.SendCoinsRequest{
×
2261
                Addr:       resp.Address,
×
2262
                Amount:     int64(amt),
×
2263
                TargetConf: 6,
×
2264
        }
×
2265
        a.RPC.SendCoins(sendReq)
×
2266
        tx := h.GetNumTxsFromMempool(1)[0]
×
2267

×
2268
        return tx
×
2269
}
×
2270

2271
// CreateSimpleNetwork creates the number of nodes specified by the number of
2272
// configs and makes a topology of `node1 -> node2 -> node3...`. Each node is
2273
// created using the specified config, the neighbors are connected, and the
2274
// channels are opened. Each node will be funded with a single UTXO of 1 BTC
2275
// except the last one.
2276
//
2277
// For instance, to create a network with 2 nodes that share the same node
2278
// config,
2279
//
2280
//        cfg := []string{"--protocol.anchors"}
2281
//        cfgs := [][]string{cfg, cfg}
2282
//        params := OpenChannelParams{...}
2283
//        chanPoints, nodes := ht.CreateSimpleNetwork(cfgs, params)
2284
//
2285
// This will create two nodes and open an anchor channel between them.
2286
func (h *HarnessTest) CreateSimpleNetwork(nodeCfgs [][]string,
2287
        p OpenChannelParams) ([]*lnrpc.ChannelPoint, []*node.HarnessNode) {
×
2288

×
2289
        // Create new nodes.
×
2290
        nodes := h.createNodes(nodeCfgs)
×
2291

×
2292
        var resp []*lnrpc.ChannelPoint
×
2293

×
2294
        // Open zero-conf channels if specified.
×
2295
        if p.ZeroConf {
×
2296
                resp = h.openZeroConfChannelsForNodes(nodes, p)
×
2297
        } else {
×
2298
                // Open channels between the nodes.
×
2299
                resp = h.openChannelsForNodes(nodes, p)
×
2300
        }
×
2301

2302
        return resp, nodes
×
2303
}
2304

2305
// acceptChannel is used to accept a single channel that comes across. This
2306
// should be run in a goroutine and is used to test nodes with the zero-conf
2307
// feature bit.
2308
func acceptChannel(t *testing.T, zeroConf bool, stream rpc.AcceptorClient) {
×
2309
        req, err := stream.Recv()
×
2310
        require.NoError(t, err)
×
2311

×
2312
        resp := &lnrpc.ChannelAcceptResponse{
×
2313
                Accept:        true,
×
2314
                PendingChanId: req.PendingChanId,
×
2315
                ZeroConf:      zeroConf,
×
2316
        }
×
2317
        err = stream.Send(resp)
×
2318
        require.NoError(t, err)
×
2319
}
×
2320

2321
// nodeNames defines a slice of human-reable names for the nodes created in the
2322
// `createNodes` method. 8 nodes are defined here as by default we can only
2323
// create this many nodes in one test.
2324
var nodeNames = []string{
2325
        "Alice", "Bob", "Carol", "Dave", "Eve", "Frank", "Grace", "Heidi",
2326
}
2327

2328
// createNodes creates the number of nodes specified by the number of configs.
2329
// Each node is created using the specified config, the neighbors are
2330
// connected.
2331
func (h *HarnessTest) createNodes(nodeCfgs [][]string) []*node.HarnessNode {
×
2332
        // Get the number of nodes.
×
2333
        numNodes := len(nodeCfgs)
×
2334

×
2335
        // Make sure we are creating a reasonable number of nodes.
×
2336
        require.LessOrEqual(h, numNodes, len(nodeNames), "too many nodes")
×
2337

×
2338
        // Make a slice of nodes.
×
2339
        nodes := make([]*node.HarnessNode, numNodes)
×
2340

×
2341
        // Create new nodes.
×
2342
        for i, nodeCfg := range nodeCfgs {
×
2343
                nodeName := nodeNames[i]
×
2344
                n := h.NewNode(nodeName, nodeCfg)
×
2345
                nodes[i] = n
×
2346
        }
×
2347

2348
        // Connect the nodes in a chain.
2349
        for i := 1; i < len(nodes); i++ {
×
2350
                nodeA := nodes[i-1]
×
2351
                nodeB := nodes[i]
×
2352
                h.EnsureConnected(nodeA, nodeB)
×
2353
        }
×
2354

2355
        // Fund all the nodes expect the last one.
2356
        for i := 0; i < len(nodes)-1; i++ {
×
2357
                node := nodes[i]
×
2358
                h.FundCoinsUnconfirmed(btcutil.SatoshiPerBitcoin, node)
×
2359
        }
×
2360

2361
        // Mine 1 block to get the above coins confirmed.
2362
        h.MineBlocksAndAssertNumTxes(1, numNodes-1)
×
2363

×
2364
        return nodes
×
2365
}
2366

2367
// openChannelsForNodes takes a list of nodes and makes a topology of `node1 ->
2368
// node2 -> node3...`.
2369
func (h *HarnessTest) openChannelsForNodes(nodes []*node.HarnessNode,
2370
        p OpenChannelParams) []*lnrpc.ChannelPoint {
×
2371

×
2372
        // Sanity check the params.
×
2373
        require.Greater(h, len(nodes), 1, "need at least 2 nodes")
×
2374

×
2375
        // attachFundingShim is a helper closure that optionally attaches a
×
2376
        // funding shim to the open channel params and returns it.
×
2377
        attachFundingShim := func(
×
2378
                nodeA, nodeB *node.HarnessNode) OpenChannelParams {
×
2379

×
2380
                // If this channel is not a script enforced lease channel,
×
2381
                // we'll do nothing and return the params.
×
2382
                leasedType := lnrpc.CommitmentType_SCRIPT_ENFORCED_LEASE
×
2383
                if p.CommitmentType != leasedType {
×
2384
                        return p
×
2385
                }
×
2386

2387
                // Otherwise derive the funding shim, attach it to the original
2388
                // open channel params and return it.
2389
                minerHeight := h.CurrentHeight()
×
2390
                thawHeight := minerHeight + thawHeightDelta
×
2391
                fundingShim, _ := h.DeriveFundingShim(
×
2392
                        nodeA, nodeB, p.Amt, thawHeight, true, leasedType,
×
2393
                )
×
2394

×
2395
                p.FundingShim = fundingShim
×
2396

×
2397
                return p
×
2398
        }
2399

2400
        // Open channels in batch to save blocks mined.
2401
        reqs := make([]*OpenChannelRequest, 0, len(nodes)-1)
×
2402
        for i := 0; i < len(nodes)-1; i++ {
×
2403
                nodeA := nodes[i]
×
2404
                nodeB := nodes[i+1]
×
2405

×
2406
                // Optionally attach a funding shim to the open channel params.
×
2407
                p = attachFundingShim(nodeA, nodeB)
×
2408

×
2409
                req := &OpenChannelRequest{
×
2410
                        Local:  nodeA,
×
2411
                        Remote: nodeB,
×
2412
                        Param:  p,
×
2413
                }
×
2414
                reqs = append(reqs, req)
×
2415
        }
×
2416
        resp := h.OpenMultiChannelsAsync(reqs)
×
2417

×
2418
        // If the channels are private, make sure the channel participants know
×
2419
        // the relevant channels.
×
2420
        if p.Private {
×
2421
                for i, chanPoint := range resp {
×
2422
                        // Get the channel participants - for n channels we
×
2423
                        // would have n+1 nodes.
×
2424
                        nodeA, nodeB := nodes[i], nodes[i+1]
×
2425
                        h.AssertChannelInGraph(nodeA, chanPoint)
×
2426
                        h.AssertChannelInGraph(nodeB, chanPoint)
×
2427
                }
×
2428
        } else {
×
2429
                // Make sure the all nodes know all the channels if they are
×
2430
                // public.
×
2431
                for _, node := range nodes {
×
2432
                        for _, chanPoint := range resp {
×
2433
                                h.AssertChannelInGraph(node, chanPoint)
×
2434
                        }
×
2435

2436
                        // Make sure every node has updated its cached graph
2437
                        // about the edges as indicated in `DescribeGraph`.
2438
                        h.AssertNumEdges(node, len(resp), false)
×
2439
                }
2440
        }
2441

2442
        return resp
×
2443
}
2444

2445
// openZeroConfChannelsForNodes takes a list of nodes and makes a topology of
2446
// `node1 -> node2 -> node3...` with zero-conf channels.
2447
func (h *HarnessTest) openZeroConfChannelsForNodes(nodes []*node.HarnessNode,
2448
        p OpenChannelParams) []*lnrpc.ChannelPoint {
×
2449

×
2450
        // Sanity check the params.
×
2451
        require.True(h, p.ZeroConf, "zero-conf channels must be enabled")
×
2452
        require.Greater(h, len(nodes), 1, "need at least 2 nodes")
×
2453

×
2454
        // We are opening numNodes-1 channels.
×
2455
        cancels := make([]context.CancelFunc, 0, len(nodes)-1)
×
2456

×
2457
        // Create the channel acceptors.
×
2458
        for _, node := range nodes[1:] {
×
2459
                acceptor, cancel := node.RPC.ChannelAcceptor()
×
2460
                go acceptChannel(h.T, true, acceptor)
×
2461

×
2462
                cancels = append(cancels, cancel)
×
2463
        }
×
2464

2465
        // Open channels between the nodes.
2466
        resp := h.openChannelsForNodes(nodes, p)
×
2467

×
2468
        for _, cancel := range cancels {
×
2469
                cancel()
×
2470
        }
×
2471

2472
        return resp
×
2473
}
2474

2475
// DeriveFundingShim creates a channel funding shim by deriving the necessary
2476
// keys on both sides.
2477
func (h *HarnessTest) DeriveFundingShim(alice, bob *node.HarnessNode,
2478
        chanSize btcutil.Amount, thawHeight uint32, publish bool,
2479
        commitType lnrpc.CommitmentType) (*lnrpc.FundingShim,
2480
        *lnrpc.ChannelPoint) {
×
2481

×
2482
        keyLoc := &signrpc.KeyLocator{KeyFamily: 9999}
×
2483
        carolFundingKey := alice.RPC.DeriveKey(keyLoc)
×
2484
        daveFundingKey := bob.RPC.DeriveKey(keyLoc)
×
2485

×
2486
        // Now that we have the multi-sig keys for each party, we can manually
×
2487
        // construct the funding transaction. We'll instruct the backend to
×
2488
        // immediately create and broadcast a transaction paying out an exact
×
2489
        // amount. Normally this would reside in the mempool, but we just
×
2490
        // confirm it now for simplicity.
×
2491
        var (
×
2492
                fundingOutput *wire.TxOut
×
2493
                musig2        bool
×
2494
                err           error
×
2495
        )
×
2496

×
2497
        if commitType == lnrpc.CommitmentType_SIMPLE_TAPROOT ||
×
2498
                commitType == lnrpc.CommitmentType_SIMPLE_TAPROOT_OVERLAY {
×
2499

×
2500
                var carolKey, daveKey *btcec.PublicKey
×
2501
                carolKey, err = btcec.ParsePubKey(carolFundingKey.RawKeyBytes)
×
2502
                require.NoError(h, err)
×
2503
                daveKey, err = btcec.ParsePubKey(daveFundingKey.RawKeyBytes)
×
2504
                require.NoError(h, err)
×
2505

×
2506
                _, fundingOutput, err = input.GenTaprootFundingScript(
×
2507
                        carolKey, daveKey, int64(chanSize),
×
2508
                        fn.None[chainhash.Hash](),
×
2509
                )
×
2510
                require.NoError(h, err)
×
2511

×
2512
                musig2 = true
×
2513
        } else {
×
2514
                _, fundingOutput, err = input.GenFundingPkScript(
×
2515
                        carolFundingKey.RawKeyBytes, daveFundingKey.RawKeyBytes,
×
2516
                        int64(chanSize),
×
2517
                )
×
2518
                require.NoError(h, err)
×
2519
        }
×
2520

2521
        var txid *chainhash.Hash
×
2522
        targetOutputs := []*wire.TxOut{fundingOutput}
×
2523
        if publish {
×
2524
                txid = h.SendOutputsWithoutChange(targetOutputs, 5)
×
2525
        } else {
×
2526
                tx := h.CreateTransaction(targetOutputs, 5)
×
2527

×
2528
                txHash := tx.TxHash()
×
2529
                txid = &txHash
×
2530
        }
×
2531

2532
        // At this point, we can being our external channel funding workflow.
2533
        // We'll start by generating a pending channel ID externally that will
2534
        // be used to track this new funding type.
2535
        pendingChanID := h.Random32Bytes()
×
2536

×
2537
        // Now that we have the pending channel ID, Dave (our responder) will
×
2538
        // register the intent to receive a new channel funding workflow using
×
2539
        // the pending channel ID.
×
2540
        chanPoint := &lnrpc.ChannelPoint{
×
2541
                FundingTxid: &lnrpc.ChannelPoint_FundingTxidBytes{
×
2542
                        FundingTxidBytes: txid[:],
×
2543
                },
×
2544
        }
×
2545
        chanPointShim := &lnrpc.ChanPointShim{
×
2546
                Amt:       int64(chanSize),
×
2547
                ChanPoint: chanPoint,
×
2548
                LocalKey: &lnrpc.KeyDescriptor{
×
2549
                        RawKeyBytes: daveFundingKey.RawKeyBytes,
×
2550
                        KeyLoc: &lnrpc.KeyLocator{
×
2551
                                KeyFamily: daveFundingKey.KeyLoc.KeyFamily,
×
2552
                                KeyIndex:  daveFundingKey.KeyLoc.KeyIndex,
×
2553
                        },
×
2554
                },
×
2555
                RemoteKey:     carolFundingKey.RawKeyBytes,
×
2556
                PendingChanId: pendingChanID,
×
2557
                ThawHeight:    thawHeight,
×
2558
                Musig2:        musig2,
×
2559
        }
×
2560
        fundingShim := &lnrpc.FundingShim{
×
2561
                Shim: &lnrpc.FundingShim_ChanPointShim{
×
2562
                        ChanPointShim: chanPointShim,
×
2563
                },
×
2564
        }
×
2565
        bob.RPC.FundingStateStep(&lnrpc.FundingTransitionMsg{
×
2566
                Trigger: &lnrpc.FundingTransitionMsg_ShimRegister{
×
2567
                        ShimRegister: fundingShim,
×
2568
                },
×
2569
        })
×
2570

×
2571
        // If we attempt to register the same shim (has the same pending chan
×
2572
        // ID), then we should get an error.
×
2573
        bob.RPC.FundingStateStepAssertErr(&lnrpc.FundingTransitionMsg{
×
2574
                Trigger: &lnrpc.FundingTransitionMsg_ShimRegister{
×
2575
                        ShimRegister: fundingShim,
×
2576
                },
×
2577
        })
×
2578

×
2579
        // We'll take the chan point shim we just registered for Dave (the
×
2580
        // responder), and swap the local/remote keys before we feed it in as
×
2581
        // Carol's funding shim as the initiator.
×
2582
        fundingShim.GetChanPointShim().LocalKey = &lnrpc.KeyDescriptor{
×
2583
                RawKeyBytes: carolFundingKey.RawKeyBytes,
×
2584
                KeyLoc: &lnrpc.KeyLocator{
×
2585
                        KeyFamily: carolFundingKey.KeyLoc.KeyFamily,
×
2586
                        KeyIndex:  carolFundingKey.KeyLoc.KeyIndex,
×
2587
                },
×
2588
        }
×
2589
        fundingShim.GetChanPointShim().RemoteKey = daveFundingKey.RawKeyBytes
×
2590

×
2591
        return fundingShim, chanPoint
×
2592
}
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