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

lightningnetwork / lnd / 13974489001

20 Mar 2025 04:32PM UTC coverage: 56.292% (-2.9%) from 59.168%
13974489001

Pull #8754

github

web-flow
Merge aed149e6b into ea050d06f
Pull Request #8754: Add `Outbound` Remote Signer implementation

594 of 1713 new or added lines in 26 files covered. (34.68%)

23052 existing lines in 272 files now uncovered.

105921 of 188165 relevant lines covered (56.29%)

23796.34 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
var (
63
        // MaxBlocksMinedPerTest is the maximum number of blocks that we allow
64
        // a test to mine. This is an exported global variable so it can be
65
        // overwritten by other projects that don't have the same constraints.
66
        MaxBlocksMinedPerTest = 50
67
)
68

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
148
        t.Helper()
×
149

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

278
        h.shutdownAllNodes()
×
279

×
280
        close(h.lndErrorChan)
×
281

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

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

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

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

304
        testCase.TestFunc(h)
×
305
}
306

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

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

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

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

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

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

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

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

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

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

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

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

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

372
        return st
×
373
}
374

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
503
        return node
×
504
}
×
505

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

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

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

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

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

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

×
534
        return node
×
535
}
536

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

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

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

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

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

×
561
                return nil
×
562
        }
563
}
564

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
702
        return n
×
703
}
×
704

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

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

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

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

×
727
        return node
×
728
}
×
729

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

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

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

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

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

754
// NewNodeWatchOnly creates a new watch-only node and asserts its
755
// creation.
756
func (h *HarnessTest) NewNodeWatchOnly(name string, extraArgs []string,
757
        password []byte, watchOnly *lnrpc.WatchOnly) *node.HarnessNode {
×
758

×
NEW
759
        hn := h.CreateNewNode(name, extraArgs, password, true)
×
NEW
760

×
NEW
761
        h.StartWatchOnly(hn, name, password, watchOnly)
×
NEW
762

×
NEW
763
        return hn
×
NEW
764
}
×
765

766
// CreateNodeWatchOnly creates a new node and asserts its creation. The function
767
// will only create the node and will not start it.
768
func (h *HarnessTest) CreateNewNode(name string, extraArgs []string,
NEW
769
        password []byte, noAuth bool) *node.HarnessNode {
×
NEW
770

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

×
NEW
774
        return hn
×
NEW
775
}
×
776

777
// StartWatchOnly starts the passed node in watch-only mode. The function will
778
// assert that the node is started and that the initialization is successful.
779
func (h *HarnessTest) StartWatchOnly(hn *node.HarnessNode, name string,
NEW
780
        password []byte, watchOnly *lnrpc.WatchOnly) {
×
NEW
781

×
NEW
782
        err := hn.StartWithNoAuth(h.runCtx)
×
783
        require.NoError(h, err, "failed to start node %s", name)
×
784

×
785
        // With the seed created, construct the init request to the node,
×
786
        // including the newly generated seed.
×
787
        initReq := &lnrpc.InitWalletRequest{
×
788
                WalletPassword: password,
×
789
                WatchOnly:      watchOnly,
×
790
        }
×
791

×
792
        // Pass the init request via rpc to finish unlocking the node. This
×
793
        // will also initialize the macaroon-authenticated LightningClient.
×
794
        _, err = h.manager.initWalletAndNode(hn, initReq)
×
795
        require.NoErrorf(h, err, "failed to init node %s", name)
×
796
}
×
797

798
// KillNode kills the node and waits for the node process to stop.
799
func (h *HarnessTest) KillNode(hn *node.HarnessNode) {
×
800
        delete(h.manager.activeNodes, hn.Cfg.NodeID)
×
801

×
802
        h.Logf("Manually killing the node %s", hn.Name())
×
803
        require.NoErrorf(h, hn.KillAndWait(), "%s: kill got error", hn.Name())
×
804
}
×
805

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

816
// SetFeeEstimateWithConf sets a fee rate of a specified conf target to be
817
// returned from fee estimator.
818
func (h *HarnessTest) SetFeeEstimateWithConf(
819
        fee chainfee.SatPerKWeight, conf uint32) {
×
820

×
821
        h.feeService.SetFeeRate(fee, conf)
×
822
}
×
823

824
// SetMinRelayFeerate sets a min relay fee rate to be returned from fee
825
// estimator.
826
func (h *HarnessTest) SetMinRelayFeerate(fee chainfee.SatPerKVByte) {
×
827
        h.feeService.SetMinRelayFeerate(fee)
×
828
}
×
829

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

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

857
        // The number of waiting close channels should be zero.
858
        if hn.State.CloseChannel.WaitingClose != 0 {
×
859
                return errStr("waiting close")
×
860
        }
×
861

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

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

874
        // The number of edges should be zero.
875
        if hn.State.Edge.Total != 0 {
×
876
                return fmt.Errorf("%s: found active edges, please "+
×
877
                        "clean them properly", hn.Name())
×
878
        }
×
879

880
        return nil
×
881
}
882

883
// GetChanPointFundingTxid takes a channel point and converts it into a chain
884
// hash.
885
func (h *HarnessTest) GetChanPointFundingTxid(
886
        cp *lnrpc.ChannelPoint) chainhash.Hash {
×
887

×
888
        txid, err := lnrpc.GetChanPointFundingTxid(cp)
×
889
        require.NoError(h, err, "unable to get txid")
×
890

×
891
        return *txid
×
892
}
×
893

894
// OutPointFromChannelPoint creates an outpoint from a given channel point.
895
func (h *HarnessTest) OutPointFromChannelPoint(
896
        cp *lnrpc.ChannelPoint) wire.OutPoint {
×
897

×
898
        txid := h.GetChanPointFundingTxid(cp)
×
899
        return wire.OutPoint{
×
900
                Hash:  txid,
×
901
                Index: cp.OutputIndex,
×
902
        }
×
903
}
×
904

905
// OpenChannelParams houses the params to specify when opening a new channel.
906
type OpenChannelParams struct {
907
        // Amt is the local amount being put into the channel.
908
        Amt btcutil.Amount
909

910
        // PushAmt is the amount that should be pushed to the remote when the
911
        // channel is opened.
912
        PushAmt btcutil.Amount
913

914
        // Private is a boolan indicating whether the opened channel should be
915
        // private.
916
        Private bool
917

918
        // SpendUnconfirmed is a boolean indicating whether we can utilize
919
        // unconfirmed outputs to fund the channel.
920
        SpendUnconfirmed bool
921

922
        // MinHtlc is the htlc_minimum_msat value set when opening the channel.
923
        MinHtlc lnwire.MilliSatoshi
924

925
        // RemoteMaxHtlcs is the remote_max_htlcs value set when opening the
926
        // channel, restricting the number of concurrent HTLCs the remote party
927
        // can add to a commitment.
928
        RemoteMaxHtlcs uint16
929

930
        // FundingShim is an optional funding shim that the caller can specify
931
        // in order to modify the channel funding workflow.
932
        FundingShim *lnrpc.FundingShim
933

934
        // SatPerVByte is the amount of satoshis to spend in chain fees per
935
        // virtual byte of the transaction.
936
        SatPerVByte btcutil.Amount
937

938
        // ConfTarget is the number of blocks that the funding transaction
939
        // should be confirmed in.
940
        ConfTarget fn.Option[int32]
941

942
        // CommitmentType is the commitment type that should be used for the
943
        // channel to be opened.
944
        CommitmentType lnrpc.CommitmentType
945

946
        // ZeroConf is used to determine if the channel will be a zero-conf
947
        // channel. This only works if the explicit negotiation is used with
948
        // anchors or script enforced leases.
949
        ZeroConf bool
950

951
        // ScidAlias denotes whether the channel will be an option-scid-alias
952
        // channel type negotiation.
953
        ScidAlias bool
954

955
        // BaseFee is the channel base fee applied during the channel
956
        // announcement phase.
957
        BaseFee uint64
958

959
        // FeeRate is the channel fee rate in ppm applied during the channel
960
        // announcement phase.
961
        FeeRate uint64
962

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

969
        // UseFeeRate, if set, instructs the downstream logic to apply the
970
        // user-specified channel fee rate to the channel update announcement.
971
        // If set to false it avoids applying a fee rate of 0 and instead
972
        // activates the default configured fee rate.
973
        UseFeeRate bool
974

975
        // FundMax is a boolean indicating whether the channel should be funded
976
        // with the maximum possible amount from the wallet.
977
        FundMax bool
978

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

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

992
        // CloseAddress sets the upfront_shutdown_script parameter during
993
        // channel open. It is expected to be encoded as a bitcoin address.
994
        CloseAddress string
995
}
996

