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

lightningnetwork / lnd / 12209990843

07 Dec 2024 02:45AM UTC coverage: 58.977% (+1.1%) from 57.911%
12209990843

Pull #9260

github

yyforyongyu
lnrpc: sort `Invoice.HTLCs` based on `HtlcIndex`

So the returned HTLCs are ordered.
Pull Request #9260: Beat itest [3/3]: fix all itest flakes

4 of 132 new or added lines in 9 files covered. (3.03%)

17 existing lines in 8 files now uncovered.

134149 of 227459 relevant lines covered (58.98%)

19442.29 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"
19
        "github.com/lightningnetwork/lnd/input"
20
        "github.com/lightningnetwork/lnd/kvdb/etcd"
21
        "github.com/lightningnetwork/lnd/lnrpc"
22
        "github.com/lightningnetwork/lnd/lnrpc/invoicesrpc"
23
        "github.com/lightningnetwork/lnd/lnrpc/routerrpc"
24
        "github.com/lightningnetwork/lnd/lnrpc/signrpc"
25
        "github.com/lightningnetwork/lnd/lnrpc/walletrpc"
26
        "github.com/lightningnetwork/lnd/lntest/miner"
27
        "github.com/lightningnetwork/lnd/lntest/node"
28
        "github.com/lightningnetwork/lnd/lntest/rpc"
29
        "github.com/lightningnetwork/lnd/lntest/wait"
30
        "github.com/lightningnetwork/lnd/lntypes"
31
        "github.com/lightningnetwork/lnd/lnwallet/chainfee"
32
        "github.com/lightningnetwork/lnd/lnwire"
33
        "github.com/lightningnetwork/lnd/routing"
34
        "github.com/stretchr/testify/require"
35
)
36

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
141
        t.Helper()
×
142

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

271
        h.shutdownAllNodes()
×
272

×
273
        close(h.lndErrorChan)
×
274

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

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

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

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

297
        testCase.TestFunc(h)
×
298
}
299

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

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

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

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

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

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

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

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

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

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

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

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

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

365
        return st
×
366
}
367

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
484
        return node
×
485
}
×
486

487
// NewNodeWithCoins creates a new node and asserts its creation. The node is
488
// guaranteed to have finished its initialization and all its subservers are
489
// started. In addition, 5 UTXO of 1 BTC each are sent to the node.
490
func (h *HarnessTest) NewNodeWithCoins(name string,
491
        extraArgs []string) *node.HarnessNode {
×
492

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

×
496
        // Start the node.
×
497
        err = node.Start(h.runCtx)
×
498
        require.NoError(h, err, "failed to start node %s", node.Name())
×
499

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

×
507
        for i := 0; i < numOutputs; i++ {
×
508
                h.createAndSendOutput(
×
509
                        node, fundAmount,
×
510
                        lnrpc.AddressType_WITNESS_PUBKEY_HASH,
×
511
                )
×
512
        }
×
513

514
        // Mine a block to confirm the transactions.
515
        h.MineBlocksAndAssertNumTxes(1, numOutputs)
×
516

×
517
        // Now block until the wallet have fully synced up.
×
518
        h.WaitForBalanceConfirmed(node, totalAmount)
×
519

×
520
        return node
×
521
}
522

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

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

×
536
        // Remove the node from active nodes.
×
537
        delete(h.manager.activeNodes, node.Cfg.NodeID)
×
538

×
539
        return func() error {
×
540
                h.manager.registerNode(node)
×
541

×
542
                if err := node.Start(h.runCtx); err != nil {
×
543
                        return err
×
544
                }
×
545
                h.WaitForBlockchainSync(node)
×
546

×
547
                return nil
×
548
        }
549
}
550

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

×
557
        err = h.manager.unlockNode(hn)
×
558
        require.NoErrorf(h, err, "failed to unlock node %s", hn.Name())
×
559

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

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

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

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

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

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

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

×
593
        hn.SetExtraArgs(extraArgs)
×
594
        h.RestartNode(hn)
×
595
}
×
596

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

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

×
612
        return h.newNodeWithSeed(name, extraArgs, req, statelessInit)
×
613
}
×
614

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

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

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

×
632
        // Generate a new seed.
×
633
        genSeedResp := node.RPC.GenSeed(req)
