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

lightningnetwork / lnd / 12430760174

20 Dec 2024 11:38AM UTC coverage: 58.684% (-0.03%) from 58.716%
12430760174

Pull #9368

github

yyforyongyu
itest: fix flake in `testCoopCloseWithExternalDeliveryImpl`

The response from `ClosedChannels` may not be up-to-date, so we wrap it
inside a wait closure.
Pull Request #9368: Fix itest re new behaviors introduced by `blockbeat`

2 of 240 new or added lines in 10 files covered. (0.83%)

228 existing lines in 43 files now uncovered.

135182 of 230357 relevant lines covered (58.68%)

19128.77 hits per line

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

0.0
/lntest/harness.go
1
package lntest
2

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
141
        t.Helper()
×
142

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

271
        h.shutdownAllNodes()
×
272

×
273
        close(h.lndErrorChan)
×
274

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

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

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

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

297
        testCase.TestFunc(h)
×
298
}
299

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

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

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

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

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

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

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

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

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

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

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

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

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

365
        return st
×
366
}
367

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
NEW
492
        return node
×
NEW
493
}
×
494

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

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

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

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

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

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

×
523
        return node
×
524
}
525

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

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

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

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

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

×
550
                return nil
×
551
        }
552
}
553

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
691
        return n
×
692
}
×
693

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

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

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

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

×
716
        return node
×
717
}
×
718

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

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

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

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

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

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

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

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

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

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

×
766
        return hn
×
767
}
×
768

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

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

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

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

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

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

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

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

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

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

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

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

851
        return nil
×
852
}
853

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

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

×
862
        return *txid
×
863
}
×
864

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1105
        return cp
×
1106
}
1107

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

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

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

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

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

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

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

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

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

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

×
1156
        return fundingChanPoint
×
1157
}
×
1158

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

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

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

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

×
1178
        return fundingChanPoint
×
1179
}
×
1180

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

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

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

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

1200
// CloseChannelAssertPending attempts to close the channel indicated by the
1201
// passed channel point, initiated by the passed node. Once the CloseChannel
1202
// rpc is called, it will consume one event and assert it's a close pending
1203
// event. In addition, it will check that the closing tx can be found in the
1204
// mempool.
1205
func (h *HarnessTest) CloseChannelAssertPending(hn *node.HarnessNode,
1206
        cp *lnrpc.ChannelPoint,
1207
        force bool) (rpc.CloseChanClient, chainhash.Hash) {
×
1208

×
1209
        // Calls the rpc to close the channel.
×
1210
        closeReq := &lnrpc.CloseChannelRequest{
×
1211
                ChannelPoint: cp,
×
1212
                Force:        force,
×
1213
                NoWait:       true,
×
1214
        }
×
1215

×
1216
        // For coop close, we use a default confg target of 6.
×
1217
        if !force {
×
1218
                closeReq.TargetConf = 6
×
1219
        }
×
1220

1221
        var (
×
1222
                stream rpc.CloseChanClient
×
1223
                event  *lnrpc.CloseStatusUpdate
×
1224
                err    error
×
1225
        )
×
1226

×
1227
        // Consume the "channel close" update in order to wait for the closing
×
1228
        // transaction to be broadcast, then wait for the closing tx to be seen
×
1229
        // within the network.
×
1230
        stream = hn.RPC.CloseChannel(closeReq)
×
1231
        _, err = h.ReceiveCloseChannelUpdate(stream)
×
1232
        require.NoError(h, err, "close channel update got error: %v", err)
×
1233

×
1234
        event, err = h.ReceiveCloseChannelUpdate(stream)
×
1235
        if err != nil {
×
1236
                h.Logf("Test: %s, close channel got error: %v",
×
1237
                        h.manager.currentTestCase, err)
×
1238
        }
×
1239
        require.NoError(h, err, "retry closing channel failed")
×
1240

×
1241
        pendingClose, ok := event.Update.(*lnrpc.CloseStatusUpdate_ClosePending)
×
1242
        require.Truef(h, ok, "expected channel close update, instead got %v",
×
1243
                pendingClose)
×
1244

×
1245
        closeTxid, err := chainhash.NewHash(pendingClose.ClosePending.Txid)
×
1246
        require.NoErrorf(h, err, "unable to decode closeTxid: %v",
×
1247
                pendingClose.ClosePending.Txid)
×
1248

×
1249
        // Assert the closing tx is in the mempool.
×
1250
        h.miner.AssertTxInMempool(*closeTxid)
×
1251

×
1252
        return stream, *closeTxid
×
1253
}
1254

1255
// CloseChannel attempts to coop close a non-anchored channel identified by the
1256
// passed channel point owned by the passed harness node. The following items
1257
// are asserted,
1258
//  1. a close pending event is sent from the close channel client.
1259
//  2. the closing tx is found in the mempool.
1260
//  3. the node reports the channel being waiting to close.
1261
//  4. a block is mined and the closing tx should be found in it.
1262
//  5. the node reports zero waiting close channels.
1263
//  6. the node receives a topology update regarding the channel close.
1264
func (h *HarnessTest) CloseChannel(hn *node.HarnessNode,
1265
        cp *lnrpc.ChannelPoint) chainhash.Hash {
×
1266

×
1267
        stream, _ := h.CloseChannelAssertPending(hn, cp, false)
×
1268

×
1269
        return h.AssertStreamChannelCoopClosed(hn, cp, false, stream)
×
1270
}
×
1271

1272
// ForceCloseChannel attempts to force close a non-anchored channel identified
1273
// by the passed channel point owned by the passed harness node. The following
1274
// items are asserted,
1275
//  1. a close pending event is sent from the close channel client.
1276
//  2. the closing tx is found in the mempool.
1277
//  3. the node reports the channel being waiting to close.
1278
//  4. a block is mined and the closing tx should be found in it.
1279
//  5. the node reports zero waiting close channels.
1280
//  6. the node receives a topology update regarding the channel close.
1281
//  7. mine DefaultCSV-1 blocks.
1282
//  8. the node reports zero pending force close channels.
1283
func (h *HarnessTest) ForceCloseChannel(hn *node.HarnessNode,
1284
        cp *lnrpc.ChannelPoint) chainhash.Hash {
×
1285

×
1286
        stream, _ := h.CloseChannelAssertPending(hn, cp, true)
×
1287

×
1288
        closingTxid := h.AssertStreamChannelForceClosed(hn, cp, false, stream)
×
1289

×
1290
        // Cleanup the force close.
×
1291
        h.CleanupForceClose(hn)
×
1292

×
1293
        return closingTxid
×
1294
}
×
1295

1296
// CloseChannelAssertErr closes the given channel and asserts an error
1297
// returned.
1298
func (h *HarnessTest) CloseChannelAssertErr(hn *node.HarnessNode,
1299
        cp *lnrpc.ChannelPoint, force bool) error {
×
1300

×
1301
        // Calls the rpc to close the channel.
×
1302
        closeReq := &lnrpc.CloseChannelRequest{
×
1303
                ChannelPoint: cp,
×
1304
                Force:        force,
×
1305
        }
×
1306
        stream := hn.RPC.CloseChannel(closeReq)
×
1307

×
1308
        // Consume the "channel close" update in order to wait for the closing
×
1309
        // transaction to be broadcast, then wait for the closing tx to be seen
×
1310
        // within the network.
×
1311
        _, err := h.ReceiveCloseChannelUpdate(stream)
×
1312
        require.Errorf(h, err, "%s: expect close channel to return an error",
×
1313
                hn.Name())
×
1314

×
1315
        return err
×
1316
}
×
1317

1318
// IsNeutrinoBackend returns a bool indicating whether the node is using a
1319
// neutrino as its backend. This is useful when we want to skip certain tests
1320
// which cannot be done with a neutrino backend.
1321
func (h *HarnessTest) IsNeutrinoBackend() bool {
×
1322
        return h.manager.chainBackend.Name() == NeutrinoBackendName
×
1323
}
×
1324

