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

lightningnetwork / lnd / 16176630036

09 Jul 2025 05:55PM UTC coverage: 67.416% (+9.8%) from 57.611%
16176630036

Pull #10061

github

web-flow
Merge 52d963bae into 0e830da9d
Pull Request #10061: itest+lntest: fix flake in `testListSweeps`

0 of 44 new or added lines in 3 files covered. (0.0%)

26 existing lines in 6 files now uncovered.

135262 of 200639 relevant lines covered (67.42%)

21810.17 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.
×
150
        ctxt, cancel := context.WithCancel(context.Background())
×
151

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

277
        h.shutdownAllNodes()
×
278

×
279
        close(h.lndErrorChan)
×
280

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

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

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

292
// RunTestCase executes a harness test case. Any errors or panics will be
293
// represented as fatal.
294
func (h *HarnessTest) RunTestCase(testCase *TestCase) {
×
295
        defer func() {
×
296
                if 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() {
×
438
        var err error
×
439
        for _, node := range h.manager.activeNodes {
×
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)
×
449
        }
450

451
        require.NoError(h, err, "failed to shutdown all nodes")
×
452
}
453

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

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

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

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

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

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

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

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

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

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

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

×
514
        return node
×
515
}
×
516

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

×
523
        node := h.NewNode(name, extraArgs)
×
524

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

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

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

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

×
545
        return node
×
546
}
547

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

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

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

×
564
        return func() error {
×
565
                h.manager.registerNode(node)
×
566

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

×
572
                return nil
×
573
        }
574
}
575

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

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

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

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

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

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

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

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

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

×
618
        hn.SetExtraArgs(extraArgs)
×
619
        h.RestartNode(hn)
×
620
}
×
621

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

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

×
637
        return h.newNodeWithSeed(name, extraArgs, req, statelessInit)
×
638
}
×
639

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

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

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

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

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

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

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

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

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

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

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

×
713
        return n
×
714
}
×
715

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

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

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

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

×
738
        return node
×
739
}
×
740

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

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

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

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

×
762
        return h.newNodeWithSeed(name, extraArgs, req, statelessInit)
×
763
}
×
764

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

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

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

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

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

×
788
        return hn
×
789
}
×
790

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

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

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

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

×
814
        h.feeService.SetFeeRate(fee, conf)
×
815
}
×
816

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

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

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

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

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

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

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

873
        return nil
×
874
}
875

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

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

×
884
        return *txid
×
885
}
×
886

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

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

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

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

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

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

915
        // MinHtlc is the htlc_minimum_msat value set when opening the channel.
916
        MinHtlc lnwire.MilliSatoshi
917

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

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

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

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

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

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

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

948
        // BaseFee is the channel base fee applied during the channel
949
        // announcement phase.
950
        BaseFee uint64
951

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
1066
        return update.ChanPending, respStream
×
1067
}
×
1068

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

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

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

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

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

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

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

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

1127
        return cp
×
1128
}
1129

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

×
1140
        chanOpenUpdate := h.OpenChannelAssertStream(alice, bob, p)
×
1141

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

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

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

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

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

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

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

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

×
1178
        return fundingChanPoint
×
1179
}
×
1180

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

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

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

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

×
1200
        return fundingChanPoint
×
1201
}
×
1202

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
1338
                if !pendingClose.ClosePending.LocalCloseTx &&
×
1339
                        closeOpts.localTxOnly {
×
1340

×
1341
                        continue
×
1342
                }
1343

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

×
1348
                        continue
×
1349
                }
1350

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

×
1357
                break
×
1358
        }
1359

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

1365
        return stream, event
×
1366
}
1367

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

×
1380
        stream, _ := h.CloseChannelAssertPending(hn, cp, false)
×
1381

×
1382
        return h.AssertStreamChannelCoopClosed(hn, cp, false, stream)
×
1383
}
×
1384

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

×
1399
        stream, _ := h.CloseChannelAssertPending(hn, cp, true)
×
1400

×
1401
        closingTxid := h.AssertStreamChannelForceClosed(hn, cp, false, stream)
×
1402

×
1403
        // Cleanup the force close.
×
1404
        h.CleanupForceClose(hn)
×
1405

×
1406
        return closingTxid
×
1407
}
×
1408

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

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

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

×
1424
        return err
×
1425
}
×
1426

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

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

×
1441
        initialBalance := target.RPC.WalletBalance()
×
1442

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

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

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

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

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

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

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

×
1486
        return msgTx
×
1487
}
1488

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

×
1495
        return h.fundCoins(amt, hn, lnrpc.AddressType_WITNESS_PUBKEY_HASH, true)
×
1496
}
×
1497

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

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

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

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

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

×
1524
        return h.fundCoins(amt, target, lnrpc.AddressType_TAPROOT_PUBKEY, true)
