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

lightningnetwork / lnd / 13986536491

21 Mar 2025 07:12AM UTC coverage: 68.805% (+9.7%) from 59.126%
13986536491

Pull #9627

github

web-flow
Merge 071ed001a into 5d921723b
Pull Request #9627: Sweep inputs even the budget cannot be covered

113 of 159 new or added lines in 6 files covered. (71.07%)

18 existing lines in 4 files now uncovered.

131503 of 191123 relevant lines covered (68.81%)

23375.23 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
        "fmt"
6
        "strings"
7
        "testing"
8
        "time"
9

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

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

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

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

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

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

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

61
var (
62
        // MaxBlocksMinedPerTest is the maximum number of blocks that we allow
63
        // a test to mine. This is an exported global variable so it can be
64
        // overwritten by other projects that don't have the same constraints.
65
        MaxBlocksMinedPerTest = 50
66
)
67

68
// TestCase defines a test case that's been used in the integration test.
69
type TestCase struct {
70
        // Name specifies the test name.
71
        Name string
72

73
        // TestFunc is the test case wrapped in a function.
74
        TestFunc func(t *HarnessTest)
75
}
76

77
// HarnessTest builds on top of a testing.T with enhanced error detection. It
78
// is responsible for managing the interactions among different nodes, and
79
// providing easy-to-use assertions.
80
type HarnessTest struct {
81
        *testing.T
82

83
        // miner is a reference to a running full node that can be used to
84
        // create new blocks on the network.
85
        miner *miner.HarnessMiner
86

87
        // manager handles the start and stop of a given node.
88
        manager *nodeManager
89

90
        // feeService is a web service that provides external fee estimates to
91
        // lnd.
92
        feeService WebFeeService
93

94
        // Channel for transmitting stderr output from failed lightning node
95
        // to main process.
96
        lndErrorChan chan error
97

98
        // runCtx is a context with cancel method. It's used to signal when the
99
        // node needs to quit, and used as the parent context when spawning
100
        // children contexts for RPC requests.
101
        runCtx context.Context //nolint:containedctx
102
        cancel context.CancelFunc
103

104
        // stopChainBackend points to the cleanup function returned by the
105
        // chainBackend.
106
        stopChainBackend func()
107

108
        // cleaned specifies whether the cleanup has been applied for the
109
        // current HarnessTest.
110
        cleaned bool
111

112
        // currentHeight is the current height of the chain backend.
113
        currentHeight uint32
114
}
115

116
// harnessOpts contains functional option to modify the behavior of the various
117
// harness calls.
118
type harnessOpts struct {
119
        useAMP bool
120
}
121

122
// defaultHarnessOpts returns a new instance of the harnessOpts with default
123
// values specified.
124
func defaultHarnessOpts() harnessOpts {
×
125
        return harnessOpts{
×
126
                useAMP: false,
×
127
        }
×
128
}
×
129

130
// HarnessOpt is a functional option that can be used to modify the behavior of
131
// harness functionality.
132
type HarnessOpt func(*harnessOpts)
133

134
// WithAMP is a functional option that can be used to enable the AMP feature
135
// for sending payments.
136
func WithAMP() HarnessOpt {
×
137
        return func(h *harnessOpts) {
×
138
                h.useAMP = true
×
139
        }
×
140
}
141

142
// NewHarnessTest creates a new instance of a harnessTest from a regular
143
// testing.T instance.
144
func NewHarnessTest(t *testing.T, lndBinary string, feeService WebFeeService,
145
        dbBackend node.DatabaseBackend, nativeSQL bool) *HarnessTest {
×
146

×
147
        t.Helper()
×
148

×
149
        // Create the run context.
×
150
        ctxt, cancel := context.WithCancel(context.Background())
×
151

×
152
        manager := newNodeManager(lndBinary, dbBackend, nativeSQL)
×
153

×
154
        return &HarnessTest{
×
155
                T:          t,
×
156
                manager:    manager,
×
157
                feeService: feeService,
×
158
                runCtx:     ctxt,
×
159
                cancel:     cancel,
×
160
                // We need to use buffered channel here as we don't want to
×
161
                // block sending errors.
×
162
                lndErrorChan: make(chan error, lndErrorChanSize),
×
163
        }
×
164
}
×
165

166
// Start will assemble the chain backend and the miner for the HarnessTest. It
167
// also starts the fee service and watches lnd process error.
168
func (h *HarnessTest) Start(chain node.BackendConfig,
169
        miner *miner.HarnessMiner) {
×
170

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

183
                case <-h.runCtx.Done():
×
184
                        return
×
185
                }
186
        }()
187

188
        // Start the fee service.
189
        err := h.feeService.Start()
×
190
        require.NoError(h, err, "failed to start fee service")
×
191

×
192
        // Assemble the node manager with chainBackend and feeServiceURL.
×
193
        h.manager.chainBackend = chain
×
194
        h.manager.feeServiceURL = h.feeService.URL()
×
195

×
196
        // Assemble the miner.
×
197
        h.miner = miner
×
198

×
199
        // Update block height.
×
200
        h.updateCurrentHeight()
×
201
}
202

203
// ChainBackendName returns the chain backend name used in the test.
204
func (h *HarnessTest) ChainBackendName() string {
×
205
        return h.manager.chainBackend.Name()
×
206
}
×
207

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

218
// setupWatchOnlyNode initializes a node with the watch-only accounts of an
219
// associated remote signing instance.
220
func (h *HarnessTest) setupWatchOnlyNode(name string,
221
        signerNode *node.HarnessNode, password []byte) *node.HarnessNode {
×
222

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

×
234
        // Fetch watch-only accounts from the signer node.
×
235
        resp := signerNode.RPC.ListAccounts(&walletrpc.ListAccountsRequest{})
×
236
        watchOnlyAccounts, err := walletrpc.AccountsToWatchOnly(resp.Accounts)
×
237
        require.NoErrorf(h, err, "unable to find watch only accounts for %s",
×
238
                name)
×
239

×
240
        // Create a new watch-only node with remote signer configuration.
×
241
        return h.NewNodeRemoteSigner(
×
242
                name, remoteSignerArgs, password,
×
243
                &lnrpc.WatchOnly{
×
244
                        MasterKeyBirthdayTimestamp: 0,
×
245
                        MasterKeyFingerprint:       nil,
×
246
                        Accounts:                   watchOnlyAccounts,
×
247
                },
×
248
        )
×
249
}
×
250

251
// createAndSendOutput send amt satoshis from the internal mining node to the
252
// targeted lightning node using a P2WKH address. No blocks are mined so
253
// transactions will sit unconfirmed in mempool.
254
func (h *HarnessTest) createAndSendOutput(target *node.HarnessNode,
255
        amt btcutil.Amount, addrType lnrpc.AddressType) {
×
256

×
257
        req := &lnrpc.NewAddressRequest{Type: addrType}
×
258
        resp := target.RPC.NewAddress(req)
×
259
        addr := h.DecodeAddress(resp.Address)
×
260
        addrScript := h.PayToAddrScript(addr)
×
261

×
262
        output := &wire.TxOut{
×
263
                PkScript: addrScript,
×
264
                Value:    int64(amt),
×
265
        }
×
266
        h.miner.SendOutput(output, defaultMinerFeeRate)
×
267
}
×
268

269
// Stop stops the test harness.
270
func (h *HarnessTest) Stop() {
×
271
        // Do nothing if it's not started.
×
272
        if h.runCtx == nil {
×
273
                h.Log("HarnessTest is not started")
×
274
                return
×
275
        }
×
276

277
        h.shutdownAllNodes()
×
278

×
279
        close(h.lndErrorChan)
×
280

×
281
        // Stop the fee service.
×
282
        err := h.feeService.Stop()
×
283
        require.NoError(h, err, "failed to stop fee service")
×
284

×
285
        // Stop the chainBackend.
×
286
        h.stopChainBackend()
×
287

×
288
        // Stop the miner.
×
289
        h.miner.Stop()
×
290
}
291

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

303
        testCase.TestFunc(h)
×
304
}
305

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

×
313
        st := &HarnessTest{
×
314
                T:            t,
×
315
                manager:      h.manager,
×
316
                miner:        h.miner,
×
317
                feeService:   h.feeService,
×
318
                lndErrorChan: make(chan error, lndErrorChanSize),
×
319
        }
×
320

×
321
        // Inherit context from the main test.
×
322
        st.runCtx, st.cancel = context.WithCancel(h.runCtx)
×
323

×
324
        // Inherit the subtest for the miner.
×
325
        st.miner.T = st.T
×
326

×
327
        // Reset fee estimator.
×
328
        st.feeService.Reset()
×
329

×
330
        // Record block height.
×
331
        h.updateCurrentHeight()
×
332
        startHeight := int32(h.CurrentHeight())
×
333

×
334
        st.Cleanup(func() {
×
335
                // Make sure the test is not consuming too many blocks.
×
336
                st.checkAndLimitBlocksMined(startHeight)
×
337

×
338
                // Don't bother run the cleanups if the test is failed.
×
339
                if st.Failed() {
×
340
                        st.Log("test failed, skipped cleanup")
×
341
                        st.shutdownNodesNoAssert()
×
342
                        return
×
343
                }
×
344

345
                // Don't run cleanup if it's already done. This can happen if
346
                // we have multiple level inheritance of the parent harness
347
                // test. For instance, a `Subtest(st)`.
348
                if st.cleaned {
×
349
                        st.Log("test already cleaned, skipped cleanup")
×
350
                        return
×
351
                }
×
352

353
                // If found running nodes, shut them down.
354
                st.shutdownAllNodes()
×
355

×
356
                // We require the mempool to be cleaned from the test.
×
357
                require.Empty(st, st.miner.GetRawMempool(), "mempool not "+
×
358
                        "cleaned, please mine blocks to clean them all.")
×
359

×
360
                // Finally, cancel the run context. We have to do it here
×
361
                // because we need to keep the context alive for the above
×
362
                // assertions used in cleanup.
×
363
                st.cancel()
×
364

×
365
                // We now want to mark the parent harness as cleaned to avoid
×
366
                // running cleanup again since its internal state has been
×
367
                // cleaned up by its child harness tests.
×
368
                h.cleaned = true
×
369
        })
370

371
        return st
×
372
}
373

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

×
381
        h.Logf("finished test: %s, start height=%d, end height=%d, mined "+
×
382
                "blocks=%d", h.manager.currentTestCase, startHeight, endHeight,
×
383
                blocksMined)
×
384

×
385
        // If the number of blocks is less than 40, we consider the test
×
386
        // healthy.
×
387
        if blocksMined < 40 {
×
388
                return
×
389
        }
×
390

391
        // Otherwise log a warning if it's mining more than 40 blocks.
392
        desc := "!============================================!\n"
×
393

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

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

×
405
        // We enforce that the test should not mine more than
×
406
        // MaxBlocksMinedPerTest (50 by default) blocks, which is more than
×
407
        // enough to test a multi hop force close scenario.
×
408
        require.LessOrEqualf(
×
409
                h, int(blocksMined), MaxBlocksMinedPerTest,
×
410
                "cannot mine more than %d blocks in one test",
×
411
                MaxBlocksMinedPerTest,
×
412
        )
×
413
}
414

415
// shutdownNodesNoAssert will shutdown all running nodes without assertions.
416
// This is used when the test has already failed, we don't want to log more
417
// errors but focusing on the original error.
418
func (h *HarnessTest) shutdownNodesNoAssert() {
×
419
        for _, node := range h.manager.activeNodes {
×
420
                _ = h.manager.shutdownNode(node)
×
421
        }
×
422
}
423

424
// shutdownAllNodes will shutdown all running nodes.
425
func (h *HarnessTest) shutdownAllNodes() {
×
426
        var err error
×
427
        for _, node := range h.manager.activeNodes {
×
428
                err = h.manager.shutdownNode(node)
×
429
                if err == nil {
×
430
                        continue
×
431
                }
432

433
                // Instead of returning the error, we will log it instead. This
434
                // is needed so other nodes can continue their shutdown
435
                // processes.
436
                h.Logf("unable to shutdown %s, got err: %v", node.Name(), err)
×
437
        }
438

439
        require.NoError(h, err, "failed to shutdown all nodes")
×
440
}
441

442
// cleanupStandbyNode is a function should be called with defer whenever a
443
// subtest is created. It will reset the standby nodes configs, snapshot the
444
// states, and validate the node has a clean state.
445
func (h *HarnessTest) cleanupStandbyNode(hn *node.HarnessNode) {
×
446
        // Remove connections made from this test.
×
447
        h.removeConnectionns(hn)
×
448

×
449
        // Delete all payments made from this test.
×
450
        hn.RPC.DeleteAllPayments()
×
451

×
452
        // Check the node's current state with timeout.
×
453
        //
×
454
        // NOTE: we need to do this in a `wait` because it takes some time for
×
455
        // the node to update its internal state. Once the RPCs are synced we
×
456
        // can then remove this wait.
×
457
        err := wait.NoError(func() error {
×
458
                // Update the node's internal state.
×
459
                hn.UpdateState()
×
460

×
461
                // Check the node is in a clean state for the following tests.
×
462
                return h.validateNodeState(hn)
×
463
        }, wait.DefaultTimeout)
×
464
        require.NoError(h, err, "timeout checking node's state")
×
465
}
466