×
634

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

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

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

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

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

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

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

×
688
        return n
×
689
}
×
690

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

×
700
        // We don't want to use the embedded etcd instance.
×
701
        h.manager.dbBackend = node.BackendBbolt
×
702

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

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

×
713
        return node
×
714
}
×
715

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

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

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

×
733
        extraArgs := node.ExtraArgsEtcd(
×
734
                etcdCfg, name, cluster, leaderSessionTTL,
×
735
        )
×
736

×
737
        return h.newNodeWithSeed(name, extraArgs, req, statelessInit)
×
738
}
×
739

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

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

×
748
        err = hn.StartWithNoAuth(h.runCtx)
×
749
        require.NoError(h, err, "failed to start node %s", name)
×
750

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

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

×
763
        return hn
×
764
}
×
765

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

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

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

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

×
789
        h.feeService.SetFeeRate(fee, conf)
×
790
}
×
791

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

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

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

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

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

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

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

848
        return nil
×
849
}
850

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

×
856
        txid, err := lnrpc.GetChanPointFundingTxid(cp)
×
857
        require.NoError(h, err, "unable to get txid")
×
858

×
859
        return *txid
×
860
}
×
861

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

×
866
        txid := h.GetChanPointFundingTxid(cp)
×
867
        return wire.OutPoint{
×
868
                Hash:  txid,
×
869
                Index: cp.OutputIndex,
×
870
        }
×
871
}
×
872

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

878
        // PushAmt is the amount that should be pushed to the remote when the
879
        // channel is opened.
880
        PushAmt btcutil.Amount
881

882
        // Private is a boolan indicating whether the opened channel should be
883
        // private.
884
        Private bool
885

886
        // SpendUnconfirmed is a boolean indicating whether we can utilize
887
        // unconfirmed outputs to fund the channel.
888
        SpendUnconfirmed bool
889

890
        // MinHtlc is the htlc_minimum_msat value set when opening the channel.
891
        MinHtlc lnwire.MilliSatoshi
892

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

898
        // FundingShim is an optional funding shim that the caller can specify
899
        // in order to modify the channel funding workflow.
900
        FundingShim *lnrpc.FundingShim
901

902
        // SatPerVByte is the amount of satoshis to spend in chain fees per
903
        // virtual byte of the transaction.
904
        SatPerVByte btcutil.Amount
905

906
        // ConfTarget is the number of blocks that the funding transaction
907
        // should be confirmed in.
908
        ConfTarget fn.Option[int32]
909

910
        // CommitmentType is the commitment type that should be used for the
911
        // channel to be opened.
912
        CommitmentType lnrpc.CommitmentType
913

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

919
        // ScidAlias denotes whether the channel will be an option-scid-alias
920
        // channel type negotiation.
921
        ScidAlias bool
922

923
        // BaseFee is the channel base fee applied during the channel
924
        // announcement phase.
925
        BaseFee uint64
926

927
        // FeeRate is the channel fee rate in ppm applied during the channel
928
        // announcement phase.
929
        FeeRate uint64
930

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

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

943
        // FundMax is a boolean indicating whether the channel should be funded
944
        // with the maximum possible amount from the wallet.
945
        FundMax bool
946

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

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

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

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

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

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

984
        // Get the requested conf target. If not set, default to 6.
985
        confTarget := p.ConfTarget.UnwrapOr(6)
×
986

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

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

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

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

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

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

×
1041
        return update.ChanPending, respStream
×
1042
}
×
1043

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

×
1052
        resp, _ := h.openChannelAssertPending(srcNode, destNode, p)
×
1053
        return resp
×
1054
}
×
1055

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

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

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

×
1080
        // First, open the channel without announcing it.
×
1081
        cp := h.OpenChannelNoAnnounce(alice, bob, p)
×
1082

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

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

1102
        return cp
×
1103
}
1104

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

×
1115
        chanOpenUpdate := h.OpenChannelAssertStream(alice, bob, p)
×
1116

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

1122
        // Open a non-zero conf channel.
1123
        return h.openChannel(alice, bob, chanOpenUpdate)
×
1124
}
1125

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

×
1134
        // Mine 1 block to confirm the funding transaction.
