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

lightningnetwork / lnd / 17190810624

24 Aug 2025 03:58PM UTC coverage: 66.74% (+9.4%) from 57.321%
17190810624

Pull #10167

github

web-flow
Merge 33cec4f6a into 0c2f045f5
Pull Request #10167: multi: bump Go to 1.24.6

6 of 40 new or added lines in 10 files covered. (15.0%)

12 existing lines in 6 files now uncovered.

135947 of 203696 relevant lines covered (66.74%)

21470.9 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
        "runtime/debug"
7
        "strings"
8
        "testing"
9
        "time"
10

11
        "github.com/btcsuite/btcd/blockchain"
12
        "github.com/btcsuite/btcd/btcec/v2"
13
        "github.com/btcsuite/btcd/btcutil"
14
        "github.com/btcsuite/btcd/chaincfg/chainhash"
15
        "github.com/btcsuite/btcd/txscript"
16
        "github.com/btcsuite/btcd/wire"
17
        "github.com/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.
×
NEW
150
        ctxt, cancel := context.WithCancel(t.Context())
×
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 r := recover(); r != nil {
×
297
                        // Wrap the recovered panic in an error.
×
298
                        var err error
×
299
                        switch v := r.(type) {
×
300
                        case error:
×
301
                                err = v
×
302
                        default:
×
303
                                err = fmt.Errorf("%v", v)
×
304
                        }
305

306
                        // Capture and print the stack trace.
307
                        stack := debug.Stack()
×
308

×
309
                        // Fail the test with panic info and stack.
×
310
                        h.Fatalf("Failed: (%v) panic with: %v\n%s",
×
311
                                testCase.Name, err, stack)
×
312
                }
313
        }()
314

315
        testCase.TestFunc(h)
×
316
}
317

318
// Subtest creates a child HarnessTest, which inherits the harness net and
319
// stand by nodes created by the parent test. It will return a cleanup function
320
// which resets  all the standby nodes' configs back to its original state and
321
// create snapshots of each nodes' internal state.
322
func (h *HarnessTest) Subtest(t *testing.T) *HarnessTest {
×
323
        t.Helper()
×
324

×
325
        st := &HarnessTest{
×
326
                T:            t,
×
327
                manager:      h.manager,
×
328
                miner:        h.miner,
×
329
                feeService:   h.feeService,
×
330
                lndErrorChan: make(chan error, lndErrorChanSize),
×
331
        }
×
332

×
333
        // Inherit context from the main test.
×
334
        st.runCtx, st.cancel = context.WithCancel(h.runCtx)
×
335

×
336
        // Inherit the subtest for the miner.
×
337
        st.miner.T = st.T
×
338

×
339
        // Reset fee estimator.
×
340
        st.feeService.Reset()
×
341

×
342
        // Record block height.
×
343
        h.updateCurrentHeight()
×
344
        startHeight := int32(h.CurrentHeight())
×
345

×
346
        st.Cleanup(func() {
×
347
                // Make sure the test is not consuming too many blocks.
×
348
                st.checkAndLimitBlocksMined(startHeight)
×
349

×
350
                // Don't bother run the cleanups if the test is failed.
×
351
                if st.Failed() {
×
352
                        st.Log("test failed, skipped cleanup")
×
353
                        st.shutdownNodesNoAssert()
×
354
                        return
×
355
                }
×
356

357
                // Don't run cleanup if it's already done. This can happen if
358
                // we have multiple level inheritance of the parent harness
359
                // test. For instance, a `Subtest(st)`.
360
                if st.cleaned {
×
361
                        st.Log("test already cleaned, skipped cleanup")
×
362
                        return
×
363
                }
×
364

365
                // If found running nodes, shut them down.
366
                st.shutdownAllNodes()
×
367

×
368
                // We require the mempool to be cleaned from the test.
×
369
                require.Empty(st, st.miner.GetRawMempool(), "mempool not "+
×
370
                        "cleaned, please mine blocks to clean them all.")
×
371

×
372
                // Finally, cancel the run context. We have to do it here
×
373
                // because we need to keep the context alive for the above
×
374
                // assertions used in cleanup.
×
375
                st.cancel()
×
376

×
377
                // We now want to mark the parent harness as cleaned to avoid
×
378
                // running cleanup again since its internal state has been
×
379
                // cleaned up by its child harness tests.
×
380
                h.cleaned = true
×
381
        })
382

383
        return st
×
384
}
385

386
// checkAndLimitBlocksMined asserts that the blocks mined in a single test
387
// doesn't exceed 50, which implicitly discourage table-drive tests, which are
388
// hard to maintain and take a long time to run.
389
func (h *HarnessTest) checkAndLimitBlocksMined(startHeight int32) {
×
390
        _, endHeight := h.GetBestBlock()
×
391
        blocksMined := endHeight - startHeight
×
392

×
393
        h.Logf("finished test: %s, start height=%d, end height=%d, mined "+
×
394
                "blocks=%d", h.manager.currentTestCase, startHeight, endHeight,
×
395
                blocksMined)
×
396

×
397
        // If the number of blocks is less than 40, we consider the test
×
398
        // healthy.
×
399
        if blocksMined < 40 {
×
400
                return
×
401
        }
×
402

403
        // Otherwise log a warning if it's mining more than 40 blocks.
404
        desc := "!============================================!\n"
×
405

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

×
409
        desc += "1. break test into smaller individual tests, especially if " +
×
410
                "this is a table-drive test.\n" +
×
411
                "2. use smaller CSV via `--bitcoin.defaultremotedelay=1.`\n" +
×
412
                "3. use smaller CLTV via `--bitcoin.timelockdelta=18.`\n" +
×
413
                "4. remove unnecessary CloseChannel when test ends.\n" +
×
414
                "5. use `CreateSimpleNetwork` for efficient channel creation.\n"
×
415
        h.Log(desc)
×
416

×
417
        // We enforce that the test should not mine more than
×
418
        // MaxBlocksMinedPerTest (50 by default) blocks, which is more than
×
419
        // enough to test a multi hop force close scenario.
×
420
        require.LessOrEqualf(
×
421
                h, int(blocksMined), MaxBlocksMinedPerTest,
×
422
                "cannot mine more than %d blocks in one test",
×
423
                MaxBlocksMinedPerTest,
×
424
        )
×
425
}
426

427
// shutdownNodesNoAssert will shutdown all running nodes without assertions.
428
// This is used when the test has already failed, we don't want to log more
429
// errors but focusing on the original error.
430
func (h *HarnessTest) shutdownNodesNoAssert() {
×
431
        for _, node := range h.manager.activeNodes {
×
432
                _ = h.manager.shutdownNode(node)
×
433
        }
×
434
}
435

436
// shutdownAllNodes will shutdown all running nodes.
437
func (h *HarnessTest) shutdownAllNodes() {
×
NEW
438
        var lastErr error
×
439
        for _, node := range h.manager.activeNodes {
×
NEW
440
                err := h.manager.shutdownNode(node)
×
441
                if err == nil {
×
442
                        continue
×
443
                }
444

445
                // Instead of returning the error, we will log it instead. This
446
                // is needed so other nodes can continue their shutdown
447
                // processes.
448
                h.Logf("unable to shutdown %s, got err: %v", node.Name(), err)
×
NEW
449

×
NEW
450
                lastErr = err
×
451
        }
452

NEW
453
        require.NoError(h, lastErr, "failed to shutdown all nodes")
×
454
}
455

456
// cleanupStandbyNode is a function should be called with defer whenever a
457
// subtest is created. It will reset the standby nodes configs, snapshot the
458
// states, and validate the node has a clean state.
459
func (h *HarnessTest) cleanupStandbyNode(hn *node.HarnessNode) {
×
460
        // Remove connections made from this test.
×
461
        h.removeConnectionns(hn)
×
462

×
463
        // Delete all payments made from this test.
×
464
        hn.RPC.DeleteAllPayments()
×
465

×
466
        // Check the node's current state with timeout.
×
467
        //
×
468
        // NOTE: we need to do this in a `wait` because it takes some time for
×
469
        // the node to update its internal state. Once the RPCs are synced we
×
470
        // can then remove this wait.
×
471
        err := wait.NoError(func() error {
×
472
                // Update the node's internal state.
×
473
                hn.UpdateState()
×
474

×
475
                // Check the node is in a clean state for the following tests.
×
476
                return h.validateNodeState(hn)
×
477
        }, wait.DefaultTimeout)
×
478
        require.NoError(h, err, "timeout checking node's state")
×
479
}
480

481
// removeConnectionns will remove all connections made on the standby nodes
482
// expect the connections between Alice and Bob.
483
func (h *HarnessTest) removeConnectionns(hn *node.HarnessNode) {
×
484
        resp := hn.RPC.ListPeers()
×
485
        for _, peer := range resp.Peers {
×
486
                hn.RPC.DisconnectPeer(peer.PubKey)
×
487
        }
×
488
}
489

490
// SetTestName set the test case name.
491
func (h *HarnessTest) SetTestName(name string) {
×
492
        cleanTestCaseName := strings.ReplaceAll(name, " ", "_")
×
493
        h.manager.currentTestCase = cleanTestCaseName
×
494
}
×
495

496
// NewNode creates a new node and asserts its creation. The node is guaranteed
497
// to have finished its initialization and all its subservers are started.
498
func (h *HarnessTest) NewNode(name string,
499
        extraArgs []string) *node.HarnessNode {
×
500

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

×
504
        // Start the node.
×
505
        err = node.Start(h.runCtx)
×
506
        require.NoError(h, err, "failed to start node %s", node.Name())
×
507

×
508
        // Get the miner's best block hash.
×
509
        bestBlock, err := h.miner.Client.GetBestBlockHash()
×
510
        require.NoError(h, err, "unable to get best block hash")
×
511

×
512
        // Wait until the node's chain backend is synced to the miner's best
×
513
        // block.
×
514
        h.WaitForBlockchainSyncTo(node, *bestBlock)
×
515

×
516
        return node
×
517
}
×
518

519
// NewNodeWithCoins creates a new node and asserts its creation. The node is
520
// guaranteed to have finished its initialization and all its subservers are
521
// started. In addition, 5 UTXO of 1 BTC each are sent to the node.
522
func (h *HarnessTest) NewNodeWithCoins(name string,
523
        extraArgs []string) *node.HarnessNode {
×
524

×
525
        node := h.NewNode(name, extraArgs)
×
526

×
527
        // Load up the wallets of the node with 5 outputs of 1 BTC each.
×
528
        const (
×
529
                numOutputs  = 5
×
530
                fundAmount  = 1 * btcutil.SatoshiPerBitcoin
×
531
                totalAmount = fundAmount * numOutputs
×
532
        )
×
533

×
534
        for i := 0; i < numOutputs; i++ {
×
535
                h.createAndSendOutput(
×
536
                        node, fundAmount,
×
537
                        lnrpc.AddressType_WITNESS_PUBKEY_HASH,
×
538
                )
×
539
        }
×
540

541
        // Mine a block to confirm the transactions.
542
        h.MineBlocksAndAssertNumTxes(1, numOutputs)
×
543

×
544
        // Now block until the wallet have fully synced up.
×
545
        h.WaitForBalanceConfirmed(node, totalAmount)
×
546

×
547
        return node
×
548
}
549

550
// Shutdown shuts down the given node and asserts that no errors occur.
551
func (h *HarnessTest) Shutdown(node *node.HarnessNode) {
×
552
        err := h.manager.shutdownNode(node)
×
553
        require.NoErrorf(h, err, "unable to shutdown %v in %v", node.Name(),
×
554
                h.manager.currentTestCase)
×
555
}
×
556

557
// SuspendNode stops the given node and returns a callback that can be used to
558
// start it again.
559
func (h *HarnessTest) SuspendNode(node *node.HarnessNode) func() error {
×
560
        err := node.Stop()
×
561
        require.NoErrorf(h, err, "failed to stop %s", node.Name())
×
562

×
563
        // Remove the node from active nodes.
×
564
        delete(h.manager.activeNodes, node.Cfg.NodeID)
×
565

×
566
        return func() error {
×
567
                h.manager.registerNode(node)
×
568

×
569
                if err := node.Start(h.runCtx); err != nil {
×
570
                        return err
×
571
                }
×
572
                h.WaitForBlockchainSync(node)
×
573

×
574
                return nil
×
575
        }
576
}
577