1325
// fundCoins attempts to send amt satoshis from the internal mining node to the
1326
// targeted lightning node. The confirmed boolean indicates whether the
1327
// transaction that pays to the target should confirm. For neutrino backend,
1328
// the `confirmed` param is ignored.
1329
func (h *HarnessTest) fundCoins(amt btcutil.Amount, target *node.HarnessNode,
1330
        addrType lnrpc.AddressType, confirmed bool) {
×
1331

×
1332
        initialBalance := target.RPC.WalletBalance()
×
1333

×
1334
        // First, obtain an address from the target lightning node, preferring
×
1335
        // to receive a p2wkh address s.t the output can immediately be used as
×
1336
        // an input to a funding transaction.
×
1337
        req := &lnrpc.NewAddressRequest{Type: addrType}
×
1338
        resp := target.RPC.NewAddress(req)
×
1339
        addr := h.DecodeAddress(resp.Address)
×
1340
        addrScript := h.PayToAddrScript(addr)
×
1341

×
1342
        // Generate a transaction which creates an output to the target
×
1343
        // pkScript of the desired amount.
×
1344
        output := &wire.TxOut{
×
1345
                PkScript: addrScript,
×
1346
                Value:    int64(amt),
×
1347
        }
×
1348
        h.miner.SendOutput(output, defaultMinerFeeRate)
×
1349

×
1350
        // Encode the pkScript in hex as this the format that it will be
×
1351
        // returned via rpc.
×
1352
        expPkScriptStr := hex.EncodeToString(addrScript)
×
1353

×
1354
        // Now, wait for ListUnspent to show the unconfirmed transaction
×
1355
        // containing the correct pkscript.
×
1356
        //
×
1357
        // Since neutrino doesn't support unconfirmed outputs, skip this check.
×
1358
        if !h.IsNeutrinoBackend() {
×
1359
                utxos := h.AssertNumUTXOsUnconfirmed(target, 1)
×
1360

×
1361
                // Assert that the lone unconfirmed utxo contains the same
×
1362
                // pkscript as the output generated above.
×
1363
                pkScriptStr := utxos[0].PkScript
×
1364
                require.Equal(h, pkScriptStr, expPkScriptStr,
×
1365
                        "pkscript mismatch")
×
1366

×
1367
                expectedBalance := btcutil.Amount(
×
1368
                        initialBalance.UnconfirmedBalance,
×
1369
                ) + amt
×
1370
                h.WaitForBalanceUnconfirmed(target, expectedBalance)
×
1371
        }
×
1372

1373
        // If the transaction should remain unconfirmed, then we'll wait until
1374
        // the target node's unconfirmed balance reflects the expected balance
1375
        // and exit.
1376
        if !confirmed {
×
1377
                return
×
1378
        }
×
1379

1380
        // Otherwise, we'll generate 1 new blocks to ensure the output gains a
1381
        // sufficient number of confirmations and wait for the balance to
1382
        // reflect what's expected.
1383
        h.MineBlocksAndAssertNumTxes(1, 1)
×
1384

×
1385
        expectedBalance := btcutil.Amount(initialBalance.ConfirmedBalance) + amt
×
1386
        h.WaitForBalanceConfirmed(target, expectedBalance)
×
1387
}
1388

1389
// FundCoins attempts to send amt satoshis from the internal mining node to the
1390
// targeted lightning node using a P2WKH address. 1 blocks are mined after in
1391
// order to confirm the transaction.
1392
func (h *HarnessTest) FundCoins(amt btcutil.Amount, hn *node.HarnessNode) {
×
1393
        h.fundCoins(amt, hn, lnrpc.AddressType_WITNESS_PUBKEY_HASH, true)
×
1394
}
×
1395

1396
// FundCoinsUnconfirmed attempts to send amt satoshis from the internal mining
1397
// node to the targeted lightning node using a P2WKH address. No blocks are
1398
// mined after and the UTXOs are unconfirmed.
1399
func (h *HarnessTest) FundCoinsUnconfirmed(amt btcutil.Amount,
1400
        hn *node.HarnessNode) {
×
1401

×
1402
        h.fundCoins(amt, hn, lnrpc.AddressType_WITNESS_PUBKEY_HASH, false)
×
1403
}
×
1404

1405
// FundCoinsNP2WKH attempts to send amt satoshis from the internal mining node
1406
// to the targeted lightning node using a NP2WKH address.
1407
func (h *HarnessTest) FundCoinsNP2WKH(amt btcutil.Amount,
1408
        target *node.HarnessNode) {
×
1409

×
1410
        h.fundCoins(amt, target, lnrpc.AddressType_NESTED_PUBKEY_HASH, true)
×
1411
}
×
1412

1413
// FundCoinsP2TR attempts to send amt satoshis from the internal mining node to
1414
// the targeted lightning node using a P2TR address.
1415
func (h *HarnessTest) FundCoinsP2TR(amt btcutil.Amount,
1416
        target *node.HarnessNode) {
×
1417

×
1418
        h.fundCoins(amt, target, lnrpc.AddressType_TAPROOT_PUBKEY, true)
×
1419
}
×
1420

1421
// FundNumCoins attempts to send the given number of UTXOs from the internal
1422
// mining node to the targeted lightning node using a P2WKH address. Each UTXO
1423
// has an amount of 1 BTC. 1 blocks are mined to confirm the tx.
NEW
1424
func (h *HarnessTest) FundNumCoins(hn *node.HarnessNode, num int) {
×
NEW
1425
        // Get the initial balance first.
×
NEW
1426
        resp := hn.RPC.WalletBalance()
×
NEW
1427
        initialBalance := btcutil.Amount(resp.ConfirmedBalance)
×
NEW
1428

×
NEW
1429
        const fundAmount = 1 * btcutil.SatoshiPerBitcoin
×
NEW
1430

×
NEW
1431
        // Send out the outputs from the miner.
×
NEW
1432
        for i := 0; i < num; i++ {
×
NEW
1433
                h.createAndSendOutput(
×
NEW
1434
                        hn, fundAmount, lnrpc.AddressType_WITNESS_PUBKEY_HASH,
×
NEW
1435
                )
×
NEW
1436
        }
×
1437

1438
        // Wait for ListUnspent to show the correct number of unconfirmed
1439
        // UTXOs.
1440
        //
1441
        // Since neutrino doesn't support unconfirmed outputs, skip this check.
NEW
1442
        if !h.IsNeutrinoBackend() {
×
NEW
1443
                h.AssertNumUTXOsUnconfirmed(hn, num)
×
NEW
1444
        }
×
1445

1446
        // Mine a block to confirm the transactions.
NEW
1447
        h.MineBlocksAndAssertNumTxes(1, num)
×
NEW
1448

×
NEW
1449
        // Now block until the wallet have fully synced up.
×
NEW
1450
        totalAmount := btcutil.Amount(fundAmount * num)
×
NEW
1451
        expectedBalance := initialBalance + totalAmount
×
NEW
1452
        h.WaitForBalanceConfirmed(hn, expectedBalance)
×
1453
}
1454