467
// removeConnectionns will remove all connections made on the standby nodes
468
// expect the connections between Alice and Bob.
469
func (h *HarnessTest) removeConnectionns(hn *node.HarnessNode) {
×
470
        resp := hn.RPC.ListPeers()
×
471
        for _, peer := range resp.Peers {
×
472
                hn.RPC.DisconnectPeer(peer.PubKey)
×
473
        }
×
474
}
475

476
// SetTestName set the test case name.
477
func (h *HarnessTest) SetTestName(name string) {
×
478
        cleanTestCaseName := strings.ReplaceAll(name, " ", "_")
×
479
        h.manager.currentTestCase = cleanTestCaseName
×
480
}
×
481

482
// NewNode creates a new node and asserts its creation. The node is guaranteed
483
// to have finished its initialization and all its subservers are started.
484
func (h *HarnessTest) NewNode(name string,
485
        extraArgs []string) *node.HarnessNode {
×
486

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

×
490
        // Start the node.
×
491
        err = node.Start(h.runCtx)
×
492
        require.NoError(h, err, "failed to start node %s", node.Name())
×
493

×
494
        // Get the miner's best block hash.
×
495
        bestBlock, err := h.miner.Client.GetBestBlockHash()
×
496
        require.NoError(h, err, "unable to get best block hash")
×
497

×
498
        // Wait until the node's chain backend is synced to the miner's best
×
499
        // block.
×
500
        h.WaitForBlockchainSyncTo(node, *bestBlock)
×
501

×
502
        return node
×
503
}
×
504

505
// NewNodeWithCoins creates a new node and asserts its creation. The node is
506
// guaranteed to have finished its initialization and all its subservers are
507
// started. In addition, 5 UTXO of 1 BTC each are sent to the node.
508
func (h *HarnessTest) NewNodeWithCoins(name string,
509
        extraArgs []string) *node.HarnessNode {
×
510

×
511
        node := h.NewNode(name, extraArgs)
×
512

×
513
        // Load up the wallets of the node with 5 outputs of 1 BTC each.
×
514
        const (
×
515
                numOutputs  = 5
×
516
                fundAmount  = 1 * btcutil.SatoshiPerBitcoin
×
517
                totalAmount = fundAmount * numOutputs
×
518
        )
×
519

×
520
        for i := 0; i < numOutputs; i++ {
×
521
                h.createAndSendOutput(
×
522
                        node, fundAmount,
×
523
                        lnrpc.AddressType_WITNESS_PUBKEY_HASH,
×
524
                )
×
525
        }
×
526

527
        // Mine a block to confirm the transactions.
528
        h.MineBlocksAndAssertNumTxes(1, numOutputs)
×
529

×
530
        // Now block until the wallet have fully synced up.
×
531
        h.WaitForBalanceConfirmed(node, totalAmount)
×
532

×
533
        return node
×
534
}
535

536
// Shutdown shuts down the given node and asserts that no errors occur.
537
func (h *HarnessTest) Shutdown(node *node.HarnessNode) {
×
538
        err := h.manager.shutdownNode(node)
×
539
        require.NoErrorf(h, err, "unable to shutdown %v in %v", node.Name(),
×
540
                h.manager.currentTestCase)
×
541
}
×
542

543
// SuspendNode stops the given node and returns a callback that can be used to
544
// start it again.
545
func (h *HarnessTest) SuspendNode(node *node.HarnessNode) func() error {
×
546
        err := node.Stop()
×
547
        require.NoErrorf(h, err, "failed to stop %s", node.Name())
×
548

×
549
        // Remove the node from active nodes.
×
550
        delete(h.manager.activeNodes, node.Cfg.NodeID)
×
551

×
552
        return func() error {
×
553
                h.manager.registerNode(node)
×
554

×
555
                if err := node.Start(h.runCtx); err != nil {
×
556
                        return err
×
557
                }
×
558
                h.WaitForBlockchainSync(node)
×
559

×
560
                return nil
×
561
        }
562
}
563

564
// RestartNode restarts a given node, unlocks it and asserts it's successfully
565
// started.
566
func (h *HarnessTest) RestartNode(hn *node.HarnessNode) {
×
567
        err := h.manager.restartNode(h.runCtx, hn, nil)
×
568
        require.NoErrorf(h, err, "failed to restart node %s", hn.Name())
×
569

×
570
        err = h.manager.unlockNode(hn)
×
571
        require.NoErrorf(h, err, "failed to unlock node %s", hn.Name())
×
572

×
573
        if !hn.Cfg.SkipUnlock {
×
574
                // Give the node some time to catch up with the chain before we
×
575
                // continue with the tests.
×
576
                h.WaitForBlockchainSync(hn)
×
577
        }
×
578
}
579

580
// RestartNodeNoUnlock restarts a given node without unlocking its wallet.
581
func (h *HarnessTest) RestartNodeNoUnlock(hn *node.HarnessNode) {
×
582
        err := h.manager.restartNode(h.runCtx, hn, nil)
×
583
        require.NoErrorf(h, err, "failed to restart node %s", hn.Name())
×
584
}
×
585

586
// RestartNodeWithChanBackups restarts a given node with the specified channel
587
// backups.
588
func (h *HarnessTest) RestartNodeWithChanBackups(hn *node.HarnessNode,
589
        chanBackups ...*lnrpc.ChanBackupSnapshot) {
×
590

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

×
594
        err = h.manager.unlockNode(hn, chanBackups...)
×
595
        require.NoErrorf(h, err, "failed to unlock node %s", hn.Name())
×
596

×
597
        // Give the node some time to catch up with the chain before we
×
598
        // continue with the tests.
×
599
        h.WaitForBlockchainSync(hn)
×
600
}
×
601

602
// RestartNodeWithExtraArgs updates the node's config and restarts it.
603
func (h *HarnessTest) RestartNodeWithExtraArgs(hn *node.HarnessNode,
604
        extraArgs []string) {
×
605

×
606
        hn.SetExtraArgs(extraArgs)
×
607
        h.RestartNode(hn)
×
608
}
×
609

610
// NewNodeWithSeed fully initializes a new HarnessNode after creating a fresh
611
// aezeed. The provided password is used as both the aezeed password and the
612
// wallet password. The generated mnemonic is returned along with the
613
// initialized harness node.
614
func (h *HarnessTest) NewNodeWithSeed(name string,
615
        extraArgs []string, password []byte,
616
        statelessInit bool) (*node.HarnessNode, []string, []byte) {
×
617

×
618
        // Create a request to generate a new aezeed. The new seed will have
×
619
        // the same password as the internal wallet.
×
620
        req := &lnrpc.GenSeedRequest{
×
621
                AezeedPassphrase: password,
×
622
                SeedEntropy:      nil,
×
623
        }
×
624

×
625
        return h.newNodeWithSeed(name, extraArgs, req, statelessInit)
×
626
}
×
627

628
// newNodeWithSeed creates and initializes a new HarnessNode such that it'll be
629
// ready to accept RPC calls. A `GenSeedRequest` is needed to generate the
630
// seed.
631
func (h *HarnessTest) newNodeWithSeed(name string,
632
        extraArgs []string, req *lnrpc.GenSeedRequest,
633
        statelessInit bool) (*node.HarnessNode, []string, []byte) {
×
634

×
635
        node, err := h.manager.newNode(
×
636
                h.T, name, extraArgs, req.AezeedPassphrase, true,
×
637
        )
×
638
        require.NoErrorf(h, err, "unable to create new node for %s", name)
×
639

×
640
        // Start the node with seed only, which will only create the `State`
×
641
        // and `WalletUnlocker` clients.
×
642
        err = node.StartWithNoAuth(h.runCtx)
×
643
        require.NoErrorf(h, err, "failed to start node %s", node.Name())
×
644

×
645
        // Generate a new seed.
×
646
        genSeedResp := node.RPC.GenSeed(req)
×
647

×
648
        // With the seed created, construct the init request to the node,
×
649
        // including the newly generated seed.
×
650
        initReq := &lnrpc.InitWalletRequest{
×
651
                WalletPassword:     req.AezeedPassphrase,
×
652
                CipherSeedMnemonic: genSeedResp.CipherSeedMnemonic,
×
653
                AezeedPassphrase:   req.AezeedPassphrase,
×
654
                StatelessInit:      statelessInit,
×
655
        }
×
656

×
657
        // Pass the init request via rpc to finish unlocking the node. This
×
658
        // will also initialize the macaroon-authenticated LightningClient.
×
659
        adminMac, err := h.manager.initWalletAndNode(node, initReq)
×
660
        require.NoErrorf(h, err, "failed to unlock and init node %s",
×
661
                node.Name())
×
662

×
663
        // In stateless initialization mode we get a macaroon back that we have
×
664
        // to return to the test, otherwise gRPC calls won't be possible since
×
665
        // there are no macaroon files created in that mode.
×
666
        // In stateful init the admin macaroon will just be nil.
×
667
        return node, genSeedResp.CipherSeedMnemonic, adminMac
×
668
}
×
669

670
// RestoreNodeWithSeed fully initializes a HarnessNode using a chosen mnemonic,
671
// password, recovery window, and optionally a set of static channel backups.
672
// After providing the initialization request to unlock the node, this method
673
// will finish initializing the LightningClient such that the HarnessNode can
674
// be used for regular rpc operations.
675
func (h *HarnessTest) RestoreNodeWithSeed(name string, extraArgs []string,
676
        password []byte, mnemonic []string, rootKey string,
677
        recoveryWindow int32,
678
        chanBackups *lnrpc.ChanBackupSnapshot) *node.HarnessNode {
×
679

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

×
683
        // Start the node with seed only, which will only create the `State`
×
684
        // and `WalletUnlocker` clients.
×
685
        err = n.StartWithNoAuth(h.runCtx)
×
686
        require.NoErrorf(h, err, "failed to start node %s", n.Name())
×
687

×
688
        // Create the wallet.
×
689
        initReq := &lnrpc.InitWalletRequest{
×
690
                WalletPassword:     password,
×
691
                CipherSeedMnemonic: mnemonic,
×
692
                AezeedPassphrase:   password,
×
693
                ExtendedMasterKey:  rootKey,
×
694
                RecoveryWindow:     recoveryWindow,
×
695
                ChannelBackups:     chanBackups,
×
696
        }
×
697
        _, err = h.manager.initWalletAndNode(n, initReq)
×
698
        require.NoErrorf(h, err, "failed to unlock and init node %s",
×
699
                n.Name())
×
700

×
701
        return n
×
702
}
×
703

704
// NewNodeEtcd starts a new node with seed that'll use an external etcd
705
// database as its storage. The passed cluster flag indicates that we'd like
706
// the node to join the cluster leader election. We won't wait until RPC is
707
// available (this is useful when the node is not expected to become the leader
708
// right away).
709
func (h *HarnessTest) NewNodeEtcd(name string, etcdCfg *etcd.Config,
710
        password []byte, cluster bool,
711
        leaderSessionTTL int) *node.HarnessNode {
×
712

×
713
        // We don't want to use the embedded etcd instance.
×
714
        h.manager.dbBackend = node.BackendBbolt
×
715

×
716
        extraArgs := node.ExtraArgsEtcd(
×
717
                etcdCfg, name, cluster, leaderSessionTTL,
×
718
        )
×
719
        node, err := h.manager.newNode(h.T, name, extraArgs, password, true)
×
720
        require.NoError(h, err, "failed to create new node with etcd")
×
721

×
722
        // Start the node daemon only.
×
723
        err = node.StartLndCmd(h.runCtx)
×
724
        require.NoError(h, err, "failed to start node %s", node.Name())
×
725

×
726
        return node
×
727
}
×
728

729
// NewNodeWithSeedEtcd starts a new node with seed that'll use an external etcd
730
// database as its storage. The passed cluster flag indicates that we'd like
731
// the node to join the cluster leader election.
732
func (h *HarnessTest) NewNodeWithSeedEtcd(name string, etcdCfg *etcd.Config,
733
        password []byte, statelessInit, cluster bool,
734
        leaderSessionTTL int) (*node.HarnessNode, []string, []byte) {
×
735

×
736
        // We don't want to use the embedded etcd instance.
×
737
        h.manager.dbBackend = node.BackendBbolt
×
738

×
739
        // Create a request to generate a new aezeed. The new seed will have
×
740
        // the same password as the internal wallet.
×
741
        req := &lnrpc.GenSeedRequest{
×
742
                AezeedPassphrase: password,
×
743
                SeedEntropy:      nil,
×
744
        }
×
745

×
746
        extraArgs := node.ExtraArgsEtcd(
×
747
                etcdCfg, name, cluster, leaderSessionTTL,
×
748
        )
×
749

×
750
        return h.newNodeWithSeed(name, extraArgs, req, statelessInit)
×
751
}
×
752

753
// NewNodeRemoteSigner creates a new remote signer node and asserts its
754
// creation.
755
func (h *HarnessTest) NewNodeRemoteSigner(name string, extraArgs []string,
756
        password []byte, watchOnly *lnrpc.WatchOnly) *node.HarnessNode {
×
757

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

×
761
        err = hn.StartWithNoAuth(h.runCtx)
×
762
        require.NoError(h, err, "failed to start node %s", name)
×
763

×
764
        // With the seed created, construct the init request to the node,
×
765
        // including the newly generated seed.
×
766
        initReq := &lnrpc.InitWalletRequest{
×
767
                WalletPassword: password,
×
768
                WatchOnly:      watchOnly,
×
769
        }
×
770

×
771
        // Pass the init request via rpc to finish unlocking the node. This
×
772
        // will also initialize the macaroon-authenticated LightningClient.
×
773
        _, err = h.manager.initWalletAndNode(hn, initReq)
×
774
        require.NoErrorf(h, err, "failed to init node %s", name)
×
775

×
776
        return hn
×
777
}
×
778