578
// RestartNode restarts a given node, unlocks it and asserts it's successfully
579
// started.
580
func (h *HarnessTest) RestartNode(hn *node.HarnessNode) {
×
581
        err := h.manager.restartNode(h.runCtx, hn, nil)
×
582
        require.NoErrorf(h, err, "failed to restart node %s", hn.Name())
×
583

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

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

594
// RestartNodeNoUnlock restarts a given node without unlocking its wallet.
595
func (h *HarnessTest) RestartNodeNoUnlock(hn *node.HarnessNode) {
×
596
        err := h.manager.restartNode(h.runCtx, hn, nil)
×
597
        require.NoErrorf(h, err, "failed to restart node %s", hn.Name())
×
598
}
×
599

600
// RestartNodeWithChanBackups restarts a given node with the specified channel
601
// backups.
602
func (h *HarnessTest) RestartNodeWithChanBackups(hn *node.HarnessNode,
603
        chanBackups ...*lnrpc.ChanBackupSnapshot) {
×
604

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

×
608
        err = h.manager.unlockNode(hn, chanBackups...)
×
609
        require.NoErrorf(h, err, "failed to unlock node %s", hn.Name())
×
610

×
611
        // Give the node some time to catch up with the chain before we
×
612
        // continue with the tests.
×
613
        h.WaitForBlockchainSync(hn)
×
614
}
×
615

616
// RestartNodeWithExtraArgs updates the node's config and restarts it.
617
func (h *HarnessTest) RestartNodeWithExtraArgs(hn *node.HarnessNode,
618
        extraArgs []string) {
×
619

×
620
        hn.SetExtraArgs(extraArgs)
×
621
        h.RestartNode(hn)
×
622
}
×
623

624
// NewNodeWithSeed fully initializes a new HarnessNode after creating a fresh
625
// aezeed. The provided password is used as both the aezeed password and the
626
// wallet password. The generated mnemonic is returned along with the
627
// initialized harness node.
628
func (h *HarnessTest) NewNodeWithSeed(name string,
629
        extraArgs []string, password []byte,
630
        statelessInit bool) (*node.HarnessNode, []string, []byte) {
×
631

×
632
        // Create a request to generate a new aezeed. The new seed will have
×
633
        // the same password as the internal wallet.
×
634
        req := &lnrpc.GenSeedRequest{
×
635
                AezeedPassphrase: password,
×
636
                SeedEntropy:      nil,
×
637
        }
×
638

×
639
        return h.newNodeWithSeed(name, extraArgs, req, statelessInit)
×
640
}
×
641

642
// newNodeWithSeed creates and initializes a new HarnessNode such that it'll be
643
// ready to accept RPC calls. A `GenSeedRequest` is needed to generate the
644
// seed.
645
func (h *HarnessTest) newNodeWithSeed(name string,
646
        extraArgs []string, req *lnrpc.GenSeedRequest,
647
        statelessInit bool) (*node.HarnessNode, []string, []byte) {
×
648

×
649
        node, err := h.manager.newNode(
×
650
                h.T, name, extraArgs, req.AezeedPassphrase, true,
×
651
        )
×
652
        require.NoErrorf(h, err, "unable to create new node for %s", name)
×
653

×
654
        // Start the node with seed only, which will only create the `State`
×
655
        // and `WalletUnlocker` clients.
×
656
        err = node.StartWithNoAuth(h.runCtx)
×
657
        require.NoErrorf(h, err, "failed to start node %s", node.Name())
×
658

×
659
        // Generate a new seed.
×
660
        genSeedResp := node.RPC.GenSeed(req)
×
661

×
662
        // With the seed created, construct the init request to the node,
×
663
        // including the newly generated seed.
×
664
        initReq := &lnrpc.InitWalletRequest{
×
665
                WalletPassword:     req.AezeedPassphrase,
×
666
                CipherSeedMnemonic: genSeedResp.CipherSeedMnemonic,
×
667
                AezeedPassphrase:   req.AezeedPassphrase,
×
668
                StatelessInit:      statelessInit,
×
669
        }
×
670

×
671
        // Pass the init request via rpc to finish unlocking the node. This
×
672
        // will also initialize the macaroon-authenticated LightningClient.
×
673
        adminMac, err := h.manager.initWalletAndNode(node, initReq)
×
674
        require.NoErrorf(h, err, "failed to unlock and init node %s",
×
675
                node.Name())
×
676

×
677
        // In stateless initialization mode we get a macaroon back that we have
×
678
        // to return to the test, otherwise gRPC calls won't be possible since
×
679
        // there are no macaroon files created in that mode.
×
680
        // In stateful init the admin macaroon will just be nil.
×
681
        return node, genSeedResp.CipherSeedMnemonic, adminMac
×
682
}
×
683

684
// RestoreNodeWithSeed fully initializes a HarnessNode using a chosen mnemonic,
685
// password, recovery window, and optionally a set of static channel backups.
686
// After providing the initialization request to unlock the node, this method
687
// will finish initializing the LightningClient such that the HarnessNode can
688
// be used for regular rpc operations.
689
func (h *HarnessTest) RestoreNodeWithSeed(name string, extraArgs []string,
690
        password []byte, mnemonic []string, rootKey string,
691
        recoveryWindow int32,
692
        chanBackups *lnrpc.ChanBackupSnapshot) *node.HarnessNode {
×
693

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

×
697
        // Start the node with seed only, which will only create the `State`
×
698
        // and `WalletUnlocker` clients.
×
699
        err = n.StartWithNoAuth(h.runCtx)
×
700
        require.NoErrorf(h, err, "failed to start node %s", n.Name())
×
701

×
702
        // Create the wallet.
×
703
        initReq := &lnrpc.InitWalletRequest{
×
704
                WalletPassword:     password,
×
705
                CipherSeedMnemonic: mnemonic,
×
706
                AezeedPassphrase:   password,
×
707
                ExtendedMasterKey:  rootKey,
×
708
                RecoveryWindow:     recoveryWindow,
×
709
                ChannelBackups:     chanBackups,
×
710
        }
×
711
        _, err = h.manager.initWalletAndNode(n, initReq)
×
712
        require.NoErrorf(h, err, "failed to unlock and init node %s",
×
713
                n.Name())
×
714

×
715
        return n
×
716
}
×
717

718
// NewNodeEtcd starts a new node with seed that'll use an external etcd
719
// database as its storage. The passed cluster flag indicates that we'd like
720
// the node to join the cluster leader election. We won't wait until RPC is
721
// available (this is useful when the node is not expected to become the leader
722
// right away).
723
func (h *HarnessTest) NewNodeEtcd(name string, etcdCfg *etcd.Config,
724
        password []byte, cluster bool,
725
        leaderSessionTTL int) *node.HarnessNode {
×
726

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

×
730
        extraArgs := node.ExtraArgsEtcd(
×
731
                etcdCfg, name, cluster, leaderSessionTTL,
×
732
        )
×
733
        node, err := h.manager.newNode(h.T, name, extraArgs, password, true)
×
734
        require.NoError(h, err, "failed to create new node with etcd")
×
735

×
736
        // Start the node daemon only.
×
737
        err = node.StartLndCmd(h.runCtx)
×
738
        require.NoError(h, err, "failed to start node %s", node.Name())
×
739

×
740
        return node
×
741
}
×
742

743
// NewNodeWithSeedEtcd starts a new node with seed that'll use an external etcd
744
// database as its storage. The passed cluster flag indicates that we'd like
745
// the node to join the cluster leader election.
746
func (h *HarnessTest) NewNodeWithSeedEtcd(name string, etcdCfg *etcd.Config,
747
        password []byte, statelessInit, cluster bool,
748
        leaderSessionTTL int) (*node.HarnessNode, []string, []byte) {
×
749

×
750
        // We don't want to use the embedded etcd instance.
×
751
        h.manager.dbBackend = node.BackendBbolt
×
752

×
753
        // Create a request to generate a new aezeed. The new seed will have
×
754
        // the same password as the internal wallet.
×
755
        req := &lnrpc.GenSeedRequest{
×
756
                AezeedPassphrase: password,
×
757
                SeedEntropy:      nil,
×
758
        }
×
759

×
760
        extraArgs := node.ExtraArgsEtcd(
×
761
                etcdCfg, name, cluster, leaderSessionTTL,
×
762
        )
×
763

×
764
        return h.newNodeWithSeed(name, extraArgs, req, statelessInit)
×
765
}
×
766

767
// NewNodeRemoteSigner creates a new remote signer node and asserts its
768
// creation.
769
func (h *HarnessTest) NewNodeRemoteSigner(name string, extraArgs []string,
770
        password []byte, watchOnly *lnrpc.WatchOnly) *node.HarnessNode {
×
771

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

×
775
        err = hn.StartWithNoAuth(h.runCtx)
×
776
        require.NoError(h, err, "failed to start node %s", name)
×
777

×
778
        // With the seed created, construct the init request to the node,
×
779
        // including the newly generated seed.
×
780
        initReq := &lnrpc.InitWalletRequest{
×
781
                WalletPassword: password,
×
782
                WatchOnly:      watchOnly,
×
783
        }
×
784

×
785
        // Pass the init request via rpc to finish unlocking the node. This
×
786
        // will also initialize the macaroon-authenticated LightningClient.
×
787
        _, err = h.manager.initWalletAndNode(hn, initReq)
×
788
        require.NoErrorf(h, err, "failed to init node %s", name)
×
789

×
790
        return hn
×
791
}
×
792

793
// KillNode kills the node and waits for the node process to stop.
794
func (h *HarnessTest) KillNode(hn *node.HarnessNode) {
×
795
        delete(h.manager.activeNodes, hn.Cfg.NodeID)
×
796

×
797
        h.Logf("Manually killing the node %s", hn.Name())
×
798
        require.NoErrorf(h, hn.KillAndWait(), "%s: kill got error", hn.Name())
×
799
}
×
800

801
// SetFeeEstimate sets a fee rate to be returned from fee estimator.
802
//
803
// NOTE: this method will set the fee rate for a conf target of 1, which is the
804
// fallback fee rate for a `WebAPIEstimator` if a higher conf target's fee rate
805
// is not set. This means if the fee rate for conf target 6 is set, the fee
806
// estimator will use that value instead.
807
func (h *HarnessTest) SetFeeEstimate(fee chainfee.SatPerKWeight) {
×
808
        h.feeService.SetFeeRate(fee, 1)
×
809
}
×
810

811
// SetFeeEstimateWithConf sets a fee rate of a specified conf target to be
812
// returned from fee estimator.
813
func (h *HarnessTest) SetFeeEstimateWithConf(
814
        fee chainfee.SatPerKWeight, conf uint32) {
×
815

×
816
        h.feeService.SetFeeRate(fee, conf)
×
817
}
×
818

819
// SetMinRelayFeerate sets a min relay fee rate to be returned from fee
820
// estimator.
821
func (h *HarnessTest) SetMinRelayFeerate(fee chainfee.SatPerKVByte) {
×
822
        h.feeService.SetMinRelayFeerate(fee)
×
823
}
×
824

825
// validateNodeState checks that the node doesn't have any uncleaned states
826
// which will affect its following tests.
827
func (h *HarnessTest) validateNodeState(hn *node.HarnessNode) error {
×
828
        errStr := func(subject string) error {
×
829
                return fmt.Errorf("%s: found %s channels, please close "+
×
830
                        "them properly", hn.Name(), subject)
×
831
        }
×
832
        // If the node still has open channels, it's most likely that the
833
        // current test didn't close it properly.
834
        if hn.State.OpenChannel.Active != 0 {
×
835
                return errStr("active")
×
836
        }
×
837
        if hn.State.OpenChannel.Public != 0 {
×
838
                return errStr("public")
×
839
        }
×
840
        if hn.State.OpenChannel.Private != 0 {
×
841
                return errStr("private")
×
842
        }
×
843
        if hn.State.OpenChannel.Pending != 0 {
×
844
                return errStr("pending open")
×
845
        }
×
846

847
        // The number of pending force close channels should be zero.
848
        if hn.State.CloseChannel.PendingForceClose != 0 {
×
849
                return errStr("pending force")
×
850
        }
×
851

852
        // The number of waiting close channels should be zero.
853
        if hn.State.CloseChannel.WaitingClose != 0 {
×
854
                return errStr("waiting close")
×
855
        }
×
856

857
        // Ths number of payments should be zero.
858
        if hn.State.Payment.Total != 0 {
×
859
                return fmt.Errorf("%s: found uncleaned payments, please "+
×
860
                        "delete all of them properly", hn.Name())
×
861
        }
×
862

863
        // The number of public edges should be zero.
864
        if hn.State.Edge.Public != 0 {
×
865
                return fmt.Errorf("%s: found active public egdes, please "+
×
866
                        "clean them properly", hn.Name())
×
867
        }
×
868

869
        // The number of edges should be zero.
870
        if hn.State.Edge.Total != 0 {
×
871
                return fmt.Errorf("%s: found active edges, please "+
×
872
                        "clean them properly", hn.Name())
×
873
        }
×
874

875
        return nil
×
876
}
877

878
// GetChanPointFundingTxid takes a channel point and converts it into a chain
879
// hash.
880
func (h *HarnessTest) GetChanPointFundingTxid(
881
        cp *lnrpc.ChannelPoint) chainhash.Hash {
×
882

×
883
        txid, err := lnrpc.GetChanPointFundingTxid(cp)
×
884
        require.NoError(h, err, "unable to get txid")
×
885

×
886
        return *txid
×
887
}
×
888

889
// OutPointFromChannelPoint creates an outpoint from a given channel point.
890
func (h *HarnessTest) OutPointFromChannelPoint(
891
        cp *lnrpc.ChannelPoint) wire.OutPoint {
×
892

×
893
        txid := h.GetChanPointFundingTxid(cp)
×
894
        return wire.OutPoint{
×
895
                Hash:  txid,
×
896
                Index: cp.OutputIndex,
×
897
        }
×
898
}
×
899

900
// OpenChannelParams houses the params to specify when opening a new channel.
901
type OpenChannelParams struct {
902
        // Amt is the local amount being put into the channel.
903
        Amt btcutil.Amount
904

905
        // PushAmt is the amount that should be pushed to the remote when the
906
        // channel is opened.
907
        PushAmt btcutil.Amount
908

909
        // Private is a boolan indicating whether the opened channel should be
910
        // private.
911
        Private bool
912

913
        // SpendUnconfirmed is a boolean indicating whether we can utilize
914
        // unconfirmed outputs to fund the channel.
915
        SpendUnconfirmed bool
916

917
        // MinHtlc is the htlc_minimum_msat value set when opening the channel.
918
        MinHtlc lnwire.MilliSatoshi
919

920
        // RemoteMaxHtlcs is the remote_max_htlcs value set when opening the
921
        // channel, restricting the number of concurrent HTLCs the remote party
922
        // can add to a commitment.
923
        RemoteMaxHtlcs uint16
924

925
        // FundingShim is an optional funding shim that the caller can specify
926
        // in order to modify the channel funding workflow.
927
        FundingShim *lnrpc.FundingShim
928

929
        // SatPerVByte is the amount of satoshis to spend in chain fees per
930
        // virtual byte of the transaction.
931
        SatPerVByte btcutil.Amount
932

933
        // ConfTarget is the number of blocks that the funding transaction
934
        // should be confirmed in.
935
        ConfTarget fn.Option[int32]
936

937
        // CommitmentType is the commitment type that should be used for the
938
        // channel to be opened.
939
        CommitmentType lnrpc.CommitmentType
940

941
        // ZeroConf is used to determine if the channel will be a zero-conf
942
        // channel. This only works if the explicit negotiation is used with
943
        // anchors or script enforced leases.
944
        ZeroConf bool
945

946
        // ScidAlias denotes whether the channel will be an option-scid-alias
947
        // channel type negotiation.
948
        ScidAlias bool
949

950
        // BaseFee is the channel base fee applied during the channel
951
        // announcement phase.
952
        BaseFee uint64
953

954
        // FeeRate is the channel fee rate in ppm applied during the channel
955
        // announcement phase.
956
        FeeRate uint64
957

958
        // UseBaseFee, if set, instructs the downstream logic to apply the
959
        // user-specified channel base fee to the channel update announcement.
960
        // If set to false it avoids applying a base fee of 0 and instead
961
        // activates the default configured base fee.
962
        UseBaseFee bool
963

964
        // UseFeeRate, if set, instructs the downstream logic to apply the
965
        // user-specified channel fee rate to the channel update announcement.
966
        // If set to false it avoids applying a fee rate of 0 and instead
967
        // activates the default configured fee rate.
968
        UseFeeRate bool
969

970
        // FundMax is a boolean indicating whether the channel should be funded
971
        // with the maximum possible amount from the wallet.
972
        FundMax bool
973

974
        // An optional note-to-self containing some useful information about the
975
        // channel. This is stored locally only, and is purely for reference. It
976
        // has no bearing on the channel's operation. Max allowed length is 500
977
        // characters.
978
        Memo string
979

980
        // Outpoints is a list of client-selected outpoints that should be used
981
        // for funding a channel. If Amt is specified then this amount is
982
        // allocated from the sum of outpoints towards funding. If the
983
        // FundMax flag is specified the entirety of selected funds is
984
        // allocated towards channel funding.
985
        Outpoints []*lnrpc.OutPoint
986

987
        // CloseAddress sets the upfront_shutdown_script parameter during
988
        // channel open. It is expected to be encoded as a bitcoin address.
989
        CloseAddress string
990
}
991

992
// prepareOpenChannel waits for both nodes to be synced to chain and returns an
993
// OpenChannelRequest.
994
func (h *HarnessTest) prepareOpenChannel(srcNode, destNode *node.HarnessNode,
995
        p OpenChannelParams) *lnrpc.OpenChannelRequest {
×
996

×
997
        // Wait until srcNode and destNode have the latest chain synced.
×
998
        // Otherwise, we may run into a check within the funding manager that
×
999
        // prevents any funding workflows from being kicked off if the chain
×
1000
        // isn't yet synced.
×
1001
        h.WaitForBlockchainSync(srcNode)
×
1002
        h.WaitForBlockchainSync(destNode)
×
1003

×
1004
        // Specify the minimal confirmations of the UTXOs used for channel
×
1005
        // funding.
×
1006
        minConfs := int32(1)
×
1007
        if p.SpendUnconfirmed {
×
1008
                minConfs = 0
×
1009
        }
×
1010

1011
        // Get the requested conf target. If not set, default to 6.
1012
        confTarget := p.ConfTarget.UnwrapOr(6)
×
1013

×
1014
        // If there's fee rate set, unset the conf target.
×
1015
        if p.SatPerVByte != 0 {
×
1016
                confTarget = 0
×
1017
        }
×
1018

1019
        // Prepare the request.
1020
        return &lnrpc.OpenChannelRequest{
×
1021
                NodePubkey:         destNode.PubKey[:],
×
1022
                LocalFundingAmount: int64(p.Amt),
×
1023
                PushSat:            int64(p.PushAmt),
×
1024
                Private:            p.Private,
×
1025
                TargetConf:         confTarget,
×
1026
                MinConfs:           minConfs,
×
1027
                SpendUnconfirmed:   p.SpendUnconfirmed,
×
1028
                MinHtlcMsat:        int64(p.MinHtlc),
×
1029
                RemoteMaxHtlcs:     uint32(p.RemoteMaxHtlcs),
×
1030
                FundingShim:        p.FundingShim,
×
1031
                SatPerVbyte:        uint64(p.SatPerVByte),
×
1032
                CommitmentType:     p.CommitmentType,
×
1033
                ZeroConf:           p.ZeroConf,
×
1034
                ScidAlias:          p.ScidAlias,
×
1035
                BaseFee:            p.BaseFee,
×
1036
                FeeRate:            p.FeeRate,
×
1037
                UseBaseFee:         p.UseBaseFee,
×
1038
                UseFeeRate:         p.UseFeeRate,
×
1039
                FundMax:            p.FundMax,
×
1040
                Memo:               p.Memo,
×
1041
                Outpoints:          p.Outpoints,
×
1042
                CloseAddress:       p.CloseAddress,
×
1043
        }
×
1044
}
1045

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

×
1054
        // Prepare the request and open the channel.
×
1055
        openReq := h.prepareOpenChannel(srcNode, destNode, p)
×
1056
        respStream := srcNode.RPC.OpenChannel(openReq)
×
1057

×
1058
        // Consume the "channel pending" update. This waits until the node
×
1059
        // notifies us that the final message in the channel funding workflow
×
1060
        // has been sent to the remote node.
×
1061
        resp := h.ReceiveOpenChannelUpdate(respStream)
×
1062

×
1063
        // Check that the update is channel pending.
×
1064
        update, ok := resp.Update.(*lnrpc.OpenStatusUpdate_ChanPending)
×
1065
        require.Truef(h, ok, "expected channel pending: update, instead got %v",
×
1066
                resp)
×
1067

×
1068
        return update.ChanPending, respStream
×
1069
}
×
1070

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