1455
// completePaymentRequestsAssertStatus sends payments from a node to complete
1456
// all payment requests. This function does not return until all payments
1457
// have reached the specified status.
1458
func (h *HarnessTest) completePaymentRequestsAssertStatus(hn *node.HarnessNode,
1459
        paymentRequests []string, status lnrpc.Payment_PaymentStatus,
1460
        opts ...HarnessOpt) {
×
1461

×
1462
        payOpts := defaultHarnessOpts()
×
1463
        for _, opt := range opts {
×
1464
                opt(&payOpts)
×
1465
        }
×
1466

1467
        // Create a buffered chan to signal the results.
1468
        results := make(chan rpc.PaymentClient, len(paymentRequests))
×
1469

×
1470
        // send sends a payment and asserts if it doesn't succeeded.
×
1471
        send := func(payReq string) {
×
1472
                req := &routerrpc.SendPaymentRequest{
×
1473
                        PaymentRequest: payReq,
×
1474
                        TimeoutSeconds: int32(wait.PaymentTimeout.Seconds()),
×
1475
                        FeeLimitMsat:   noFeeLimitMsat,
×
1476
                        Amp:            payOpts.useAMP,
×
1477
                }
×
1478
                stream := hn.RPC.SendPayment(req)
×
1479

×
1480
                // Signal sent succeeded.
×
1481
                results <- stream
×
1482
        }
×
1483

1484
        // Launch all payments simultaneously.
1485
        for _, payReq := range paymentRequests {
×
1486
                payReqCopy := payReq
×
1487
                go send(payReqCopy)
×
1488
        }
×
1489

1490
        // Wait for all payments to report the expected status.
1491
        timer := time.After(wait.PaymentTimeout)
×
1492
        select {
×
1493
        case stream := <-results:
×
1494
                h.AssertPaymentStatusFromStream(stream, status)
×
1495

1496
        case <-timer:
×
1497
                require.Fail(h, "timeout", "waiting payment results timeout")
×
1498
        }
1499
}
1500

1501
// CompletePaymentRequests sends payments from a node to complete all payment
1502
// requests. This function does not return until all payments successfully
1503
// complete without errors.
1504
func (h *HarnessTest) CompletePaymentRequests(hn *node.HarnessNode,
1505
        paymentRequests []string, opts ...HarnessOpt) {
×
1506

×
1507
        h.completePaymentRequestsAssertStatus(
×
1508
                hn, paymentRequests, lnrpc.Payment_SUCCEEDED, opts...,
×
1509
        )
×
1510
}
×
1511

1512
// CompletePaymentRequestsNoWait sends payments from a node to complete all
1513
// payment requests without waiting for the results. Instead, it checks the
1514
// number of updates in the specified channel has increased.
1515
func (h *HarnessTest) CompletePaymentRequestsNoWait(hn *node.HarnessNode,
1516
        paymentRequests []string, chanPoint *lnrpc.ChannelPoint) {
×
1517

×
1518
        // We start by getting the current state of the client's channels. This
×
1519
        // is needed to ensure the payments actually have been committed before
×
1520
        // we return.
×
1521
        oldResp := h.GetChannelByChanPoint(hn, chanPoint)
×
1522

×
1523
        // Send payments and assert they are in-flight.
×
1524
        h.completePaymentRequestsAssertStatus(
×
1525
                hn, paymentRequests, lnrpc.Payment_IN_FLIGHT,
×
1526
        )
×
1527

×
1528
        // We are not waiting for feedback in the form of a response, but we
×
1529
        // should still wait long enough for the server to receive and handle
×
1530
        // the send before cancelling the request. We wait for the number of
×
1531
        // updates to one of our channels has increased before we return.
×
1532
        err := wait.NoError(func() error {
×
1533
                newResp := h.GetChannelByChanPoint(hn, chanPoint)
×
1534

×
1535
                // If this channel has an increased number of updates, we
×
1536
                // assume the payments are committed, and we can return.
×
1537
                if newResp.NumUpdates > oldResp.NumUpdates {
×
1538
                        return nil
×
1539
                }
×
1540

1541
                // Otherwise return an error as the NumUpdates are not
1542
                // increased.
1543
                return fmt.Errorf("%s: channel:%v not updated after sending "+
×
1544
                        "payments, old updates: %v, new updates: %v", hn.Name(),
×
1545
                        chanPoint, oldResp.NumUpdates, newResp.NumUpdates)
×
1546
        }, DefaultTimeout)
1547
        require.NoError(h, err, "timeout while checking for channel updates")
×
1548
}
1549

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

×
1556
        // Wait until srcNode and destNode have the latest chain synced.
×
1557
        // Otherwise, we may run into a check within the funding manager that
×
1558
        // prevents any funding workflows from being kicked off if the chain
×
1559
        // isn't yet synced.
×
1560
        h.WaitForBlockchainSync(srcNode)
×
1561
        h.WaitForBlockchainSync(destNode)
×
1562

×
1563
        // Send the request to open a channel to the source node now. This will
×
1564
        // open a long-lived stream where we'll receive status updates about
×
1565
        // the progress of the channel.
×
1566
        // respStream := h.OpenChannelStreamAndAssert(srcNode, destNode, p)
×
1567
        req := &lnrpc.OpenChannelRequest{
×
1568
                NodePubkey:         destNode.PubKey[:],
×
1569
                LocalFundingAmount: int64(p.Amt),
×
1570
                PushSat:            int64(p.PushAmt),
×
1571
                Private:            p.Private,
×
1572
                SpendUnconfirmed:   p.SpendUnconfirmed,
×
1573
                MinHtlcMsat:        int64(p.MinHtlc),
×
1574
                FundingShim:        p.FundingShim,
×
1575
                CommitmentType:     p.CommitmentType,
×
1576
        }
×
1577
        respStream := srcNode.RPC.OpenChannel(req)
×
1578

×
1579
        // Consume the "PSBT funding ready" update. This waits until the node
×
1580
        // notifies us that the PSBT can now be funded.
×
1581
        resp := h.ReceiveOpenChannelUpdate(respStream)
×
1582
        upd, ok := resp.Update.(*lnrpc.OpenStatusUpdate_PsbtFund)
×
1583
        require.Truef(h, ok, "expected PSBT funding update, got %v", resp)
×
1584

×
1585
        // Make sure the channel funding address has the correct type for the
×
1586
        // given commitment type.
×
1587
        fundingAddr, err := btcutil.DecodeAddress(
×
1588
                upd.PsbtFund.FundingAddress, miner.HarnessNetParams,
×
1589
        )
×
1590
        require.NoError(h, err)
×
1591

×
1592
        switch p.CommitmentType {
×
1593
        case lnrpc.CommitmentType_SIMPLE_TAPROOT:
×
1594
                require.IsType(h, &btcutil.AddressTaproot{}, fundingAddr)
×
1595

1596
        default:
×
1597
                require.IsType(
×
1598
                        h, &btcutil.AddressWitnessScriptHash{}, fundingAddr,
×
1599
                )
×
1600
        }
1601

1602
        return respStream, upd.PsbtFund.Psbt
×
1603
}
1604

1605
// CleanupForceClose mines blocks to clean up the force close process. This is
1606
// used for tests that are not asserting the expected behavior is found during
1607
// the force close process, e.g., num of sweeps, etc. Instead, it provides a
1608
// shortcut to move the test forward with a clean mempool.
1609
func (h *HarnessTest) CleanupForceClose(hn *node.HarnessNode) {
×
1610
        // Wait for the channel to be marked pending force close.
×
1611
        h.AssertNumPendingForceClose(hn, 1)
×
1612

×
1613
        // Mine enough blocks for the node to sweep its funds from the force
×
1614
        // closed channel. The commit sweep resolver is offers the input to the
×
1615
        // sweeper when it's force closed, and broadcast the sweep tx at
×
1616
        // defaulCSV-1.
×
1617
        //
×
1618
        // NOTE: we might empty blocks here as we don't know the exact number
×
1619
        // of blocks to mine. This may end up mining more blocks than needed.
×
1620
        h.MineEmptyBlocks(node.DefaultCSV - 1)
×
1621

×
1622
        // Assert there is one pending sweep.
×
1623
        h.AssertNumPendingSweeps(hn, 1)
×
1624

×
1625
        // The node should now sweep the funds, clean up by mining the sweeping
×
1626
        // tx.
×
1627
        h.MineBlocksAndAssertNumTxes(1, 1)
×
1628

×
1629
        // Mine blocks to get any second level HTLC resolved. If there are no
×
1630
        // HTLCs, this will behave like h.AssertNumPendingCloseChannels.
×
1631
        h.mineTillForceCloseResolved(hn)
×
1632
}
×
1633