×
1135
        block := h.MineBlocksAndAssertNumTxes(1, 1)[0]
×
1136

×
1137
        // Wait for the channel open event.
×
1138
        fundingChanPoint := h.WaitForChannelOpenEvent(stream)
×
1139

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

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

×
1149
        // Check that the channel can be seen in their ListChannels.
×
1150
        h.AssertChannelExists(alice, fundingChanPoint)
×
1151
        h.AssertChannelExists(bob, fundingChanPoint)
×
1152

×
1153
        return fundingChanPoint
×
1154
}
×
1155

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

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

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

×
1171
        // Finally, check that the channel can be seen in their ListChannels.
×
1172
        h.AssertChannelExists(alice, fundingChanPoint)
×
1173
        h.AssertChannelExists(bob, fundingChanPoint)
×
1174

×
1175
        return fundingChanPoint
×
1176
}
×
1177

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

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

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

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

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

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

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

1218
        var (
×
1219
                stream rpc.CloseChanClient
×
1220
                event  *lnrpc.CloseStatusUpdate
×
1221
                err    error
×
1222
        )
×
1223

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

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

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

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

×
1246
        // Assert the closing tx is in the mempool.
×
1247
        h.miner.AssertTxInMempool(*closeTxid)
×
1248

×
1249
        return stream, *closeTxid
×
1250
}
1251

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

×
1264
        stream, _ := h.CloseChannelAssertPending(hn, cp, false)
×
1265

×
1266
        return h.AssertStreamChannelCoopClosed(hn, cp, false, stream)
×
1267
}
×
1268

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

×
1283
        stream, _ := h.CloseChannelAssertPending(hn, cp, true)
×
1284

×
1285
        closingTxid := h.AssertStreamChannelForceClosed(hn, cp, false, stream)
×
1286

×
1287
        // Cleanup the force close.
×
1288
        h.CleanupForceClose(hn)
×
1289

×
1290
        return closingTxid
×
1291
}
×
1292

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

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

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

×
1312
        return err
×
1313
}
×
1314

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

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

×
1329
        initialBalance := target.RPC.WalletBalance()
×
1330

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

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

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

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

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

×
1364
                expectedBalance := btcutil.Amount(
×
1365
                        initialBalance.UnconfirmedBalance,
×
1366
                ) + amt
×
1367
                h.WaitForBalanceUnconfirmed(target, expectedBalance)
×
1368
        }
×
1369

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

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

×
1382
        expectedBalance := btcutil.Amount(initialBalance.ConfirmedBalance) + amt
×
1383
        h.WaitForBalanceConfirmed(target, expectedBalance)
×
1384
}
1385

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

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

×
1399
        h.fundCoins(amt, hn, lnrpc.AddressType_WITNESS_PUBKEY_HASH, false)
×
1400
}
×
1401

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

×
1407
        h.fundCoins(amt, target, lnrpc.AddressType_NESTED_PUBKEY_HASH, true)
×
1408
}
×
1409

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

×
1415
        h.fundCoins(amt, target, lnrpc.AddressType_TAPROOT_PUBKEY, true)
×
1416
}
×
1417

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

×
NEW
1426
        const fundAmount = 1 * btcutil.SatoshiPerBitcoin
×
NEW
1427

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

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

1443
        // Mine a block to confirm the transactions.
NEW
1444
        h.MineBlocksAndAssertNumTxes(1, num)
×
NEW
1445

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

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

×
1459
        payOpts := defaultHarnessOpts()
×
1460
        for _, opt := range opts {
×
1461
                opt(&payOpts)
×
1462
        }
×
1463

1464
        // Create a buffered chan to signal the results.
1465
        results := make(chan rpc.PaymentClient, len(paymentRequests))
×
1466

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

×
1477
                // Signal sent succeeded.
×
1478
                results <- stream
×
1479
        }
×
1480

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

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

1493
        case <-timer:
×
1494
                require.Fail(h, "timeout", "waiting payment results timeout")
×
1495
        }
1496
}
1497

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

×
1504
        h.completePaymentRequestsAssertStatus(
×
1505
                hn, paymentRequests, lnrpc.Payment_SUCCEEDED, opts...,
×
1506
        )
×
1507
}
×
1508

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

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

×
1520
        // Send payments and assert they are in-flight.