×
1079
        resp, _ := h.openChannelAssertPending(srcNode, destNode, p)
×
1080
        return resp
×
1081
}
×
1082

1083
// OpenChannelAssertStream attempts to open a channel between srcNode and
1084
// destNode with the passed channel funding parameters. Once the `OpenChannel`
1085
// is called, it will consume the first event it receives from the open channel
1086
// client and asserts it's a channel pending event. It returns the open channel
1087
// stream.
1088
func (h *HarnessTest) OpenChannelAssertStream(srcNode,
1089
        destNode *node.HarnessNode, p OpenChannelParams) rpc.OpenChanClient {
×
1090

×
1091
        _, stream := h.openChannelAssertPending(srcNode, destNode, p)
×
1092
        return stream
×
1093
}
×
1094

1095
// OpenChannel attempts to open a channel with the specified parameters
1096
// extended from Alice to Bob. Additionally, for public channels, it will mine
1097
// extra blocks so they are announced to the network. In specific, the
1098
// following items are asserted,
1099
//   - for non-zero conf channel, 1 blocks will be mined to confirm the funding
1100
//     tx.
1101
//   - both nodes should see the channel edge update in their network graph.
1102
//   - both nodes can report the status of the new channel from ListChannels.
1103
//   - extra blocks are mined if it's a public channel.
1104
func (h *HarnessTest) OpenChannel(alice, bob *node.HarnessNode,
1105
        p OpenChannelParams) *lnrpc.ChannelPoint {
×
1106

×
1107
        // First, open the channel without announcing it.
×
1108
        cp := h.OpenChannelNoAnnounce(alice, bob, p)
×
1109

×
1110
        // If this is a private channel, there's no need to mine extra blocks
×
1111
        // since it will never be announced to the network.
×
1112
        if p.Private {
×
1113
                return cp
×
1114
        }
×
1115

1116
        // Mine extra blocks to announce the channel.
1117
        if p.ZeroConf {
×
1118
                // For a zero-conf channel, no blocks have been mined so we
×
1119
                // need to mine 6 blocks.
×
1120
                //
×
1121
                // Mine 1 block to confirm the funding transaction.
×
1122
                h.MineBlocksAndAssertNumTxes(numBlocksOpenChannel, 1)
×
1123
        } else {
×
1124
                // For a regular channel, 1 block has already been mined to
×
1125
                // confirm the funding transaction, so we mine 5 blocks.
×
1126
                h.MineBlocks(numBlocksOpenChannel - 1)
×
1127
        }
×
1128

1129
        return cp
×
1130
}
1131

1132
// OpenChannelNoAnnounce attempts to open a channel with the specified
1133
// parameters extended from Alice to Bob without mining the necessary blocks to
1134
// announce the channel. Additionally, the following items are asserted,
1135
//   - for non-zero conf channel, 1 blocks will be mined to confirm the funding
1136
//     tx.
1137
//   - both nodes should see the channel edge update in their network graph.
1138
//   - both nodes can report the status of the new channel from ListChannels.
1139
func (h *HarnessTest) OpenChannelNoAnnounce(alice, bob *node.HarnessNode,
1140
        p OpenChannelParams) *lnrpc.ChannelPoint {
×
1141

×
1142
        chanOpenUpdate := h.OpenChannelAssertStream(alice, bob, p)
×
1143

×
1144
        // Open a zero conf channel.
×
1145
        if p.ZeroConf {
×
1146
                return h.openChannelZeroConf(alice, bob, chanOpenUpdate)
×
1147
        }
×
1148

1149
        // Open a non-zero conf channel.
1150
        return h.openChannel(alice, bob, chanOpenUpdate)
×
1151
}
1152

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

×
1161
        // Mine 1 block to confirm the funding transaction.
×
1162
        block := h.MineBlocksAndAssertNumTxes(1, 1)[0]
×
1163

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

×
1167
        // Check that the funding tx is found in the first block.
×
1168
        fundingTxID := h.GetChanPointFundingTxid(fundingChanPoint)
×
1169
        h.AssertTxInBlock(block, fundingTxID)
×
1170

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

×
1176
        // Check that the channel can be seen in their ListChannels.
×
1177
        h.AssertChannelExists(alice, fundingChanPoint)
×
1178
        h.AssertChannelExists(bob, fundingChanPoint)
×
1179

×
1180
        return fundingChanPoint
×
1181
}
×
1182

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

×
1190
        // Wait for the channel open event.
×
1191
        fundingChanPoint := h.WaitForChannelOpenEvent(stream)
×
1192

×
1193
        // Check that both alice and bob have seen the channel from their
×
1194
        // network topology.
×
1195
        h.AssertChannelInGraph(alice, fundingChanPoint)
×
1196
        h.AssertChannelInGraph(bob, fundingChanPoint)
×
1197

×
1198
        // Finally, check that the channel can be seen in their ListChannels.