779
// KillNode kills the node and waits for the node process to stop.
780
func (h *HarnessTest) KillNode(hn *node.HarnessNode) {
×
781
        delete(h.manager.activeNodes, hn.Cfg.NodeID)
×
782

×
783
        h.Logf("Manually killing the node %s", hn.Name())
×
784
        require.NoErrorf(h, hn.KillAndWait(), "%s: kill got error", hn.Name())
×
785
}
×
786

787
// SetFeeEstimate sets a fee rate to be returned from fee estimator.
788
//
789
// NOTE: this method will set the fee rate for a conf target of 1, which is the
790
// fallback fee rate for a `WebAPIEstimator` if a higher conf target's fee rate
791
// is not set. This means if the fee rate for conf target 6 is set, the fee
792
// estimator will use that value instead.
793
func (h *HarnessTest) SetFeeEstimate(fee chainfee.SatPerKWeight) {
×
794
        h.feeService.SetFeeRate(fee, 1)
×
795
}
×
796

797
// SetFeeEstimateWithConf sets a fee rate of a specified conf target to be
798
// returned from fee estimator.
799
func (h *HarnessTest) SetFeeEstimateWithConf(
800
        fee chainfee.SatPerKWeight, conf uint32) {
×
801

×
802
        h.feeService.SetFeeRate(fee, conf)
×
803
}
×
804

805
// SetMinRelayFeerate sets a min relay fee rate to be returned from fee
806
// estimator.
807
func (h *HarnessTest) SetMinRelayFeerate(fee chainfee.SatPerKVByte) {
×
808
        h.feeService.SetMinRelayFeerate(fee)
×
809
}
×
810

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

833
        // The number of pending force close channels should be zero.
834
        if hn.State.CloseChannel.PendingForceClose != 0 {
×
835
                return errStr("pending force")
×
836
        }
×
837

838
        // The number of waiting close channels should be zero.
839
        if hn.State.CloseChannel.WaitingClose != 0 {
×
840
                return errStr("waiting close")
×
841
        }
×
842

843
        // Ths number of payments should be zero.
844
        if hn.State.Payment.Total != 0 {
×
845
                return fmt.Errorf("%s: found uncleaned payments, please "+
×
846
                        "delete all of them properly", hn.Name())
×
847
        }
×
848

849
        // The number of public edges should be zero.
850
        if hn.State.Edge.Public != 0 {
×
851
                return fmt.Errorf("%s: found active public egdes, please "+
×
852
                        "clean them properly", hn.Name())
×
853
        }
×
854

855
        // The number of edges should be zero.
856
        if hn.State.Edge.Total != 0 {
×
857
                return fmt.Errorf("%s: found active edges, please "+
×
858
                        "clean them properly", hn.Name())
×
859
        }
×
860

861
        return nil
×
862
}
863

864
// GetChanPointFundingTxid takes a channel point and converts it into a chain
865
// hash.
866
func (h *HarnessTest) GetChanPointFundingTxid(
867
        cp *lnrpc.ChannelPoint) chainhash.Hash {
×
868

×
869
        txid, err := lnrpc.GetChanPointFundingTxid(cp)
×
870
        require.NoError(h, err, "unable to get txid")
×
871

×
872
        return *txid
×
873
}
×
874

875
// OutPointFromChannelPoint creates an outpoint from a given channel point.
876
func (h *HarnessTest) OutPointFromChannelPoint(
877
        cp *lnrpc.ChannelPoint) wire.OutPoint {
×
878

×
879
        txid := h.GetChanPointFundingTxid(cp)
×
880
        return wire.OutPoint{
×
881
                Hash:  txid,
×
882
                Index: cp.OutputIndex,
×
883
        }
×
884
}
×
885

886
// OpenChannelParams houses the params to specify when opening a new channel.
887
type OpenChannelParams struct {
888
        // Amt is the local amount being put into the channel.
889
        Amt btcutil.Amount
890

891
        // PushAmt is the amount that should be pushed to the remote when the
892
        // channel is opened.
893
        PushAmt btcutil.Amount
894

895
        // Private is a boolan indicating whether the opened channel should be
896
        // private.
897
        Private bool
898

899
        // SpendUnconfirmed is a boolean indicating whether we can utilize
900
        // unconfirmed outputs to fund the channel.
901
        SpendUnconfirmed bool
902

903
        // MinHtlc is the htlc_minimum_msat value set when opening the channel.
904
        MinHtlc lnwire.MilliSatoshi
905

906
        // RemoteMaxHtlcs is the remote_max_htlcs value set when opening the
907
        // channel, restricting the number of concurrent HTLCs the remote party
908
        // can add to a commitment.
909
        RemoteMaxHtlcs uint16
910

911
        // FundingShim is an optional funding shim that the caller can specify
912
        // in order to modify the channel funding workflow.
913
        FundingShim *lnrpc.FundingShim
914

915
        // SatPerVByte is the amount of satoshis to spend in chain fees per
916
        // virtual byte of the transaction.
917
        SatPerVByte btcutil.Amount
918

919
        // ConfTarget is the number of blocks that the funding transaction
920
        // should be confirmed in.
921
        ConfTarget fn.Option[int32]
922

923
        // CommitmentType is the commitment type that should be used for the
924
        // channel to be opened.
925
        CommitmentType lnrpc.CommitmentType
926

927
        // ZeroConf is used to determine if the channel will be a zero-conf
928
        // channel. This only works if the explicit negotiation is used with
929
        // anchors or script enforced leases.
930
        ZeroConf bool
931

932
        // ScidAlias denotes whether the channel will be an option-scid-alias
933
        // channel type negotiation.
934
        ScidAlias bool
935

936
        // BaseFee is the channel base fee applied during the channel
937
        // announcement phase.
938
        BaseFee uint64
939

940
        // FeeRate is the channel fee rate in ppm applied during the channel
941
        // announcement phase.
942
        FeeRate uint64
943

944
        // UseBaseFee, if set, instructs the downstream logic to apply the
945
        // user-specified channel base fee to the channel update announcement.
946
        // If set to false it avoids applying a base fee of 0 and instead
947
        // activates the default configured base fee.
948
        UseBaseFee bool
949

950
        // UseFeeRate, if set, instructs the downstream logic to apply the
951
        // user-specified channel fee rate to the channel update announcement.
952
        // If set to false it avoids applying a fee rate of 0 and instead
953
        // activates the default configured fee rate.
954
        UseFeeRate bool
955

956
        // FundMax is a boolean indicating whether the channel should be funded
957
        // with the maximum possible amount from the wallet.
958
        FundMax bool
959

960
        // An optional note-to-self containing some useful information about the
961
        // channel. This is stored locally only, and is purely for reference. It
962
        // has no bearing on the channel's operation. Max allowed length is 500
963
        // characters.
964
        Memo string
965

966
        // Outpoints is a list of client-selected outpoints that should be used
967
        // for funding a channel. If Amt is specified then this amount is
968
        // allocated from the sum of outpoints towards funding. If the
969
        // FundMax flag is specified the entirety of selected funds is
970
        // allocated towards channel funding.
971
        Outpoints []*lnrpc.OutPoint
972

973
        // CloseAddress sets the upfront_shutdown_script parameter during
974
        // channel open. It is expected to be encoded as a bitcoin address.
975
        CloseAddress string
976
}
977

978
// prepareOpenChannel waits for both nodes to be synced to chain and returns an
979
// OpenChannelRequest.
980
func (h *HarnessTest) prepareOpenChannel(srcNode, destNode *node.HarnessNode,
981
        p OpenChannelParams) *lnrpc.OpenChannelRequest {
×
982

×
983
        // Wait until srcNode and destNode have the latest chain synced.
×
984
        // Otherwise, we may run into a check within the funding manager that
×
985
        // prevents any funding workflows from being kicked off if the chain
×
986
        // isn't yet synced.
×
987
        h.WaitForBlockchainSync(srcNode)
×
988
        h.WaitForBlockchainSync(destNode)
×
989

×
990
        // Specify the minimal confirmations of the UTXOs used for channel
×
991
        // funding.
×
992
        minConfs := int32(1)
×
993
        if p.SpendUnconfirmed {
×
994
                minConfs = 0
×
995
        }
×
996

997
        // Get the requested conf target. If not set, default to 6.
998
        confTarget := p.ConfTarget.UnwrapOr(6)
×
999

×
1000
        // If there's fee rate set, unset the conf target.
×
1001
        if p.SatPerVByte != 0 {
×
1002
                confTarget = 0
×
1003
        }
×
1004

1005
        // Prepare the request.
1006
        return &lnrpc.OpenChannelRequest{
×
1007
                NodePubkey:         destNode.PubKey[:],
×
1008
                LocalFundingAmount: int64(p.Amt),
×
1009
                PushSat:            int64(p.PushAmt),
×
1010
                Private:            p.Private,
×
1011
                TargetConf:         confTarget,
×
1012
                MinConfs:           minConfs,
×
1013
                SpendUnconfirmed:   p.SpendUnconfirmed,
×
1014
                MinHtlcMsat:        int64(p.MinHtlc),
×
1015
                RemoteMaxHtlcs:     uint32(p.RemoteMaxHtlcs),
×
1016
                FundingShim:        p.FundingShim,
×
1017
                SatPerVbyte:        uint64(p.SatPerVByte),
×
1018
                CommitmentType:     p.CommitmentType,
×
1019
                ZeroConf:           p.ZeroConf,
×
1020
                ScidAlias:          p.ScidAlias,
×
1021
                BaseFee:            p.BaseFee,
×
1022
                FeeRate:            p.FeeRate,
×
1023
                UseBaseFee:         p.UseBaseFee,
×
1024
                UseFeeRate:         p.UseFeeRate,
×
1025
                FundMax:            p.FundMax,
×
1026
                Memo:               p.Memo,
×
1027
                Outpoints:          p.Outpoints,
×
1028
                CloseAddress:       p.CloseAddress,
×
1029
        }
×
1030
}
1031

1032
// OpenChannelAssertPending attempts to open a channel between srcNode and
1033
// destNode with the passed channel funding parameters. Once the `OpenChannel`
1034
// is called, it will consume the first event it receives from the open channel
1035
// client and asserts it's a channel pending event.
1036
func (h *HarnessTest) openChannelAssertPending(srcNode,
1037
        destNode *node.HarnessNode,
1038
        p OpenChannelParams) (*lnrpc.PendingUpdate, rpc.OpenChanClient) {
×
1039

×
1040
        // Prepare the request and open the channel.
×
1041
        openReq := h.prepareOpenChannel(srcNode, destNode, p)
×
1042
        respStream := srcNode.RPC.OpenChannel(openReq)
×
1043

×
1044
        // Consume the "channel pending" update. This waits until the node
×
1045
        // notifies us that the final message in the channel funding workflow
×
1046
        // has been sent to the remote node.
×
1047
        resp := h.ReceiveOpenChannelUpdate(respStream)
×
1048

×
1049
        // Check that the update is channel pending.
×
1050
        update, ok := resp.Update.(*lnrpc.OpenStatusUpdate_ChanPending)
×
1051
        require.Truef(h, ok, "expected channel pending: update, instead got %v",
×
1052
                resp)
×
1053

×
1054
        return update.ChanPending, respStream
×
1055
}
×
1056

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

×
1065
        resp, _ := h.openChannelAssertPending(srcNode, destNode, p)
×
1066
        return resp
×
1067
}
×
1068

1069
// OpenChannelAssertStream attempts to open a channel between srcNode and
1070
// destNode with the passed channel funding parameters. Once the `OpenChannel`
1071
// is called, it will consume the first event it receives from the open channel
1072
// client and asserts it's a channel pending event. It returns the open channel
1073
// stream.
1074
func (h *HarnessTest) OpenChannelAssertStream(srcNode,
1075
        destNode *node.HarnessNode, p OpenChannelParams) rpc.OpenChanClient {
×
1076

×
1077
        _, stream := h.openChannelAssertPending(srcNode, destNode, p)
×
1078
        return stream
×
1079
}
×
1080

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

×
1093
        // First, open the channel without announcing it.
×
1094
        cp := h.OpenChannelNoAnnounce(alice, bob, p)
×
1095

×
1096
        // If this is a private channel, there's no need to mine extra blocks
×
1097
        // since it will never be announced to the network.
×
1098
        if p.Private {
×
1099
                return cp
×
1100
        }
×
1101

1102
        // Mine extra blocks to announce the channel.
1103
        if p.ZeroConf {
×
1104
                // For a zero-conf channel, no blocks have been mined so we
×
1105
                // need to mine 6 blocks.
×
1106
                //
×
1107
                // Mine 1 block to confirm the funding transaction.
×
1108
                h.MineBlocksAndAssertNumTxes(numBlocksOpenChannel, 1)
×
1109
        } else {
×
1110
                // For a regular channel, 1 block has already been mined to
×
1111
                // confirm the funding transaction, so we mine 5 blocks.
×
1112
                h.MineBlocks(numBlocksOpenChannel - 1)
×
1113
        }
×
1114

1115
        return cp
×
1116
}
1117