1634
// CreatePayReqs is a helper method that will create a slice of payment
1635
// requests for the given node.
1636
func (h *HarnessTest) CreatePayReqs(hn *node.HarnessNode,
1637
        paymentAmt btcutil.Amount, numInvoices int,
1638
        routeHints ...*lnrpc.RouteHint) ([]string, [][]byte, []*lnrpc.Invoice) {
×
1639

×
1640
        payReqs := make([]string, numInvoices)
×
1641
        rHashes := make([][]byte, numInvoices)
×
1642
        invoices := make([]*lnrpc.Invoice, numInvoices)
×
1643
        for i := 0; i < numInvoices; i++ {
×
1644
                preimage := h.Random32Bytes()
×
1645

×
1646
                invoice := &lnrpc.Invoice{
×
1647
                        Memo:       "testing",
×
1648
                        RPreimage:  preimage,
×
1649
                        Value:      int64(paymentAmt),
×
1650
                        RouteHints: routeHints,
×
1651
                }
×
1652
                resp := hn.RPC.AddInvoice(invoice)
×
1653

×
1654
                // Set the payment address in the invoice so the caller can
×
1655
                // properly use it.
×
1656
                invoice.PaymentAddr = resp.PaymentAddr
×
1657

×
1658
                payReqs[i] = resp.PaymentRequest
×
1659
                rHashes[i] = resp.RHash
×
1660
                invoices[i] = invoice
×
1661
        }
×
1662

1663
        return payReqs, rHashes, invoices
×
1664
}
1665

1666
// BackupDB creates a backup of the current database. It will stop the node
1667
// first, copy the database files, and restart the node.
1668
func (h *HarnessTest) BackupDB(hn *node.HarnessNode) {
×
1669
        restart := h.SuspendNode(hn)
×
1670

×
1671
        err := hn.BackupDB()
×
1672
        require.NoErrorf(h, err, "%s: failed to backup db", hn.Name())
×
1673

×
1674
        err = restart()
×
1675
        require.NoErrorf(h, err, "%s: failed to restart", hn.Name())
×
1676
}
×
1677

1678
// RestartNodeAndRestoreDB restarts a given node with a callback to restore the
1679
// db.
1680
func (h *HarnessTest) RestartNodeAndRestoreDB(hn *node.HarnessNode) {
×
1681
        cb := func() error { return hn.RestoreDB() }
×
1682
        err := h.manager.restartNode(h.runCtx, hn, cb)
×
1683
        require.NoErrorf(h, err, "failed to restart node %s", hn.Name())
×
1684

×
1685
        err = h.manager.unlockNode(hn)
×
1686
        require.NoErrorf(h, err, "failed to unlock node %s", hn.Name())
×
1687

×
1688
        // Give the node some time to catch up with the chain before we
×
1689
        // continue with the tests.
×
1690
        h.WaitForBlockchainSync(hn)
×
1691
}
1692

1693
// CleanShutDown is used to quickly end a test by shutting down all non-standby
1694
// nodes and mining blocks to empty the mempool.
1695
//
1696
// NOTE: this method provides a faster exit for a test that involves force
1697
// closures as the caller doesn't need to mine all the blocks to make sure the
1698
// mempool is empty.
1699
func (h *HarnessTest) CleanShutDown() {
×
NEW
1700
        // First, shutdown all nodes to prevent new transactions being created
×
NEW
1701
        // and fed into the mempool.
×
NEW
1702
        h.shutdownAllNodes()
×
1703

×
1704
        // Now mine blocks till the mempool is empty.
×
1705
        h.cleanMempool()
×
1706
}
×
1707

1708
// QueryChannelByChanPoint tries to find a channel matching the channel point
1709
// and asserts. It returns the channel found.
1710
func (h *HarnessTest) QueryChannelByChanPoint(hn *node.HarnessNode,
1711
        chanPoint *lnrpc.ChannelPoint,
1712
        opts ...ListChannelOption) *lnrpc.Channel {
×
1713

×
1714
        channel, err := h.findChannel(hn, chanPoint, opts...)
×
1715
        require.NoError(h, err, "failed to query channel")
×
1716

×
1717
        return channel
×
1718
}
×
1719

1720
// SendPaymentAndAssertStatus sends a payment from the passed node and asserts
1721
// the desired status is reached.
1722
func (h *HarnessTest) SendPaymentAndAssertStatus(hn *node.HarnessNode,
1723
        req *routerrpc.SendPaymentRequest,
1724
        status lnrpc.Payment_PaymentStatus) *lnrpc.Payment {
×
1725

×
1726
        stream := hn.RPC.SendPayment(req)
×
1727
        return h.AssertPaymentStatusFromStream(stream, status)
×
1728
}
×
1729

1730
// SendPaymentAssertFail sends a payment from the passed node and asserts the
1731
// payment is failed with the specified failure reason .
1732
func (h *HarnessTest) SendPaymentAssertFail(hn *node.HarnessNode,
1733
        req *routerrpc.SendPaymentRequest,
1734
        reason lnrpc.PaymentFailureReason) *lnrpc.Payment {
×
1735

×
1736
        payment := h.SendPaymentAndAssertStatus(hn, req, lnrpc.Payment_FAILED)
×
1737
        require.Equal(h, reason, payment.FailureReason,
×
1738
                "payment failureReason not matched")
×
1739

×
1740
        return payment
×
1741
}
×
1742

1743
// SendPaymentAssertSettled sends a payment from the passed node and asserts the
1744
// payment is settled.
1745
func (h *HarnessTest) SendPaymentAssertSettled(hn *node.HarnessNode,
1746
        req *routerrpc.SendPaymentRequest) *lnrpc.Payment {
×
1747

×
1748
        return h.SendPaymentAndAssertStatus(hn, req, lnrpc.Payment_SUCCEEDED)
×
1749
}
×
1750

1751
// SendPaymentAssertInflight sends a payment from the passed node and asserts
1752
// the payment is inflight.
1753
func (h *HarnessTest) SendPaymentAssertInflight(hn *node.HarnessNode,
1754
        req *routerrpc.SendPaymentRequest) *lnrpc.Payment {
×
1755

×
1756
        return h.SendPaymentAndAssertStatus(hn, req, lnrpc.Payment_IN_FLIGHT)
×
1757
}
×
1758

1759
// OpenChannelRequest is used to open a channel using the method
1760
// OpenMultiChannelsAsync.
1761
type OpenChannelRequest struct {
1762
        // Local is the funding node.
1763
        Local *node.HarnessNode
1764

1765
        // Remote is the receiving node.
1766
        Remote *node.HarnessNode
1767

1768
        // Param is the open channel params.
1769
        Param OpenChannelParams
1770

1771
        // stream is the client created after calling OpenChannel RPC.
1772
        stream rpc.OpenChanClient
1773

1774
        // result is a channel used to send the channel point once the funding
1775
        // has succeeded.
1776
        result chan *lnrpc.ChannelPoint
1777
}
1778