×
1521
        h.completePaymentRequestsAssertStatus(
×
1522
                hn, paymentRequests, lnrpc.Payment_IN_FLIGHT,
×
1523
        )
×
1524

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

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

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

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

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

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

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

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

×
1589
        switch p.CommitmentType {
×
1590
        case lnrpc.CommitmentType_SIMPLE_TAPROOT:
×
1591
                require.IsType(h, &btcutil.AddressTaproot{}, fundingAddr)
×
1592

1593
        default:
×
1594
                require.IsType(
×
1595
                        h, &btcutil.AddressWitnessScriptHash{}, fundingAddr,
×
1596
                )
×
1597
        }
1598

1599
        return respStream, upd.PsbtFund.Psbt
×
1600
}
1601

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

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

×
1619
        // Assert there is one pending sweep.
×
1620
        h.AssertNumPendingSweeps(hn, 1)
×
1621

×
1622
        // The node should now sweep the funds, clean up by mining the sweeping
×
1623
        // tx.
×
1624
        h.MineBlocksAndAssertNumTxes(1, 1)
×
1625

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

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

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

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

×
1651
                // Set the payment address in the invoice so the caller can
×
1652
                // properly use it.
×
1653
                invoice.PaymentAddr = resp.PaymentAddr
×
1654

×
1655
                payReqs[i] = resp.PaymentRequest
×
1656
                rHashes[i] = resp.RHash
×
1657
                invoices[i] = invoice
×
1658
        }
×
1659

1660
        return payReqs, rHashes, invoices
×
1661
}
1662

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

×
1668
        err := hn.BackupDB()
×
1669
        require.NoErrorf(h, err, "%s: failed to backup db", hn.Name())
×
1670

×
1671
        err = restart()
×
1672
        require.NoErrorf(h, err, "%s: failed to restart", hn.Name())
×
1673
}
×
1674

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

×
1682
        err = h.manager.unlockNode(hn)
×
1683
        require.NoErrorf(h, err, "failed to unlock node %s", hn.Name())
×
1684

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

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

×
1701
        // Now mine blocks till the mempool is empty.
×
1702
        h.cleanMempool()
×
1703
}
×
1704

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

×
1711
        channel, err := h.findChannel(hn, chanPoint, opts...)
×
1712
        require.NoError(h, err, "failed to query channel")
×
1713

×
1714
        return channel
×
1715
}
×
1716

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

×
1723
        stream := hn.RPC.SendPayment(req)
×
1724
        return h.AssertPaymentStatusFromStream(stream, status)
×
1725
}
×
1726

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

×
1733
        payment := h.SendPaymentAndAssertStatus(hn, req, lnrpc.Payment_FAILED)
×
1734
        require.Equal(h, reason, payment.FailureReason,
×
1735
                "payment failureReason not matched")
×
1736

×
1737
        return payment
×
1738
}
×
1739

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

×
1745
        return h.SendPaymentAndAssertStatus(hn, req, lnrpc.Payment_SUCCEEDED)
×
1746
}
×
1747

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

×
1753
        return h.SendPaymentAndAssertStatus(hn, req, lnrpc.Payment_IN_FLIGHT)
×
1754
}
×
1755

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

1762
        // Remote is the receiving node.
1763
        Remote *node.HarnessNode
1764

1765
        // Param is the open channel params.
1766
        Param OpenChannelParams
1767

1768
        // stream is the client created after calling OpenChannel RPC.
1769
        stream rpc.OpenChanClient
1770

1771
        // result is a channel used to send the channel point once the funding
1772
        // has succeeded.
1773
        result chan *lnrpc.ChannelPoint
1774
}
1775

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

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

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

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

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

×
1812
                req.result <- cp
×
1813
        }
1814

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

1820
        // Mine one block to confirm all the funding transactions.
1821
        h.MineBlocksAndAssertNumTxes(1, len(reqs))
×
1822

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

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

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

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

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

×
1852
        return channelPoints
×
1853
}
1854

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

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

1873
        select {
×
1874
        case <-time.After(DefaultTimeout):
×
1875
                require.Fail(h, "timeout", "timeout receiving invoice update")
×
1876

1877
        case err := <-errChan:
×
1878
                require.Failf(h, "err from stream",
×
1879
                        "received err from stream: %v", err)
×
1880

1881
        case updateMsg := <-chanMsg:
×
1882
                return updateMsg
×
1883
        }