997
// prepareOpenChannel waits for both nodes to be synced to chain and returns an
998
// OpenChannelRequest.
999
func (h *HarnessTest) prepareOpenChannel(srcNode, destNode *node.HarnessNode,
1000
        p OpenChannelParams) *lnrpc.OpenChannelRequest {
×
1001

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

×
1009
        // Specify the minimal confirmations of the UTXOs used for channel
×
1010
        // funding.
×
1011
        minConfs := int32(1)
×
1012
        if p.SpendUnconfirmed {
×
1013
                minConfs = 0
×
1014
        }
×
1015

1016
        // Get the requested conf target. If not set, default to 6.
1017
        confTarget := p.ConfTarget.UnwrapOr(6)
×
1018

×
1019
        // If there's fee rate set, unset the conf target.
×
1020
        if p.SatPerVByte != 0 {
×
1021
                confTarget = 0
×
1022
        }
×
1023

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

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

×
1059
        // Prepare the request and open the channel.
×
1060
        openReq := h.prepareOpenChannel(srcNode, destNode, p)
×
1061
        respStream := srcNode.RPC.OpenChannel(openReq)
×
1062

×
1063
        // Consume the "channel pending" update. This waits until the node
×
1064
        // notifies us that the final message in the channel funding workflow
×
1065
        // has been sent to the remote node.
×
1066
        resp := h.ReceiveOpenChannelUpdate(respStream)
×
1067

×
1068
        // Check that the update is channel pending.
×
1069
        update, ok := resp.Update.(*lnrpc.OpenStatusUpdate_ChanPending)
×
1070
        require.Truef(h, ok, "expected channel pending: update, instead got %v",
×
1071
                resp)
×
1072

×
1073
        return update.ChanPending, respStream
×
1074
}
×
1075

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

×
1084
        resp, _ := h.openChannelAssertPending(srcNode, destNode, p)
×
1085
        return resp
×
1086
}
×
1087

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

×
1096
        _, stream := h.openChannelAssertPending(srcNode, destNode, p)
×
1097
        return stream
×
1098
}
×
1099

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

×
1112
        // First, open the channel without announcing it.
×
1113
        cp := h.OpenChannelNoAnnounce(alice, bob, p)
×
1114

×
1115
        // If this is a private channel, there's no need to mine extra blocks
×
1116
        // since it will never be announced to the network.
×
1117
        if p.Private {
×
1118
                return cp
×
1119
        }
×
1120

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

1134
        return cp
×
1135
}
1136

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

×
1147
        chanOpenUpdate := h.OpenChannelAssertStream(alice, bob, p)
×
1148

×
1149
        // Open a zero conf channel.
×
1150
        if p.ZeroConf {
×
1151
                return h.openChannelZeroConf(alice, bob, chanOpenUpdate)
×
1152
        }
×
1153

1154
        // Open a non-zero conf channel.
1155
        return h.openChannel(alice, bob, chanOpenUpdate)
×
1156
}
1157

1158
// openChannel attempts to open a channel with the specified parameters
1159
// extended from Alice to Bob. Additionally, the following items are asserted,
1160
//   - 1 block is mined and the funding transaction should be found in it.
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) openChannel(alice, bob *node.HarnessNode,
1164
        stream rpc.OpenChanClient) *lnrpc.ChannelPoint {
×
1165

×
1166
        // Mine 1 block to confirm the funding transaction.
×
1167
        block := h.MineBlocksAndAssertNumTxes(1, 1)[0]
×
1168

×
1169
        // Wait for the channel open event.
×
1170
        fundingChanPoint := h.WaitForChannelOpenEvent(stream)
×
1171

×
1172
        // Check that the funding tx is found in the first block.
×
1173
        fundingTxID := h.GetChanPointFundingTxid(fundingChanPoint)
×
1174
        h.AssertTxInBlock(block, fundingTxID)
×
1175

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

×
1181
        // Check that the channel can be seen in their ListChannels.
×
1182
        h.AssertChannelExists(alice, fundingChanPoint)
×
1183
        h.AssertChannelExists(bob, fundingChanPoint)
×
1184

×
1185
        return fundingChanPoint
×
1186
}
×
1187

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

×
1195
        // Wait for the channel open event.
×
1196
        fundingChanPoint := h.WaitForChannelOpenEvent(stream)
×
1197

×
1198
        // Check that both alice and bob have seen the channel from their
×
1199
        // network topology.
×
1200
        h.AssertChannelInGraph(alice, fundingChanPoint)
×
1201
        h.AssertChannelInGraph(bob, fundingChanPoint)
×
1202

×
1203
        // Finally, check that the channel can be seen in their ListChannels.
×
1204
        h.AssertChannelExists(alice, fundingChanPoint)
×
1205
        h.AssertChannelExists(bob, fundingChanPoint)
×
1206

×
1207
        return fundingChanPoint
×
1208
}
×
1209

1210
// OpenChannelAssertErr opens a channel between node srcNode and destNode,
1211
// asserts that the expected error is returned from the channel opening.
1212
func (h *HarnessTest) OpenChannelAssertErr(srcNode, destNode *node.HarnessNode,
1213
        p OpenChannelParams, expectedErr error) {
×
1214

×
1215
        // Prepare the request and open the channel.
×
1216
        openReq := h.prepareOpenChannel(srcNode, destNode, p)
×
1217
        respStream := srcNode.RPC.OpenChannel(openReq)
×
1218

×
1219
        // Receive an error to be sent from the stream.
×
1220
        _, err := h.receiveOpenChannelUpdate(respStream)
×
1221
        require.NotNil(h, err, "expected channel opening to fail")
×
1222

×
1223
        // Use string comparison here as we haven't codified all the RPC errors
×
1224
        // yet.
×
1225
        require.Containsf(h, err.Error(), expectedErr.Error(), "unexpected "+
×
1226
                "error returned, want %v, got %v", expectedErr, err)
×
1227
}
×
1228

1229
// closeChannelOpts holds the options for closing a channel.
1230
type closeChannelOpts struct {
1231
        feeRate fn.Option[chainfee.SatPerVByte]
1232

1233
        // localTxOnly is a boolean indicating if we should only attempt to
1234
        // consume close pending notifications for the local transaction.
1235
        localTxOnly bool
1236

1237
        // skipMempoolCheck is a boolean indicating if we should skip the normal
1238
        // mempool check after a coop close.
1239
        skipMempoolCheck bool
1240

1241
        // errString is an expected error. If this is non-blank, then we'll
1242
        // assert that the coop close wasn't possible, and returns an error that
1243
        // contains this err string.
1244
        errString string
1245
}
1246