×
1199
        h.AssertChannelExists(alice, fundingChanPoint)
×
1200
        h.AssertChannelExists(bob, fundingChanPoint)
×
1201

×
1202
        return fundingChanPoint
×
1203
}
×
1204

1205
// OpenChannelAssertErr opens a channel between node srcNode and destNode,
1206
// asserts that the expected error is returned from the channel opening.
1207
func (h *HarnessTest) OpenChannelAssertErr(srcNode, destNode *node.HarnessNode,
1208
        p OpenChannelParams, expectedErr error) {
×
1209

×
1210
        // Prepare the request and open the channel.
×
1211
        openReq := h.prepareOpenChannel(srcNode, destNode, p)
×
1212
        respStream := srcNode.RPC.OpenChannel(openReq)
×
1213

×
1214
        // Receive an error to be sent from the stream.
×
1215
        _, err := h.receiveOpenChannelUpdate(respStream)
×
1216
        require.NotNil(h, err, "expected channel opening to fail")
×
1217

×
1218
        // Use string comparison here as we haven't codified all the RPC errors
×
1219
        // yet.
×
1220
        require.Containsf(h, err.Error(), expectedErr.Error(), "unexpected "+
×
1221
                "error returned, want %v, got %v", expectedErr, err)
×
1222
}
×
1223

1224
// closeChannelOpts holds the options for closing a channel.
1225
type closeChannelOpts struct {
1226
        feeRate fn.Option[chainfee.SatPerVByte]
1227

1228
        // localTxOnly is a boolean indicating if we should only attempt to
1229
        // consume close pending notifications for the local transaction.
1230
        localTxOnly bool
1231

1232
        // skipMempoolCheck is a boolean indicating if we should skip the normal
1233
        // mempool check after a coop close.
1234
        skipMempoolCheck bool
1235

1236
        // errString is an expected error. If this is non-blank, then we'll
1237
        // assert that the coop close wasn't possible, and returns an error that
1238
        // contains this err string.
1239
        errString string
1240
}
1241

1242
// CloseChanOpt is a functional option to modify the way we close a channel.
1243
type CloseChanOpt func(*closeChannelOpts)
1244

1245
// WithCoopCloseFeeRate is a functional option to set the fee rate for a coop
1246
// close attempt.
1247
func WithCoopCloseFeeRate(rate chainfee.SatPerVByte) CloseChanOpt {
×
1248
        return func(o *closeChannelOpts) {
×
1249
                o.feeRate = fn.Some(rate)
×
1250
        }
×
1251
}
1252

1253
// WithLocalTxNotify is a functional option to indicate that we should only
1254
// notify for the local txn. This is useful for the RBF coop close type, as
1255
// it'll notify for both local and remote txns.
1256
func WithLocalTxNotify() CloseChanOpt {
×
1257
        return func(o *closeChannelOpts) {
×
1258
                o.localTxOnly = true
×
1259
        }
×
1260
}
1261

1262
// WithSkipMempoolCheck is a functional option to indicate that we should skip
1263
// the mempool check. This can be used when a coop close iteration may not
1264
// result in a newly broadcast transaction.
1265
func WithSkipMempoolCheck() CloseChanOpt {
×
1266
        return func(o *closeChannelOpts) {
×
1267
                o.skipMempoolCheck = true
×
1268
        }
×
1269
}
1270

1271
// WithExpectedErrString is a functional option that can be used to assert that
1272
// an error occurs during the coop close process.
1273
func WithExpectedErrString(errString string) CloseChanOpt {
×
1274
        return func(o *closeChannelOpts) {
×
1275
                o.errString = errString
×
1276
        }
×
1277
}
1278

1279
// defaultCloseOpts returns the set of default close options.
1280
func defaultCloseOpts() *closeChannelOpts {
×
1281
        return &closeChannelOpts{}
×
1282
}
×
1283

1284
// CloseChannelAssertPending attempts to close the channel indicated by the
1285
// passed channel point, initiated by the passed node. Once the CloseChannel
1286
// rpc is called, it will consume one event and assert it's a close pending
1287
// event. In addition, it will check that the closing tx can be found in the
1288
// mempool.
1289
func (h *HarnessTest) CloseChannelAssertPending(hn *node.HarnessNode,
1290
        cp *lnrpc.ChannelPoint, force bool,
1291
        opts ...CloseChanOpt) (rpc.CloseChanClient, *lnrpc.CloseStatusUpdate) {
×
1292

×
1293
        closeOpts := defaultCloseOpts()
×
1294
        for _, optFunc := range opts {
×
1295
                optFunc(closeOpts)
×
1296
        }
×
1297

1298
        // Calls the rpc to close the channel.
1299
        closeReq := &lnrpc.CloseChannelRequest{
×
1300
                ChannelPoint: cp,
×
1301
                Force:        force,
×
1302
                NoWait:       true,
×
1303
        }
×
1304

×
1305
        closeOpts.feeRate.WhenSome(func(feeRate chainfee.SatPerVByte) {
×
1306
                closeReq.SatPerVbyte = uint64(feeRate)
×
1307
        })
×
1308

1309
        var (
×
1310
                stream rpc.CloseChanClient
×
1311
                event  *lnrpc.CloseStatusUpdate
×
1312
                err    error
×
1313
        )
×
1314

×
1315
        // Consume the "channel close" update in order to wait for the closing
×
1316
        // transaction to be broadcast, then wait for the closing tx to be seen
×
1317
        // within the network.
×
1318
        stream = hn.RPC.CloseChannel(closeReq)
×
1319
        _, err = h.ReceiveCloseChannelUpdate(stream)
×
1320
        require.NoError(h, err, "close channel update got error: %v", err)
×
1321

×
1322
        var closeTxid *chainhash.Hash
×
1323
        for {
×
1324
                event, err = h.ReceiveCloseChannelUpdate(stream)
×
1325
                if err != nil {
×
1326
                        h.Logf("Test: %s, close channel got error: %v",
×
1327
                                h.manager.currentTestCase, err)
×
1328
                }
×
1329
                if err != nil && closeOpts.errString == "" {
×
1330
                        require.NoError(h, err, "retry closing channel failed")
×
1331
                } else if err != nil && closeOpts.errString != "" {
×
1332
                        require.ErrorContains(h, err, closeOpts.errString)
×
1333
                        return nil, nil
×
1334
                }
×
1335

1336
                pendingClose, ok := event.Update.(*lnrpc.CloseStatusUpdate_ClosePending) //nolint:ll
×
1337
                require.Truef(h, ok, "expected channel close "+
×
1338
                        "update, instead got %v", pendingClose)
×
1339

×
1340
                if !pendingClose.ClosePending.LocalCloseTx &&
×
1341
                        closeOpts.localTxOnly {
×
1342

×
1343
                        continue
×
1344
                }
1345

1346
                notifyRate := pendingClose.ClosePending.FeePerVbyte
×
1347
                if closeOpts.localTxOnly &&
×
1348
                        notifyRate != int64(closeReq.SatPerVbyte) {
×
1349

×
1350
                        continue
×
1351
                }
1352

1353
                closeTxid, err = chainhash.NewHash(
×
1354
                        pendingClose.ClosePending.Txid,
×
1355
                )
×
1356
                require.NoErrorf(h, err, "unable to decode closeTxid: %v",
×
1357
                        pendingClose.ClosePending.Txid)
×
1358

×
1359
                break
×
1360
        }
1361

1362
        if !closeOpts.skipMempoolCheck {
×
1363
                // Assert the closing tx is in the mempool.
×
1364
                h.miner.AssertTxInMempool(*closeTxid)
×
1365
        }
×
1366

1367
        return stream, event
×
1368
}
1369

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

×
1382
        stream, _ := h.CloseChannelAssertPending(hn, cp, false)
×
1383

×
1384
        return h.AssertStreamChannelCoopClosed(hn, cp, false, stream)
×
1385
}
×
1386

1387
// ForceCloseChannel attempts to force close a non-anchored channel identified
1388
// by the passed channel point owned by the passed harness node. The following
1389
// items are asserted,
1390
//  1. a close pending event is sent from the close channel client.
1391
//  2. the closing tx is found in the mempool.
1392
//  3. the node reports the channel being waiting to close.
1393
//  4. a block is mined and the closing tx should be found in it.
1394
//  5. the node reports zero waiting close channels.
1395
//  6. the node receives a topology update regarding the channel close.
1396
//  7. mine DefaultCSV-1 blocks.
1397
//  8. the node reports zero pending force close channels.
1398
func (h *HarnessTest) ForceCloseChannel(hn *node.HarnessNode,
1399
        cp *lnrpc.ChannelPoint) chainhash.Hash {
×
1400

×
1401
        stream, _ := h.CloseChannelAssertPending(hn, cp, true)
×
1402

×
1403
        closingTxid := h.AssertStreamChannelForceClosed(hn, cp, false, stream)
×
1404

×
1405
        // Cleanup the force close.
×
1406
        h.CleanupForceClose(hn)
×
1407

×
1408
        return closingTxid
×
1409
}
×
1410

1411
// CloseChannelAssertErr closes the given channel and asserts an error
1412
// returned.
1413
func (h *HarnessTest) CloseChannelAssertErr(hn *node.HarnessNode,
1414
        req *lnrpc.CloseChannelRequest) error {
×
1415

×
1416
        // Calls the rpc to close the channel.
×
1417
        stream := hn.RPC.CloseChannel(req)
×
1418

×
1419
        // Consume the "channel close" update in order to wait for the closing
×
1420
        // transaction to be broadcast, then wait for the closing tx to be seen
×
1421
        // within the network.
×
1422
        _, err := h.ReceiveCloseChannelUpdate(stream)
×
1423
        require.Errorf(h, err, "%s: expect close channel to return an error",
×
1424
                hn.Name())
×
1425

×
1426
        return err
×
1427
}
×
1428

1429
// IsNeutrinoBackend returns a bool indicating whether the node is using a
1430
// neutrino as its backend. This is useful when we want to skip certain tests
1431
// which cannot be done with a neutrino backend.
1432
func (h *HarnessTest) IsNeutrinoBackend() bool {
×
1433
        return h.manager.chainBackend.Name() == NeutrinoBackendName
×
1434
}
×
1435

1436
// fundCoins attempts to send amt satoshis from the internal mining node to the
1437
// targeted lightning node. The confirmed boolean indicates whether the
1438
// transaction that pays to the target should confirm. For neutrino backend,
1439
// the `confirmed` param is ignored.
1440
func (h *HarnessTest) fundCoins(amt btcutil.Amount, target *node.HarnessNode,
1441
        addrType lnrpc.AddressType, confirmed bool) *wire.MsgTx {
×
1442

×
1443
        initialBalance := target.RPC.WalletBalance()
×
1444

×
1445
        // First, obtain an address from the target lightning node, preferring
×
1446
        // to receive a p2wkh address s.t the output can immediately be used as
×
1447
        // an input to a funding transaction.
×
1448
        req := &lnrpc.NewAddressRequest{Type: addrType}
×
1449
        resp := target.RPC.NewAddress(req)
×
1450
        addr := h.DecodeAddress(resp.Address)
×
1451
        addrScript := h.PayToAddrScript(addr)
×
1452

×
1453
        // Generate a transaction which creates an output to the target
×
1454
        // pkScript of the desired amount.
×
1455
        output := &wire.TxOut{
×
1456
                PkScript: addrScript,
×
1457
                Value:    int64(amt),
×
1458
        }
×
1459
        txid := h.miner.SendOutput(output, defaultMinerFeeRate)
×
1460

×
1461
        // Get the funding tx.
×
1462
        tx := h.GetRawTransaction(*txid)
×
1463
        msgTx := tx.MsgTx()
×
1464

×
1465
        // Since neutrino doesn't support unconfirmed outputs, skip this check.
×
1466
        if !h.IsNeutrinoBackend() {
×
1467
                expectedBalance := btcutil.Amount(
×
1468
                        initialBalance.UnconfirmedBalance,
×
1469
                ) + amt
×
1470
                h.WaitForBalanceUnconfirmed(target, expectedBalance)
×
1471
        }
×
1472

1473
        // If the transaction should remain unconfirmed, then we'll wait until
1474
        // the target node's unconfirmed balance reflects the expected balance
1475
        // and exit.
1476
        if !confirmed {
×
1477
                return msgTx
×
1478
        }
×
1479

1480
        // Otherwise, we'll generate 1 new blocks to ensure the output gains a
1481
        // sufficient number of confirmations and wait for the balance to
1482
        // reflect what's expected.
1483
        h.MineBlockWithTx(msgTx)
×
1484

×
1485
        expectedBalance := btcutil.Amount(initialBalance.ConfirmedBalance) + amt
×
1486
        h.WaitForBalanceConfirmed(target, expectedBalance)
×
1487

×
1488
        return msgTx
×
1489
}
1490