1118
// OpenChannelNoAnnounce attempts to open a channel with the specified
1119
// parameters extended from Alice to Bob without mining the necessary blocks to
1120
// announce the channel. Additionally, the following items are asserted,
1121
//   - for non-zero conf channel, 1 blocks will be mined to confirm the funding
1122
//     tx.
1123
//   - both nodes should see the channel edge update in their network graph.
1124
//   - both nodes can report the status of the new channel from ListChannels.
1125
func (h *HarnessTest) OpenChannelNoAnnounce(alice, bob *node.HarnessNode,
1126
        p OpenChannelParams) *lnrpc.ChannelPoint {
×
1127

×
1128
        chanOpenUpdate := h.OpenChannelAssertStream(alice, bob, p)
×
1129

×
1130
        // Open a zero conf channel.
×
1131
        if p.ZeroConf {
×
1132
                return h.openChannelZeroConf(alice, bob, chanOpenUpdate)
×
1133
        }
×
1134

1135
        // Open a non-zero conf channel.
1136
        return h.openChannel(alice, bob, chanOpenUpdate)
×
1137
}
1138

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

×
1147
        // Mine 1 block to confirm the funding transaction.
×
1148
        block := h.MineBlocksAndAssertNumTxes(1, 1)[0]
×
1149

×
1150
        // Wait for the channel open event.
×
1151
        fundingChanPoint := h.WaitForChannelOpenEvent(stream)
×
1152

×
1153
        // Check that the funding tx is found in the first block.
×
1154
        fundingTxID := h.GetChanPointFundingTxid(fundingChanPoint)
×
1155
        h.AssertTxInBlock(block, fundingTxID)
×
1156

×
1157
        // Check that both alice and bob have seen the channel from their
×
1158
        // network topology.
×
1159
        h.AssertChannelInGraph(alice, fundingChanPoint)
×
1160
        h.AssertChannelInGraph(bob, fundingChanPoint)
×
1161

×
1162
        // Check that the channel can be seen in their ListChannels.
×
1163
        h.AssertChannelExists(alice, fundingChanPoint)
×
1164
        h.AssertChannelExists(bob, fundingChanPoint)
×
1165

×
1166
        return fundingChanPoint
×
1167
}
×
1168

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

×
1176
        // Wait for the channel open event.
×
1177
        fundingChanPoint := h.WaitForChannelOpenEvent(stream)
×
1178

×
1179
        // Check that both alice and bob have seen the channel from their
×
1180
        // network topology.
×
1181
        h.AssertChannelInGraph(alice, fundingChanPoint)
×
1182
        h.AssertChannelInGraph(bob, fundingChanPoint)
×
1183

×
1184
        // Finally, check that the channel can be seen in their ListChannels.
×
1185
        h.AssertChannelExists(alice, fundingChanPoint)
×
1186
        h.AssertChannelExists(bob, fundingChanPoint)
×
1187

×
1188
        return fundingChanPoint
×
1189
}
×
1190

1191
// OpenChannelAssertErr opens a channel between node srcNode and destNode,
1192
// asserts that the expected error is returned from the channel opening.
1193
func (h *HarnessTest) OpenChannelAssertErr(srcNode, destNode *node.HarnessNode,
1194
        p OpenChannelParams, expectedErr error) {
×
1195

×
1196
        // Prepare the request and open the channel.
×
1197
        openReq := h.prepareOpenChannel(srcNode, destNode, p)
×
1198
        respStream := srcNode.RPC.OpenChannel(openReq)
×
1199

×
1200
        // Receive an error to be sent from the stream.
×
1201
        _, err := h.receiveOpenChannelUpdate(respStream)
×
1202
        require.NotNil(h, err, "expected channel opening to fail")
×
1203

×
1204
        // Use string comparison here as we haven't codified all the RPC errors
×
1205
        // yet.
×
1206
        require.Containsf(h, err.Error(), expectedErr.Error(), "unexpected "+
×
1207
                "error returned, want %v, got %v", expectedErr, err)
×
1208
}
×
1209

1210
// closeChannelOpts holds the options for closing a channel.
1211
type closeChannelOpts struct {
1212
        feeRate fn.Option[chainfee.SatPerVByte]
1213

1214
        // localTxOnly is a boolean indicating if we should only attempt to
1215
        // consume close pending notifications for the local transaction.
1216
        localTxOnly bool
1217

1218
        // skipMempoolCheck is a boolean indicating if we should skip the normal
1219
        // mempool check after a coop close.
1220
        skipMempoolCheck bool
1221

1222
        // errString is an expected error. If this is non-blank, then we'll
1223
        // assert that the coop close wasn't possible, and returns an error that
1224
        // contains this err string.
1225
        errString string
1226
}
1227

1228
// CloseChanOpt is a functional option to modify the way we close a channel.
1229
type CloseChanOpt func(*closeChannelOpts)
1230

1231
// WithCoopCloseFeeRate is a functional option to set the fee rate for a coop
1232
// close attempt.
1233
func WithCoopCloseFeeRate(rate chainfee.SatPerVByte) CloseChanOpt {
×
1234
        return func(o *closeChannelOpts) {
×
1235
                o.feeRate = fn.Some(rate)
×
1236
        }
×
1237
}
1238

1239
// WithLocalTxNotify is a functional option to indicate that we should only
1240
// notify for the local txn. This is useful for the RBF coop close type, as
1241
// it'll notify for both local and remote txns.
1242
func WithLocalTxNotify() CloseChanOpt {
×
1243
        return func(o *closeChannelOpts) {
×
1244
                o.localTxOnly = true
×
1245
        }
×
1246
}
1247

1248
// WithSkipMempoolCheck is a functional option to indicate that we should skip
1249
// the mempool check. This can be used when a coop close iteration may not
1250
// result in a newly broadcast transaction.
1251
func WithSkipMempoolCheck() CloseChanOpt {
×
1252
        return func(o *closeChannelOpts) {
×
1253
                o.skipMempoolCheck = true
×
1254
        }
×
1255
}
1256

1257
// WithExpectedErrString is a functional option that can be used to assert that
1258
// an error occurs during the coop close process.
1259
func WithExpectedErrString(errString string) CloseChanOpt {
×
1260
        return func(o *closeChannelOpts) {
×
1261
                o.errString = errString
×
1262
        }
×
1263
}
1264

1265
// defaultCloseOpts returns the set of default close options.
1266
func defaultCloseOpts() *closeChannelOpts {
×
1267
        return &closeChannelOpts{}
×
1268
}
×
1269

1270
// CloseChannelAssertPending attempts to close the channel indicated by the
1271
// passed channel point, initiated by the passed node. Once the CloseChannel
1272
// rpc is called, it will consume one event and assert it's a close pending
1273
// event. In addition, it will check that the closing tx can be found in the
1274
// mempool.
1275
func (h *HarnessTest) CloseChannelAssertPending(hn *node.HarnessNode,
1276
        cp *lnrpc.ChannelPoint, force bool,
1277
        opts ...CloseChanOpt) (rpc.CloseChanClient, *lnrpc.CloseStatusUpdate) {
×
1278

×
1279
        closeOpts := defaultCloseOpts()
×
1280
        for _, optFunc := range opts {
×
1281
                optFunc(closeOpts)
×
1282
        }
×
1283

1284
        // Calls the rpc to close the channel.
1285
        closeReq := &lnrpc.CloseChannelRequest{
×
1286
                ChannelPoint: cp,
×
1287
                Force:        force,
×
1288
                NoWait:       true,
×
1289
        }
×
1290

×
1291
        closeOpts.feeRate.WhenSome(func(feeRate chainfee.SatPerVByte) {
×
1292
                closeReq.SatPerVbyte = uint64(feeRate)
×
1293
        })
×
1294

1295
        var (
×
1296
                stream rpc.CloseChanClient
×
1297
                event  *lnrpc.CloseStatusUpdate
×
1298
                err    error
×
1299
        )
×
1300

×
1301
        // Consume the "channel close" update in order to wait for the closing
×
1302
        // transaction to be broadcast, then wait for the closing tx to be seen
×
1303
        // within the network.
×
1304
        stream = hn.RPC.CloseChannel(closeReq)
×
1305
        _, err = h.ReceiveCloseChannelUpdate(stream)
×
1306
        require.NoError(h, err, "close channel update got error: %v", err)
×
1307

×
1308
        var closeTxid *chainhash.Hash
×
1309
        for {
×
1310
                event, err = h.ReceiveCloseChannelUpdate(stream)
×
1311
                if err != nil {
×
1312
                        h.Logf("Test: %s, close channel got error: %v",
×
1313
                                h.manager.currentTestCase, err)
×
1314
                }
×
1315
                if err != nil && closeOpts.errString == "" {
×
1316
                        require.NoError(h, err, "retry closing channel failed")
×
1317
                } else if err != nil && closeOpts.errString != "" {
×
1318
                        require.ErrorContains(h, err, closeOpts.errString)
×
1319
                        return nil, nil
×
1320
                }
×
1321

1322
                pendingClose, ok := event.Update.(*lnrpc.CloseStatusUpdate_ClosePending) //nolint:ll
×
1323
                require.Truef(h, ok, "expected channel close "+
×
1324
                        "update, instead got %v", pendingClose)
×
1325

×
1326
                if !pendingClose.ClosePending.LocalCloseTx &&
×
1327
                        closeOpts.localTxOnly {
×
1328

×
1329
                        continue
×
1330
                }
1331

1332
                notifyRate := pendingClose.ClosePending.FeePerVbyte
×
1333
                if closeOpts.localTxOnly &&
×
1334
                        notifyRate != int64(closeReq.SatPerVbyte) {
×
1335

×
1336
                        continue
×
1337
                }
1338

1339
                closeTxid, err = chainhash.NewHash(
×
1340
                        pendingClose.ClosePending.Txid,
×
1341
                )
×
1342
                require.NoErrorf(h, err, "unable to decode closeTxid: %v",
×
1343
                        pendingClose.ClosePending.Txid)
×
1344

×
1345
                break
×
1346
        }
1347

1348
        if !closeOpts.skipMempoolCheck {
×
1349
                // Assert the closing tx is in the mempool.
×
1350
                h.miner.AssertTxInMempool(*closeTxid)
×
1351
        }
×
1352

1353
        return stream, event
×
1354
}
1355

1356
// CloseChannel attempts to coop close a non-anchored channel identified by the
1357
// passed channel point owned by the passed harness node. The following items
1358
// 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
func (h *HarnessTest) CloseChannel(hn *node.HarnessNode,
1366
        cp *lnrpc.ChannelPoint) chainhash.Hash {
×
1367

×
1368
        stream, _ := h.CloseChannelAssertPending(hn, cp, false)
×
1369

×
1370
        return h.AssertStreamChannelCoopClosed(hn, cp, false, stream)
×
1371
}
×
1372

1373
// ForceCloseChannel attempts to force close a non-anchored channel identified
1374
// by the passed channel point owned by the passed harness node. The following
1375
// items are asserted,
1376
//  1. a close pending event is sent from the close channel client.
1377
//  2. the closing tx is found in the mempool.
1378
//  3. the node reports the channel being waiting to close.
1379
//  4. a block is mined and the closing tx should be found in it.
1380
//  5. the node reports zero waiting close channels.
1381
//  6. the node receives a topology update regarding the channel close.
1382
//  7. mine DefaultCSV-1 blocks.
1383
//  8. the node reports zero pending force close channels.
1384
func (h *HarnessTest) ForceCloseChannel(hn *node.HarnessNode,
1385
        cp *lnrpc.ChannelPoint) chainhash.Hash {
×
1386

×
1387
        stream, _ := h.CloseChannelAssertPending(hn, cp, true)
×
1388

×
1389
        closingTxid := h.AssertStreamChannelForceClosed(hn, cp, false, stream)
×
1390

×
1391
        // Cleanup the force close.
×
1392
        h.CleanupForceClose(hn)
×
1393

×
1394
        return closingTxid
×
1395
}
×
1396

1397
// CloseChannelAssertErr closes the given channel and asserts an error
1398
// returned.
1399
func (h *HarnessTest) CloseChannelAssertErr(hn *node.HarnessNode,
1400
        req *lnrpc.CloseChannelRequest) error {
×
1401

×
1402
        // Calls the rpc to close the channel.
×
1403
        stream := hn.RPC.CloseChannel(req)
×
1404

×
1405
        // Consume the "channel close" update in order to wait for the closing
×
1406
        // transaction to be broadcast, then wait for the closing tx to be seen
×
1407
        // within the network.
×
1408
        _, err := h.ReceiveCloseChannelUpdate(stream)
×
1409
        require.Errorf(h, err, "%s: expect close channel to return an error",
×
1410
                hn.Name())
×
1411

×
1412
        return err
×
1413
}
×
1414

1415
// IsNeutrinoBackend returns a bool indicating whether the node is using a
1416
// neutrino as its backend. This is useful when we want to skip certain tests
1417
// which cannot be done with a neutrino backend.
1418
func (h *HarnessTest) IsNeutrinoBackend() bool {
×
1419
        return h.manager.chainBackend.Name() == NeutrinoBackendName
×
1420
}
×
1421