1247
// CloseChanOpt is a functional option to modify the way we close a channel.
1248
type CloseChanOpt func(*closeChannelOpts)
1249

1250
// WithCoopCloseFeeRate is a functional option to set the fee rate for a coop
1251
// close attempt.
1252
func WithCoopCloseFeeRate(rate chainfee.SatPerVByte) CloseChanOpt {
×
1253
        return func(o *closeChannelOpts) {
×
1254
                o.feeRate = fn.Some(rate)
×
1255
        }
×
1256
}
1257

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

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

1276
// WithExpectedErrString is a functional option that can be used to assert that
1277
// an error occurs during the coop close process.
1278
func WithExpectedErrString(errString string) CloseChanOpt {
×
1279
        return func(o *closeChannelOpts) {
×
1280
                o.errString = errString
×
1281
        }
×
1282
}
1283

1284
// defaultCloseOpts returns the set of default close options.
1285
func defaultCloseOpts() *closeChannelOpts {
×
1286
        return &closeChannelOpts{}
×
1287
}
×
1288

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

×
1298
        closeOpts := defaultCloseOpts()
×
1299
        for _, optFunc := range opts {
×
1300
                optFunc(closeOpts)
×
1301
        }
×
1302

1303
        // Calls the rpc to close the channel.
1304
        closeReq := &lnrpc.CloseChannelRequest{
×
1305
                ChannelPoint: cp,
×
1306
                Force:        force,
×
1307
                NoWait:       true,
×
1308
        }
×
1309

×
1310
        closeOpts.feeRate.WhenSome(func(feeRate chainfee.SatPerVByte) {
×
1311
                closeReq.SatPerVbyte = uint64(feeRate)
×
1312
        })
×
1313

1314
        var (
×
1315
                stream rpc.CloseChanClient
×
1316
                event  *lnrpc.CloseStatusUpdate
×
1317
                err    error
×
1318
        )
×
1319

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

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

1341
                pendingClose, ok := event.Update.(*lnrpc.CloseStatusUpdate_ClosePending) //nolint:ll
×
1342
                require.Truef(h, ok, "expected channel close "+
×
1343
                        "update, instead got %v", pendingClose)
×
1344

×
1345
                if !pendingClose.ClosePending.LocalCloseTx &&
×
1346
                        closeOpts.localTxOnly {
×
1347

×
1348
                        continue
×
1349
                }
1350

1351
                notifyRate := pendingClose.ClosePending.FeePerVbyte
×
1352
                if closeOpts.localTxOnly &&
×
1353
                        notifyRate != int64(closeReq.SatPerVbyte) {
×
1354

×
1355
                        continue
×
1356
                }
1357

1358
                closeTxid, err = chainhash.NewHash(
×
1359
                        pendingClose.ClosePending.Txid,
×
1360
                )
×
1361
                require.NoErrorf(h, err, "unable to decode closeTxid: %v",
×
1362
                        pendingClose.ClosePending.Txid)
×
1363

×
1364
                break
×
1365
        }
1366

1367
        if !closeOpts.skipMempoolCheck {
×
1368
                // Assert the closing tx is in the mempool.
×
1369
                h.miner.AssertTxInMempool(*closeTxid)
×
1370
        }
×
1371

1372
        return stream, event
×
1373
}
1374

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

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

×
1389
        return h.AssertStreamChannelCoopClosed(hn, cp, false, stream)
×
1390
}
×
1391

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

×
1406
        stream, _ := h.CloseChannelAssertPending(hn, cp, true)
×
1407

×
1408
        closingTxid := h.AssertStreamChannelForceClosed(hn, cp, false, stream)
×
1409

×
1410
        // Cleanup the force close.
×
1411
        h.CleanupForceClose(hn)
×
1412

×
1413
        return closingTxid
×
1414
}
×
1415

1416
// CloseChannelAssertErr closes the given channel and asserts an error
1417
// returned.
1418
func (h *HarnessTest) CloseChannelAssertErr(hn *node.HarnessNode,
1419
        req *lnrpc.CloseChannelRequest) error {
×
1420

×
1421
        // Calls the rpc to close the channel.
×
1422
        stream := hn.RPC.CloseChannel(req)
×
1423

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

×
1431
        return err
×
1432
}
×
1433

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

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

×
1448
        initialBalance := target.RPC.WalletBalance()
×
1449

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

×
1458
        // Generate a transaction which creates an output to the target
×
1459
        // pkScript of the desired amount.
×
1460
        output := &wire.TxOut{
×
1461
                PkScript: addrScript,
×
1462
                Value:    int64(amt),
×
1463
        }
×
1464
        h.miner.SendOutput(output, defaultMinerFeeRate)
×
1465

×
1466
        // Encode the pkScript in hex as this the format that it will be
×
1467
        // returned via rpc.
×
1468
        expPkScriptStr := hex.EncodeToString(addrScript)
×
1469

×
1470
        // Now, wait for ListUnspent to show the unconfirmed transaction
×
1471
        // containing the correct pkscript.
×
1472
        //
×
1473
        // Since neutrino doesn't support unconfirmed outputs, skip this check.
×
1474
        if !h.IsNeutrinoBackend() {
×
1475
                utxos := h.AssertNumUTXOsUnconfirmed(target, 1)
×
1476

×
1477
                // Assert that the lone unconfirmed utxo contains the same
×
1478
                // pkscript as the output generated above.
×
1479
                pkScriptStr := utxos[0].PkScript
×
1480
                require.Equal(h, pkScriptStr, expPkScriptStr,
×
1481
                        "pkscript mismatch")
×
1482

×
1483
                expectedBalance := btcutil.Amount(
×
1484
                        initialBalance.UnconfirmedBalance,
×
1485
                ) + amt
×
1486
                h.WaitForBalanceUnconfirmed(target, expectedBalance)
×
1487
        }
×
1488

1489
        // If the transaction should remain unconfirmed, then we'll wait until
1490
        // the target node's unconfirmed balance reflects the expected balance
1491
        // and exit.
1492
        if !confirmed {
×
1493
                return
×
1494
        }
×
1495

1496
        // Otherwise, we'll generate 1 new blocks to ensure the output gains a
1497
        // sufficient number of confirmations and wait for the balance to
1498
        // reflect what's expected.
1499
        h.MineBlocksAndAssertNumTxes(1, 1)
×
1500

×
1501
        expectedBalance := btcutil.Amount(initialBalance.ConfirmedBalance) + amt
×
1502
        h.WaitForBalanceConfirmed(target, expectedBalance)
×
1503
}
1504

1505
// FundCoins attempts to send amt satoshis from the internal mining node to the
1506
// targeted lightning node using a P2WKH address. 1 blocks are mined after in
1507
// order to confirm the transaction.
1508
func (h *HarnessTest) FundCoins(amt btcutil.Amount, hn *node.HarnessNode) {
×
1509
        h.fundCoins(amt, hn, lnrpc.AddressType_WITNESS_PUBKEY_HASH, true)
×
1510
}
×
1511

1512
// FundCoinsUnconfirmed attempts to send amt satoshis from the internal mining
1513
// node to the targeted lightning node using a P2WKH address. No blocks are
1514
// mined after and the UTXOs are unconfirmed.
1515
func (h *HarnessTest) FundCoinsUnconfirmed(amt btcutil.Amount,
1516
        hn *node.HarnessNode) {
×
1517

×
1518
        h.fundCoins(amt, hn, lnrpc.AddressType_WITNESS_PUBKEY_HASH, false)
×
1519
}
×
1520

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

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