1779
// OpenMultiChannelsAsync takes a list of OpenChannelRequest and opens them in
1780
// batch. The channel points are returned in same the order of the requests
1781
// once all of the channel open succeeded.
1782
//
1783
// NOTE: compared to open multiple channel sequentially, this method will be
1784
// faster as it doesn't need to mine 6 blocks for each channel open. However,
1785
// it does make debugging the logs more difficult as messages are intertwined.
1786
func (h *HarnessTest) OpenMultiChannelsAsync(
1787
        reqs []*OpenChannelRequest) []*lnrpc.ChannelPoint {
×
1788

×
1789
        // openChannel opens a channel based on the request.
×
1790
        openChannel := func(req *OpenChannelRequest) {
×
1791
                stream := h.OpenChannelAssertStream(
×
1792
                        req.Local, req.Remote, req.Param,
×
1793
                )
×
1794
                req.stream = stream
×
1795
        }
×
1796

1797
        // assertChannelOpen is a helper closure that asserts a channel is
1798
        // open.
1799
        assertChannelOpen := func(req *OpenChannelRequest) {
×
1800
                // Wait for the channel open event from the stream.
×
1801
                cp := h.WaitForChannelOpenEvent(req.stream)
×
1802

×
1803
                if !req.Param.Private {
×
1804
                        // Check that both alice and bob have seen the channel
×
1805
                        // from their channel watch request.
×
1806
                        h.AssertChannelInGraph(req.Local, cp)
×
1807
                        h.AssertChannelInGraph(req.Remote, cp)
×
1808
                }
×
1809

1810
                // Finally, check that the channel can be seen in their
1811
                // ListChannels.
1812
                h.AssertChannelExists(req.Local, cp)
×
1813
                h.AssertChannelExists(req.Remote, cp)
×
1814

×
1815
                req.result <- cp
×
1816
        }
1817

1818
        // Go through the requests and make the OpenChannel RPC call.
1819
        for _, r := range reqs {
×
1820
                openChannel(r)
×
1821
        }
×
1822

1823
        // Mine one block to confirm all the funding transactions.
1824
        h.MineBlocksAndAssertNumTxes(1, len(reqs))
×
1825

×
1826
        // Mine 5 more blocks so all the public channels are announced to the
×
1827
        // network.
×
1828
        h.MineBlocks(numBlocksOpenChannel - 1)
×
1829

×
1830
        // Once the blocks are mined, we fire goroutines for each of the
×
1831
        // request to watch for the channel openning.
×
1832
        for _, r := range reqs {
×
1833
                r.result = make(chan *lnrpc.ChannelPoint, 1)
×
1834
                go assertChannelOpen(r)
×
1835
        }
×
1836

1837
        // Finally, collect the results.
1838
        channelPoints := make([]*lnrpc.ChannelPoint, 0)
×
1839
        for _, r := range reqs {
×
1840
                select {
×
1841
                case cp := <-r.result:
×
1842
                        channelPoints = append(channelPoints, cp)
×
1843

1844
                case <-time.After(wait.ChannelOpenTimeout):
×
1845
                        require.Failf(h, "timeout", "wait channel point "+
×
1846
                                "timeout for channel %s=>%s", r.Local.Name(),
×
1847
                                r.Remote.Name())
×
1848
                }
1849
        }
1850

1851
        // Assert that we have the expected num of channel points.
1852
        require.Len(h, channelPoints, len(reqs),
×
1853
                "returned channel points not match")
×
1854

×
1855
        return channelPoints
×
1856
}
1857

1858
// ReceiveInvoiceUpdate waits until a message is received on the subscribe
1859
// invoice stream or the timeout is reached.
1860
func (h *HarnessTest) ReceiveInvoiceUpdate(
1861
        stream rpc.InvoiceUpdateClient) *lnrpc.Invoice {
×
1862

×
1863
        chanMsg := make(chan *lnrpc.Invoice)
×
1864
        errChan := make(chan error)
×
1865
        go func() {
×
1866
                // Consume one message. This will block until the message is
×
1867
                // received.
×
1868
                resp, err := stream.Recv()
×
1869
                if err != nil {
×
1870
                        errChan <- err
×
1871
                        return
×
1872
                }
×
1873
                chanMsg <- resp
×
1874
        }()
1875

1876
        select {
×
1877
        case <-time.After(DefaultTimeout):
×
1878
                require.Fail(h, "timeout", "timeout receiving invoice update")
×
1879

1880
        case err := <-errChan:
×
1881
                require.Failf(h, "err from stream",
×
1882
                        "received err from stream: %v", err)
×
1883

1884
        case updateMsg := <-chanMsg:
×
1885
                return updateMsg
×
1886
        }
1887

1888
        return nil
×
1889
}
1890

1891
// CalculateTxFee retrieves parent transactions and reconstructs the fee paid.
1892
func (h *HarnessTest) CalculateTxFee(tx *wire.MsgTx) btcutil.Amount {
×
1893
        var balance btcutil.Amount
×
1894
        for _, in := range tx.TxIn {
×
1895
                parentHash := in.PreviousOutPoint.Hash
×
1896
                rawTx := h.miner.GetRawTransaction(parentHash)
×
1897
                parent := rawTx.MsgTx()
×
1898
                value := parent.TxOut[in.PreviousOutPoint.Index].Value
×
1899

×
1900
                balance += btcutil.Amount(value)
×
1901
        }
×
1902

1903
        for _, out := range tx.TxOut {
×
1904
                balance -= btcutil.Amount(out.Value)
×
1905
        }
×
1906

1907
        return balance
×
1908
}
1909

1910
// CalculateTxWeight calculates the weight for a given tx.
1911
//
1912
// TODO(yy): use weight estimator to get more accurate result.
1913
func (h *HarnessTest) CalculateTxWeight(tx *wire.MsgTx) lntypes.WeightUnit {
×
1914
        utx := btcutil.NewTx(tx)
×
1915
        return lntypes.WeightUnit(blockchain.GetTransactionWeight(utx))
×
1916
}
×
1917

1918
// CalculateTxFeeRate calculates the fee rate for a given tx.
1919
func (h *HarnessTest) CalculateTxFeeRate(
1920
        tx *wire.MsgTx) chainfee.SatPerKWeight {
×
1921

×
1922
        w := h.CalculateTxWeight(tx)
×
1923
        fee := h.CalculateTxFee(tx)
×
1924

×
1925
        return chainfee.NewSatPerKWeight(fee, w)
×
1926
}
×
1927

1928
// CalculateTxesFeeRate takes a list of transactions and estimates the fee rate
1929
// used to sweep them.
1930
//
1931
// NOTE: only used in current test file.
1932
func (h *HarnessTest) CalculateTxesFeeRate(txns []*wire.MsgTx) int64 {
×
1933
        const scale = 1000
×
1934

×
1935
        var totalWeight, totalFee int64
×
1936
        for _, tx := range txns {
×
1937
                utx := btcutil.NewTx(tx)
×
1938
                totalWeight += blockchain.GetTransactionWeight(utx)
×
1939

×
1940
                fee := h.CalculateTxFee(tx)
×
1941
                totalFee += int64(fee)
×
1942
        }
×
1943
        feeRate := totalFee * scale / totalWeight
×
1944

×
1945
        return feeRate
×
1946
}
1947

1948
// AssertSweepFound looks up a sweep in a nodes list of broadcast sweeps and
1949
// asserts it's found.
1950
//
1951
// NOTE: Does not account for node's internal state.
1952
func (h *HarnessTest) AssertSweepFound(hn *node.HarnessNode,
1953
        sweep string, verbose bool, startHeight int32) {
×
1954

×
1955
        err := wait.NoError(func() error {
×
1956
                // List all sweeps that alice's node had broadcast.
×
1957
                sweepResp := hn.RPC.ListSweeps(verbose, startHeight)
×
1958

×
1959
                var found bool
×
1960
                if verbose {
×
1961
                        found = findSweepInDetails(h, sweep, sweepResp)
×
1962
                } else {
×
1963
                        found = findSweepInTxids(h, sweep, sweepResp)
×
1964
                }
×
1965

1966
                if found {
×
1967
                        return nil
×
1968
                }
×
1969

1970
                return fmt.Errorf("sweep tx %v not found in resp %v", sweep,
×
1971
                        sweepResp)
×
1972
        }, wait.DefaultTimeout)
1973
        require.NoError(h, err, "%s: timeout checking sweep tx", hn.Name())
×
1974
}
1975

1976
func findSweepInTxids(ht *HarnessTest, sweepTxid string,
1977
        sweepResp *walletrpc.ListSweepsResponse) bool {
×
1978

×
1979
        sweepTxIDs := sweepResp.GetTransactionIds()
×
1980
        require.NotNil(ht, sweepTxIDs, "expected transaction ids")
×
1981
        require.Nil(ht, sweepResp.GetTransactionDetails())
×
1982

×
1983
        // Check that the sweep tx we have just produced is present.
×
1984
        for _, tx := range sweepTxIDs.TransactionIds {
×
1985
                if tx == sweepTxid {
×
1986
                        return true
×
1987
                }
×
1988
        }
1989

1990
        return false
×
1991
}
1992