1422
// fundCoins attempts to send amt satoshis from the internal mining node to the
1423
// targeted lightning node. The confirmed boolean indicates whether the
1424
// transaction that pays to the target should confirm. For neutrino backend,
1425
// the `confirmed` param is ignored.
1426
func (h *HarnessTest) fundCoins(amt btcutil.Amount, target *node.HarnessNode,
NEW
1427
        addrType lnrpc.AddressType, confirmed bool) *wire.MsgTx {
×
1428

×
1429
        initialBalance := target.RPC.WalletBalance()
×
1430

×
1431
        // First, obtain an address from the target lightning node, preferring
×
1432
        // to receive a p2wkh address s.t the output can immediately be used as
×
1433
        // an input to a funding transaction.
×
1434
        req := &lnrpc.NewAddressRequest{Type: addrType}
×
1435
        resp := target.RPC.NewAddress(req)
×
1436
        addr := h.DecodeAddress(resp.Address)
×
1437
        addrScript := h.PayToAddrScript(addr)
×
1438

×
1439
        // Generate a transaction which creates an output to the target
×
1440
        // pkScript of the desired amount.
×
1441
        output := &wire.TxOut{
×
1442
                PkScript: addrScript,
×
1443
                Value:    int64(amt),
×
1444
        }
×
NEW
1445
        txid := h.miner.SendOutput(output, defaultMinerFeeRate)
×
1446

×
NEW
1447
        // Get the funding tx.
×
NEW
1448
        tx := h.GetRawTransaction(*txid)
×
NEW
1449
        msgTx := tx.MsgTx()
×
1450

×
1451
        // Since neutrino doesn't support unconfirmed outputs, skip this check.
×
1452
        if !h.IsNeutrinoBackend() {
×
1453
                expectedBalance := btcutil.Amount(
×
1454
                        initialBalance.UnconfirmedBalance,
×
1455
                ) + amt
×
1456
                h.WaitForBalanceUnconfirmed(target, expectedBalance)
×
1457
        }
×
1458

1459
        // If the transaction should remain unconfirmed, then we'll wait until
1460
        // the target node's unconfirmed balance reflects the expected balance
1461
        // and exit.
1462
        if !confirmed {
×
NEW
1463
                return msgTx
×
1464
        }
×
1465

1466
        // Otherwise, we'll generate 1 new blocks to ensure the output gains a
1467
        // sufficient number of confirmations and wait for the balance to
1468
        // reflect what's expected.
NEW
1469
        h.MineBlockWithTx(msgTx)
×
1470

×
1471
        expectedBalance := btcutil.Amount(initialBalance.ConfirmedBalance) + amt
×
1472
        h.WaitForBalanceConfirmed(target, expectedBalance)
×
NEW
1473

×
NEW
1474
        return msgTx
×
1475
}
1476

1477
// FundCoins attempts to send amt satoshis from the internal mining node to the
1478
// targeted lightning node using a P2WKH address. 1 blocks are mined after in
1479
// order to confirm the transaction.
1480
func (h *HarnessTest) FundCoins(amt btcutil.Amount,
NEW
1481
        hn *node.HarnessNode) *wire.MsgTx {
×
NEW
1482

×
NEW
1483
        return h.fundCoins(amt, hn, lnrpc.AddressType_WITNESS_PUBKEY_HASH, true)
×
1484
}
×
1485

1486
// FundCoinsUnconfirmed attempts to send amt satoshis from the internal mining
1487
// node to the targeted lightning node using a P2WKH address. No blocks are
1488
// mined after and the UTXOs are unconfirmed.
1489
func (h *HarnessTest) FundCoinsUnconfirmed(amt btcutil.Amount,
NEW
1490
        hn *node.HarnessNode) *wire.MsgTx {
×
1491

×
NEW
1492
        return h.fundCoins(
×
NEW
1493
                amt, hn, lnrpc.AddressType_WITNESS_PUBKEY_HASH, false,
×
NEW
1494
        )
×
1495
}
×
1496

1497
// FundCoinsNP2WKH attempts to send amt satoshis from the internal mining node
1498
// to the targeted lightning node using a NP2WKH address.
1499
func (h *HarnessTest) FundCoinsNP2WKH(amt btcutil.Amount,
NEW
1500
        target *node.HarnessNode) *wire.MsgTx {
×
1501

×
NEW
1502
        return h.fundCoins(
×
NEW
1503
                amt, target, lnrpc.AddressType_NESTED_PUBKEY_HASH, true,
×
NEW
1504
        )
×
1505
}
×
1506

1507
// FundCoinsP2TR attempts to send amt satoshis from the internal mining node to
1508
// the targeted lightning node using a P2TR address.
1509
func (h *HarnessTest) FundCoinsP2TR(amt btcutil.Amount,
NEW
1510
        target *node.HarnessNode) *wire.MsgTx {
×
1511

×
NEW
1512
        return h.fundCoins(amt, target, lnrpc.AddressType_TAPROOT_PUBKEY, true)
×
1513
}
×
1514

1515
// FundNumCoins attempts to send the given number of UTXOs from the internal
1516
// mining node to the targeted lightning node using a P2WKH address. Each UTXO
1517
// has an amount of 1 BTC. 1 blocks are mined to confirm the tx.
1518
func (h *HarnessTest) FundNumCoins(hn *node.HarnessNode, num int) {
×
1519
        // Get the initial balance first.
×
1520
        resp := hn.RPC.WalletBalance()
×
1521
        initialBalance := btcutil.Amount(resp.ConfirmedBalance)
×
1522

×
1523
        const fundAmount = 1 * btcutil.SatoshiPerBitcoin
×
1524

×
1525
        // Send out the outputs from the miner.
×
1526
        for i := 0; i < num; i++ {
×
1527
                h.createAndSendOutput(
×
1528
                        hn, fundAmount, lnrpc.AddressType_WITNESS_PUBKEY_HASH,
×
1529
                )
×
1530
        }
×
1531

1532
        // Wait for ListUnspent to show the correct number of unconfirmed
1533
        // UTXOs.
1534
        //
1535
        // Since neutrino doesn't support unconfirmed outputs, skip this check.
1536
        if !h.IsNeutrinoBackend() {
×
1537
                h.AssertNumUTXOsUnconfirmed(hn, num)
×
1538
        }
×
1539

1540
        // Mine a block to confirm the transactions.
1541
        h.MineBlocksAndAssertNumTxes(1, num)
×
1542

×
1543
        // Now block until the wallet have fully synced up.
×
1544
        totalAmount := btcutil.Amount(fundAmount * num)
×
1545
        expectedBalance := initialBalance + totalAmount
×
1546
        h.WaitForBalanceConfirmed(hn, expectedBalance)
×
1547
}
1548

1549
// completePaymentRequestsAssertStatus sends payments from a node to complete
1550
// all payment requests. This function does not return until all payments
1551
// have reached the specified status.
1552
func (h *HarnessTest) completePaymentRequestsAssertStatus(hn *node.HarnessNode,
1553
        paymentRequests []string, status lnrpc.Payment_PaymentStatus,
1554
        opts ...HarnessOpt) {
×
1555

×
1556
        payOpts := defaultHarnessOpts()
×
1557
        for _, opt := range opts {
×
1558
                opt(&payOpts)
×
1559
        }
×
1560

1561
        // Create a buffered chan to signal the results.
1562
        results := make(chan rpc.PaymentClient, len(paymentRequests))
×
1563

×
1564
        // send sends a payment and asserts if it doesn't succeeded.
×
1565
        send := func(payReq string) {
×
1566
                req := &routerrpc.SendPaymentRequest{
×
1567
                        PaymentRequest: payReq,
×
1568
                        TimeoutSeconds: int32(wait.PaymentTimeout.Seconds()),
×
1569
                        FeeLimitMsat:   noFeeLimitMsat,
×
1570
                        Amp:            payOpts.useAMP,
×
1571
                }
×
1572
                stream := hn.RPC.SendPayment(req)
×
1573

×
1574
                // Signal sent succeeded.
×
1575
                results <- stream
×
1576
        }
×
1577

1578
        // Launch all payments simultaneously.
1579
        for _, payReq := range paymentRequests {
×
1580
                payReqCopy := payReq
×
1581
                go send(payReqCopy)
×
1582
        }
×
1583

1584
        // Wait for all payments to report the expected status.
1585
        timer := time.After(wait.PaymentTimeout)
×
1586
        select {
×
1587
        case stream := <-results:
×
1588
                h.AssertPaymentStatusFromStream(stream, status)
×
1589

1590
        case <-timer:
×
1591
                require.Fail(h, "timeout", "waiting payment results timeout")
×
1592
        }
1593
}
1594

1595
// CompletePaymentRequests sends payments from a node to complete all payment
1596
// requests. This function does not return until all payments successfully
1597
// complete without errors.
1598
func (h *HarnessTest) CompletePaymentRequests(hn *node.HarnessNode,
1599
        paymentRequests []string, opts ...HarnessOpt) {
×
1600

×
1601
        h.completePaymentRequestsAssertStatus(
×
1602
                hn, paymentRequests, lnrpc.Payment_SUCCEEDED, opts...,
×
1603
        )
×
1604
}
×
1605

1606
// CompletePaymentRequestsNoWait sends payments from a node to complete all
1607
// payment requests without waiting for the results. Instead, it checks the
1608
// number of updates in the specified channel has increased.
1609
func (h *HarnessTest) CompletePaymentRequestsNoWait(hn *node.HarnessNode,
1610
        paymentRequests []string, chanPoint *lnrpc.ChannelPoint) {
×
1611

×
1612
        // We start by getting the current state of the client's channels. This
×
1613
        // is needed to ensure the payments actually have been committed before
×
1614
        // we return.
×
1615
        oldResp := h.GetChannelByChanPoint(hn, chanPoint)
×
1616

×
1617
        // Send payments and assert they are in-flight.
×
1618
        h.completePaymentRequestsAssertStatus(
×
1619
                hn, paymentRequests, lnrpc.Payment_IN_FLIGHT,
×
1620
        )
×
1621

×
1622
        // We are not waiting for feedback in the form of a response, but we
×
1623
        // should still wait long enough for the server to receive and handle
×
1624
        // the send before cancelling the request. We wait for the number of
×
1625
        // updates to one of our channels has increased before we return.
×
1626
        err := wait.NoError(func() error {
×
1627
                newResp := h.GetChannelByChanPoint(hn, chanPoint)
×
1628

×
1629
                // If this channel has an increased number of updates, we
×
1630
                // assume the payments are committed, and we can return.
×
1631
                if newResp.NumUpdates > oldResp.NumUpdates {
×
1632
                        return nil
×
1633
                }
×
1634

1635
                // Otherwise return an error as the NumUpdates are not
1636
                // increased.
1637
                return fmt.Errorf("%s: channel:%v not updated after sending "+
×
1638
                        "payments, old updates: %v, new updates: %v", hn.Name(),
×
1639
                        chanPoint, oldResp.NumUpdates, newResp.NumUpdates)
×
1640
        }, DefaultTimeout)
1641
        require.NoError(h, err, "timeout while checking for channel updates")
×
1642
}
1643

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

×
1650
        // Wait until srcNode and destNode have the latest chain synced.
×
1651
        // Otherwise, we may run into a check within the funding manager that
×
1652
        // prevents any funding workflows from being kicked off if the chain
×
1653
        // isn't yet synced.
×
1654
        h.WaitForBlockchainSync(srcNode)
×
1655
        h.WaitForBlockchainSync(destNode)
×
1656

×
1657
        // Send the request to open a channel to the source node now. This will
×
1658
        // open a long-lived stream where we'll receive status updates about
×
1659
        // the progress of the channel.
×
1660
        // respStream := h.OpenChannelStreamAndAssert(srcNode, destNode, p)
×
1661
        req := &lnrpc.OpenChannelRequest{
×
1662
                NodePubkey:         destNode.PubKey[:],
×
1663
                LocalFundingAmount: int64(p.Amt),
×
1664
                PushSat:            int64(p.PushAmt),
×
1665
                Private:            p.Private,
×
1666
                SpendUnconfirmed:   p.SpendUnconfirmed,
×
1667
                MinHtlcMsat:        int64(p.MinHtlc),
×
1668
                FundingShim:        p.FundingShim,
×
1669
                CommitmentType:     p.CommitmentType,
×
1670
        }
×
1671
        respStream := srcNode.RPC.OpenChannel(req)
×
1672

×
1673
        // Consume the "PSBT funding ready" update. This waits until the node
×
1674
        // notifies us that the PSBT can now be funded.
×
1675
        resp := h.ReceiveOpenChannelUpdate(respStream)
×
1676
        upd, ok := resp.Update.(*lnrpc.OpenStatusUpdate_PsbtFund)
×
1677
        require.Truef(h, ok, "expected PSBT funding update, got %v", resp)
×
1678

×
1679
        // Make sure the channel funding address has the correct type for the
×
1680
        // given commitment type.
×
1681
        fundingAddr, err := btcutil.DecodeAddress(
×
1682
                upd.PsbtFund.FundingAddress, miner.HarnessNetParams,
×
1683
        )
×
1684
        require.NoError(h, err)
×
1685

×
1686
        switch p.CommitmentType {
×
1687
        case lnrpc.CommitmentType_SIMPLE_TAPROOT:
×
1688
                require.IsType(h, &btcutil.AddressTaproot{}, fundingAddr)
×
1689

1690
        default:
×
1691
                require.IsType(
×
1692
                        h, &btcutil.AddressWitnessScriptHash{}, fundingAddr,
×
1693
                )
×
1694
        }
1695

1696
        return respStream, upd.PsbtFund.Psbt
×
1697
}
1698