1529
// FundCoinsP2TR attempts to send amt satoshis from the internal mining node to
1530
// the targeted lightning node using a P2TR address.
1531
func (h *HarnessTest) FundCoinsP2TR(amt btcutil.Amount,
1532
        target *node.HarnessNode) {
×
1533

×
1534
        h.fundCoins(amt, target, lnrpc.AddressType_TAPROOT_PUBKEY, true)
×
1535
}
×
1536

1537
// FundNumCoins attempts to send the given number of UTXOs from the internal
1538
// mining node to the targeted lightning node using a P2WKH address. Each UTXO
1539
// has an amount of 1 BTC. 1 blocks are mined to confirm the tx.
1540
func (h *HarnessTest) FundNumCoins(hn *node.HarnessNode, num int) {
×
1541
        // Get the initial balance first.
×
1542
        resp := hn.RPC.WalletBalance()
×
1543
        initialBalance := btcutil.Amount(resp.ConfirmedBalance)
×
1544

×
1545
        const fundAmount = 1 * btcutil.SatoshiPerBitcoin
×
1546

×
1547
        // Send out the outputs from the miner.
×
1548
        for i := 0; i < num; i++ {
×
1549
                h.createAndSendOutput(
×
1550
                        hn, fundAmount, lnrpc.AddressType_WITNESS_PUBKEY_HASH,
×
1551
                )
×
1552
        }
×
1553

1554
        // Wait for ListUnspent to show the correct number of unconfirmed
1555
        // UTXOs.
1556
        //
1557
        // Since neutrino doesn't support unconfirmed outputs, skip this check.
1558
        if !h.IsNeutrinoBackend() {
×
1559
                h.AssertNumUTXOsUnconfirmed(hn, num)
×
1560
        }
×
1561

1562
        // Mine a block to confirm the transactions.
1563
        h.MineBlocksAndAssertNumTxes(1, num)
×
1564

×
1565
        // Now block until the wallet have fully synced up.
×
1566
        totalAmount := btcutil.Amount(fundAmount * num)
×
1567
        expectedBalance := initialBalance + totalAmount
×
1568
        h.WaitForBalanceConfirmed(hn, expectedBalance)
×
1569
}
1570

1571
// completePaymentRequestsAssertStatus sends payments from a node to complete
1572
// all payment requests. This function does not return until all payments
1573
// have reached the specified status.
1574
func (h *HarnessTest) completePaymentRequestsAssertStatus(hn *node.HarnessNode,
1575
        paymentRequests []string, status lnrpc.Payment_PaymentStatus,
1576
        opts ...HarnessOpt) {
×
1577

×
1578
        payOpts := defaultHarnessOpts()
×
1579
        for _, opt := range opts {
×
1580
                opt(&payOpts)
×
1581
        }
×
1582

1583
        // Create a buffered chan to signal the results.
1584
        results := make(chan rpc.PaymentClient, len(paymentRequests))
×
1585

×
1586
        // send sends a payment and asserts if it doesn't succeeded.
×
1587
        send := func(payReq string) {
×
1588
                req := &routerrpc.SendPaymentRequest{
×
1589
                        PaymentRequest: payReq,
×
1590
                        TimeoutSeconds: int32(wait.PaymentTimeout.Seconds()),
×
1591
                        FeeLimitMsat:   noFeeLimitMsat,
×
1592
                        Amp:            payOpts.useAMP,
×
1593
                }
×
1594
                stream := hn.RPC.SendPayment(req)
×
1595

×
1596
                // Signal sent succeeded.
×
1597
                results <- stream
×
1598
        }
×
1599

1600
        // Launch all payments simultaneously.
1601
        for _, payReq := range paymentRequests {
×
1602
                payReqCopy := payReq
×
1603
                go send(payReqCopy)
×
1604
        }
×
1605

1606
        // Wait for all payments to report the expected status.
1607
        timer := time.After(wait.PaymentTimeout)
×
1608
        select {
×
1609
        case stream := <-results:
×
1610
                h.AssertPaymentStatusFromStream(stream, status)
×
1611

1612
        case <-timer:
×
1613
                require.Fail(h, "timeout", "waiting payment results timeout")
×
1614
        }
1615
}
1616

1617
// CompletePaymentRequests sends payments from a node to complete all payment
1618
// requests. This function does not return until all payments successfully
1619
// complete without errors.
1620
func (h *HarnessTest) CompletePaymentRequests(hn *node.HarnessNode,
1621
        paymentRequests []string, opts ...HarnessOpt) {
×
1622

×
1623
        h.completePaymentRequestsAssertStatus(
×
1624
                hn, paymentRequests, lnrpc.Payment_SUCCEEDED, opts...,
×
1625
        )
×
1626
}
×
1627

1628
// CompletePaymentRequestsNoWait sends payments from a node to complete all
1629
// payment requests without waiting for the results. Instead, it checks the
1630
// number of updates in the specified channel has increased.
1631
func (h *HarnessTest) CompletePaymentRequestsNoWait(hn *node.HarnessNode,
1632
        paymentRequests []string, chanPoint *lnrpc.ChannelPoint) {
×
1633

×
1634
        // We start by getting the current state of the client's channels. This
×
1635
        // is needed to ensure the payments actually have been committed before
×
1636
        // we return.
×
1637
        oldResp := h.GetChannelByChanPoint(hn, chanPoint)
×
1638

×
1639
        // Send payments and assert they are in-flight.
×
1640
        h.completePaymentRequestsAssertStatus(
×
1641
                hn, paymentRequests, lnrpc.Payment_IN_FLIGHT,
×
1642
        )
×
1643

×
1644
        // We are not waiting for feedback in the form of a response, but we
×
1645
        // should still wait long enough for the server to receive and handle
×
1646
        // the send before cancelling the request. We wait for the number of
×
1647
        // updates to one of our channels has increased before we return.
×
1648
        err := wait.NoError(func() error {
×
1649
                newResp := h.GetChannelByChanPoint(hn, chanPoint)
×
1650

×
1651
                // If this channel has an increased number of updates, we
×
1652
                // assume the payments are committed, and we can return.
×
1653
                if newResp.NumUpdates > oldResp.NumUpdates {
×
1654
                        return nil
×
1655
                }
×
1656

1657
                // Otherwise return an error as the NumUpdates are not
1658
                // increased.
1659
                return fmt.Errorf("%s: channel:%v not updated after sending "+
×
1660
                        "payments, old updates: %v, new updates: %v", hn.Name(),
×
1661
                        chanPoint, oldResp.NumUpdates, newResp.NumUpdates)
×
1662
        }, DefaultTimeout)
1663
        require.NoError(h, err, "timeout while checking for channel updates")
×
1664
}
1665

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

×
1672
        // Wait until srcNode and destNode have the latest chain synced.
×
1673
        // Otherwise, we may run into a check within the funding manager that
×
1674
        // prevents any funding workflows from being kicked off if the chain
×
1675
        // isn't yet synced.
×
1676
        h.WaitForBlockchainSync(srcNode)
×
1677
        h.WaitForBlockchainSync(destNode)
×
1678

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

×
1695
        // Consume the "PSBT funding ready" update. This waits until the node
×
1696
        // notifies us that the PSBT can now be funded.
×
1697
        resp := h.ReceiveOpenChannelUpdate(respStream)
×
1698
        upd, ok := resp.Update.(*lnrpc.OpenStatusUpdate_PsbtFund)
×
1699
        require.Truef(h, ok, "expected PSBT funding update, got %v", resp)
×
1700

×
1701
        // Make sure the channel funding address has the correct type for the
×
1702
        // given commitment type.