1884

1885
        return nil
×
1886
}
1887

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

×
1897
                balance += btcutil.Amount(value)
×
1898
        }
×
1899

1900
        for _, out := range tx.TxOut {
×
1901
                balance -= btcutil.Amount(out.Value)
×
1902
        }
×
1903

1904
        return balance
×
1905
}
1906

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

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

×
1919
        w := h.CalculateTxWeight(tx)
×
1920
        fee := h.CalculateTxFee(tx)
×
1921

×
1922
        return chainfee.NewSatPerKWeight(fee, w)
×
1923
}
×
1924

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

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

×
1937
                fee := h.CalculateTxFee(tx)
×
1938
                totalFee += int64(fee)
×
1939
        }
×
1940
        feeRate := totalFee * scale / totalWeight
×
1941

×
1942
        return feeRate
×
1943
}
1944

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

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

×
1956
                var found bool
×
1957
                if verbose {
×
1958
                        found = findSweepInDetails(h, sweep, sweepResp)
×
1959
                } else {
×
1960
                        found = findSweepInTxids(h, sweep, sweepResp)
×
1961
                }
×
1962

1963
                if found {
×
1964
                        return nil
×
1965
                }
×
1966

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

1973
func findSweepInTxids(ht *HarnessTest, sweepTxid string,
1974
        sweepResp *walletrpc.ListSweepsResponse) bool {
×
1975

×
1976
        sweepTxIDs := sweepResp.GetTransactionIds()
×
1977
        require.NotNil(ht, sweepTxIDs, "expected transaction ids")
×
1978
        require.Nil(ht, sweepResp.GetTransactionDetails())
×
1979

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

1987
        return false
×
1988
}
1989

1990
func findSweepInDetails(ht *HarnessTest, sweepTxid string,
1991
        sweepResp *walletrpc.ListSweepsResponse) bool {
×
1992

×
1993
        sweepDetails := sweepResp.GetTransactionDetails()
×
1994
        require.NotNil(ht, sweepDetails, "expected transaction details")
×
1995
        require.Nil(ht, sweepResp.GetTransactionIds())
×
1996

×
1997
        for _, tx := range sweepDetails.Transactions {
×
1998
                if tx.TxHash == sweepTxid {
×
1999
                        return true
×
2000
                }
×
2001
        }
2002

2003
        return false
×
2004
}
2005

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

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

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

2031
                routes = resp
×
2032

×
2033
                return nil
×
2034
        }, DefaultTimeout)
2035

2036
        require.NoError(h, err, "timeout querying routes")
×
2037

×
2038
        return routes
×
2039
}
2040

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

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

2059
        select {
×
2060
        case <-time.After(DefaultTimeout):
×
2061
                require.Fail(h, "timeout", "timeout intercepting htlc")
×
2062

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

2067
        case updateMsg := <-chanMsg:
×
2068
                return updateMsg
×
2069
        }
2070

2071
        return nil
×
2072
}
2073

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

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

2092
        select {
×
2093
        case <-time.After(DefaultTimeout):
×
2094
                require.Fail(h, "timeout", "timeout invoice HTLC modifier")
×
2095

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

2101
        case updateMsg := <-chanMsg:
×
2102
                return updateMsg
×
2103
        }
2104

2105
        return nil
×
2106
}
2107

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

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

2126
        select {
×
2127
        case <-time.After(DefaultTimeout):
×
2128
                require.Fail(h, "timeout", "timeout intercepting htlc")
×
2129

2130
        case err := <-errChan:
×
2131
                require.Failf(h, "err from stream",
×
2132
                        "received err from stream: %v", err)
×
2133

2134
        case updateMsg := <-chanMsg:
×
2135
                return updateMsg
×
2136
        }
2137

2138
        return nil
×
2139
}
2140

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

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

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

×
2161
        return p2trOutputIndex
×
2162
}
2163

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

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

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

×
2185
        return tx
×
2186
}
×
2187

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

×
2206
        // Create new nodes.
×
2207
        nodes := h.createNodes(nodeCfgs)
×
2208