1699
// CleanupForceClose mines blocks to clean up the force close process. This is
1700
// used for tests that are not asserting the expected behavior is found during
1701
// the force close process, e.g., num of sweeps, etc. Instead, it provides a
1702
// shortcut to move the test forward with a clean mempool.
1703
func (h *HarnessTest) CleanupForceClose(hn *node.HarnessNode) {
×
1704
        // Wait for the channel to be marked pending force close.
×
1705
        h.AssertNumPendingForceClose(hn, 1)
×
1706

×
1707
        // Mine enough blocks for the node to sweep its funds from the force
×
1708
        // closed channel. The commit sweep resolver is offers the input to the
×
1709
        // sweeper when it's force closed, and broadcast the sweep tx at
×
1710
        // defaulCSV-1.
×
1711
        //
×
1712
        // NOTE: we might empty blocks here as we don't know the exact number
×
1713
        // of blocks to mine. This may end up mining more blocks than needed.
×
1714
        h.MineEmptyBlocks(node.DefaultCSV - 1)
×
1715

×
1716
        // Assert there is one pending sweep.
×
1717
        h.AssertNumPendingSweeps(hn, 1)
×
1718

×
1719
        // The node should now sweep the funds, clean up by mining the sweeping
×
1720
        // tx.
×
1721
        h.MineBlocksAndAssertNumTxes(1, 1)
×
1722

×
1723
        // Mine blocks to get any second level HTLC resolved. If there are no
×
1724
        // HTLCs, this will behave like h.AssertNumPendingCloseChannels.
×
1725
        h.mineTillForceCloseResolved(hn)
×
1726
}
×
1727

1728
// CreatePayReqs is a helper method that will create a slice of payment
1729
// requests for the given node.
1730
func (h *HarnessTest) CreatePayReqs(hn *node.HarnessNode,
1731
        paymentAmt btcutil.Amount, numInvoices int,
1732
        routeHints ...*lnrpc.RouteHint) ([]string, [][]byte, []*lnrpc.Invoice) {
×
1733

×
1734
        payReqs := make([]string, numInvoices)
×
1735
        rHashes := make([][]byte, numInvoices)
×
1736
        invoices := make([]*lnrpc.Invoice, numInvoices)
×
1737
        for i := 0; i < numInvoices; i++ {
×
1738
                preimage := h.Random32Bytes()
×
1739

×
1740
                invoice := &lnrpc.Invoice{
×
1741
                        Memo:       "testing",
×
1742
                        RPreimage:  preimage,
×
1743
                        Value:      int64(paymentAmt),
×
1744
                        RouteHints: routeHints,
×
1745
                }
×
1746
                resp := hn.RPC.AddInvoice(invoice)
×
1747

×
1748
                // Set the payment address in the invoice so the caller can
×
1749
                // properly use it.
×
1750
                invoice.PaymentAddr = resp.PaymentAddr
×
1751

×
1752
                payReqs[i] = resp.PaymentRequest
×
1753
                rHashes[i] = resp.RHash
×
1754
                invoices[i] = invoice
×
1755
        }
×
1756

1757
        return payReqs, rHashes, invoices
×
1758
}
1759

1760
// BackupDB creates a backup of the current database. It will stop the node
1761
// first, copy the database files, and restart the node.
1762
func (h *HarnessTest) BackupDB(hn *node.HarnessNode) {
×
1763
        restart := h.SuspendNode(hn)
×
1764

×
1765
        err := hn.BackupDB()
×
1766
        require.NoErrorf(h, err, "%s: failed to backup db", hn.Name())
×
1767

×
1768
        err = restart()
×
1769
        require.NoErrorf(h, err, "%s: failed to restart", hn.Name())
×
1770
}
×
1771

1772
// RestartNodeAndRestoreDB restarts a given node with a callback to restore the
1773
// db.
1774
func (h *HarnessTest) RestartNodeAndRestoreDB(hn *node.HarnessNode) {
×
1775
        cb := func() error { return hn.RestoreDB() }
×
1776
        err := h.manager.restartNode(h.runCtx, hn, cb)
×
1777
        require.NoErrorf(h, err, "failed to restart node %s", hn.Name())
×
1778

×
1779
        err = h.manager.unlockNode(hn)
×
1780
        require.NoErrorf(h, err, "failed to unlock node %s", hn.Name())
×
1781

×
1782
        // Give the node some time to catch up with the chain before we
×
1783
        // continue with the tests.
×
1784
        h.WaitForBlockchainSync(hn)
×
1785
}
1786

1787
// CleanShutDown is used to quickly end a test by shutting down all non-standby
1788
// nodes and mining blocks to empty the mempool.
1789
//
1790
// NOTE: this method provides a faster exit for a test that involves force
1791
// closures as the caller doesn't need to mine all the blocks to make sure the
1792
// mempool is empty.
1793
func (h *HarnessTest) CleanShutDown() {
×
1794
        // First, shutdown all nodes to prevent new transactions being created
×
1795
        // and fed into the mempool.
×
1796
        h.shutdownAllNodes()
×
1797

×
1798
        // Now mine blocks till the mempool is empty.
×
1799
        h.cleanMempool()
×
1800
}
×
1801

1802
// QueryChannelByChanPoint tries to find a channel matching the channel point
1803
// and asserts. It returns the channel found.
1804
func (h *HarnessTest) QueryChannelByChanPoint(hn *node.HarnessNode,
1805
        chanPoint *lnrpc.ChannelPoint,
1806
        opts ...ListChannelOption) *lnrpc.Channel {
×
1807

×
1808
        channel, err := h.findChannel(hn, chanPoint, opts...)
×
1809
        require.NoError(h, err, "failed to query channel")
×
1810

×
1811
        return channel
×
1812
}
×
1813

1814
// SendPaymentAndAssertStatus sends a payment from the passed node and asserts
1815
// the desired status is reached.
1816
func (h *HarnessTest) SendPaymentAndAssertStatus(hn *node.HarnessNode,
1817
        req *routerrpc.SendPaymentRequest,
1818
        status lnrpc.Payment_PaymentStatus) *lnrpc.Payment {
×
1819

×
1820
        stream := hn.RPC.SendPayment(req)
×
1821
        return h.AssertPaymentStatusFromStream(stream, status)
×
1822
}
×
1823

1824
// SendPaymentAssertFail sends a payment from the passed node and asserts the
1825
// payment is failed with the specified failure reason .
1826
func (h *HarnessTest) SendPaymentAssertFail(hn *node.HarnessNode,
1827
        req *routerrpc.SendPaymentRequest,
1828
        reason lnrpc.PaymentFailureReason) *lnrpc.Payment {
×
1829

×
1830
        payment := h.SendPaymentAndAssertStatus(hn, req, lnrpc.Payment_FAILED)
×
1831
        require.Equal(h, reason, payment.FailureReason,
×
1832
                "payment failureReason not matched")
×
1833

×
1834
        return payment
×
1835
}
×
1836

1837
// SendPaymentAssertSettled sends a payment from the passed node and asserts the
1838
// payment is settled.
1839
func (h *HarnessTest) SendPaymentAssertSettled(hn *node.HarnessNode,
1840
        req *routerrpc.SendPaymentRequest) *lnrpc.Payment {
×
1841

×
1842
        return h.SendPaymentAndAssertStatus(hn, req, lnrpc.Payment_SUCCEEDED)
×
1843
}
×
1844

1845
// SendPaymentAssertInflight sends a payment from the passed node and asserts
1846
// the payment is inflight.
1847
func (h *HarnessTest) SendPaymentAssertInflight(hn *node.HarnessNode,
1848
        req *routerrpc.SendPaymentRequest) *lnrpc.Payment {
×
1849

×
1850
        return h.SendPaymentAndAssertStatus(hn, req, lnrpc.Payment_IN_FLIGHT)
×
1851
}
×
1852

1853
// OpenChannelRequest is used to open a channel using the method
1854
// OpenMultiChannelsAsync.
1855
type OpenChannelRequest struct {
1856
        // Local is the funding node.
1857
        Local *node.HarnessNode
1858

1859
        // Remote is the receiving node.
1860
        Remote *node.HarnessNode
1861

1862
        // Param is the open channel params.
1863
        Param OpenChannelParams
1864

1865
        // stream is the client created after calling OpenChannel RPC.
1866
        stream rpc.OpenChanClient
1867

1868
        // result is a channel used to send the channel point once the funding
1869
        // has succeeded.
1870
        result chan *lnrpc.ChannelPoint
1871
}
1872

1873
// OpenMultiChannelsAsync takes a list of OpenChannelRequest and opens them in
1874
// batch. The channel points are returned in same the order of the requests
1875
// once all of the channel open succeeded.
1876
//
1877
// NOTE: compared to open multiple channel sequentially, this method will be
1878
// faster as it doesn't need to mine 6 blocks for each channel open. However,
1879
// it does make debugging the logs more difficult as messages are intertwined.
1880
func (h *HarnessTest) OpenMultiChannelsAsync(
1881
        reqs []*OpenChannelRequest) []*lnrpc.ChannelPoint {
×
1882

×
1883
        // openChannel opens a channel based on the request.
×
1884
        openChannel := func(req *OpenChannelRequest) {
×
1885
                stream := h.OpenChannelAssertStream(
×
1886
                        req.Local, req.Remote, req.Param,
×
1887
                )
×
1888
                req.stream = stream
×
1889
        }
×
1890

1891
        // assertChannelOpen is a helper closure that asserts a channel is
1892
        // open.
1893
        assertChannelOpen := func(req *OpenChannelRequest) {
×
1894
                // Wait for the channel open event from the stream.
×
1895
                cp := h.WaitForChannelOpenEvent(req.stream)
×
1896

×
1897
                if !req.Param.Private {
×
1898
                        // Check that both alice and bob have seen the channel
×
1899
                        // from their channel watch request.
×
1900
                        h.AssertChannelInGraph(req.Local, cp)
×
1901
                        h.AssertChannelInGraph(req.Remote, cp)
×
1902
                }
×
1903

1904
                // Finally, check that the channel can be seen in their
1905
                // ListChannels.
1906
                h.AssertChannelExists(req.Local, cp)
×
1907
                h.AssertChannelExists(req.Remote, cp)
×
1908

×
1909
                req.result <- cp
×
1910
        }
1911

1912
        // Go through the requests and make the OpenChannel RPC call.
1913
        for _, r := range reqs {
×
1914
                openChannel(r)
×
1915
        }
×
1916

1917
        // Mine one block to confirm all the funding transactions.
1918
        h.MineBlocksAndAssertNumTxes(1, len(reqs))
×
1919

×
1920
        // Mine 5 more blocks so all the public channels are announced to the
×
1921
        // network.
×
1922
        h.MineBlocks(numBlocksOpenChannel - 1)
×
1923

×
1924
        // Once the blocks are mined, we fire goroutines for each of the
×
1925
        // request to watch for the channel openning.
×
1926
        for _, r := range reqs {
×
1927
                r.result = make(chan *lnrpc.ChannelPoint, 1)
×
1928
                go assertChannelOpen(r)
×
1929
        }
×
1930

1931
        // Finally, collect the results.
1932
        channelPoints := make([]*lnrpc.ChannelPoint, 0)
×
1933
        for _, r := range reqs {
×
1934
                select {
×
1935
                case cp := <-r.result:
×
1936
                        channelPoints = append(channelPoints, cp)
×
1937

1938
                case <-time.After(wait.ChannelOpenTimeout):
×
1939
                        require.Failf(h, "timeout", "wait channel point "+
×
1940
                                "timeout for channel %s=>%s", r.Local.Name(),
×
1941
                                r.Remote.Name())
×
1942
                }
1943
        }
1944

1945
        // Assert that we have the expected num of channel points.
1946
        require.Len(h, channelPoints, len(reqs),
×
1947
                "returned channel points not match")
×
1948

×
1949
        return channelPoints
×
1950
}
1951

1952
// ReceiveInvoiceUpdate waits until a message is received on the subscribe
1953
// invoice stream or the timeout is reached.
1954
func (h *HarnessTest) ReceiveInvoiceUpdate(
1955
        stream rpc.InvoiceUpdateClient) *lnrpc.Invoice {
×
1956

×
1957
        chanMsg := make(chan *lnrpc.Invoice)
×
1958
        errChan := make(chan error)
×
1959
        go func() {
×
1960
                // Consume one message. This will block until the message is
×
1961
                // received.
×
1962
                resp, err := stream.Recv()
×
1963
                if err != nil {
×
1964
                        errChan <- err
×
1965
                        return
×
1966
                }
×
1967
                chanMsg <- resp
×
1968
        }()
1969

1970
        select {
×
1971
        case <-time.After(DefaultTimeout):
×
1972
                require.Fail(h, "timeout", "timeout receiving invoice update")
×
1973

1974
        case err := <-errChan:
×
1975
                require.Failf(h, "err from stream",
×
1976
                        "received err from stream: %v", err)
×
1977

1978
        case updateMsg := <-chanMsg:
×
1979
                return updateMsg
×
1980
        }
1981

1982
        return nil
×
1983
}
1984

1985
// CalculateTxFee retrieves parent transactions and reconstructs the fee paid.
1986
func (h *HarnessTest) CalculateTxFee(tx *wire.MsgTx) btcutil.Amount {
×
1987
        var balance btcutil.Amount
×
1988
        for _, in := range tx.TxIn {
×
1989
                parentHash := in.PreviousOutPoint.Hash
×
1990
                rawTx := h.miner.GetRawTransaction(parentHash)
×
1991
                parent := rawTx.MsgTx()
×
1992
                value := parent.TxOut[in.PreviousOutPoint.Index].Value
×
1993

×
1994
                balance += btcutil.Amount(value)
×
1995
        }
×
1996

1997
        for _, out := range tx.TxOut {
×
1998
                balance -= btcutil.Amount(out.Value)
×
1999
        }
×
2000

2001
        return balance
×
2002
}
2003