1491
// FundCoins attempts to send amt satoshis from the internal mining node to the
1492
// targeted lightning node using a P2WKH address. 1 blocks are mined after in
1493
// order to confirm the transaction.
1494
func (h *HarnessTest) FundCoins(amt btcutil.Amount,
1495
        hn *node.HarnessNode) *wire.MsgTx {
×
1496

×
1497
        return h.fundCoins(amt, hn, lnrpc.AddressType_WITNESS_PUBKEY_HASH, true)
×
1498
}
×
1499

1500
// FundCoinsUnconfirmed attempts to send amt satoshis from the internal mining
1501
// node to the targeted lightning node using a P2WKH address. No blocks are
1502
// mined after and the UTXOs are unconfirmed.
1503
func (h *HarnessTest) FundCoinsUnconfirmed(amt btcutil.Amount,
1504
        hn *node.HarnessNode) *wire.MsgTx {
×
1505

×
1506
        return h.fundCoins(
×
1507
                amt, hn, lnrpc.AddressType_WITNESS_PUBKEY_HASH, false,
×
1508
        )
×
1509
}
×
1510

1511
// FundCoinsNP2WKH attempts to send amt satoshis from the internal mining node
1512
// to the targeted lightning node using a NP2WKH address.
1513
func (h *HarnessTest) FundCoinsNP2WKH(amt btcutil.Amount,
1514
        target *node.HarnessNode) *wire.MsgTx {
×
1515

×
1516
        return h.fundCoins(
×
1517
                amt, target, lnrpc.AddressType_NESTED_PUBKEY_HASH, true,
×
1518
        )
×
1519
}
×
1520

1521
// FundCoinsP2TR attempts to send amt satoshis from the internal mining node to
1522
// the targeted lightning node using a P2TR address.
1523
func (h *HarnessTest) FundCoinsP2TR(amt btcutil.Amount,
1524
        target *node.HarnessNode) *wire.MsgTx {
×
1525

×
1526
        return h.fundCoins(amt, target, lnrpc.AddressType_TAPROOT_PUBKEY, true)
×
1527
}
×
1528

1529
// FundNumCoins attempts to send the given number of UTXOs from the internal
1530
// mining node to the targeted lightning node using a P2WKH address. Each UTXO
1531
// has an amount of 1 BTC. 1 blocks are mined to confirm the tx.
1532
func (h *HarnessTest) FundNumCoins(hn *node.HarnessNode, num int) {
×
1533
        // Get the initial balance first.
×
1534
        resp := hn.RPC.WalletBalance()
×
1535
        initialBalance := btcutil.Amount(resp.ConfirmedBalance)
×
1536

×
1537
        const fundAmount = 1 * btcutil.SatoshiPerBitcoin
×
1538

×
1539
        // Send out the outputs from the miner.
×
1540
        for i := 0; i < num; i++ {
×
1541
                h.createAndSendOutput(
×
1542
                        hn, fundAmount, lnrpc.AddressType_WITNESS_PUBKEY_HASH,
×
1543
                )
×
1544
        }
×
1545

1546
        // Wait for ListUnspent to show the correct number of unconfirmed
1547
        // UTXOs.
1548
        //
1549
        // Since neutrino doesn't support unconfirmed outputs, skip this check.
1550
        if !h.IsNeutrinoBackend() {
×
1551
                h.AssertNumUTXOsUnconfirmed(hn, num)
×
1552
        }
×
1553

1554
        // Mine a block to confirm the transactions.
1555
        h.MineBlocksAndAssertNumTxes(1, num)
×
1556

×
1557
        // Now block until the wallet have fully synced up.
×
1558
        totalAmount := btcutil.Amount(fundAmount * num)
×
1559
        expectedBalance := initialBalance + totalAmount
×
1560
        h.WaitForBalanceConfirmed(hn, expectedBalance)
×
1561
}
1562

1563
// completePaymentRequestsAssertStatus sends payments from a node to complete
1564
// all payment requests. This function does not return until all payments
1565
// have reached the specified status.
1566
func (h *HarnessTest) completePaymentRequestsAssertStatus(hn *node.HarnessNode,
1567
        paymentRequests []string, status lnrpc.Payment_PaymentStatus,
1568
        opts ...HarnessOpt) {
×
1569

×
1570
        payOpts := defaultHarnessOpts()
×
1571
        for _, opt := range opts {
×
1572
                opt(&payOpts)
×
1573
        }
×
1574

1575
        // Create a buffered chan to signal the results.
1576
        results := make(chan rpc.PaymentClient, len(paymentRequests))
×
1577

×
1578
        // send sends a payment and asserts if it doesn't succeeded.
×
1579
        send := func(payReq string) {
×
1580
                req := &routerrpc.SendPaymentRequest{
×
1581
                        PaymentRequest: payReq,
×
1582
                        TimeoutSeconds: int32(wait.PaymentTimeout.Seconds()),
×
1583
                        FeeLimitMsat:   noFeeLimitMsat,
×
1584
                        Amp:            payOpts.useAMP,
×
1585
                }
×
1586
                stream := hn.RPC.SendPayment(req)
×
1587

×
1588
                // Signal sent succeeded.
×
1589
                results <- stream
×
1590
        }
×
1591

1592
        // Launch all payments simultaneously.
1593
        for _, payReq := range paymentRequests {
×
1594
                payReqCopy := payReq
×
1595
                go send(payReqCopy)
×
1596
        }
×
1597

1598
        // Wait for all payments to report the expected status.
1599
        timer := time.After(wait.PaymentTimeout)
×
1600
        select {
×
1601
        case stream := <-results:
×
1602
                h.AssertPaymentStatusFromStream(stream, status)
×
1603

1604
        case <-timer:
×
1605
                require.Failf(h, "timeout", "%s: waiting payment results "+
×
1606
                        "timeout", hn.Name())
×
1607
        }
1608
}
1609

1610
// CompletePaymentRequests sends payments from a node to complete all payment
1611
// requests. This function does not return until all payments successfully
1612
// complete without errors.
1613
func (h *HarnessTest) CompletePaymentRequests(hn *node.HarnessNode,
1614
        paymentRequests []string, opts ...HarnessOpt) {
×
1615

×
1616
        h.completePaymentRequestsAssertStatus(
×
1617
                hn, paymentRequests, lnrpc.Payment_SUCCEEDED, opts...,
×
1618
        )
×
1619
}
×
1620

1621
// CompletePaymentRequestsNoWait sends payments from a node to complete all
1622
// payment requests without waiting for the results. Instead, it checks the
1623
// number of updates in the specified channel has increased.
1624
func (h *HarnessTest) CompletePaymentRequestsNoWait(hn *node.HarnessNode,
1625
        paymentRequests []string, chanPoint *lnrpc.ChannelPoint) {
×
1626

×
1627
        // We start by getting the current state of the client's channels. This
×
1628
        // is needed to ensure the payments actually have been committed before
×
1629
        // we return.
×
1630
        oldResp := h.GetChannelByChanPoint(hn, chanPoint)
×
1631

×
1632
        // Send payments and assert they are in-flight.
×
1633
        h.completePaymentRequestsAssertStatus(
×
1634
                hn, paymentRequests, lnrpc.Payment_IN_FLIGHT,
×
1635
        )
×
1636

×
1637
        // We are not waiting for feedback in the form of a response, but we
×
1638
        // should still wait long enough for the server to receive and handle
×
1639
        // the send before cancelling the request. We wait for the number of
×
1640
        // updates to one of our channels has increased before we return.
×
1641
        err := wait.NoError(func() error {
×
1642
                newResp := h.GetChannelByChanPoint(hn, chanPoint)
×
1643

×
1644
                // If this channel has an increased number of updates, we
×
1645
                // assume the payments are committed, and we can return.
×
1646
                if newResp.NumUpdates > oldResp.NumUpdates {
×
1647
                        return nil
×
1648
                }
×
1649

1650
                // Otherwise return an error as the NumUpdates are not
1651
                // increased.
1652
                return fmt.Errorf("%s: channel:%v not updated after sending "+
×
1653
                        "payments, old updates: %v, new updates: %v", hn.Name(),
×
1654
                        chanPoint, oldResp.NumUpdates, newResp.NumUpdates)
×
1655
        }, DefaultTimeout)
1656
        require.NoError(h, err, "timeout while checking for channel updates")
×
1657
}
1658

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

×
1665
        // Wait until srcNode and destNode have the latest chain synced.
×
1666
        // Otherwise, we may run into a check within the funding manager that
×
1667
        // prevents any funding workflows from being kicked off if the chain
×
1668
        // isn't yet synced.
×
1669
        h.WaitForBlockchainSync(srcNode)
×
1670
        h.WaitForBlockchainSync(destNode)
×
1671

×
1672
        // Send the request to open a channel to the source node now. This will
×
1673
        // open a long-lived stream where we'll receive status updates about
×
1674
        // the progress of the channel.
×
1675
        // respStream := h.OpenChannelStreamAndAssert(srcNode, destNode, p)
×
1676
        req := &lnrpc.OpenChannelRequest{
×
1677
                NodePubkey:         destNode.PubKey[:],
×
1678
                LocalFundingAmount: int64(p.Amt),
×
1679
                PushSat:            int64(p.PushAmt),
×
1680
                Private:            p.Private,
×
1681
                SpendUnconfirmed:   p.SpendUnconfirmed,
×
1682
                MinHtlcMsat:        int64(p.MinHtlc),
×
1683
                FundingShim:        p.FundingShim,
×
1684
                CommitmentType:     p.CommitmentType,
×
1685
        }
×
1686
        respStream := srcNode.RPC.OpenChannel(req)
×
1687

×
1688
        // Consume the "PSBT funding ready" update. This waits until the node
×
1689
        // notifies us that the PSBT can now be funded.
×
1690
        resp := h.ReceiveOpenChannelUpdate(respStream)
×
1691
        upd, ok := resp.Update.(*lnrpc.OpenStatusUpdate_PsbtFund)
×
1692
        require.Truef(h, ok, "expected PSBT funding update, got %v", resp)
×
1693

×
1694
        // Make sure the channel funding address has the correct type for the
×
1695
        // given commitment type.
×
1696
        fundingAddr, err := btcutil.DecodeAddress(
×
1697
                upd.PsbtFund.FundingAddress, miner.HarnessNetParams,
×
1698
        )
×
1699
        require.NoError(h, err)
×
1700

×
1701
        switch p.CommitmentType {
×
1702
        case lnrpc.CommitmentType_SIMPLE_TAPROOT:
×
1703
                require.IsType(h, &btcutil.AddressTaproot{}, fundingAddr)
×
1704

1705
        default:
×
1706
                require.IsType(
×
1707
                        h, &btcutil.AddressWitnessScriptHash{}, fundingAddr,
×
1708
                )
×
1709
        }
1710

1711
        return respStream, upd.PsbtFund.Psbt
×
1712
}
1713

1714
// CleanupForceClose mines blocks to clean up the force close process. This is
1715
// used for tests that are not asserting the expected behavior is found during
1716
// the force close process, e.g., num of sweeps, etc. Instead, it provides a
1717
// shortcut to move the test forward with a clean mempool.
1718
func (h *HarnessTest) CleanupForceClose(hn *node.HarnessNode) {
×
1719
        // Wait for the channel to be marked pending force close.
×
1720
        h.AssertNumPendingForceClose(hn, 1)
×
1721

×
1722
        // Mine enough blocks for the node to sweep its funds from the force
×
1723
        // closed channel. The commit sweep resolver is offers the input to the
×
1724
        // sweeper when it's force closed, and broadcast the sweep tx at
×
1725
        // defaulCSV-1.
×
1726
        //
×
1727
        // NOTE: we might empty blocks here as we don't know the exact number
×
1728
        // of blocks to mine. This may end up mining more blocks than needed.
×
1729
        h.MineEmptyBlocks(node.DefaultCSV - 1)
×
1730

×
1731
        // Assert there is one pending sweep.
×
1732
        h.AssertNumPendingSweeps(hn, 1)
×
1733

×
1734
        // The node should now sweep the funds, clean up by mining the sweeping
×
1735
        // tx.
×
1736
        h.MineBlocksAndAssertNumTxes(1, 1)
×
1737

×
1738
        // Mine blocks to get any second level HTLC resolved. If there are no
×
1739
        // HTLCs, this will behave like h.AssertNumPendingCloseChannels.
×
1740
        h.mineTillForceCloseResolved(hn)
×
1741
}
×
1742