×
1703
        fundingAddr, err := btcutil.DecodeAddress(
×
1704
                upd.PsbtFund.FundingAddress, miner.HarnessNetParams,
×
1705
        )
×
1706
        require.NoError(h, err)
×
1707

×
1708
        switch p.CommitmentType {
×
1709
        case lnrpc.CommitmentType_SIMPLE_TAPROOT:
×
1710
                require.IsType(h, &btcutil.AddressTaproot{}, fundingAddr)
×
1711

1712
        default:
×
1713
                require.IsType(
×
1714
                        h, &btcutil.AddressWitnessScriptHash{}, fundingAddr,
×
1715
                )
×
1716
        }
1717

1718
        return respStream, upd.PsbtFund.Psbt
×
1719
}
1720

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

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

×
1738
        // Assert there is one pending sweep.
×
1739
        h.AssertNumPendingSweeps(hn, 1)
×
1740

×
1741
        // The node should now sweep the funds, clean up by mining the sweeping
×
1742
        // tx.
×
1743
        h.MineBlocksAndAssertNumTxes(1, 1)
×
1744

×
1745
        // Mine blocks to get any second level HTLC resolved. If there are no
×
1746
        // HTLCs, this will behave like h.AssertNumPendingCloseChannels.
×
1747
        h.mineTillForceCloseResolved(hn)
×
1748
}
×
1749

1750
// CreatePayReqs is a helper method that will create a slice of payment
1751
// requests for the given node.
1752
func (h *HarnessTest) CreatePayReqs(hn *node.HarnessNode,
1753
        paymentAmt btcutil.Amount, numInvoices int,
1754
        routeHints ...*lnrpc.RouteHint) ([]string, [][]byte, []*lnrpc.Invoice) {
×
1755

×
1756
        payReqs := make([]string, numInvoices)
×
1757
        rHashes := make([][]byte, numInvoices)
×
1758
        invoices := make([]*lnrpc.Invoice, numInvoices)
×
1759
        for i := 0; i < numInvoices; i++ {
×
1760
                preimage := h.Random32Bytes()
×
1761

×
1762
                invoice := &lnrpc.Invoice{
×
1763
                        Memo:       "testing",
×
1764
                        RPreimage:  preimage,
×
1765
                        Value:      int64(paymentAmt),
×
1766
                        RouteHints: routeHints,
×
1767
                }
×
1768
                resp := hn.RPC.AddInvoice(invoice)
×
1769

×
1770
                // Set the payment address in the invoice so the caller can
×
1771
                // properly use it.
×
1772
                invoice.PaymentAddr = resp.PaymentAddr
×
1773

×
1774
                payReqs[i] = resp.PaymentRequest
×
1775
                rHashes[i] = resp.RHash
×
1776
                invoices[i] = invoice
×
1777
        }
×
1778

1779
        return payReqs, rHashes, invoices
×
1780
}
1781

1782
// BackupDB creates a backup of the current database. It will stop the node
1783
// first, copy the database files, and restart the node.
1784
func (h *HarnessTest) BackupDB(hn *node.HarnessNode) {
×
1785
        restart := h.SuspendNode(hn)
×
1786

×
1787
        err := hn.BackupDB()
×
1788
        require.NoErrorf(h, err, "%s: failed to backup db", hn.Name())
×
1789

×
1790
        err = restart()
×
1791
        require.NoErrorf(h, err, "%s: failed to restart", hn.Name())
×
1792
}
×
1793

1794
// RestartNodeAndRestoreDB restarts a given node with a callback to restore the
1795
// db.
1796
func (h *HarnessTest) RestartNodeAndRestoreDB(hn *node.HarnessNode) {
×
1797
        cb := func() error { return hn.RestoreDB() }
×
1798
        err := h.manager.restartNode(h.runCtx, hn, cb)
×
1799
        require.NoErrorf(h, err, "failed to restart node %s", hn.Name())
×
1800

×
1801
        err = h.manager.unlockNode(hn)
×
1802
        require.NoErrorf(h, err, "failed to unlock node %s", hn.Name())
×
1803

×
1804
        // Give the node some time to catch up with the chain before we
×
1805
        // continue with the tests.
×
1806
        h.WaitForBlockchainSync(hn)
×
1807
}
1808

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

×
1820
        // Now mine blocks till the mempool is empty.
×
1821
        h.cleanMempool()
×
1822
}
×
1823

1824
// QueryChannelByChanPoint tries to find a channel matching the channel point
1825
// and asserts. It returns the channel found.
1826
func (h *HarnessTest) QueryChannelByChanPoint(hn *node.HarnessNode,
1827
        chanPoint *lnrpc.ChannelPoint,
1828
        opts ...ListChannelOption) *lnrpc.Channel {
×
1829

×
1830
        channel, err := h.findChannel(hn, chanPoint, opts...)
×
1831
        require.NoError(h, err, "failed to query channel")
×
1832

×
1833
        return channel
×
1834
}
×
1835

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

×
1842
        stream := hn.RPC.SendPayment(req)
×
1843
        return h.AssertPaymentStatusFromStream(stream, status)
×
1844
}
×
1845

1846
// SendPaymentAssertFail sends a payment from the passed node and asserts the
1847
// payment is failed with the specified failure reason .
1848
func (h *HarnessTest) SendPaymentAssertFail(hn *node.HarnessNode,
1849
        req *routerrpc.SendPaymentRequest,
1850
        reason lnrpc.PaymentFailureReason) *lnrpc.Payment {
×
1851

×
1852
        payment := h.SendPaymentAndAssertStatus(hn, req, lnrpc.Payment_FAILED)
×
1853
        require.Equal(h, reason, payment.FailureReason,
×
1854
                "payment failureReason not matched")
×
1855

×
1856
        return payment
×
1857
}
×
1858

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

×
1864
        return h.SendPaymentAndAssertStatus(hn, req, lnrpc.Payment_SUCCEEDED)
×
1865
}
×
1866

1867
// SendPaymentAssertInflight sends a payment from the passed node and asserts
1868
// the payment is inflight.
1869
func (h *HarnessTest) SendPaymentAssertInflight(hn *node.HarnessNode,
1870
        req *routerrpc.SendPaymentRequest) *lnrpc.Payment {
×
1871

×
1872
        return h.SendPaymentAndAssertStatus(hn, req, lnrpc.Payment_IN_FLIGHT)
×
1873
}
×
1874

1875
// OpenChannelRequest is used to open a channel using the method
1876
// OpenMultiChannelsAsync.
1877
type OpenChannelRequest struct {
1878
        // Local is the funding node.
1879
        Local *node.HarnessNode
1880

1881
        // Remote is the receiving node.
1882
        Remote *node.HarnessNode
1883

1884
        // Param is the open channel params.
1885
        Param OpenChannelParams
1886

1887
        // stream is the client created after calling OpenChannel RPC.
1888
        stream rpc.OpenChanClient
1889

1890
        // result is a channel used to send the channel point once the funding
1891
        // has succeeded.
1892
        result chan *lnrpc.ChannelPoint
1893
}
1894

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

×
1905
        // openChannel opens a channel based on the request.
×
1906
        openChannel := func(req *OpenChannelRequest) {
×
1907
                stream := h.OpenChannelAssertStream(
×
1908
                        req.Local, req.Remote, req.Param,
×
1909
                )
×
1910
                req.stream = stream
×
1911
        }
×
1912

1913
        // assertChannelOpen is a helper closure that asserts a channel is
1914
        // open.