×
2209
        var resp []*lnrpc.ChannelPoint
×
2210

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

2219
        return resp, nodes
×
2220
}
2221

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

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

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

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

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

×
2255
        // Make a slice of nodes.
×
2256
        nodes := make([]*node.HarnessNode, numNodes)
×
2257

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

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

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

2278
        // Mine 1 block to get the above coins confirmed.
2279
        h.MineBlocksAndAssertNumTxes(1, numNodes-1)
×
2280

×
2281
        return nodes
×
2282
}
2283

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

×
2289
        // Sanity check the params.
×
2290
        require.Greater(h, len(nodes), 1, "need at least 2 nodes")
×
2291

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

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

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

×
2312
                p.FundingShim = fundingShim
×
2313

×
2314
                return p
×
2315
        }
2316

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

×
2323
                // Optionally attach a funding shim to the open channel params.
×
2324
                p = attachFundingShim(nodeA, nodeB)
×
2325

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

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

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

2359
        return resp
×
2360
}
2361

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

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

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

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

×
2379
                cancels = append(cancels, cancel)
×
2380
        }
×
2381

2382
        // Open channels between the nodes.
2383
        resp := h.openChannelsForNodes(nodes, p)
×
2384

×
2385
        for _, cancel := range cancels {
×
2386
                cancel()
×
2387
        }
×
2388

2389
        return resp
×
2390
}
2391

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

×
2399
        keyLoc := &signrpc.KeyLocator{KeyFamily: 9999}
×
2400
        carolFundingKey := alice.RPC.DeriveKey(keyLoc)
×
2401
        daveFundingKey := bob.RPC.DeriveKey(keyLoc)
×
2402

×
2403
        // Now that we have the multi-sig keys for each party, we can manually
×
2404
        // construct the funding transaction. We'll instruct the backend to
×
2405
        // immediately create and broadcast a transaction paying out an exact
×
2406
        // amount. Normally this would reside in the mempool, but we just
×
2407
        // confirm it now for simplicity.
×
2408
        var (
×
2409
                fundingOutput *wire.TxOut
×
2410
                musig2        bool
×
2411
                err           error
×
2412
        )
×
2413
        if commitType == lnrpc.CommitmentType_SIMPLE_TAPROOT {
×
2414
                var carolKey, daveKey *btcec.PublicKey
×
2415
                carolKey, err = btcec.ParsePubKey(carolFundingKey.RawKeyBytes)
×
2416
                require.NoError(h, err)
×
2417
                daveKey, err = btcec.ParsePubKey(daveFundingKey.RawKeyBytes)
×
2418
                require.NoError(h, err)
×
2419

×
2420
                _, fundingOutput, err = input.GenTaprootFundingScript(
×
2421
                        carolKey, daveKey, int64(chanSize),
×
2422
                        fn.None[chainhash.Hash](),
×
2423
                )
×
2424
                require.NoError(h, err)
×
2425

×
2426
                musig2 = true
×
2427
        } else {
×
2428
                _, fundingOutput, err = input.GenFundingPkScript(
×
2429
                        carolFundingKey.RawKeyBytes, daveFundingKey.RawKeyBytes,
×
2430
                        int64(chanSize),
×
2431
                )
×
2432
                require.NoError(h, err)
×
2433
        }
×
2434

2435
        var txid *chainhash.Hash
×
2436
        targetOutputs := []*wire.TxOut{fundingOutput}
×
2437
        if publish {
×
2438
                txid = h.SendOutputsWithoutChange(targetOutputs, 5)
×
2439
        } else {
×
2440
                tx := h.CreateTransaction(targetOutputs, 5)
×
2441

×
2442
                txHash := tx.TxHash()
×
2443
                txid = &txHash
×
2444
        }
×
2445

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

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

×
2485
        // If we attempt to register the same shim (has the same pending chan
×
2486
        // ID), then we should get an error.
×
2487
        bob.RPC.FundingStateStepAssertErr(&lnrpc.FundingTransitionMsg{
×
2488
                Trigger: &lnrpc.FundingTransitionMsg_ShimRegister{
×
2489
                        ShimRegister: fundingShim,
×
2490
                },
×
2491
        })
×
2492

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

×
2505
        return fundingShim, chanPoint
×
2506
}
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