1993
func findSweepInDetails(ht *HarnessTest, sweepTxid string,
1994
        sweepResp *walletrpc.ListSweepsResponse) bool {
×
1995

×
1996
        sweepDetails := sweepResp.GetTransactionDetails()
×
1997
        require.NotNil(ht, sweepDetails, "expected transaction details")
×
1998
        require.Nil(ht, sweepResp.GetTransactionIds())
×
1999

×
2000
        for _, tx := range sweepDetails.Transactions {
×
2001
                if tx.TxHash == sweepTxid {
×
2002
                        return true
×
2003
                }
×
2004
        }
2005

2006
        return false
×
2007
}
2008

2009
// QueryRoutesAndRetry attempts to keep querying a route until timeout is
2010
// reached.
2011
//
2012
// NOTE: when a channel is opened, we may need to query multiple times to get
2013
// it in our QueryRoutes RPC. This happens even after we check the channel is
2014
// heard by the node using ht.AssertChannelOpen. Deep down, this is because our
2015
// GraphTopologySubscription and QueryRoutes give different results regarding a
2016
// specific channel, with the formal reporting it being open while the latter
2017
// not, resulting GraphTopologySubscription acting "faster" than QueryRoutes.
2018
// TODO(yy): make sure related subsystems share the same view on a given
2019
// channel.
2020
func (h *HarnessTest) QueryRoutesAndRetry(hn *node.HarnessNode,
2021
        req *lnrpc.QueryRoutesRequest) *lnrpc.QueryRoutesResponse {
×
2022

×
2023
        var routes *lnrpc.QueryRoutesResponse
×
2024
        err := wait.NoError(func() error {
×
2025
                ctxt, cancel := context.WithCancel(h.runCtx)
×
2026
                defer cancel()
×
2027

×
2028
                resp, err := hn.RPC.LN.QueryRoutes(ctxt, req)
×
2029
                if err != nil {
×
2030
                        return fmt.Errorf("%s: failed to query route: %w",
×
2031
                                hn.Name(), err)
×
2032
                }
×
2033

2034
                routes = resp
×
2035

×
2036
                return nil
×
2037
        }, DefaultTimeout)
2038

2039
        require.NoError(h, err, "timeout querying routes")
×
2040

×
2041
        return routes
×
2042
}
2043

2044
// ReceiveHtlcInterceptor waits until a message is received on the htlc
2045
// interceptor stream or the timeout is reached.
2046
func (h *HarnessTest) ReceiveHtlcInterceptor(
2047
        stream rpc.InterceptorClient) *routerrpc.ForwardHtlcInterceptRequest {
×
2048

×
2049
        chanMsg := make(chan *routerrpc.ForwardHtlcInterceptRequest)
×
2050
        errChan := make(chan error)
×
2051
        go func() {
×
2052
                // Consume one message. This will block until the message is
×
2053
                // received.
×
2054
                resp, err := stream.Recv()
×
2055
                if err != nil {
×
2056
                        errChan <- err
×
2057
                        return
×
2058
                }
×
2059
                chanMsg <- resp
×
2060
        }()
2061

2062
        select {
×
2063
        case <-time.After(DefaultTimeout):
×
2064
                require.Fail(h, "timeout", "timeout intercepting htlc")
×
2065

2066
        case err := <-errChan:
×
2067
                require.Failf(h, "err from HTLC interceptor stream",
×
2068
                        "received err from HTLC interceptor stream: %v", err)
×
2069

2070
        case updateMsg := <-chanMsg:
×
2071
                return updateMsg
×
2072
        }
2073

2074
        return nil
×
2075
}
2076

2077
// ReceiveInvoiceHtlcModification waits until a message is received on the
2078
// invoice HTLC modifier stream or the timeout is reached.
2079
func (h *HarnessTest) ReceiveInvoiceHtlcModification(
2080
        stream rpc.InvoiceHtlcModifierClient) *invoicesrpc.HtlcModifyRequest {
×
2081

×
2082
        chanMsg := make(chan *invoicesrpc.HtlcModifyRequest)
×
2083
        errChan := make(chan error)
×
2084
        go func() {
×
2085
                // Consume one message. This will block until the message is
×
2086
                // received.
×
2087
                resp, err := stream.Recv()
×
2088
                if err != nil {
×
2089
                        errChan <- err
×
2090
                        return
×
2091
                }
×
2092
                chanMsg <- resp
×
2093
        }()
2094

2095
        select {
×
2096
        case <-time.After(DefaultTimeout):
×
2097
                require.Fail(h, "timeout", "timeout invoice HTLC modifier")
×
2098

2099
        case err := <-errChan:
×
2100
                require.Failf(h, "err from invoice HTLC modifier stream",
×
2101
                        "received err from invoice HTLC modifier stream: %v",
×
2102
                        err)
×
2103

2104
        case updateMsg := <-chanMsg:
×
2105
                return updateMsg
×
2106
        }
2107

2108
        return nil
×
2109
}
2110

2111
// ReceiveChannelEvent waits until a message is received from the
2112
// ChannelEventsClient stream or the timeout is reached.
2113
func (h *HarnessTest) ReceiveChannelEvent(
2114
        stream rpc.ChannelEventsClient) *lnrpc.ChannelEventUpdate {
×
2115

×
2116
        chanMsg := make(chan *lnrpc.ChannelEventUpdate)
×
2117
        errChan := make(chan error)
×
2118
        go func() {
×
2119
                // Consume one message. This will block until the message is
×
2120
                // received.
×
2121
                resp, err := stream.Recv()
×
2122
                if err != nil {
×
2123
                        errChan <- err
×
2124
                        return
×
2125
                }
×
2126
                chanMsg <- resp
×
2127
        }()
2128

2129
        select {
×
2130
        case <-time.After(DefaultTimeout):
×
2131
                require.Fail(h, "timeout", "timeout intercepting htlc")
×
2132

2133
        case err := <-errChan:
×
2134
                require.Failf(h, "err from stream",
×
2135
                        "received err from stream: %v", err)
×
2136

2137
        case updateMsg := <-chanMsg:
×
2138
                return updateMsg
×
2139
        }
2140

2141
        return nil
×
2142
}
2143

2144
// GetOutputIndex returns the output index of the given address in the given
2145
// transaction.
2146
func (h *HarnessTest) GetOutputIndex(txid chainhash.Hash, addr string) int {
×
2147
        // We'll then extract the raw transaction from the mempool in order to
×
2148
        // determine the index of the p2tr output.
×
2149
        tx := h.miner.GetRawTransaction(txid)
×
2150

×
2151
        p2trOutputIndex := -1
×
2152
        for i, txOut := range tx.MsgTx().TxOut {
×
2153
                _, addrs, _, err := txscript.ExtractPkScriptAddrs(
×
2154
                        txOut.PkScript, h.miner.ActiveNet,
×
2155
                )
×
2156
                require.NoError(h, err)
×
2157

×
2158
                if addrs[0].String() == addr {
×
2159
                        p2trOutputIndex = i
×
2160
                }
×
2161
        }
2162
        require.Greater(h, p2trOutputIndex, -1)
×
2163

×
2164
        return p2trOutputIndex
×
2165
}
2166

2167
// SendCoins sends a coin from node A to node B with the given amount, returns
2168
// the sending tx.
2169
func (h *HarnessTest) SendCoins(a, b *node.HarnessNode,
2170
        amt btcutil.Amount) *wire.MsgTx {
×
2171

×
2172
        // Create an address for Bob receive the coins.
×
2173
        req := &lnrpc.NewAddressRequest{
×
2174
                Type: lnrpc.AddressType_TAPROOT_PUBKEY,
×
2175
        }
×
2176
        resp := b.RPC.NewAddress(req)
×
2177

×
2178
        // Send the coins from Alice to Bob. We should expect a tx to be
×
2179
        // broadcast and seen in the mempool.
×
2180
        sendReq := &lnrpc.SendCoinsRequest{
×
2181
                Addr:       resp.Address,
×
2182
                Amount:     int64(amt),
×
2183
                TargetConf: 6,
×
2184
        }
×
2185
        a.RPC.SendCoins(sendReq)
×
2186
        tx := h.GetNumTxsFromMempool(1)[0]
×
2187

×
2188
        return tx
×
2189
}
×
2190