1915
        assertChannelOpen := func(req *OpenChannelRequest) {
×
1916
                // Wait for the channel open event from the stream.
×
1917
                cp := h.WaitForChannelOpenEvent(req.stream)
×
1918

×
1919
                if !req.Param.Private {
×
1920
                        // Check that both alice and bob have seen the channel
×
1921
                        // from their channel watch request.
×
1922
                        h.AssertChannelInGraph(req.Local, cp)
×
1923
                        h.AssertChannelInGraph(req.Remote, cp)
×
1924
                }
×
1925

1926
                // Finally, check that the channel can be seen in their
1927
                // ListChannels.
1928
                h.AssertChannelExists(req.Local, cp)
×
1929
                h.AssertChannelExists(req.Remote, cp)
×
1930

×
1931
                req.result <- cp
×
1932
        }
1933

1934
        // Go through the requests and make the OpenChannel RPC call.
1935
        for _, r := range reqs {
×
1936
                openChannel(r)
×
1937
        }
×
1938

1939
        // Mine one block to confirm all the funding transactions.
1940
        h.MineBlocksAndAssertNumTxes(1, len(reqs))
×
1941

×
1942
        // Mine 5 more blocks so all the public channels are announced to the
×
1943
        // network.
×
1944
        h.MineBlocks(numBlocksOpenChannel - 1)
×
1945

×
1946
        // Once the blocks are mined, we fire goroutines for each of the
×
1947
        // request to watch for the channel openning.
×
1948
        for _, r := range reqs {
×
1949
                r.result = make(chan *lnrpc.ChannelPoint, 1)
×
1950
                go assertChannelOpen(r)
×
1951
        }
×
1952

1953
        // Finally, collect the results.
1954
        channelPoints := make([]*lnrpc.ChannelPoint, 0)
×
1955
        for _, r := range reqs {
×
1956
                select {
×
1957
                case cp := <-r.result:
×
1958
                        channelPoints = append(channelPoints, cp)
×
1959

1960
                case <-time.After(wait.ChannelOpenTimeout):
×
1961
                        require.Failf(h, "timeout", "wait channel point "+
×
1962
                                "timeout for channel %s=>%s", r.Local.Name(),
×
1963
                                r.Remote.Name())
×
1964
                }
1965
        }
1966

1967
        // Assert that we have the expected num of channel points.
1968
        require.Len(h, channelPoints, len(reqs),
×
1969
                "returned channel points not match")
×
1970

×
1971
        return channelPoints
×
1972
}
1973

1974
// ReceiveInvoiceUpdate waits until a message is received on the subscribe
1975
// invoice stream or the timeout is reached.
1976
func (h *HarnessTest) ReceiveInvoiceUpdate(
1977
        stream rpc.InvoiceUpdateClient) *lnrpc.Invoice {
×
1978

×
1979
        chanMsg := make(chan *lnrpc.Invoice)
×
1980
        errChan := make(chan error)
×
1981
        go func() {
×
1982
                // Consume one message. This will block until the message is
×
1983
                // received.
×
1984
                resp, err := stream.Recv()
×
1985
                if err != nil {
×
1986
                        errChan <- err
×
1987
                        return
×
1988
                }
×
1989
                chanMsg <- resp
×
1990
        }()
1991

1992
        select {
×
1993
        case <-time.After(DefaultTimeout):
×
1994
                require.Fail(h, "timeout", "timeout receiving invoice update")
×
1995

1996
        case err := <-errChan:
×
1997
                require.Failf(h, "err from stream",
×
1998
                        "received err from stream: %v", err)
×
1999

2000
        case updateMsg := <-chanMsg:
×
2001
                return updateMsg
×
2002
        }
2003

2004
        return nil
×
2005
}
2006

2007
// CalculateTxFee retrieves parent transactions and reconstructs the fee paid.
2008
func (h *HarnessTest) CalculateTxFee(tx *wire.MsgTx) btcutil.Amount {
×
2009
        var balance btcutil.Amount
×
2010
        for _, in := range tx.TxIn {
×
2011
                parentHash := in.PreviousOutPoint.Hash
×
2012
                rawTx := h.miner.GetRawTransaction(parentHash)
×
2013
                parent := rawTx.MsgTx()
×
2014
                value := parent.TxOut[in.PreviousOutPoint.Index].Value
×
2015

×
2016
                balance += btcutil.Amount(value)
×
2017
        }
×
2018

2019
        for _, out := range tx.TxOut {
×
2020
                balance -= btcutil.Amount(out.Value)
×
2021
        }
×
2022

2023
        return balance
×
2024
}
2025

2026
// CalculateTxWeight calculates the weight for a given tx.
2027
//
2028
// TODO(yy): use weight estimator to get more accurate result.
2029
func (h *HarnessTest) CalculateTxWeight(tx *wire.MsgTx) lntypes.WeightUnit {
×
2030
        utx := btcutil.NewTx(tx)
×
2031
        return lntypes.WeightUnit(blockchain.GetTransactionWeight(utx))
×
2032
}
×
2033

2034
// CalculateTxFeeRate calculates the fee rate for a given tx.
2035
func (h *HarnessTest) CalculateTxFeeRate(
2036
        tx *wire.MsgTx) chainfee.SatPerKWeight {
×
2037

×
2038
        w := h.CalculateTxWeight(tx)
×
2039
        fee := h.CalculateTxFee(tx)
×
2040

×
2041
        return chainfee.NewSatPerKWeight(fee, w)
×
2042
}
×
2043

2044
// CalculateTxesFeeRate takes a list of transactions and estimates the fee rate
2045
// used to sweep them.
2046
//
2047
// NOTE: only used in current test file.
2048
func (h *HarnessTest) CalculateTxesFeeRate(txns []*wire.MsgTx) int64 {
×
2049
        const scale = 1000
×
2050

×
2051
        var totalWeight, totalFee int64
×
2052
        for _, tx := range txns {
×
2053
                utx := btcutil.NewTx(tx)
×
2054
                totalWeight += blockchain.GetTransactionWeight(utx)
×
2055

×
2056
                fee := h.CalculateTxFee(tx)
×
2057
                totalFee += int64(fee)
×
2058
        }
×
2059
        feeRate := totalFee * scale / totalWeight
×
2060

×
2061
        return feeRate
×
2062
}
2063

2064
// AssertSweepFound looks up a sweep in a nodes list of broadcast sweeps and
2065
// asserts it's found.
2066
//
2067
// NOTE: Does not account for node's internal state.
2068
func (h *HarnessTest) AssertSweepFound(hn *node.HarnessNode,
2069
        sweep string, verbose bool, startHeight int32) {
×
2070

×
2071
        err := wait.NoError(func() error {
×
2072
                // List all sweeps that alice's node had broadcast.
×
2073
                sweepResp := hn.RPC.ListSweeps(verbose, startHeight)
×
2074

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

2082
                if found {
×
2083
                        return nil
×
2084
                }
×
2085

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

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

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

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

2106
        return false
×
2107
}
2108

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

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

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

2122
        return false
×
2123
}
2124

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

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

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

2150
                routes = resp
×
2151

×
2152
                return nil
×
2153
        }, DefaultTimeout)
2154

2155
        require.NoError(h, err, "timeout querying routes")
×
2156

×
2157
        return routes
×
2158
}
2159

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

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

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

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

2186
        case updateMsg := <-chanMsg:
×
2187
                return updateMsg
×
2188
        }
2189

2190
        return nil
×
2191
}
2192

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

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

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

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

2220
        case updateMsg := <-chanMsg:
×
2221
                return updateMsg
×
2222
        }
2223

2224
        return nil
×
2225
}
2226

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

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

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

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

2253
        case updateMsg := <-chanMsg:
×
2254
                return updateMsg