1743
// CreatePayReqs is a helper method that will create a slice of payment
1744
// requests for the given node.
1745
func (h *HarnessTest) CreatePayReqs(hn *node.HarnessNode,
1746
        paymentAmt btcutil.Amount, numInvoices int,
1747
        routeHints ...*lnrpc.RouteHint) ([]string, [][]byte, []*lnrpc.Invoice) {
×
1748

×
1749
        payReqs := make([]string, numInvoices)
×
1750
        rHashes := make([][]byte, numInvoices)
×
1751
        invoices := make([]*lnrpc.Invoice, numInvoices)
×
1752
        for i := 0; i < numInvoices; i++ {
×
1753
                preimage := h.Random32Bytes()
×
1754

×
1755
                invoice := &lnrpc.Invoice{
×
1756
                        Memo:       "testing",
×
1757
                        RPreimage:  preimage,
×
1758
                        Value:      int64(paymentAmt),
×
1759
                        RouteHints: routeHints,
×
1760
                }
×
1761
                resp := hn.RPC.AddInvoice(invoice)
×
1762

×
1763
                // Set the payment address in the invoice so the caller can
×
1764
                // properly use it.
×
1765
                invoice.PaymentAddr = resp.PaymentAddr
×
1766

×
1767
                payReqs[i] = resp.PaymentRequest
×
1768
                rHashes[i] = resp.RHash
×
1769
                invoices[i] = invoice
×
1770
        }
×
1771

1772
        return payReqs, rHashes, invoices
×
1773
}
1774

1775
// BackupDB creates a backup of the current database. It will stop the node
1776
// first, copy the database files, and restart the node.
1777
func (h *HarnessTest) BackupDB(hn *node.HarnessNode) {
×
1778
        restart := h.SuspendNode(hn)
×
1779

×
1780
        err := hn.BackupDB()
×
1781
        require.NoErrorf(h, err, "%s: failed to backup db", hn.Name())
×
1782

×
1783
        err = restart()
×
1784
        require.NoErrorf(h, err, "%s: failed to restart", hn.Name())
×
1785
}
×
1786

1787
// RestartNodeAndRestoreDB restarts a given node with a callback to restore the
1788
// db.
1789
func (h *HarnessTest) RestartNodeAndRestoreDB(hn *node.HarnessNode) {
×
1790
        cb := func() error { return hn.RestoreDB() }
×
1791
        err := h.manager.restartNode(h.runCtx, hn, cb)
×
1792
        require.NoErrorf(h, err, "failed to restart node %s", hn.Name())
×
1793

×
1794
        err = h.manager.unlockNode(hn)
×
1795
        require.NoErrorf(h, err, "failed to unlock node %s", hn.Name())
×
1796

×
1797
        // Give the node some time to catch up with the chain before we
×
1798
        // continue with the tests.
×
1799
        h.WaitForBlockchainSync(hn)
×
1800
}
1801

1802
// CleanShutDown is used to quickly end a test by shutting down all non-standby
1803
// nodes and mining blocks to empty the mempool.
1804
//
1805
// NOTE: this method provides a faster exit for a test that involves force
1806
// closures as the caller doesn't need to mine all the blocks to make sure the
1807
// mempool is empty.
1808
func (h *HarnessTest) CleanShutDown() {
×
1809
        // First, shutdown all nodes to prevent new transactions being created
×
1810
        // and fed into the mempool.
×
1811
        h.shutdownAllNodes()
×
1812

×
1813
        // Now mine blocks till the mempool is empty.
×
1814
        h.cleanMempool()
×
1815
}
×
1816

1817
// QueryChannelByChanPoint tries to find a channel matching the channel point
1818
// and asserts. It returns the channel found.
1819
func (h *HarnessTest) QueryChannelByChanPoint(hn *node.HarnessNode,
1820
        chanPoint *lnrpc.ChannelPoint,
1821
        opts ...ListChannelOption) *lnrpc.Channel {
×
1822

×
1823
        channel, err := h.findChannel(hn, chanPoint, opts...)
×
1824
        require.NoError(h, err, "failed to query channel")
×
1825

×
1826
        return channel
×
1827
}
×
1828

1829
// SendPaymentAndAssertStatus sends a payment from the passed node and asserts
1830
// the desired status is reached.
1831
func (h *HarnessTest) SendPaymentAndAssertStatus(hn *node.HarnessNode,
1832
        req *routerrpc.SendPaymentRequest,
1833
        status lnrpc.Payment_PaymentStatus) *lnrpc.Payment {
×
1834

×
1835
        stream := hn.RPC.SendPayment(req)
×
1836
        return h.AssertPaymentStatusFromStream(stream, status)
×
1837
}
×
1838

1839
// SendPaymentAssertFail sends a payment from the passed node and asserts the
1840
// payment is failed with the specified failure reason .
1841
func (h *HarnessTest) SendPaymentAssertFail(hn *node.HarnessNode,
1842
        req *routerrpc.SendPaymentRequest,
1843
        reason lnrpc.PaymentFailureReason) *lnrpc.Payment {
×
1844

×
1845
        payment := h.SendPaymentAndAssertStatus(hn, req, lnrpc.Payment_FAILED)
×
1846
        require.Equal(h, reason, payment.FailureReason,
×
1847
                "payment failureReason not matched")
×
1848

×
1849
        return payment
×
1850
}
×
1851

1852
// SendPaymentAssertSettled sends a payment from the passed node and asserts the
1853
// payment is settled.
1854
func (h *HarnessTest) SendPaymentAssertSettled(hn *node.HarnessNode,
1855
        req *routerrpc.SendPaymentRequest) *lnrpc.Payment {
×
1856

×
1857
        return h.SendPaymentAndAssertStatus(hn, req, lnrpc.Payment_SUCCEEDED)
×
1858
}
×
1859

1860
// SendPaymentAssertInflight sends a payment from the passed node and asserts
1861
// the payment is inflight.
1862
func (h *HarnessTest) SendPaymentAssertInflight(hn *node.HarnessNode,
1863
        req *routerrpc.SendPaymentRequest) *lnrpc.Payment {
×
1864

×
1865
        return h.SendPaymentAndAssertStatus(hn, req, lnrpc.Payment_IN_FLIGHT)
×
1866
}
×
1867

1868
// OpenChannelRequest is used to open a channel using the method
1869
// OpenMultiChannelsAsync.
1870
type OpenChannelRequest struct {
1871
        // Local is the funding node.
1872
        Local *node.HarnessNode
1873

1874
        // Remote is the receiving node.
1875
        Remote *node.HarnessNode
1876

1877
        // Param is the open channel params.
1878
        Param OpenChannelParams
1879

1880
        // stream is the client created after calling OpenChannel RPC.
1881
        stream rpc.OpenChanClient
1882

1883
        // result is a channel used to send the channel point once the funding
1884
        // has succeeded.
1885
        result chan *lnrpc.ChannelPoint
1886
}
1887

1888
// OpenMultiChannelsAsync takes a list of OpenChannelRequest and opens them in
1889
// batch. The channel points are returned in same the order of the requests
1890
// once all of the channel open succeeded.
1891
//
1892
// NOTE: compared to open multiple channel sequentially, this method will be
1893
// faster as it doesn't need to mine 6 blocks for each channel open. However,
1894
// it does make debugging the logs more difficult as messages are intertwined.
1895
func (h *HarnessTest) OpenMultiChannelsAsync(
1896
        reqs []*OpenChannelRequest) []*lnrpc.ChannelPoint {
×
1897

×
1898
        // openChannel opens a channel based on the request.
×
1899
        openChannel := func(req *OpenChannelRequest) {
×
1900
                stream := h.OpenChannelAssertStream(
×
1901
                        req.Local, req.Remote, req.Param,
×
1902
                )
×
1903
                req.stream = stream
×
1904
        }
×
1905

1906
        // assertChannelOpen is a helper closure that asserts a channel is
1907
        // open.
1908
        assertChannelOpen := func(req *OpenChannelRequest) {
×
1909
                // Wait for the channel open event from the stream.
×
1910
                cp := h.WaitForChannelOpenEvent(req.stream)
×
1911

×
1912
                if !req.Param.Private {
×
1913
                        // Check that both alice and bob have seen the channel
×
1914
                        // from their channel watch request.
×
1915
                        h.AssertChannelInGraph(req.Local, cp)
×
1916
                        h.AssertChannelInGraph(req.Remote, cp)
×
1917
                }
×
1918

1919
                // Finally, check that the channel can be seen in their
1920
                // ListChannels.
1921
                h.AssertChannelExists(req.Local, cp)
×
1922
                h.AssertChannelExists(req.Remote, cp)
×
1923

×
1924
                req.result <- cp
×
1925
        }
1926

1927
        // Go through the requests and make the OpenChannel RPC call.
1928
        for _, r := range reqs {
×
1929
                openChannel(r)
×
1930
        }
×
1931

1932
        // Mine one block to confirm all the funding transactions.
1933
        h.MineBlocksAndAssertNumTxes(1, len(reqs))
×
1934

×
1935
        // Mine 5 more blocks so all the public channels are announced to the
×
1936
        // network.
×
1937
        h.MineBlocks(numBlocksOpenChannel - 1)
×
1938

×
1939
        // Once the blocks are mined, we fire goroutines for each of the
×
1940
        // request to watch for the channel openning.
×
1941
        for _, r := range reqs {
×
1942
                r.result = make(chan *lnrpc.ChannelPoint, 1)
×
1943
                go assertChannelOpen(r)
×
1944
        }
×
1945

1946
        // Finally, collect the results.
1947
        channelPoints := make([]*lnrpc.ChannelPoint, 0)
×
1948
        for _, r := range reqs {
×
1949
                select {
×
1950
                case cp := <-r.result:
×
1951
                        channelPoints = append(channelPoints, cp)
×
1952

1953
                case <-time.After(wait.ChannelOpenTimeout):
×
1954
                        require.Failf(h, "timeout", "wait channel point "+
×
1955
                                "timeout for channel %s=>%s", r.Local.Name(),
×
1956
                                r.Remote.Name())
×
1957
                }
1958
        }
1959

1960
        // Assert that we have the expected num of channel points.
1961
        require.Len(h, channelPoints, len(reqs),
×
1962
                "returned channel points not match")
×
1963

×
1964
        return channelPoints
×
1965
}
1966

1967
// ReceiveInvoiceUpdate waits until a message is received on the subscribe
1968
// invoice stream or the timeout is reached.
1969
func (h *HarnessTest) ReceiveInvoiceUpdate(
1970
        stream rpc.InvoiceUpdateClient) *lnrpc.Invoice {
×
1971

×
1972
        chanMsg := make(chan *lnrpc.Invoice)
×
1973
        errChan := make(chan error)
×
1974
        go func() {
×
1975
                // Consume one message. This will block until the message is
×
1976
                // received.
×
1977
                resp, err := stream.Recv()
×
1978
                if err != nil {
×
1979
                        errChan <- err
×
1980
                        return
×
1981
                }
×
1982
                chanMsg <- resp
×
1983
        }()
1984

1985
        select {
×
1986
        case <-time.After(DefaultTimeout):
×
1987
                require.Fail(h, "timeout", "timeout receiving invoice update")
×
1988

1989
        case err := <-errChan:
×
1990
                require.Failf(h, "err from stream",
×
1991
                        "received err from stream: %v", err)
×
1992

1993
        case updateMsg := <-chanMsg:
×
1994
                return updateMsg
×
1995
        }
1996

1997
        return nil
×
1998
}
1999

2000
// CalculateTxFee retrieves parent transactions and reconstructs the fee paid.
2001
func (h *HarnessTest) CalculateTxFee(tx *wire.MsgTx) btcutil.Amount {
×
2002
        var balance btcutil.Amount
×
2003
        for _, in := range tx.TxIn {
×
2004
                parentHash := in.PreviousOutPoint.Hash
×
2005
                rawTx := h.miner.GetRawTransaction(parentHash)
×
2006
                parent := rawTx.MsgTx()
×
2007
                value := parent.TxOut[in.PreviousOutPoint.Index].Value
×
2008

×
2009
                balance += btcutil.Amount(value)
×
2010
        }
×
2011

2012
        for _, out := range tx.TxOut {
×
2013
                balance -= btcutil.Amount(out.Value)
×
2014
        }
×
2015

2016
        return balance
×
2017
}
2018

2019
// CalculateTxWeight calculates the weight for a given tx.
2020
//
2021
// TODO(yy): use weight estimator to get more accurate result.
2022
func (h *HarnessTest) CalculateTxWeight(tx *wire.MsgTx) lntypes.WeightUnit {
×
2023
        utx := btcutil.NewTx(tx)
×
2024
        return lntypes.WeightUnit(blockchain.GetTransactionWeight(utx))
×
2025
}
×
2026