2191
// CreateSimpleNetwork creates the number of nodes specified by the number of
2192
// configs and makes a topology of `node1 -> node2 -> node3...`. Each node is
2193
// created using the specified config, the neighbors are connected, and the
2194
// channels are opened. Each node will be funded with a single UTXO of 1 BTC
2195
// except the last one.
2196
//
2197
// For instance, to create a network with 2 nodes that share the same node
2198
// config,
2199
//
2200
//        cfg := []string{"--protocol.anchors"}
2201
//        cfgs := [][]string{cfg, cfg}
2202
//        params := OpenChannelParams{...}
2203
//        chanPoints, nodes := ht.CreateSimpleNetwork(cfgs, params)
2204
//
2205
// This will create two nodes and open an anchor channel between them.
2206
func (h *HarnessTest) CreateSimpleNetwork(nodeCfgs [][]string,
2207
        p OpenChannelParams) ([]*lnrpc.ChannelPoint, []*node.HarnessNode) {
×
2208

×
2209
        // Create new nodes.
×
2210
        nodes := h.createNodes(nodeCfgs)
×
2211

×
2212
        var resp []*lnrpc.ChannelPoint
×
2213

×
2214
        // Open zero-conf channels if specified.
×
2215
        if p.ZeroConf {
×
2216
                resp = h.openZeroConfChannelsForNodes(nodes, p)
×
2217
        } else {
×
2218
                // Open channels between the nodes.
×
2219
                resp = h.openChannelsForNodes(nodes, p)
×
2220
        }
×
2221

2222
        return resp, nodes
×
2223
}
2224

2225
// acceptChannel is used to accept a single channel that comes across. This
2226
// should be run in a goroutine and is used to test nodes with the zero-conf
2227
// feature bit.
2228
func acceptChannel(t *testing.T, zeroConf bool, stream rpc.AcceptorClient) {
×
2229
        req, err := stream.Recv()
×
2230
        require.NoError(t, err)
×
2231

×
2232
        resp := &lnrpc.ChannelAcceptResponse{
×
2233
                Accept:        true,
×
2234
                PendingChanId: req.PendingChanId,
×
2235
                ZeroConf:      zeroConf,
×
2236
        }
×
2237
        err = stream.Send(resp)
×
2238
        require.NoError(t, err)
×
2239
}
×
2240

2241
// nodeNames defines a slice of human-reable names for the nodes created in the
2242
// `createNodes` method. 8 nodes are defined here as by default we can only
2243
// create this many nodes in one test.
2244
var nodeNames = []string{
2245
        "Alice", "Bob", "Carol", "Dave", "Eve", "Frank", "Grace", "Heidi",
2246
}
2247

2248
// createNodes creates the number of nodes specified by the number of configs.
2249
// Each node is created using the specified config, the neighbors are
2250
// connected.
2251
func (h *HarnessTest) createNodes(nodeCfgs [][]string) []*node.HarnessNode {
×
2252
        // Get the number of nodes.
×
2253
        numNodes := len(nodeCfgs)
×
2254

×
NEW
2255
        // Make sure we are creating a reasonable number of nodes.
×
NEW
2256
        require.LessOrEqual(h, numNodes, len(nodeNames), "too many nodes")
×
NEW
2257

×
2258
        // Make a slice of nodes.
×
2259
        nodes := make([]*node.HarnessNode, numNodes)
×
2260

×
2261
        // Create new nodes.
×
2262
        for i, nodeCfg := range nodeCfgs {
×
NEW
2263
                nodeName := nodeNames[i]
×
2264
                n := h.NewNode(nodeName, nodeCfg)
×
2265
                nodes[i] = n
×
2266
        }
×
2267

2268
        // Connect the nodes in a chain.
2269
        for i := 1; i < len(nodes); i++ {
×
2270
                nodeA := nodes[i-1]
×
2271
                nodeB := nodes[i]
×
2272
                h.EnsureConnected(nodeA, nodeB)
×
2273
        }
×
2274

2275
        // Fund all the nodes expect the last one.
2276
        for i := 0; i < len(nodes)-1; i++ {
×
2277
                node := nodes[i]
×
2278
                h.FundCoinsUnconfirmed(btcutil.SatoshiPerBitcoin, node)
×
2279
        }
×
2280

2281
        // Mine 1 block to get the above coins confirmed.
2282
        h.MineBlocksAndAssertNumTxes(1, numNodes-1)
×
2283

×
2284
        return nodes
×
2285
}
2286

2287
// openChannelsForNodes takes a list of nodes and makes a topology of `node1 ->
2288
// node2 -> node3...`.
2289
func (h *HarnessTest) openChannelsForNodes(nodes []*node.HarnessNode,
2290
        p OpenChannelParams) []*lnrpc.ChannelPoint {
×
2291

×
2292
        // Sanity check the params.
×
2293
        require.Greater(h, len(nodes), 1, "need at least 2 nodes")
×
2294

×
2295
        // attachFundingShim is a helper closure that optionally attaches a
×
2296
        // funding shim to the open channel params and returns it.
×
2297
        attachFundingShim := func(
×
2298
                nodeA, nodeB *node.HarnessNode) OpenChannelParams {
×
2299

×
2300
                // If this channel is not a script enforced lease channel,
×
2301
                // we'll do nothing and return the params.
×
2302
                leasedType := lnrpc.CommitmentType_SCRIPT_ENFORCED_LEASE
×
2303
                if p.CommitmentType != leasedType {
×
2304
                        return p
×
2305
                }
×
2306

2307
                // Otherwise derive the funding shim, attach it to the original
2308
                // open channel params and return it.
2309
                minerHeight := h.CurrentHeight()
×
2310
                thawHeight := minerHeight + thawHeightDelta
×
2311
                fundingShim, _ := h.DeriveFundingShim(
×
2312
                        nodeA, nodeB, p.Amt, thawHeight, true, leasedType,
×
2313
                )
×
2314

×
2315
                p.FundingShim = fundingShim
×
2316

×
2317
                return p
×
2318
        }
2319

2320
        // Open channels in batch to save blocks mined.
2321
        reqs := make([]*OpenChannelRequest, 0, len(nodes)-1)
×
2322
        for i := 0; i < len(nodes)-1; i++ {
×
2323
                nodeA := nodes[i]
×
2324
                nodeB := nodes[i+1]
×
2325

×
2326
                // Optionally attach a funding shim to the open channel params.
×
2327
                p = attachFundingShim(nodeA, nodeB)
×
2328

×
2329
                req := &OpenChannelRequest{
×
2330
                        Local:  nodeA,
×
2331
                        Remote: nodeB,
×
2332
                        Param:  p,
×
2333
                }
×
2334
                reqs = append(reqs, req)
×
2335
        }
×
2336
        resp := h.OpenMultiChannelsAsync(reqs)
×
2337

×
NEW
2338
        // If the channels are private, make sure the channel participants know
×
NEW
2339
        // the relevant channels.
×
NEW
2340
        if p.Private {
×
NEW
2341
                for i, chanPoint := range resp {
×
NEW
2342
                        // Get the channel participants - for n channels we
×
NEW
2343
                        // would have n+1 nodes.
×
NEW
2344
                        nodeA, nodeB := nodes[i], nodes[i+1]
×
NEW
2345
                        h.AssertChannelInGraph(nodeA, chanPoint)
×
NEW
2346
                        h.AssertChannelInGraph(nodeB, chanPoint)
×
NEW
2347
                }
×
NEW
2348
        } else {
×
NEW
2349
                // Make sure the all nodes know all the channels if they are
×
NEW
2350
                // public.
×
2351
                for _, node := range nodes {
×
2352
                        for _, chanPoint := range resp {
×
2353
                                h.AssertChannelInGraph(node, chanPoint)
×
2354
                        }
×
2355

2356
                        // Make sure every node has updated its cached graph
2357
                        // about the edges as indicated in `DescribeGraph`.
NEW
2358
                        h.AssertNumEdges(node, len(resp), false)
×
2359
                }
2360
        }
2361

2362
        return resp
×
2363
}
2364