×
1525
}
×
1526

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

×
1535
        const fundAmount = 1 * btcutil.SatoshiPerBitcoin
×
1536

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

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

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

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

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

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

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

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

×
1586
                // Signal sent succeeded.
×
1587
                results <- stream
×
1588
        }
×
1589

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1709
        return respStream, upd.PsbtFund.Psbt
×
1710
}
1711

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

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

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

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

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

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

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

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

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

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

1770
        return payReqs, rHashes, invoices
×
1771
}
1772

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

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

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

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

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

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

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

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

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

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

×
1824
        return channel
×
1825
}
×
1826

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

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

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

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

×
1847
        return payment
×
1848
}
×
1849

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

×
1855
        return h.SendPaymentAndAssertStatus(hn, req, lnrpc.Payment_SUCCEEDED)
×
1856
}
×
1857

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

×
1863
        return h.SendPaymentAndAssertStatus(hn, req, lnrpc.Payment_IN_FLIGHT)
×
1864
}
×
1865

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

1872
        // Remote is the receiving node.
1873
        Remote *node.HarnessNode
1874

1875
        // Param is the open channel params.
1876
        Param OpenChannelParams
1877

1878
        // stream is the client created after calling OpenChannel RPC.
1879
        stream rpc.OpenChanClient
1880

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

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

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

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

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

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

×
1922
                req.result <- cp
×
1923
        }
1924

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

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

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

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

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

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

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

×
1962
        return channelPoints
×
1963
}
1964

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

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

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

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

1991
        case updateMsg := <-chanMsg:
×
1992
                return updateMsg
×
1993
        }
1994

1995
        return nil
×
1996
}
1997

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

×
2007
                balance += btcutil.Amount(value)
×
2008
        }
×
2009

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

2014
        return balance
×
2015
}
2016

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

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

×
2029
        w := h.CalculateTxWeight(tx)
×
2030
        fee := h.CalculateTxFee(tx)
×
2031

×
2032
        return chainfee.NewSatPerKWeight(fee, w)
×
2033
}
×
2034

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

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

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

×
2052
        return feeRate
×
2053
}
2054

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

×
NEW
2062
        req := &walletrpc.ListSweepsRequest{
×
NEW
2063
                Verbose:     verbose,
×
NEW
2064
                StartHeight: startHeight,
×
NEW
2065
        }
×
NEW
2066

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

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

2078
                if found {
×
2079
                        return nil
×
2080
                }
×
2081

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

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

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

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

2102
        return false
×
2103
}
2104

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

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

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

2118
        return false
×
2119
}
2120

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

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

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

2146
                routes = resp
×
2147

×
2148
                return nil
×
2149
        }, DefaultTimeout)
2150

2151
        require.NoError(h, err, "timeout querying routes")
×
2152

×
2153
        return routes
×
2154
}
2155

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

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

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

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

2182
        case updateMsg := <-chanMsg:
×
2183
                return updateMsg
×
2184
        }
2185

2186
        return nil
×
2187
}
2188

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

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

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

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

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

2220
        return nil
×
2221
}
2222

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

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

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

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

2249
        case updateMsg := <-chanMsg:
×
2250
                return updateMsg
×
2251
        }
2252

2253
        return nil
×
2254
}
2255

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

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

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

×
2276
        return p2trOutputIndex
×
2277
}
2278

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

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

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

×
2300
        return tx
×
2301
}
×
2302

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

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

×
2322
        return tx
×
2323
}
×
2324

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

×
2343
        // Create new nodes.
×
2344
        nodes := h.createNodes(nodeCfgs)
×
2345

×
2346
        var resp []*lnrpc.ChannelPoint
×
2347

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

2356
        return resp, nodes
×
2357
}
2358

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

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

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

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

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

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

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

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

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

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

×
2418
        return nodes
×
2419
}
2420

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

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

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

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

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

×
2449
                p.FundingShim = fundingShim
×
2450

×
2451
                return p
×
2452
        }
2453

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

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

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

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

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

2496
        return resp
×
2497
}
2498

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

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

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

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

×
2516
                cancels = append(cancels, cancel)
×
2517
        }
×
2518

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

×
2522
        for _, cancel := range cancels {
×
2523
                cancel()
×
2524
        }
×
2525

2526
        return resp
×
2527
}
2528

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

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

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

×
2551
        if commitType == lnrpc.CommitmentType_SIMPLE_TAPROOT ||
×
2552
                commitType == lnrpc.CommitmentType_SIMPLE_TAPROOT_OVERLAY {
×
2553

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

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

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

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

×
2582
                txHash := tx.TxHash()
×
2583
                txid = &txHash
×
2584
        }
×
2585

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

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

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

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

×
2645
        return fundingShim, chanPoint
×
2646
}
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