2027
// CalculateTxFeeRate calculates the fee rate for a given tx.
2028
func (h *HarnessTest) CalculateTxFeeRate(
2029
        tx *wire.MsgTx) chainfee.SatPerKWeight {
×
2030

×
2031
        w := h.CalculateTxWeight(tx)
×
2032
        fee := h.CalculateTxFee(tx)
×
2033

×
2034
        return chainfee.NewSatPerKWeight(fee, w)
×
2035
}
×
2036

2037
// CalculateTxesFeeRate takes a list of transactions and estimates the fee rate
2038
// used to sweep them.
2039
//
2040
// NOTE: only used in current test file.
2041
func (h *HarnessTest) CalculateTxesFeeRate(txns []*wire.MsgTx) int64 {
×
2042
        const scale = 1000
×
2043

×
2044
        var totalWeight, totalFee int64
×
2045
        for _, tx := range txns {
×
2046
                utx := btcutil.NewTx(tx)
×
2047
                totalWeight += blockchain.GetTransactionWeight(utx)
×
2048

×
2049
                fee := h.CalculateTxFee(tx)
×
2050
                totalFee += int64(fee)
×
2051
        }
×
2052
        feeRate := totalFee * scale / totalWeight
×
2053

×
2054
        return feeRate
×
2055
}
2056

2057
// AssertSweepFound looks up a sweep in a nodes list of broadcast sweeps and
2058
// asserts it's found.
2059
//
2060
// NOTE: Does not account for node's internal state.
2061
func (h *HarnessTest) AssertSweepFound(hn *node.HarnessNode,
2062
        sweep string, verbose bool, startHeight int32) {
×
2063

×
2064
        req := &walletrpc.ListSweepsRequest{
×
2065
                Verbose:     verbose,
×
2066
                StartHeight: startHeight,
×
2067
        }
×
2068

×
2069
        err := wait.NoError(func() error {
×
2070
                // List all sweeps that alice's node had broadcast.
×
2071
                sweepResp := hn.RPC.ListSweeps(req)
×
2072

×
2073
                var found bool
×
2074
                if verbose {
×
2075
                        found = findSweepInDetails(h, sweep, sweepResp)
×
2076
                } else {
×
2077
                        found = findSweepInTxids(h, sweep, sweepResp)
×
2078
                }
×
2079

2080
                if found {
×
2081
                        return nil
×
2082
                }
×
2083

2084
                return fmt.Errorf("sweep tx %v not found in resp %v", sweep,
×
2085
                        sweepResp)
×
2086
        }, wait.DefaultTimeout)
2087
        require.NoError(h, err, "%s: timeout checking sweep tx", hn.Name())
×
2088
}
2089

2090
func findSweepInTxids(ht *HarnessTest, sweepTxid string,
2091
        sweepResp *walletrpc.ListSweepsResponse) bool {
×
2092

×
2093
        sweepTxIDs := sweepResp.GetTransactionIds()
×
2094
        require.NotNil(ht, sweepTxIDs, "expected transaction ids")
×
2095
        require.Nil(ht, sweepResp.GetTransactionDetails())
×
2096

×
2097
        // Check that the sweep tx we have just produced is present.
×
2098
        for _, tx := range sweepTxIDs.TransactionIds {
×
2099
                if tx == sweepTxid {
×
2100
                        return true
×
2101
                }
×
2102
        }
2103

2104
        return false
×
2105
}
2106

2107
func findSweepInDetails(ht *HarnessTest, sweepTxid string,
2108
        sweepResp *walletrpc.ListSweepsResponse) bool {
×
2109

×
2110
        sweepDetails := sweepResp.GetTransactionDetails()
×
2111
        require.NotNil(ht, sweepDetails, "expected transaction details")
×
2112
        require.Nil(ht, sweepResp.GetTransactionIds())
×
2113

×
2114
        for _, tx := range sweepDetails.Transactions {
×
2115
                if tx.TxHash == sweepTxid {
×
2116
                        return true
×
2117
                }
×
2118
        }
2119

2120
        return false
×
2121
}
2122

2123
// QueryRoutesAndRetry attempts to keep querying a route until timeout is
2124
// reached.
2125
//
2126
// NOTE: when a channel is opened, we may need to query multiple times to get
2127
// it in our QueryRoutes RPC. This happens even after we check the channel is
2128
// heard by the node using ht.AssertChannelOpen. Deep down, this is because our
2129
// GraphTopologySubscription and QueryRoutes give different results regarding a
2130
// specific channel, with the formal reporting it being open while the latter
2131
// not, resulting GraphTopologySubscription acting "faster" than QueryRoutes.
2132
// TODO(yy): make sure related subsystems share the same view on a given
2133
// channel.
2134
func (h *HarnessTest) QueryRoutesAndRetry(hn *node.HarnessNode,
2135
        req *lnrpc.QueryRoutesRequest) *lnrpc.QueryRoutesResponse {
×
2136

×
2137
        var routes *lnrpc.QueryRoutesResponse
×
2138
        err := wait.NoError(func() error {
×
2139
                ctxt, cancel := context.WithCancel(h.runCtx)
×
2140
                defer cancel()
×
2141

×
2142
                resp, err := hn.RPC.LN.QueryRoutes(ctxt, req)
×
2143
                if err != nil {
×
2144
                        return fmt.Errorf("%s: failed to query route: %w",
×
2145
                                hn.Name(), err)
×
2146
                }
×
2147

2148
                routes = resp
×
2149

×
2150
                return nil
×
2151
        }, DefaultTimeout)
2152

2153
        require.NoError(h, err, "timeout querying routes")
×
2154

×
2155
        return routes
×
2156
}
2157