2365
// openZeroConfChannelsForNodes takes a list of nodes and makes a topology of
2366
// `node1 -> node2 -> node3...` with zero-conf channels.
2367
func (h *HarnessTest) openZeroConfChannelsForNodes(nodes []*node.HarnessNode,
2368
        p OpenChannelParams) []*lnrpc.ChannelPoint {
×
2369

×
2370
        // Sanity check the params.
×
2371
        require.True(h, p.ZeroConf, "zero-conf channels must be enabled")
×
2372
        require.Greater(h, len(nodes), 1, "need at least 2 nodes")
×
2373

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

×
2377
        // Create the channel acceptors.
×
2378
        for _, node := range nodes[1:] {
×
2379
                acceptor, cancel := node.RPC.ChannelAcceptor()
×
2380
                go acceptChannel(h.T, true, acceptor)
×
2381

×
2382
                cancels = append(cancels, cancel)
×
2383
        }
×
2384

2385
        // Open channels between the nodes.
2386
        resp := h.openChannelsForNodes(nodes, p)
×
2387

×
2388
        for _, cancel := range cancels {
×
2389
                cancel()
×
2390
        }
×
2391

2392
        return resp
×
2393
}
2394

2395
// DeriveFundingShim creates a channel funding shim by deriving the necessary
2396
// keys on both sides.
2397
func (h *HarnessTest) DeriveFundingShim(alice, bob *node.HarnessNode,
2398
        chanSize btcutil.Amount, thawHeight uint32, publish bool,
2399
        commitType lnrpc.CommitmentType) (*lnrpc.FundingShim,
2400
        *lnrpc.ChannelPoint) {
×
2401

×
2402
        keyLoc := &signrpc.KeyLocator{KeyFamily: 9999}
×
2403
        carolFundingKey := alice.RPC.DeriveKey(keyLoc)
×
2404
        daveFundingKey := bob.RPC.DeriveKey(keyLoc)
×
2405

×
2406
        // Now that we have the multi-sig keys for each party, we can manually
×
2407
        // construct the funding transaction. We'll instruct the backend to
×
2408
        // immediately create and broadcast a transaction paying out an exact
×
2409
        // amount. Normally this would reside in the mempool, but we just
×
2410
        // confirm it now for simplicity.
×
2411
        var (
×
2412
                fundingOutput *wire.TxOut
×
2413
                musig2        bool
×
2414
                err           error
×
2415
        )
×
2416

×
2417
        if commitType == lnrpc.CommitmentType_SIMPLE_TAPROOT ||
×
2418
                commitType == lnrpc.CommitmentType_SIMPLE_TAPROOT_OVERLAY {
×
2419

×
2420
                var carolKey, daveKey *btcec.PublicKey
×
2421
                carolKey, err = btcec.ParsePubKey(carolFundingKey.RawKeyBytes)
×
2422
                require.NoError(h, err)
×
2423
                daveKey, err = btcec.ParsePubKey(daveFundingKey.RawKeyBytes)
×
2424
                require.NoError(h, err)
×
2425

×
2426
                _, fundingOutput, err = input.GenTaprootFundingScript(
×
2427
                        carolKey, daveKey, int64(chanSize),
×
2428
                        fn.None[chainhash.Hash](),
×
2429
                )
×
2430
                require.NoError(h, err)
×
2431

×
2432
                musig2 = true
×
2433
        } else {
×
2434
                _, fundingOutput, err = input.GenFundingPkScript(
×
2435
                        carolFundingKey.RawKeyBytes, daveFundingKey.RawKeyBytes,
×
2436
                        int64(chanSize),
×
2437
                )
×
2438
                require.NoError(h, err)
×
2439
        }
×
2440

2441
        var txid *chainhash.Hash
×
2442
        targetOutputs := []*wire.TxOut{fundingOutput}
×
2443
        if publish {
×
2444
                txid = h.SendOutputsWithoutChange(targetOutputs, 5)
×
2445
        } else {
×
2446
                tx := h.CreateTransaction(targetOutputs, 5)
×
2447

×
2448
                txHash := tx.TxHash()
×
2449
                txid = &txHash
×
2450
        }
×
2451

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

×
2457
        // Now that we have the pending channel ID, Dave (our responder) will
×
2458
        // register the intent to receive a new channel funding workflow using
×
2459
        // the pending channel ID.
×
2460
        chanPoint := &lnrpc.ChannelPoint{
×
2461
                FundingTxid: &lnrpc.ChannelPoint_FundingTxidBytes{
×
2462
                        FundingTxidBytes: txid[:],
×
2463
                },
×
2464
        }
×
2465
        chanPointShim := &lnrpc.ChanPointShim{
×
2466
                Amt:       int64(chanSize),
×
2467
                ChanPoint: chanPoint,
×
2468
                LocalKey: &lnrpc.KeyDescriptor{
×
2469
                        RawKeyBytes: daveFundingKey.RawKeyBytes,
×
2470
                        KeyLoc: &lnrpc.KeyLocator{
×
2471
                                KeyFamily: daveFundingKey.KeyLoc.KeyFamily,
×
2472
                                KeyIndex:  daveFundingKey.KeyLoc.KeyIndex,
×
2473
                        },
×
2474
                },
×
2475
                RemoteKey:     carolFundingKey.RawKeyBytes,
×
2476
                PendingChanId: pendingChanID,
×
2477
                ThawHeight:    thawHeight,
×
2478
                Musig2:        musig2,
×
2479
        }
×
2480
        fundingShim := &lnrpc.FundingShim{
×
2481
                Shim: &lnrpc.FundingShim_ChanPointShim{
×
2482
                        ChanPointShim: chanPointShim,
×
2483
                },
×
2484
        }
×
2485
        bob.RPC.FundingStateStep(&lnrpc.FundingTransitionMsg{
×
2486
                Trigger: &lnrpc.FundingTransitionMsg_ShimRegister{
×
2487
                        ShimRegister: fundingShim,
×
2488
                },
×
2489
        })
×
2490

×
2491
        // If we attempt to register the same shim (has the same pending chan
×
2492
        // ID), then we should get an error.
×
2493
        bob.RPC.FundingStateStepAssertErr(&lnrpc.FundingTransitionMsg{
×
2494
                Trigger: &lnrpc.FundingTransitionMsg_ShimRegister{
×
2495
                        ShimRegister: fundingShim,
×
2496
                },
×
2497
        })
×
2498

×
2499
        // We'll take the chan point shim we just registered for Dave (the
×
2500
        // responder), and swap the local/remote keys before we feed it in as
×
2501
        // Carol's funding shim as the initiator.
×
2502
        fundingShim.GetChanPointShim().LocalKey = &lnrpc.KeyDescriptor{
×
2503
                RawKeyBytes: carolFundingKey.RawKeyBytes,
×
2504
                KeyLoc: &lnrpc.KeyLocator{
×
2505
                        KeyFamily: carolFundingKey.KeyLoc.KeyFamily,
×
2506
                        KeyIndex:  carolFundingKey.KeyLoc.KeyIndex,
×
2507
                },
×
2508
        }
×
2509
        fundingShim.GetChanPointShim().RemoteKey = daveFundingKey.RawKeyBytes
×
2510

×
2511
        return fundingShim, chanPoint
×
2512
}
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