×
2255
        }
2256

2257
        return nil
×
2258
}
2259

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

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

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

×
2280
        return p2trOutputIndex
×
2281
}
2282

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

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

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

×
2304
        return tx
×
2305
}
×
2306

2307
// CreateSimpleNetwork creates the number of nodes specified by the number of
2308
// configs and makes a topology of `node1 -> node2 -> node3...`. Each node is
2309
// created using the specified config, the neighbors are connected, and the
2310
// channels are opened. Each node will be funded with a single UTXO of 1 BTC
2311
// except the last one.
2312
//
2313
// For instance, to create a network with 2 nodes that share the same node
2314
// config,
2315
//
2316
//        cfg := []string{"--protocol.anchors"}
2317
//        cfgs := [][]string{cfg, cfg}
2318
//        params := OpenChannelParams{...}
2319
//        chanPoints, nodes := ht.CreateSimpleNetwork(cfgs, params)
2320
//
2321
// This will create two nodes and open an anchor channel between them.
2322
func (h *HarnessTest) CreateSimpleNetwork(nodeCfgs [][]string,
2323
        p OpenChannelParams) ([]*lnrpc.ChannelPoint, []*node.HarnessNode) {
×
2324

×
2325
        // Create new nodes.
×
2326
        nodes := h.createNodes(nodeCfgs)
×
2327

×
2328
        var resp []*lnrpc.ChannelPoint
×
2329

×
2330
        // Open zero-conf channels if specified.
×
2331
        if p.ZeroConf {
×
2332
                resp = h.openZeroConfChannelsForNodes(nodes, p)
×
2333
        } else {
×
2334
                // Open channels between the nodes.
×
2335
                resp = h.openChannelsForNodes(nodes, p)
×
2336
        }
×
2337

2338
        return resp, nodes
×
2339
}
2340

2341
// acceptChannel is used to accept a single channel that comes across. This
2342
// should be run in a goroutine and is used to test nodes with the zero-conf
2343
// feature bit.
2344
func acceptChannel(t *testing.T, zeroConf bool, stream rpc.AcceptorClient) {
×
2345
        req, err := stream.Recv()
×
2346
        require.NoError(t, err)
×
2347

×
2348
        resp := &lnrpc.ChannelAcceptResponse{
×
2349
                Accept:        true,
×
2350
                PendingChanId: req.PendingChanId,
×
2351
                ZeroConf:      zeroConf,
×
2352
        }
×
2353
        err = stream.Send(resp)
×
2354
        require.NoError(t, err)
×
2355
}
×
2356

2357
// nodeNames defines a slice of human-reable names for the nodes created in the
2358
// `createNodes` method. 8 nodes are defined here as by default we can only
2359
// create this many nodes in one test.
2360
var nodeNames = []string{
2361
        "Alice", "Bob", "Carol", "Dave", "Eve", "Frank", "Grace", "Heidi",
2362
}
2363

2364
// createNodes creates the number of nodes specified by the number of configs.
2365
// Each node is created using the specified config, the neighbors are
2366
// connected.
2367
func (h *HarnessTest) createNodes(nodeCfgs [][]string) []*node.HarnessNode {
×
2368
        // Get the number of nodes.
×
2369
        numNodes := len(nodeCfgs)
×
2370

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

×
2374
        // Make a slice of nodes.
×
2375
        nodes := make([]*node.HarnessNode, numNodes)
×
2376

×
2377
        // Create new nodes.
×
2378
        for i, nodeCfg := range nodeCfgs {
×
2379
                nodeName := nodeNames[i]
×
2380
                n := h.NewNode(nodeName, nodeCfg)
×
2381
                nodes[i] = n
×
2382
        }
×
2383

2384
        // Connect the nodes in a chain.
2385
        for i := 1; i < len(nodes); i++ {
×
2386
                nodeA := nodes[i-1]
×
2387
                nodeB := nodes[i]
×
2388
                h.EnsureConnected(nodeA, nodeB)
×
2389
        }
×
2390

2391
        // Fund all the nodes expect the last one.
2392
        for i := 0; i < len(nodes)-1; i++ {
×
2393
                node := nodes[i]
×
2394
                h.FundCoinsUnconfirmed(btcutil.SatoshiPerBitcoin, node)
×
2395
        }
×
2396

2397
        // Mine 1 block to get the above coins confirmed.
2398
        h.MineBlocksAndAssertNumTxes(1, numNodes-1)
×
2399

×
2400
        return nodes
×
2401
}
2402

2403
// openChannelsForNodes takes a list of nodes and makes a topology of `node1 ->
2404
// node2 -> node3...`.
2405
func (h *HarnessTest) openChannelsForNodes(nodes []*node.HarnessNode,
2406
        p OpenChannelParams) []*lnrpc.ChannelPoint {
×
2407

×
2408
        // Sanity check the params.
×
2409
        require.Greater(h, len(nodes), 1, "need at least 2 nodes")
×
2410

×
2411
        // attachFundingShim is a helper closure that optionally attaches a
×
2412
        // funding shim to the open channel params and returns it.
×
2413
        attachFundingShim := func(
×
2414
                nodeA, nodeB *node.HarnessNode) OpenChannelParams {
×
2415

×
2416
                // If this channel is not a script enforced lease channel,
×
2417
                // we'll do nothing and return the params.
×
2418
                leasedType := lnrpc.CommitmentType_SCRIPT_ENFORCED_LEASE
×
2419
                if p.CommitmentType != leasedType {
×
2420
                        return p
×
2421
                }
×
2422

2423
                // Otherwise derive the funding shim, attach it to the original
2424
                // open channel params and return it.
2425
                minerHeight := h.CurrentHeight()
×
2426
                thawHeight := minerHeight + thawHeightDelta
×
2427
                fundingShim, _ := h.DeriveFundingShim(
×
2428
                        nodeA, nodeB, p.Amt, thawHeight, true, leasedType,
×
2429
                )
×
2430

×
2431
                p.FundingShim = fundingShim
×
2432

×
2433
                return p
×
2434
        }
2435

2436
        // Open channels in batch to save blocks mined.
2437
        reqs := make([]*OpenChannelRequest, 0, len(nodes)-1)
×
2438
        for i := 0; i < len(nodes)-1; i++ {
×
2439
                nodeA := nodes[i]
×
2440
                nodeB := nodes[i+1]
×
2441

×
2442
                // Optionally attach a funding shim to the open channel params.
×
2443
                p = attachFundingShim(nodeA, nodeB)
×
2444

×
2445
                req := &OpenChannelRequest{
×
2446
                        Local:  nodeA,
×
2447
                        Remote: nodeB,
×
2448
                        Param:  p,
×
2449
                }
×
2450
                reqs = append(reqs, req)
×
2451
        }
×
2452
        resp := h.OpenMultiChannelsAsync(reqs)
×
2453

×
2454
        // If the channels are private, make sure the channel participants know
×
2455
        // the relevant channels.
×
2456
        if p.Private {
×
2457
                for i, chanPoint := range resp {
×
2458
                        // Get the channel participants - for n channels we
×
2459
                        // would have n+1 nodes.
×
2460
                        nodeA, nodeB := nodes[i], nodes[i+1]
×
2461
                        h.AssertChannelInGraph(nodeA, chanPoint)
×
2462
                        h.AssertChannelInGraph(nodeB, chanPoint)
×
2463
                }
×
2464
        } else {
×
2465
                // Make sure the all nodes know all the channels if they are
×
2466
                // public.
×
2467
                for _, node := range nodes {
×
2468
                        for _, chanPoint := range resp {
×
2469
                                h.AssertChannelInGraph(node, chanPoint)
×
2470
                        }
×
2471

2472
                        // Make sure every node has updated its cached graph
2473
                        // about the edges as indicated in `DescribeGraph`.
2474
                        h.AssertNumEdges(node, len(resp), false)
×
2475
                }
2476
        }
2477

2478
        return resp
×
2479
}
2480