2004
// CalculateTxWeight calculates the weight for a given tx.
2005
//
2006
// TODO(yy): use weight estimator to get more accurate result.
2007
func (h *HarnessTest) CalculateTxWeight(tx *wire.MsgTx) lntypes.WeightUnit {
×
2008
        utx := btcutil.NewTx(tx)
×
2009
        return lntypes.WeightUnit(blockchain.GetTransactionWeight(utx))
×
2010
}
×
2011

2012
// CalculateTxFeeRate calculates the fee rate for a given tx.
2013
func (h *HarnessTest) CalculateTxFeeRate(
2014
        tx *wire.MsgTx) chainfee.SatPerKWeight {
×
2015

×
2016
        w := h.CalculateTxWeight(tx)
×
2017
        fee := h.CalculateTxFee(tx)
×
2018

×
2019
        return chainfee.NewSatPerKWeight(fee, w)
×
2020
}
×
2021

2022
// CalculateTxesFeeRate takes a list of transactions and estimates the fee rate
2023
// used to sweep them.
2024
//
2025
// NOTE: only used in current test file.
2026
func (h *HarnessTest) CalculateTxesFeeRate(txns []*wire.MsgTx) int64 {
×
2027
        const scale = 1000
×
2028

×
2029
        var totalWeight, totalFee int64
×
2030
        for _, tx := range txns {
×
2031
                utx := btcutil.NewTx(tx)
×
2032
                totalWeight += blockchain.GetTransactionWeight(utx)
×
2033

×
2034
                fee := h.CalculateTxFee(tx)
×
2035
                totalFee += int64(fee)
×
2036
        }
×
2037
        feeRate := totalFee * scale / totalWeight
×
2038

×
2039
        return feeRate
×
2040
}
2041

2042
// AssertSweepFound looks up a sweep in a nodes list of broadcast sweeps and
2043
// asserts it's found.
2044
//
2045
// NOTE: Does not account for node's internal state.
2046
func (h *HarnessTest) AssertSweepFound(hn *node.HarnessNode,
2047
        sweep string, verbose bool, startHeight int32) {
×
2048

×
2049
        err := wait.NoError(func() error {
×
2050
                // List all sweeps that alice's node had broadcast.
×
2051
                sweepResp := hn.RPC.ListSweeps(verbose, startHeight)
×
2052

×
2053
                var found bool
×
2054
                if verbose {
×
2055
                        found = findSweepInDetails(h, sweep, sweepResp)
×
2056
                } else {
×
2057
                        found = findSweepInTxids(h, sweep, sweepResp)
×
2058
                }
×
2059

2060
                if found {
×
2061
                        return nil
×
2062
                }
×
2063

2064
                return fmt.Errorf("sweep tx %v not found in resp %v", sweep,
×
2065
                        sweepResp)
×
2066
        }, wait.DefaultTimeout)
2067
        require.NoError(h, err, "%s: timeout checking sweep tx", hn.Name())
×
2068
}
2069

2070
func findSweepInTxids(ht *HarnessTest, sweepTxid string,
2071
        sweepResp *walletrpc.ListSweepsResponse) bool {
×
2072

×
2073
        sweepTxIDs := sweepResp.GetTransactionIds()
×
2074
        require.NotNil(ht, sweepTxIDs, "expected transaction ids")
×
2075
        require.Nil(ht, sweepResp.GetTransactionDetails())
×
2076

×
2077
        // Check that the sweep tx we have just produced is present.
×
2078
        for _, tx := range sweepTxIDs.TransactionIds {
×
2079
                if tx == sweepTxid {
×
2080
                        return true
×
2081
                }
×
2082
        }
2083

2084
        return false
×
2085
}
2086

2087
func findSweepInDetails(ht *HarnessTest, sweepTxid string,
2088
        sweepResp *walletrpc.ListSweepsResponse) bool {
×
2089

×
2090
        sweepDetails := sweepResp.GetTransactionDetails()
×
2091
        require.NotNil(ht, sweepDetails, "expected transaction details")
×
2092
        require.Nil(ht, sweepResp.GetTransactionIds())
×
2093

×
2094
        for _, tx := range sweepDetails.Transactions {
×
2095
                if tx.TxHash == sweepTxid {
×
2096
                        return true
×
2097
                }
×
2098
        }
2099

2100
        return false
×
2101
}
2102

2103
// QueryRoutesAndRetry attempts to keep querying a route until timeout is
2104
// reached.
2105
//
2106
// NOTE: when a channel is opened, we may need to query multiple times to get
2107
// it in our QueryRoutes RPC. This happens even after we check the channel is
2108
// heard by the node using ht.AssertChannelOpen. Deep down, this is because our
2109
// GraphTopologySubscription and QueryRoutes give different results regarding a
2110
// specific channel, with the formal reporting it being open while the latter
2111
// not, resulting GraphTopologySubscription acting "faster" than QueryRoutes.
2112
// TODO(yy): make sure related subsystems share the same view on a given
2113
// channel.
2114
func (h *HarnessTest) QueryRoutesAndRetry(hn *node.HarnessNode,
2115
        req *lnrpc.QueryRoutesRequest) *lnrpc.QueryRoutesResponse {
×
2116

×
2117
        var routes *lnrpc.QueryRoutesResponse
×
2118
        err := wait.NoError(func() error {
×
2119
                ctxt, cancel := context.WithCancel(h.runCtx)
×
2120
                defer cancel()
×
2121

×
2122
                resp, err := hn.RPC.LN.QueryRoutes(ctxt, req)
×
2123
                if err != nil {
×
2124
                        return fmt.Errorf("%s: failed to query route: %w",
×
2125
                                hn.Name(), err)
×
2126
                }
×
2127

2128
                routes = resp
×
2129

×
2130
                return nil
×
2131
        }, DefaultTimeout)
2132

2133
        require.NoError(h, err, "timeout querying routes")
×
2134

×
2135
        return routes
×
2136
}
2137

2138
// ReceiveHtlcInterceptor waits until a message is received on the htlc
2139
// interceptor stream or the timeout is reached.
2140
func (h *HarnessTest) ReceiveHtlcInterceptor(
2141
        stream rpc.InterceptorClient) *routerrpc.ForwardHtlcInterceptRequest {
×
2142

×
2143
        chanMsg := make(chan *routerrpc.ForwardHtlcInterceptRequest)
×
2144
        errChan := make(chan error)
×
2145
        go func() {
×
2146
                // Consume one message. This will block until the message is
×
2147
                // received.
×
2148
                resp, err := stream.Recv()
×
2149
                if err != nil {
×
2150
                        errChan <- err
×
2151
                        return
×
2152
                }
×
2153
                chanMsg <- resp
×
2154
        }()
2155

2156
        select {
×
2157
        case <-time.After(DefaultTimeout):
×
2158
                require.Fail(h, "timeout", "timeout intercepting htlc")
×
2159

2160
        case err := <-errChan:
×
2161
                require.Failf(h, "err from HTLC interceptor stream",
×
2162
                        "received err from HTLC interceptor stream: %v", err)
×
2163

2164
        case updateMsg := <-chanMsg:
×
2165
                return updateMsg
×
2166
        }
2167

2168
        return nil
×
2169
}
2170

2171
// ReceiveInvoiceHtlcModification waits until a message is received on the
2172
// invoice HTLC modifier stream or the timeout is reached.
2173
func (h *HarnessTest) ReceiveInvoiceHtlcModification(
2174
        stream rpc.InvoiceHtlcModifierClient) *invoicesrpc.HtlcModifyRequest {
×
2175

×
2176
        chanMsg := make(chan *invoicesrpc.HtlcModifyRequest)
×
2177
        errChan := make(chan error)
×
2178
        go func() {
×
2179
                // Consume one message. This will block until the message is
×
2180
                // received.
×
2181
                resp, err := stream.Recv()
×
2182
                if err != nil {
×
2183
                        errChan <- err
×
2184
                        return
×
2185
                }
×
2186
                chanMsg <- resp
×
2187
        }()
2188

2189
        select {
×
2190
        case <-time.After(DefaultTimeout):
×
2191
                require.Fail(h, "timeout", "timeout invoice HTLC modifier")
×
2192

2193
        case err := <-errChan:
×
2194
                require.Failf(h, "err from invoice HTLC modifier stream",
×
2195
                        "received err from invoice HTLC modifier stream: %v",
×
2196
                        err)
×
2197

2198
        case updateMsg := <-chanMsg:
×
2199
                return updateMsg
×
2200
        }
2201

2202
        return nil
×
2203
}
2204

2205
// ReceiveChannelEvent waits until a message is received from the
2206
// ChannelEventsClient stream or the timeout is reached.
2207
func (h *HarnessTest) ReceiveChannelEvent(
2208
        stream rpc.ChannelEventsClient) *lnrpc.ChannelEventUpdate {
×
2209

×
2210
        chanMsg := make(chan *lnrpc.ChannelEventUpdate)
×
2211
        errChan := make(chan error)
×
2212
        go func() {
×
2213
                // Consume one message. This will block until the message is
×
2214
                // received.
×
2215
                resp, err := stream.Recv()
×
2216
                if err != nil {
×
2217
                        errChan <- err
×
2218
                        return
×
2219
                }
×
2220
                chanMsg <- resp
×
2221
        }()
2222

2223
        select {
×
2224
        case <-time.After(DefaultTimeout):
×
2225
                require.Fail(h, "timeout", "timeout intercepting htlc")
×
2226

2227
        case err := <-errChan:
×
2228
                require.Failf(h, "err from stream",
×
2229
                        "received err from stream: %v", err)
×
2230

2231
        case updateMsg := <-chanMsg:
×
2232
                return updateMsg
×
2233
        }
2234

2235
        return nil
×
2236
}
2237

2238
// GetOutputIndex returns the output index of the given address in the given
2239
// transaction.
2240
func (h *HarnessTest) GetOutputIndex(txid chainhash.Hash, addr string) int {
×
2241
        // We'll then extract the raw transaction from the mempool in order to
×
2242
        // determine the index of the p2tr output.
×
2243
        tx := h.miner.GetRawTransaction(txid)
×
2244

×
2245
        p2trOutputIndex := -1
×
2246
        for i, txOut := range tx.MsgTx().TxOut {
×
2247
                _, addrs, _, err := txscript.ExtractPkScriptAddrs(
×
2248
                        txOut.PkScript, h.miner.ActiveNet,
×
2249
                )
×
2250
                require.NoError(h, err)
×
2251

×
2252
                if addrs[0].String() == addr {
×
2253
                        p2trOutputIndex = i
×
2254
                }
×
2255
        }
2256
        require.Greater(h, p2trOutputIndex, -1)
×
2257

×
2258
        return p2trOutputIndex
×
2259
}
2260

2261
// SendCoins sends a coin from node A to node B with the given amount, returns
2262
// the sending tx.
2263
func (h *HarnessTest) SendCoins(a, b *node.HarnessNode,
2264
        amt btcutil.Amount) *wire.MsgTx {
×
2265

×
2266
        // Create an address for Bob receive the coins.
×
2267
        req := &lnrpc.NewAddressRequest{
×
2268
                Type: lnrpc.AddressType_TAPROOT_PUBKEY,
×
2269
        }
×
2270
        resp := b.RPC.NewAddress(req)
×
2271

×
2272
        // Send the coins from Alice to Bob. We should expect a tx to be
×
2273
        // broadcast and seen in the mempool.
×
2274
        sendReq := &lnrpc.SendCoinsRequest{
×
2275
                Addr:       resp.Address,
×
2276
                Amount:     int64(amt),
×
2277
                TargetConf: 6,
×
2278
        }
×
2279
        a.RPC.SendCoins(sendReq)
×
2280
        tx := h.GetNumTxsFromMempool(1)[0]
×
2281

×
2282
        return tx
×
2283
}
×
2284

2285
// CreateSimpleNetwork creates the number of nodes specified by the number of
2286
// configs and makes a topology of `node1 -> node2 -> node3...`. Each node is
2287
// created using the specified config, the neighbors are connected, and the
2288
// channels are opened. Each node will be funded with a single UTXO of 1 BTC
2289
// except the last one.
2290
//
2291
// For instance, to create a network with 2 nodes that share the same node
2292
// config,
2293
//
2294
//        cfg := []string{"--protocol.anchors"}
2295
//        cfgs := [][]string{cfg, cfg}
2296
//        params := OpenChannelParams{...}
2297
//        chanPoints, nodes := ht.CreateSimpleNetwork(cfgs, params)
2298
//
2299
// This will create two nodes and open an anchor channel between them.
2300
func (h *HarnessTest) CreateSimpleNetwork(nodeCfgs [][]string,
2301
        p OpenChannelParams) ([]*lnrpc.ChannelPoint, []*node.HarnessNode) {
×
2302

×
2303
        // Create new nodes.
×
2304
        nodes := h.createNodes(nodeCfgs)
×
2305

×
2306
        var resp []*lnrpc.ChannelPoint
×
2307

×
2308
        // Open zero-conf channels if specified.
×
2309
        if p.ZeroConf {
×
2310
                resp = h.openZeroConfChannelsForNodes(nodes, p)
×
2311
        } else {
×
2312
                // Open channels between the nodes.
×
2313
                resp = h.openChannelsForNodes(nodes, p)
×
2314
        }
×
2315

2316
        return resp, nodes
×
2317
}
2318