2158
// ReceiveHtlcInterceptor waits until a message is received on the htlc
2159
// interceptor stream or the timeout is reached.
2160
func (h *HarnessTest) ReceiveHtlcInterceptor(
2161
        stream rpc.InterceptorClient) *routerrpc.ForwardHtlcInterceptRequest {
×
2162

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

2176
        select {
×
2177
        case <-time.After(DefaultTimeout):
×
2178
                require.Fail(h, "timeout", "timeout intercepting htlc")
×
2179

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

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

2188
        return nil
×
2189
}
2190

2191
// ReceiveInvoiceHtlcModification waits until a message is received on the
2192
// invoice HTLC modifier stream or the timeout is reached.
2193
func (h *HarnessTest) ReceiveInvoiceHtlcModification(
2194
        stream rpc.InvoiceHtlcModifierClient) *invoicesrpc.HtlcModifyRequest {
×
2195

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

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

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

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

2222
        return nil
×
2223
}
2224

2225
// ReceiveChannelEvent waits until a message is received from the
2226
// ChannelEventsClient stream or the timeout is reached.
2227
func (h *HarnessTest) ReceiveChannelEvent(
2228
        stream rpc.ChannelEventsClient) *lnrpc.ChannelEventUpdate {
×
2229

×
2230
        chanMsg := make(chan *lnrpc.ChannelEventUpdate)
×
2231
        errChan := make(chan error)
×
2232
        go func() {
×
2233
                // Consume one message. This will block until the message is
×
2234
                // received.
×
2235
                resp, err := stream.Recv()
×
2236
                if err != nil {
×
2237
                        errChan <- err
×
2238
                        return
×
2239
                }
×
2240
                chanMsg <- resp
×
2241
        }()
2242

2243
        select {
×
2244
        case <-time.After(DefaultTimeout):
×
2245
                require.Fail(h, "timeout", "timeout intercepting htlc")
×
2246

2247
        case err := <-errChan:
×
2248
                require.Failf(h, "err from stream",
×
2249
                        "received err from stream: %v", err)
×
2250

2251
        case updateMsg := <-chanMsg:
×
2252
                return updateMsg
×
2253
        }
2254

2255
        return nil
×
2256
}
2257

2258
// GetOutputIndex returns the output index of the given address in the given
2259
// transaction.
2260
func (h *HarnessTest) GetOutputIndex(txid chainhash.Hash, addr string) int {
×
2261
        // We'll then extract the raw transaction from the mempool in order to
×
2262
        // determine the index of the p2tr output.
×
2263
        tx := h.miner.GetRawTransaction(txid)
×
2264

×
2265
        p2trOutputIndex := -1
×
2266
        for i, txOut := range tx.MsgTx().TxOut {
×
2267
                _, addrs, _, err := txscript.ExtractPkScriptAddrs(
×
2268
                        txOut.PkScript, h.miner.ActiveNet,
×
2269
                )
×
2270
                require.NoError(h, err)
×
2271

×
2272
                if addrs[0].String() == addr {
×
2273
                        p2trOutputIndex = i
×
2274
                }
×
2275
        }
2276
        require.Greater(h, p2trOutputIndex, -1)
×
2277

×
2278
        return p2trOutputIndex
×
2279
}
2280

2281
// SendCoins sends a coin from node A to node B with the given amount, returns
2282
// the sending tx.
2283
func (h *HarnessTest) SendCoins(a, b *node.HarnessNode,
2284
        amt btcutil.Amount) *wire.MsgTx {
×
2285

×
2286
        // Create an address for Bob receive the coins.
×
2287
        req := &lnrpc.NewAddressRequest{
×
2288
                Type: lnrpc.AddressType_TAPROOT_PUBKEY,
×
2289
        }
×
2290
        resp := b.RPC.NewAddress(req)
×
2291

×
2292
        // Send the coins from Alice to Bob. We should expect a tx to be
×
2293
        // broadcast and seen in the mempool.
×
2294
        sendReq := &lnrpc.SendCoinsRequest{
×
2295
                Addr:       resp.Address,
×
2296
                Amount:     int64(amt),
×
2297
                TargetConf: 6,
×
2298
        }
×
2299
        a.RPC.SendCoins(sendReq)
×
2300
        tx := h.GetNumTxsFromMempool(1)[0]
×
2301

×
2302
        return tx
×
2303
}
×
2304

2305
// SendCoins sends all coins from node A to node B, returns the sending tx.
2306
func (h *HarnessTest) SendAllCoins(a, b *node.HarnessNode) *wire.MsgTx {
×
2307
        // Create an address for Bob receive the coins.
×
2308
        req := &lnrpc.NewAddressRequest{
×
2309
                Type: lnrpc.AddressType_TAPROOT_PUBKEY,
×
2310
        }
×
2311
        resp := b.RPC.NewAddress(req)
×
2312

×
2313
        // Send the coins from Alice to Bob. We should expect a tx to be
×
2314
        // broadcast and seen in the mempool.
×
2315
        sendReq := &lnrpc.SendCoinsRequest{
×
2316
                Addr:             resp.Address,
×
2317
                TargetConf:       6,
×
2318
                SendAll:          true,
×
2319
                SpendUnconfirmed: true,
×
2320
        }
×
2321
        a.RPC.SendCoins(sendReq)
×
2322
        tx := h.GetNumTxsFromMempool(1)[0]
×
2323

×
2324
        return tx
×
2325
}
×
2326

2327
// CreateSimpleNetwork creates the number of nodes specified by the number of
2328
// configs and makes a topology of `node1 -> node2 -> node3...`. Each node is
2329
// created using the specified config, the neighbors are connected, and the
2330
// channels are opened. Each node will be funded with a single UTXO of 1 BTC
2331
// except the last one.
2332
//
2333
// For instance, to create a network with 2 nodes that share the same node
2334
// config,
2335
//
2336
//        cfg := []string{"--protocol.anchors"}
2337
//        cfgs := [][]string{cfg, cfg}
2338
//        params := OpenChannelParams{...}
2339
//        chanPoints, nodes := ht.CreateSimpleNetwork(cfgs, params)
2340
//
2341
// This will create two nodes and open an anchor channel between them.
2342
func (h *HarnessTest) CreateSimpleNetwork(nodeCfgs [][]string,
2343
        p OpenChannelParams) ([]*lnrpc.ChannelPoint, []*node.HarnessNode) {
×
2344

×
2345
        // Create new nodes.
×
2346
        nodes := h.createNodes(nodeCfgs)
×
2347

×
2348
        var resp []*lnrpc.ChannelPoint
×
2349

×
2350
        // Open zero-conf channels if specified.
×
2351
        if p.ZeroConf {
×
2352
                resp = h.openZeroConfChannelsForNodes(nodes, p)
×
2353
        } else {
×
2354
                // Open channels between the nodes.
×
2355
                resp = h.openChannelsForNodes(nodes, p)
×
2356
        }
×
2357

2358
        return resp, nodes
×
2359
}
2360

2361
// acceptChannel is used to accept a single channel that comes across. This
2362
// should be run in a goroutine and is used to test nodes with the zero-conf
2363
// feature bit.
2364
func acceptChannel(t *testing.T, zeroConf bool, stream rpc.AcceptorClient) {
×
2365
        req, err := stream.Recv()
×
2366
        require.NoError(t, err)
×
2367

×
2368
        resp := &lnrpc.ChannelAcceptResponse{
×
2369
                Accept:        true,
×
2370
                PendingChanId: req.PendingChanId,
×
2371
                ZeroConf:      zeroConf,
×
2372
        }
×
2373
        err = stream.Send(resp)
×
2374
        require.NoError(t, err)
×
2375
}
×
2376

2377
// nodeNames defines a slice of human-reable names for the nodes created in the
2378
// `createNodes` method. 8 nodes are defined here as by default we can only
2379
// create this many nodes in one test.
2380
var nodeNames = []string{
2381
        "Alice", "Bob", "Carol", "Dave", "Eve", "Frank", "Grace", "Heidi",
2382
}
2383

2384
// createNodes creates the number of nodes specified by the number of configs.
2385
// Each node is created using the specified config, the neighbors are
2386
// connected.
2387
func (h *HarnessTest) createNodes(nodeCfgs [][]string) []*node.HarnessNode {
×
2388
        // Get the number of nodes.
×
2389
        numNodes := len(nodeCfgs)
×
2390

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

×
2394
        // Make a slice of nodes.
×
2395
        nodes := make([]*node.HarnessNode, numNodes)
×
2396

×
2397
        // Create new nodes.
×
2398
        for i, nodeCfg := range nodeCfgs {
×
2399
                nodeName := nodeNames[i]
×
2400
                n := h.NewNode(nodeName, nodeCfg)
×
2401
                nodes[i] = n
×
2402
        }
×
2403

2404
        // Connect the nodes in a chain.
2405
        for i := 1; i < len(nodes); i++ {
×
2406
                nodeA := nodes[i-1]
×
2407
                nodeB := nodes[i]
×
2408
                h.EnsureConnected(nodeA, nodeB)
×
2409
        }
×
2410

2411
        // Fund all the nodes expect the last one.
2412
        for i := 0; i < len(nodes)-1; i++ {
×
2413
                node := nodes[i]
×
2414
                h.FundCoinsUnconfirmed(btcutil.SatoshiPerBitcoin, node)
×
2415
        }
×
2416

2417
        // Mine 1 block to get the above coins confirmed.
2418
        h.MineBlocksAndAssertNumTxes(1, numNodes-1)
×
2419

×
2420
        return nodes
×
2421
}
2422

2423
// openChannelsForNodes takes a list of nodes and makes a topology of `node1 ->
2424
// node2 -> node3...`.
2425
func (h *HarnessTest) openChannelsForNodes(nodes []*node.HarnessNode,
2426
        p OpenChannelParams) []*lnrpc.ChannelPoint {
×
2427

×
2428
        // Sanity check the params.
×
2429
        require.Greater(h, len(nodes), 1, "need at least 2 nodes")
×
2430

×
2431
        // attachFundingShim is a helper closure that optionally attaches a
×
2432
        // funding shim to the open channel params and returns it.
×
2433
        attachFundingShim := func(
×
2434
                nodeA, nodeB *node.HarnessNode) OpenChannelParams {
×
2435

×
2436
                // If this channel is not a script enforced lease channel,
×
2437
                // we'll do nothing and return the params.
×
2438
                leasedType := lnrpc.CommitmentType_SCRIPT_ENFORCED_LEASE
×
2439
                if p.CommitmentType != leasedType {
×
2440
                        return p
×
2441
                }
×
2442

2443
                // Otherwise derive the funding shim, attach it to the original
2444
                // open channel params and return it.
2445
                minerHeight := h.CurrentHeight()
×
2446
                thawHeight := minerHeight + thawHeightDelta
×
2447
                fundingShim, _ := h.DeriveFundingShim(
×
2448
                        nodeA, nodeB, p.Amt, thawHeight, true, leasedType,
×
2449
                )
×
2450

×
2451
                p.FundingShim = fundingShim
×
2452

×
2453
                return p
×
2454
        }
2455

2456
        // Open channels in batch to save blocks mined.
2457
        reqs := make([]*OpenChannelRequest, 0, len(nodes)-1)
×
2458
        for i := 0; i < len(nodes)-1; i++ {
×
2459
                nodeA := nodes[i]
×
2460
                nodeB := nodes[i+1]
×
2461

×
2462
                // Optionally attach a funding shim to the open channel params.
×
2463
                p = attachFundingShim(nodeA, nodeB)
×
2464

×
2465
                req := &OpenChannelRequest{
×
2466
                        Local:  nodeA,
×
2467
                        Remote: nodeB,
×
2468
                        Param:  p,
×
2469
                }
×
2470
                reqs = append(reqs, req)
×
2471
        }
×
2472
        resp := h.OpenMultiChannelsAsync(reqs)
×
2473

×
2474
        // If the channels are private, make sure the channel participants know
×
2475
        // the relevant channels.
×
2476
        if p.Private {
×
2477
                for i, chanPoint := range resp {
×
2478
                        // Get the channel participants - for n channels we
×
2479
                        // would have n+1 nodes.
×
2480
                        nodeA, nodeB := nodes[i], nodes[i+1]
×
2481
                        h.AssertChannelInGraph(nodeA, chanPoint)
×
2482
                        h.AssertChannelInGraph(nodeB, chanPoint)
×
2483
                }
×
2484
        } else {
×
2485
                // Make sure the all nodes know all the channels if they are
×
2486
                // public.
×
2487
                for _, node := range nodes {
×
2488
                        for _, chanPoint := range resp {
×
2489
                                h.AssertChannelInGraph(node, chanPoint)
×
2490
                        }
×
2491

2492
                        // Make sure every node has updated its cached graph
2493
                        // about the edges as indicated in `DescribeGraph`.
2494
                        h.AssertNumEdges(node, len(resp), false)
×
2495
                }
2496
        }
2497

2498
        return resp
×
2499
}
2500

2501
// openZeroConfChannelsForNodes takes a list of nodes and makes a topology of
2502
// `node1 -> node2 -> node3...` with zero-conf channels.
2503
func (h *HarnessTest) openZeroConfChannelsForNodes(nodes []*node.HarnessNode,
2504
        p OpenChannelParams) []*lnrpc.ChannelPoint {
×
2505

×
2506
        // Sanity check the params.
×
2507
        require.True(h, p.ZeroConf, "zero-conf channels must be enabled")
×
2508
        require.Greater(h, len(nodes), 1, "need at least 2 nodes")
×
2509

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

×
2513
        // Create the channel acceptors.
×
2514
        for _, node := range nodes[1:] {
×
2515
                acceptor, cancel := node.RPC.ChannelAcceptor()
×
2516
                go acceptChannel(h.T, true, acceptor)
×
2517

×
2518
                cancels = append(cancels, cancel)
×
2519
        }
×
2520

2521
        // Open channels between the nodes.
2522
        resp := h.openChannelsForNodes(nodes, p)
×
2523

×
2524
        for _, cancel := range cancels {
×
2525
                cancel()
×
2526
        }
×
2527

2528
        return resp
×
2529
}
2530

2531
// DeriveFundingShim creates a channel funding shim by deriving the necessary
2532
// keys on both sides.
2533
func (h *HarnessTest) DeriveFundingShim(alice, bob *node.HarnessNode,
2534
        chanSize btcutil.Amount, thawHeight uint32, publish bool,
2535
        commitType lnrpc.CommitmentType) (*lnrpc.FundingShim,
2536
        *lnrpc.ChannelPoint) {
×
2537

×
2538
        keyLoc := &signrpc.KeyLocator{KeyFamily: 9999}
×
2539
        carolFundingKey := alice.RPC.DeriveKey(keyLoc)
×
2540
        daveFundingKey := bob.RPC.DeriveKey(keyLoc)
×
2541

×
2542
        // Now that we have the multi-sig keys for each party, we can manually
×
2543
        // construct the funding transaction. We'll instruct the backend to
×
2544
        // immediately create and broadcast a transaction paying out an exact
×
2545
        // amount. Normally this would reside in the mempool, but we just
×
2546
        // confirm it now for simplicity.
×
2547
        var (
×
2548
                fundingOutput *wire.TxOut
×
2549
                musig2        bool
×
2550
                err           error
×
2551
        )
×
2552

×
2553
        if commitType == lnrpc.CommitmentType_SIMPLE_TAPROOT ||
×
2554
                commitType == lnrpc.CommitmentType_SIMPLE_TAPROOT_OVERLAY {
×
2555

×
2556
                var carolKey, daveKey *btcec.PublicKey
×
2557
                carolKey, err = btcec.ParsePubKey(carolFundingKey.RawKeyBytes)
×
2558
                require.NoError(h, err)
×
2559
                daveKey, err = btcec.ParsePubKey(daveFundingKey.RawKeyBytes)
×
2560
                require.NoError(h, err)
×
2561

×
2562
                _, fundingOutput, err = input.GenTaprootFundingScript(
×
2563
                        carolKey, daveKey, int64(chanSize),
×
2564
                        fn.None[chainhash.Hash](),
×
2565
                )
×
2566
                require.NoError(h, err)
×
2567

×
2568
                musig2 = true
×
2569
        } else {
×
2570
                _, fundingOutput, err = input.GenFundingPkScript(
×
2571
                        carolFundingKey.RawKeyBytes, daveFundingKey.RawKeyBytes,
×
2572
                        int64(chanSize),
×
2573
                )
×
2574
                require.NoError(h, err)
×
2575
        }
×
2576

2577
        var txid *chainhash.Hash
×
2578
        targetOutputs := []*wire.TxOut{fundingOutput}
×
2579
        if publish {
×
2580
                txid = h.SendOutputsWithoutChange(targetOutputs, 5)
×
2581
        } else {
×
2582
                tx := h.CreateTransaction(targetOutputs, 5)
×
2583

×
2584
                txHash := tx.TxHash()
×
2585
                txid = &txHash
×
2586
        }
×
2587

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

×
2593
        // Now that we have the pending channel ID, Dave (our responder) will
×
2594
        // register the intent to receive a new channel funding workflow using
×
2595
        // the pending channel ID.
×
2596
        chanPoint := &lnrpc.ChannelPoint{
×
2597
                FundingTxid: &lnrpc.ChannelPoint_FundingTxidBytes{
×
2598
                        FundingTxidBytes: txid[:],
×
2599
                },
×
2600
        }
×
2601
        chanPointShim := &lnrpc.ChanPointShim{
×
2602
                Amt:       int64(chanSize),
×
2603
                ChanPoint: chanPoint,
×
2604
                LocalKey: &lnrpc.KeyDescriptor{
×
2605
                        RawKeyBytes: daveFundingKey.RawKeyBytes,
×
2606
                        KeyLoc: &lnrpc.KeyLocator{
×
2607
                                KeyFamily: daveFundingKey.KeyLoc.KeyFamily,
×
2608
                                KeyIndex:  daveFundingKey.KeyLoc.KeyIndex,
×
2609
                        },
×
2610
                },
×
2611
                RemoteKey:     carolFundingKey.RawKeyBytes,
×
2612
                PendingChanId: pendingChanID,
×
2613
                ThawHeight:    thawHeight,
×
2614
                Musig2:        musig2,
×
2615
        }
×
2616
        fundingShim := &lnrpc.FundingShim{
×
2617
                Shim: &lnrpc.FundingShim_ChanPointShim{
×
2618
                        ChanPointShim: chanPointShim,
×
2619
                },
×
2620
        }
×
2621
        bob.RPC.FundingStateStep(&lnrpc.FundingTransitionMsg{
×
2622
                Trigger: &lnrpc.FundingTransitionMsg_ShimRegister{
×
2623
                        ShimRegister: fundingShim,
×
2624
                },
×
2625
        })
×
2626

×
2627
        // If we attempt to register the same shim (has the same pending chan
×
2628
        // ID), then we should get an error.
×
2629
        bob.RPC.FundingStateStepAssertErr(&lnrpc.FundingTransitionMsg{
×
2630
                Trigger: &lnrpc.FundingTransitionMsg_ShimRegister{
×
2631
                        ShimRegister: fundingShim,
×
2632
                },
×
2633
        })
×
2634

×
2635
        // We'll take the chan point shim we just registered for Dave (the
×
2636
        // responder), and swap the local/remote keys before we feed it in as
×
2637
        // Carol's funding shim as the initiator.
×
2638
        fundingShim.GetChanPointShim().LocalKey = &lnrpc.KeyDescriptor{
×
2639
                RawKeyBytes: carolFundingKey.RawKeyBytes,
×
2640
                KeyLoc: &lnrpc.KeyLocator{
×
2641
                        KeyFamily: carolFundingKey.KeyLoc.KeyFamily,
×
2642
                        KeyIndex:  carolFundingKey.KeyLoc.KeyIndex,
×
2643
                },
×
2644
        }
×
2645
        fundingShim.GetChanPointShim().RemoteKey = daveFundingKey.RawKeyBytes
×
2646

×
2647
        return fundingShim, chanPoint
×
2648
}
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