2481
// openZeroConfChannelsForNodes takes a list of nodes and makes a topology of
2482
// `node1 -> node2 -> node3...` with zero-conf channels.
2483
func (h *HarnessTest) openZeroConfChannelsForNodes(nodes []*node.HarnessNode,
2484
        p OpenChannelParams) []*lnrpc.ChannelPoint {
×
2485

×
2486
        // Sanity check the params.
×
2487
        require.True(h, p.ZeroConf, "zero-conf channels must be enabled")
×
2488
        require.Greater(h, len(nodes), 1, "need at least 2 nodes")
×
2489

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

×
2493
        // Create the channel acceptors.
×
2494
        for _, node := range nodes[1:] {
×
2495
                acceptor, cancel := node.RPC.ChannelAcceptor()
×
2496
                go acceptChannel(h.T, true, acceptor)
×
2497

×
2498
                cancels = append(cancels, cancel)
×
2499
        }
×
2500

2501
        // Open channels between the nodes.
2502
        resp := h.openChannelsForNodes(nodes, p)
×
2503

×
2504
        for _, cancel := range cancels {
×
2505
                cancel()
×
2506
        }
×
2507

2508
        return resp
×
2509
}
2510

2511
// DeriveFundingShim creates a channel funding shim by deriving the necessary
2512
// keys on both sides.
2513
func (h *HarnessTest) DeriveFundingShim(alice, bob *node.HarnessNode,
2514
        chanSize btcutil.Amount, thawHeight uint32, publish bool,
2515
        commitType lnrpc.CommitmentType) (*lnrpc.FundingShim,
2516
        *lnrpc.ChannelPoint) {
×
2517

×
2518
        keyLoc := &signrpc.KeyLocator{KeyFamily: 9999}
×
2519
        carolFundingKey := alice.RPC.DeriveKey(keyLoc)
×
2520
        daveFundingKey := bob.RPC.DeriveKey(keyLoc)
×
2521

×
2522
        // Now that we have the multi-sig keys for each party, we can manually
×
2523
        // construct the funding transaction. We'll instruct the backend to
×
2524
        // immediately create and broadcast a transaction paying out an exact
×
2525
        // amount. Normally this would reside in the mempool, but we just
×
2526
        // confirm it now for simplicity.
×
2527
        var (
×
2528
                fundingOutput *wire.TxOut
×
2529
                musig2        bool
×
2530
                err           error
×
2531
        )
×
2532

×
2533
        if commitType == lnrpc.CommitmentType_SIMPLE_TAPROOT ||
×
2534
                commitType == lnrpc.CommitmentType_SIMPLE_TAPROOT_OVERLAY {
×
2535

×
2536
                var carolKey, daveKey *btcec.PublicKey
×
2537
                carolKey, err = btcec.ParsePubKey(carolFundingKey.RawKeyBytes)
×
2538
                require.NoError(h, err)
×
2539
                daveKey, err = btcec.ParsePubKey(daveFundingKey.RawKeyBytes)
×
2540
                require.NoError(h, err)
×
2541

×
2542
                _, fundingOutput, err = input.GenTaprootFundingScript(
×
2543
                        carolKey, daveKey, int64(chanSize),
×
2544
                        fn.None[chainhash.Hash](),
×
2545
                )
×
2546
                require.NoError(h, err)
×
2547

×
2548
                musig2 = true
×
2549
        } else {
×
2550
                _, fundingOutput, err = input.GenFundingPkScript(
×
2551
                        carolFundingKey.RawKeyBytes, daveFundingKey.RawKeyBytes,
×
2552
                        int64(chanSize),
×
2553
                )
×
2554
                require.NoError(h, err)
×
2555
        }
×
2556

2557
        var txid *chainhash.Hash
×
2558
        targetOutputs := []*wire.TxOut{fundingOutput}
×
2559
        if publish {
×
2560
                txid = h.SendOutputsWithoutChange(targetOutputs, 5)
×
2561
        } else {
×
2562
                tx := h.CreateTransaction(targetOutputs, 5)
×
2563

×
2564
                txHash := tx.TxHash()
×
2565
                txid = &txHash
×
2566
        }
×
2567

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

×
2573
        // Now that we have the pending channel ID, Dave (our responder) will
×
2574
        // register the intent to receive a new channel funding workflow using
×
2575
        // the pending channel ID.
×
2576
        chanPoint := &lnrpc.ChannelPoint{
×
2577
                FundingTxid: &lnrpc.ChannelPoint_FundingTxidBytes{
×
2578
                        FundingTxidBytes: txid[:],
×
2579
                },
×
2580
        }
×
2581
        chanPointShim := &lnrpc.ChanPointShim{
×
2582
                Amt:       int64(chanSize),
×
2583
                ChanPoint: chanPoint,
×
2584
                LocalKey: &lnrpc.KeyDescriptor{
×
2585
                        RawKeyBytes: daveFundingKey.RawKeyBytes,
×
2586
                        KeyLoc: &lnrpc.KeyLocator{
×
2587
                                KeyFamily: daveFundingKey.KeyLoc.KeyFamily,
×
2588
                                KeyIndex:  daveFundingKey.KeyLoc.KeyIndex,
×
2589
                        },
×
2590
                },
×
2591
                RemoteKey:     carolFundingKey.RawKeyBytes,
×
2592
                PendingChanId: pendingChanID,
×
2593
                ThawHeight:    thawHeight,
×
2594
                Musig2:        musig2,
×
2595
        }
×
2596
        fundingShim := &lnrpc.FundingShim{
×
2597
                Shim: &lnrpc.FundingShim_ChanPointShim{
×
2598
                        ChanPointShim: chanPointShim,
×
2599
                },
×
2600
        }
×
2601
        bob.RPC.FundingStateStep(&lnrpc.FundingTransitionMsg{
×
2602
                Trigger: &lnrpc.FundingTransitionMsg_ShimRegister{
×
2603
                        ShimRegister: fundingShim,
×
2604
                },
×
2605
        })
×
2606

×
2607
        // If we attempt to register the same shim (has the same pending chan
×
2608
        // ID), then we should get an error.
×
2609
        bob.RPC.FundingStateStepAssertErr(&lnrpc.FundingTransitionMsg{
×
2610
                Trigger: &lnrpc.FundingTransitionMsg_ShimRegister{
×
2611
                        ShimRegister: fundingShim,
×
2612
                },
×
2613
        })
×
2614

×
2615
        // We'll take the chan point shim we just registered for Dave (the
×
2616
        // responder), and swap the local/remote keys before we feed it in as
×
2617
        // Carol's funding shim as the initiator.
×
2618
        fundingShim.GetChanPointShim().LocalKey = &lnrpc.KeyDescriptor{
×
2619
                RawKeyBytes: carolFundingKey.RawKeyBytes,
×
2620
                KeyLoc: &lnrpc.KeyLocator{
×
2621
                        KeyFamily: carolFundingKey.KeyLoc.KeyFamily,
×
2622
                        KeyIndex:  carolFundingKey.KeyLoc.KeyIndex,
×
2623
                },
×
2624
        }
×
2625
        fundingShim.GetChanPointShim().RemoteKey = daveFundingKey.RawKeyBytes
×
2626

×
2627
        return fundingShim, chanPoint
×
2628
}
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