2319
// acceptChannel is used to accept a single channel that comes across. This
2320
// should be run in a goroutine and is used to test nodes with the zero-conf
2321
// feature bit.
2322
func acceptChannel(t *testing.T, zeroConf bool, stream rpc.AcceptorClient) {
×
2323
        req, err := stream.Recv()
×
2324
        require.NoError(t, err)
×
2325

×
2326
        resp := &lnrpc.ChannelAcceptResponse{
×
2327
                Accept:        true,
×
2328
                PendingChanId: req.PendingChanId,
×
2329
                ZeroConf:      zeroConf,
×
2330
        }
×
2331
        err = stream.Send(resp)
×
2332
        require.NoError(t, err)
×
2333
}
×
2334

2335
// nodeNames defines a slice of human-reable names for the nodes created in the
2336
// `createNodes` method. 8 nodes are defined here as by default we can only
2337
// create this many nodes in one test.
2338
var nodeNames = []string{
2339
        "Alice", "Bob", "Carol", "Dave", "Eve", "Frank", "Grace", "Heidi",
2340
}
2341

2342
// createNodes creates the number of nodes specified by the number of configs.
2343
// Each node is created using the specified config, the neighbors are
2344
// connected.
2345
func (h *HarnessTest) createNodes(nodeCfgs [][]string) []*node.HarnessNode {
×
2346
        // Get the number of nodes.
×
2347
        numNodes := len(nodeCfgs)
×
2348

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

×
2352
        // Make a slice of nodes.
×
2353
        nodes := make([]*node.HarnessNode, numNodes)
×
2354

×
2355
        // Create new nodes.
×
2356
        for i, nodeCfg := range nodeCfgs {
×
2357
                nodeName := nodeNames[i]
×
2358
                n := h.NewNode(nodeName, nodeCfg)
×
2359
                nodes[i] = n
×
2360
        }
×
2361

2362
        // Connect the nodes in a chain.
2363
        for i := 1; i < len(nodes); i++ {
×
2364
                nodeA := nodes[i-1]
×
2365
                nodeB := nodes[i]
×
2366
                h.EnsureConnected(nodeA, nodeB)
×
2367
        }
×
2368

2369
        // Fund all the nodes expect the last one.
2370
        for i := 0; i < len(nodes)-1; i++ {
×
2371
                node := nodes[i]
×
2372
                h.FundCoinsUnconfirmed(btcutil.SatoshiPerBitcoin, node)
×
2373
        }
×
2374

2375
        // Mine 1 block to get the above coins confirmed.
2376
        h.MineBlocksAndAssertNumTxes(1, numNodes-1)
×
2377

×
2378
        return nodes
×
2379
}
2380

2381
// openChannelsForNodes takes a list of nodes and makes a topology of `node1 ->
2382
// node2 -> node3...`.
2383
func (h *HarnessTest) openChannelsForNodes(nodes []*node.HarnessNode,
2384
        p OpenChannelParams) []*lnrpc.ChannelPoint {
×
2385

×
2386
        // Sanity check the params.
×
2387
        require.Greater(h, len(nodes), 1, "need at least 2 nodes")
×
2388

×
2389
        // attachFundingShim is a helper closure that optionally attaches a
×
2390
        // funding shim to the open channel params and returns it.
×
2391
        attachFundingShim := func(
×
2392
                nodeA, nodeB *node.HarnessNode) OpenChannelParams {
×
2393

×
2394
                // If this channel is not a script enforced lease channel,
×
2395
                // we'll do nothing and return the params.
×
2396
                leasedType := lnrpc.CommitmentType_SCRIPT_ENFORCED_LEASE
×
2397
                if p.CommitmentType != leasedType {
×
2398
                        return p
×
2399
                }
×
2400

2401
                // Otherwise derive the funding shim, attach it to the original
2402
                // open channel params and return it.
2403
                minerHeight := h.CurrentHeight()
×
2404
                thawHeight := minerHeight + thawHeightDelta
×
2405
                fundingShim, _ := h.DeriveFundingShim(
×
2406
                        nodeA, nodeB, p.Amt, thawHeight, true, leasedType,
×
2407
                )
×
2408

×
2409
                p.FundingShim = fundingShim
×
2410

×
2411
                return p
×
2412
        }
2413

2414
        // Open channels in batch to save blocks mined.
2415
        reqs := make([]*OpenChannelRequest, 0, len(nodes)-1)
×
2416
        for i := 0; i < len(nodes)-1; i++ {
×
2417
                nodeA := nodes[i]
×
2418
                nodeB := nodes[i+1]
×
2419

×
2420
                // Optionally attach a funding shim to the open channel params.
×
2421
                p = attachFundingShim(nodeA, nodeB)
×
2422

×
2423
                req := &OpenChannelRequest{
×
2424
                        Local:  nodeA,
×
2425
                        Remote: nodeB,
×
2426
                        Param:  p,
×
2427
                }
×
2428
                reqs = append(reqs, req)
×
2429
        }
×
2430
        resp := h.OpenMultiChannelsAsync(reqs)
×
2431

×
2432
        // If the channels are private, make sure the channel participants know
×
2433
        // the relevant channels.
×
2434
        if p.Private {
×
2435
                for i, chanPoint := range resp {
×
2436
                        // Get the channel participants - for n channels we
×
2437
                        // would have n+1 nodes.
×
2438
                        nodeA, nodeB := nodes[i], nodes[i+1]
×
2439
                        h.AssertChannelInGraph(nodeA, chanPoint)
×
2440
                        h.AssertChannelInGraph(nodeB, chanPoint)
×
2441
                }
×
2442
        } else {
×
2443
                // Make sure the all nodes know all the channels if they are
×
2444
                // public.
×
2445
                for _, node := range nodes {
×
2446
                        for _, chanPoint := range resp {
×
2447
                                h.AssertChannelInGraph(node, chanPoint)
×
2448
                        }
×
2449

2450
                        // Make sure every node has updated its cached graph
2451
                        // about the edges as indicated in `DescribeGraph`.
2452
                        h.AssertNumEdges(node, len(resp), false)
×
2453
                }
2454
        }
2455

2456
        return resp
×
2457
}
2458

2459
// openZeroConfChannelsForNodes takes a list of nodes and makes a topology of
2460
// `node1 -> node2 -> node3...` with zero-conf channels.
2461
func (h *HarnessTest) openZeroConfChannelsForNodes(nodes []*node.HarnessNode,
2462
        p OpenChannelParams) []*lnrpc.ChannelPoint {
×
2463

×
2464
        // Sanity check the params.
×
2465
        require.True(h, p.ZeroConf, "zero-conf channels must be enabled")
×
2466
        require.Greater(h, len(nodes), 1, "need at least 2 nodes")
×
2467

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

×
2471
        // Create the channel acceptors.
×
2472
        for _, node := range nodes[1:] {
×
2473
                acceptor, cancel := node.RPC.ChannelAcceptor()
×
2474
                go acceptChannel(h.T, true, acceptor)
×
2475

×
2476
                cancels = append(cancels, cancel)
×
2477
        }
×
2478

2479
        // Open channels between the nodes.
2480
        resp := h.openChannelsForNodes(nodes, p)
×
2481

×
2482
        for _, cancel := range cancels {
×
2483
                cancel()
×
2484
        }
×
2485

2486
        return resp
×
2487
}
2488

2489
// DeriveFundingShim creates a channel funding shim by deriving the necessary
2490
// keys on both sides.
2491
func (h *HarnessTest) DeriveFundingShim(alice, bob *node.HarnessNode,
2492
        chanSize btcutil.Amount, thawHeight uint32, publish bool,
2493
        commitType lnrpc.CommitmentType) (*lnrpc.FundingShim,
2494
        *lnrpc.ChannelPoint) {
×
2495

×
2496
        keyLoc := &signrpc.KeyLocator{KeyFamily: 9999}
×
2497
        carolFundingKey := alice.RPC.DeriveKey(keyLoc)
×
2498
        daveFundingKey := bob.RPC.DeriveKey(keyLoc)
×
2499

×
2500
        // Now that we have the multi-sig keys for each party, we can manually
×
2501
        // construct the funding transaction. We'll instruct the backend to
×
2502
        // immediately create and broadcast a transaction paying out an exact
×
2503
        // amount. Normally this would reside in the mempool, but we just
×
2504
        // confirm it now for simplicity.
×
2505
        var (
×
2506
                fundingOutput *wire.TxOut
×
2507
                musig2        bool
×
2508
                err           error
×
2509
        )
×
2510

×
2511
        if commitType == lnrpc.CommitmentType_SIMPLE_TAPROOT ||
×
2512
                commitType == lnrpc.CommitmentType_SIMPLE_TAPROOT_OVERLAY {
×
2513

×
2514
                var carolKey, daveKey *btcec.PublicKey
×
2515
                carolKey, err = btcec.ParsePubKey(carolFundingKey.RawKeyBytes)
×
2516
                require.NoError(h, err)
×
2517
                daveKey, err = btcec.ParsePubKey(daveFundingKey.RawKeyBytes)
×
2518
                require.NoError(h, err)
×
2519

×
2520
                _, fundingOutput, err = input.GenTaprootFundingScript(
×
2521
                        carolKey, daveKey, int64(chanSize),
×
2522
                        fn.None[chainhash.Hash](),
×
2523
                )
×
2524
                require.NoError(h, err)
×
2525

×
2526
                musig2 = true
×
2527
        } else {
×
2528
                _, fundingOutput, err = input.GenFundingPkScript(
×
2529
                        carolFundingKey.RawKeyBytes, daveFundingKey.RawKeyBytes,
×
2530
                        int64(chanSize),
×
2531
                )
×
2532
                require.NoError(h, err)
×
2533
        }
×
2534

2535
        var txid *chainhash.Hash
×
2536
        targetOutputs := []*wire.TxOut{fundingOutput}
×
2537
        if publish {
×
2538
                txid = h.SendOutputsWithoutChange(targetOutputs, 5)
×
2539
        } else {
×
2540
                tx := h.CreateTransaction(targetOutputs, 5)
×
2541

×
2542
                txHash := tx.TxHash()
×
2543
                txid = &txHash
×
2544
        }
×
2545

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

×
2551
        // Now that we have the pending channel ID, Dave (our responder) will
×
2552
        // register the intent to receive a new channel funding workflow using
×
2553
        // the pending channel ID.
×
2554
        chanPoint := &lnrpc.ChannelPoint{
×
2555
                FundingTxid: &lnrpc.ChannelPoint_FundingTxidBytes{
×
2556
                        FundingTxidBytes: txid[:],
×
2557
                },
×
2558
        }
×
2559
        chanPointShim := &lnrpc.ChanPointShim{
×
2560
                Amt:       int64(chanSize),
×
2561
                ChanPoint: chanPoint,
×
2562
                LocalKey: &lnrpc.KeyDescriptor{
×
2563
                        RawKeyBytes: daveFundingKey.RawKeyBytes,
×
2564
                        KeyLoc: &lnrpc.KeyLocator{
×
2565
                                KeyFamily: daveFundingKey.KeyLoc.KeyFamily,
×
2566
                                KeyIndex:  daveFundingKey.KeyLoc.KeyIndex,
×
2567
                        },
×
2568
                },
×
2569
                RemoteKey:     carolFundingKey.RawKeyBytes,
×
2570
                PendingChanId: pendingChanID,
×
2571
                ThawHeight:    thawHeight,
×
2572
                Musig2:        musig2,
×
2573
        }
×
2574
        fundingShim := &lnrpc.FundingShim{
×
2575
                Shim: &lnrpc.FundingShim_ChanPointShim{
×
2576
                        ChanPointShim: chanPointShim,
×
2577
                },
×
2578
        }
×
2579
        bob.RPC.FundingStateStep(&lnrpc.FundingTransitionMsg{
×
2580
                Trigger: &lnrpc.FundingTransitionMsg_ShimRegister{
×
2581
                        ShimRegister: fundingShim,
×
2582
                },
×
2583
        })
×
2584

×
2585
        // If we attempt to register the same shim (has the same pending chan
×
2586
        // ID), then we should get an error.
×
2587
        bob.RPC.FundingStateStepAssertErr(&lnrpc.FundingTransitionMsg{
×
2588
                Trigger: &lnrpc.FundingTransitionMsg_ShimRegister{
×
2589
                        ShimRegister: fundingShim,
×
2590
                },
×
2591
        })
×
2592

×
2593
        // We'll take the chan point shim we just registered for Dave (the
×
2594
        // responder), and swap the local/remote keys before we feed it in as
×
2595
        // Carol's funding shim as the initiator.
×
2596
        fundingShim.GetChanPointShim().LocalKey = &lnrpc.KeyDescriptor{
×
2597
                RawKeyBytes: carolFundingKey.RawKeyBytes,
×
2598
                KeyLoc: &lnrpc.KeyLocator{
×
2599
                        KeyFamily: carolFundingKey.KeyLoc.KeyFamily,
×
2600
                        KeyIndex:  carolFundingKey.KeyLoc.KeyIndex,
×
2601
                },
×
2602
        }
×
2603
        fundingShim.GetChanPointShim().RemoteKey = daveFundingKey.RawKeyBytes
×
2604

×
2605
        return fundingShim, chanPoint
×
2606
}
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