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

lightningnetwork / lnd / 18852986778

27 Oct 2025 07:10PM UTC coverage: 54.859% (-11.8%) from 66.648%
18852986778

Pull #10265

github

web-flow
Merge 45787b3d5 into 9a7b526c0
Pull Request #10265: multi: update close logic to handle re-orgs of depth n-1, where n is num confs - add min conf floor

529 of 828 new or added lines in 17 files covered. (63.89%)

24026 existing lines in 286 files now uncovered.

110927 of 202205 relevant lines covered (54.86%)

21658.16 hits per line

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

0.0
/lntest/harness_assertion.go
1
package lntest
2

3
import (
4
        "bytes"
5
        "context"
6
        "crypto/rand"
7
        "encoding/hex"
8
        "encoding/json"
9
        "fmt"
10
        "math"
11
        "sort"
12
        "strings"
13
        "time"
14

15
        "github.com/btcsuite/btcd/btcec/v2"
16
        "github.com/btcsuite/btcd/btcec/v2/schnorr"
17
        "github.com/btcsuite/btcd/btcutil"
18
        "github.com/btcsuite/btcd/chaincfg/chainhash"
19
        "github.com/btcsuite/btcd/txscript"
20
        "github.com/btcsuite/btcd/wire"
21
        "github.com/davecgh/go-spew/spew"
22
        "github.com/lightningnetwork/lnd/channeldb"
23
        "github.com/lightningnetwork/lnd/lnrpc"
24
        "github.com/lightningnetwork/lnd/lnrpc/invoicesrpc"
25
        "github.com/lightningnetwork/lnd/lnrpc/routerrpc"
26
        "github.com/lightningnetwork/lnd/lnrpc/walletrpc"
27
        "github.com/lightningnetwork/lnd/lntest/miner"
28
        "github.com/lightningnetwork/lnd/lntest/node"
29
        "github.com/lightningnetwork/lnd/lntest/rpc"
30
        "github.com/lightningnetwork/lnd/lntest/wait"
31
        "github.com/lightningnetwork/lnd/lntypes"
32
        "github.com/lightningnetwork/lnd/lnutils"
33
        "github.com/stretchr/testify/require"
34
        "google.golang.org/protobuf/proto"
35
)
36

37
// FindChannelOption is a functional type for an option that modifies a
38
// ListChannelsRequest.
39
type ListChannelOption func(r *lnrpc.ListChannelsRequest)
40

41
// WithPeerAliasLookup is an option for setting the peer alias lookup flag on a
42
// ListChannelsRequest.
43
func WithPeerAliasLookup() ListChannelOption {
×
44
        return func(r *lnrpc.ListChannelsRequest) {
×
45
                r.PeerAliasLookup = true
×
46
        }
×
47
}
48

49
// WaitForBlockchainSync waits until the node is synced to chain.
50
func (h *HarnessTest) WaitForBlockchainSync(hn *node.HarnessNode) {
×
51
        err := wait.NoError(func() error {
×
52
                resp := hn.RPC.GetInfo()
×
53
                if resp.SyncedToChain {
×
54
                        return nil
×
55
                }
×
56

57
                return fmt.Errorf("%s is not synced to chain", hn.Name())
×
58
        }, DefaultTimeout)
59

60
        require.NoError(h, err, "timeout waiting for blockchain sync")
×
61
}
62

63
// WaitForBlockchainSyncTo waits until the node is synced to bestBlock.
64
func (h *HarnessTest) WaitForBlockchainSyncTo(hn *node.HarnessNode,
65
        bestBlock chainhash.Hash) {
×
66

×
67
        bestBlockHash := bestBlock.String()
×
68
        err := wait.NoError(func() error {
×
69
                resp := hn.RPC.GetInfo()
×
70
                if resp.SyncedToChain {
×
71
                        if resp.BlockHash == bestBlockHash {
×
72
                                return nil
×
73
                        }
×
74

75
                        return fmt.Errorf("%s's backend is synced to the "+
×
76
                                "wrong block (expected=%s, actual=%s)",
×
77
                                hn.Name(), bestBlockHash, resp.BlockHash)
×
78
                }
79

80
                return fmt.Errorf("%s is not synced to chain", hn.Name())
×
81
        }, DefaultTimeout)
82

83
        require.NoError(h, err, "timeout waiting for blockchain sync")
×
84
}
85

86
// AssertPeerConnected asserts that the given node b is connected to a.
87
func (h *HarnessTest) AssertPeerConnected(a, b *node.HarnessNode) {
×
88
        err := wait.NoError(func() error {
×
89
                // We require the RPC call to be succeeded and won't wait for
×
90
                // it as it's an unexpected behavior.
×
91
                resp := a.RPC.ListPeers()
×
92

×
93
                // If node B is seen in the ListPeers response from node A,
×
94
                // then we can return true as the connection has been fully
×
95
                // established.
×
96
                for _, peer := range resp.Peers {
×
97
                        if peer.PubKey == b.PubKeyStr {
×
98
                                return nil
×
99
                        }
×
100
                }
101

102
                return fmt.Errorf("%s not found in %s's ListPeers",
×
103
                        b.Name(), a.Name())
×
104
        }, DefaultTimeout)
105

106
        require.NoError(h, err, "unable to connect %s to %s, got error: "+
×
107
                "peers not connected within %v seconds",
×
108
                a.Name(), b.Name(), DefaultTimeout)
×
109
}
110

111
// ConnectNodes creates a connection between the two nodes and asserts the
112
// connection is succeeded.
113
func (h *HarnessTest) ConnectNodes(a, b *node.HarnessNode) {
×
114
        bobInfo := b.RPC.GetInfo()
×
115

×
116
        req := &lnrpc.ConnectPeerRequest{
×
117
                Addr: &lnrpc.LightningAddress{
×
118
                        Pubkey: bobInfo.IdentityPubkey,
×
119
                        Host:   b.Cfg.P2PAddr(),
×
120
                },
×
121
        }
×
122
        a.RPC.ConnectPeer(req)
×
123
        h.AssertConnected(a, b)
×
124
}
×
125

126
// ConnectNodesPerm creates a persistent connection between the two nodes and
127
// asserts the connection is succeeded.
128
func (h *HarnessTest) ConnectNodesPerm(a, b *node.HarnessNode) {
×
129
        bobInfo := b.RPC.GetInfo()
×
130

×
131
        req := &lnrpc.ConnectPeerRequest{
×
132
                Addr: &lnrpc.LightningAddress{
×
133
                        Pubkey: bobInfo.IdentityPubkey,
×
134
                        Host:   b.Cfg.P2PAddr(),
×
135
                },
×
136
                Perm: true,
×
137
        }
×
138
        a.RPC.ConnectPeer(req)
×
139
        h.AssertPeerConnected(a, b)
×
140
}
×
141

142
// DisconnectNodes disconnects the given two nodes and asserts the
143
// disconnection is succeeded. The request is made from node a and sent to node
144
// b.
145
func (h *HarnessTest) DisconnectNodes(a, b *node.HarnessNode) {
×
146
        bobInfo := b.RPC.GetInfo()
×
147
        a.RPC.DisconnectPeer(bobInfo.IdentityPubkey)
×
148

×
149
        // Assert disconnected.
×
150
        h.AssertPeerNotConnected(a, b)
×
151
}
×
152

153
// EnsureConnected will try to connect to two nodes, returning no error if they
154
// are already connected. If the nodes were not connected previously, this will
155
// behave the same as ConnectNodes. If a pending connection request has already
156
// been made, the method will block until the two nodes appear in each other's
157
// peers list, or until the DefaultTimeout expires.
158
func (h *HarnessTest) EnsureConnected(a, b *node.HarnessNode) {
×
159
        // errConnectionRequested is used to signal that a connection was
×
160
        // requested successfully, which is distinct from already being
×
161
        // connected to the peer.
×
162
        errConnectionRequested := "connection request in progress"
×
163

×
164
        // windowsErr is an error we've seen from windows build where
×
165
        // connecting to an already connected node gives such error from the
×
166
        // receiver side.
×
167
        windowsErr := "An established connection was aborted by the software " +
×
168
                "in your host machine."
×
169

×
170
        tryConnect := func(a, b *node.HarnessNode) error {
×
171
                bInfo := b.RPC.GetInfo()
×
172

×
173
                req := &lnrpc.ConnectPeerRequest{
×
174
                        Addr: &lnrpc.LightningAddress{
×
175
                                Pubkey: bInfo.IdentityPubkey,
×
176
                                Host:   b.Cfg.P2PAddr(),
×
177
                        },
×
178
                }
×
179

×
180
                ctxt, cancel := context.WithTimeout(h.runCtx, DefaultTimeout)
×
181
                defer cancel()
×
182

×
183
                _, err := a.RPC.LN.ConnectPeer(ctxt, req)
×
184

×
185
                // Request was successful.
×
186
                if err == nil {
×
187
                        return nil
×
188
                }
×
189

190
                // If the two are already connected, we return early with no
191
                // error.
192
                if strings.Contains(err.Error(), "already connected to peer") {
×
193
                        return nil
×
194
                }
×
195

196
                // Otherwise we log the error to console.
197
                h.Logf("EnsureConnected %s=>%s got err: %v", a.Name(),
×
198
                        b.Name(), err)
×
199

×
200
                // If the connection is in process, we return no error.
×
201
                if strings.Contains(err.Error(), errConnectionRequested) {
×
202
                        return nil
×
203
                }
×
204

205
                // We may get connection refused error if we happens to be in
206
                // the middle of a previous node disconnection, e.g., a restart
207
                // from one of the nodes.
208
                if strings.Contains(err.Error(), "connection refused") {
×
209
                        return nil
×
210
                }
×
211

212
                // Check for windows error. If Alice connects to Bob, Alice
213
                // will throw "i/o timeout" and Bob will give windowsErr.
214
                if strings.Contains(err.Error(), windowsErr) {
×
215
                        return nil
×
216
                }
×
217

218
                if strings.Contains(err.Error(), "i/o timeout") {
×
219
                        return nil
×
220
                }
×
221

222
                return err
×
223
        }
224

225
        // Return any critical errors returned by either alice or bob.
226
        require.NoError(h, tryConnect(a, b), "connection failed between %s "+
×
227
                "and %s", a.Cfg.Name, b.Cfg.Name)
×
228

×
229
        // When Alice and Bob each makes a connection to the other side at the
×
230
        // same time, it's likely neither connections could succeed. Bob's
×
231
        // connection will be canceled by Alice since she has an outbound
×
232
        // connection to Bob already, and same happens to Alice's. Thus the two
×
233
        // connections cancel each other out.
×
234
        // TODO(yy): move this back when the above issue is fixed.
×
235
        // require.NoError(h, tryConnect(b, a), "connection failed between %s "+
×
236
        //         "and %s", a.Cfg.Name, b.Cfg.Name)
×
237

×
238
        // Otherwise one or both requested a connection, so we wait for the
×
239
        // peers lists to reflect the connection.
×
240
        h.AssertPeerConnected(a, b)
×
241
        h.AssertPeerConnected(b, a)
×
242
}
243

244
// ConnectNodesNoAssert creates a connection from node A to node B.
245
func (h *HarnessTest) ConnectNodesNoAssert(a, b *node.HarnessNode) (
246
        *lnrpc.ConnectPeerResponse, error) {
×
247

×
248
        bobInfo := b.RPC.GetInfo()
×
249

×
250
        req := &lnrpc.ConnectPeerRequest{
×
251
                Addr: &lnrpc.LightningAddress{
×
252
                        Pubkey: bobInfo.IdentityPubkey,
×
253
                        Host:   b.Cfg.P2PAddr(),
×
254
                },
×
255
        }
×
256
        ctxt, cancel := context.WithTimeout(h.runCtx, DefaultTimeout)
×
257
        defer cancel()
×
258

×
259
        return a.RPC.LN.ConnectPeer(ctxt, req)
×
260
}
×
261

262
// AssertNumEdges checks that an expected number of edges can be found in the
263
// node specified.
264
func (h *HarnessTest) AssertNumEdges(hn *node.HarnessNode,
265
        expected int, includeUnannounced bool) []*lnrpc.ChannelEdge {
×
266

×
267
        var edges []*lnrpc.ChannelEdge
×
268

×
269
        old := hn.State.Edge.Public
×
270
        if includeUnannounced {
×
271
                old = hn.State.Edge.Total
×
272
        }
×
273

274
        err := wait.NoError(func() error {
×
275
                req := &lnrpc.ChannelGraphRequest{
×
276
                        IncludeUnannounced: includeUnannounced,
×
277
                }
×
278
                resp := hn.RPC.DescribeGraph(req)
×
279
                total := len(resp.Edges)
×
280

×
281
                if total-old == expected {
×
282
                        if expected != 0 {
×
283
                                // NOTE: assume edges come in ascending order
×
284
                                // that the old edges are at the front of the
×
285
                                // slice.
×
286
                                edges = resp.Edges[old:]
×
287
                        }
×
288

289
                        return nil
×
290
                }
291

292
                return errNumNotMatched(hn.Name(), "num of channel edges",
×
293
                        expected, total-old, total, old)
×
294
        }, DefaultTimeout)
295

296
        require.NoError(h, err, "timeout while checking for edges")
×
297

×
298
        return edges
×
299
}
300

301
// ReceiveOpenChannelUpdate waits until a message is received on the stream or
302
// the timeout is reached.
303
func (h *HarnessTest) ReceiveOpenChannelUpdate(
304
        stream rpc.OpenChanClient) *lnrpc.OpenStatusUpdate {
×
305

×
306
        update, err := h.receiveOpenChannelUpdate(stream)
×
307
        require.NoError(h, err, "received err from open channel stream")
×
308

×
309
        return update
×
310
}
×
311

312
// ReceiveOpenChannelError waits for the expected error during the open channel
313
// flow from the peer or times out.
314
func (h *HarnessTest) ReceiveOpenChannelError(
315
        stream rpc.OpenChanClient, expectedErr error) {
×
316

×
317
        _, err := h.receiveOpenChannelUpdate(stream)
×
318
        require.Contains(h, err.Error(), expectedErr.Error(),
×
319
                "error not matched")
×
320
}
×
321

322
// receiveOpenChannelUpdate waits until a message or an error is received on
323
// the stream or the timeout is reached.
324
//
325
// TODO(yy): use generics to unify all receiving stream update once go@1.18 is
326
// used.
327
func (h *HarnessTest) receiveOpenChannelUpdate(
328
        stream rpc.OpenChanClient) (*lnrpc.OpenStatusUpdate, error) {
×
329

×
330
        chanMsg := make(chan *lnrpc.OpenStatusUpdate)
×
331
        errChan := make(chan error)
×
332
        go func() {
×
333
                // Consume one message. This will block until the message is
×
334
                // received.
×
335
                resp, err := stream.Recv()
×
336
                if err != nil {
×
337
                        errChan <- err
×
338
                        return
×
339
                }
×
340
                chanMsg <- resp
×
341
        }()
342

343
        select {
×
344
        case <-time.After(DefaultTimeout):
×
345
                require.Fail(h, "timeout", "timeout waiting for open channel "+
×
346
                        "update sent")
×
347
                return nil, nil
×
348

349
        case err := <-errChan:
×
350
                return nil, err
×
351

352
        case updateMsg := <-chanMsg:
×
353
                return updateMsg, nil
×
354
        }
355
}
356

357
// WaitForChannelOpenEvent waits for a notification that a channel is open by
358
// consuming a message from the passed open channel stream.
359
func (h HarnessTest) WaitForChannelOpenEvent(
360
        stream rpc.OpenChanClient) *lnrpc.ChannelPoint {
×
361

×
362
        // Consume one event.
×
363
        event := h.ReceiveOpenChannelUpdate(stream)
×
364

×
365
        resp, ok := event.Update.(*lnrpc.OpenStatusUpdate_ChanOpen)
×
366
        require.Truef(h, ok, "expected channel open update, instead got %v",
×
367
                resp)
×
368

×
369
        return resp.ChanOpen.ChannelPoint
×
370
}
×
371

372
// AssertChannelExists asserts that an active channel identified by the
373
// specified channel point exists from the point-of-view of the node.
374
func (h *HarnessTest) AssertChannelExists(hn *node.HarnessNode,
375
        cp *lnrpc.ChannelPoint) *lnrpc.Channel {
×
376

×
377
        return h.assertChannelStatus(hn, cp, true)
×
378
}
×
379

380
// AssertChannelActive checks if a channel identified by the specified channel
381
// point is active.
382
func (h *HarnessTest) AssertChannelActive(hn *node.HarnessNode,
383
        cp *lnrpc.ChannelPoint) *lnrpc.Channel {
×
384

×
385
        return h.assertChannelStatus(hn, cp, true)
×
386
}
×
387

388
// AssertChannelInactive checks if a channel identified by the specified channel
389
// point is inactive.
390
func (h *HarnessTest) AssertChannelInactive(hn *node.HarnessNode,
391
        cp *lnrpc.ChannelPoint) *lnrpc.Channel {
×
392

×
393
        return h.assertChannelStatus(hn, cp, false)
×
394
}
×
395

396
// assertChannelStatus asserts that a channel identified by the specified
397
// channel point exists from the point-of-view of the node and that it is either
398
// active or inactive depending on the value of the active parameter.
399
func (h *HarnessTest) assertChannelStatus(hn *node.HarnessNode,
400
        cp *lnrpc.ChannelPoint, active bool) *lnrpc.Channel {
×
401

×
402
        var (
×
403
                channel *lnrpc.Channel
×
404
                err     error
×
405
        )
×
406

×
407
        err = wait.NoError(func() error {
×
408
                channel, err = h.findChannel(hn, cp)
×
409
                if err != nil {
×
410
                        return err
×
411
                }
×
412

413
                // Check whether the channel is active, exit early if it is.
414
                if channel.Active == active {
×
415
                        return nil
×
416
                }
×
417

418
                return fmt.Errorf("expected channel_active=%v, got %v",
×
419
                        active, channel.Active)
×
420
        }, DefaultTimeout)
421

422
        require.NoErrorf(h, err, "%s: timeout checking for channel point: %v",
×
423
                hn.Name(), h.OutPointFromChannelPoint(cp))
×
424

×
425
        return channel
×
426
}
427

428
// AssertOutputScriptClass checks that the specified transaction output has the
429
// expected script class.
430
func (h *HarnessTest) AssertOutputScriptClass(tx *btcutil.Tx,
431
        outputIndex uint32, scriptClass txscript.ScriptClass) {
×
432

×
433
        require.Greater(h, len(tx.MsgTx().TxOut), int(outputIndex))
×
434

×
435
        txOut := tx.MsgTx().TxOut[outputIndex]
×
436

×
437
        pkScript, err := txscript.ParsePkScript(txOut.PkScript)
×
438
        require.NoError(h, err)
×
439
        require.Equal(h, scriptClass, pkScript.Class())
×
440
}
×
441

442
// findChannel tries to find a target channel in the node using the given
443
// channel point.
444
func (h *HarnessTest) findChannel(hn *node.HarnessNode,
445
        chanPoint *lnrpc.ChannelPoint,
446
        opts ...ListChannelOption) (*lnrpc.Channel, error) {
×
447

×
448
        // Get the funding point.
×
449
        fp := h.OutPointFromChannelPoint(chanPoint)
×
450

×
451
        req := &lnrpc.ListChannelsRequest{}
×
452

×
453
        for _, opt := range opts {
×
454
                opt(req)
×
455
        }
×
456

457
        channelInfo := hn.RPC.ListChannels(req)
×
458

×
459
        // Find the target channel.
×
460
        for _, channel := range channelInfo.Channels {
×
461
                if channel.ChannelPoint == fp.String() {
×
462
                        return channel, nil
×
463
                }
×
464
        }
465

466
        return nil, fmt.Errorf("%s: channel not found using %s", hn.Name(),
×
467
                fp.String())
×
468
}
469

470
// ReceiveCloseChannelUpdate waits until a message or an error is received on
471
// the subscribe channel close stream or the timeout is reached.
472
func (h *HarnessTest) ReceiveCloseChannelUpdate(
473
        stream rpc.CloseChanClient) (*lnrpc.CloseStatusUpdate, error) {
×
474

×
475
        chanMsg := make(chan *lnrpc.CloseStatusUpdate)
×
476
        errChan := make(chan error)
×
477
        go func() {
×
478
                // Consume one message. This will block until the message is
×
479
                // received.
×
480
                resp, err := stream.Recv()
×
481
                if err != nil {
×
482
                        errChan <- err
×
483
                        return
×
484
                }
×
485
                chanMsg <- resp
×
486
        }()
487

488
        select {
×
489
        case <-time.After(DefaultTimeout):
×
490
                require.Fail(h, "timeout", "timeout waiting for close channel "+
×
491
                        "update sent")
×
492

×
493
                return nil, nil
×
494

495
        case err := <-errChan:
×
496
                return nil, fmt.Errorf("received err from close channel "+
×
497
                        "stream: %v", err)
×
498

499
        case updateMsg := <-chanMsg:
×
500
                return updateMsg, nil
×
501
        }
502
}
503

504
type WaitingCloseChannel *lnrpc.PendingChannelsResponse_WaitingCloseChannel
505

506
// AssertChannelWaitingClose asserts that the given channel found in the node
507
// is waiting close. Returns the WaitingCloseChannel if found.
508
func (h *HarnessTest) AssertChannelWaitingClose(hn *node.HarnessNode,
509
        chanPoint *lnrpc.ChannelPoint) WaitingCloseChannel {
×
510

×
511
        var target WaitingCloseChannel
×
512

×
513
        op := h.OutPointFromChannelPoint(chanPoint)
×
514

×
515
        err := wait.NoError(func() error {
×
516
                resp := hn.RPC.PendingChannels()
×
517

×
518
                for _, waitingClose := range resp.WaitingCloseChannels {
×
519
                        if waitingClose.Channel.ChannelPoint == op.String() {
×
520
                                target = waitingClose
×
521
                                return nil
×
522
                        }
×
523
                }
524

525
                return fmt.Errorf("%v: channel %s not found in waiting close",
×
526
                        hn.Name(), op)
×
527
        }, DefaultTimeout)
528
        require.NoError(h, err, "assert channel waiting close timed out")
×
529

×
530
        return target
×
531
}
532

533
// AssertTopologyChannelClosed asserts a given channel is closed by checking
534
// the graph topology subscription of the specified node. Returns the closed
535
// channel update if found.
536
func (h *HarnessTest) AssertTopologyChannelClosed(hn *node.HarnessNode,
537
        chanPoint *lnrpc.ChannelPoint) *lnrpc.ClosedChannelUpdate {
×
538

×
539
        closedChan, err := hn.Watcher.WaitForChannelClose(chanPoint)
×
540
        require.NoError(h, err, "failed to wait for channel close")
×
541

×
542
        return closedChan
×
543
}
×
544

545
// WaitForChannelCloseEvent waits for a notification that a channel is closed
546
// by consuming a message from the passed close channel stream. Returns the
547
// closing txid if found.
548
func (h HarnessTest) WaitForChannelCloseEvent(
549
        stream rpc.CloseChanClient) chainhash.Hash {
×
550

×
551
        // Consume one event.
×
552
        event, err := h.ReceiveCloseChannelUpdate(stream)
×
553
        require.NoError(h, err)
×
554

×
555
        resp, ok := event.Update.(*lnrpc.CloseStatusUpdate_ChanClose)
×
NEW
556
        require.Truef(h, ok, "expected channel close update, instead got %T: %v",
×
NEW
557
                event.Update, spew.Sdump(event.Update))
×
558

×
559
        txid, err := chainhash.NewHash(resp.ChanClose.ClosingTxid)
×
560
        require.NoErrorf(h, err, "wrong format found in closing txid: %v",
×
561
                resp.ChanClose.ClosingTxid)
×
562

×
563
        return *txid
×
564
}
×
565

566
// AssertNumWaitingClose checks that a PendingChannels response from the node
567
// reports the expected number of waiting close channels.
568
func (h *HarnessTest) AssertNumWaitingClose(hn *node.HarnessNode,
569
        num int) []*lnrpc.PendingChannelsResponse_WaitingCloseChannel {
×
570

×
571
        var channels []*lnrpc.PendingChannelsResponse_WaitingCloseChannel
×
572
        oldWaiting := hn.State.CloseChannel.WaitingClose
×
573

×
574
        err := wait.NoError(func() error {
×
575
                resp := hn.RPC.PendingChannels()
×
576
                channels = resp.WaitingCloseChannels
×
577
                total := len(channels)
×
578

×
579
                got := total - oldWaiting
×
580
                if got == num {
×
581
                        return nil
×
582
                }
×
583

584
                return errNumNotMatched(hn.Name(), "waiting close channels",
×
585
                        num, got, total, oldWaiting)
×
586
        }, DefaultTimeout)
587

588
        require.NoErrorf(h, err, "%s: assert waiting close timeout",
×
589
                hn.Name())
×
590

×
591
        return channels
×
592
}
593

594
// AssertNumPendingForceClose checks that a PendingChannels response from the
595
// node reports the expected number of pending force close channels.
596
func (h *HarnessTest) AssertNumPendingForceClose(hn *node.HarnessNode,
597
        num int) []*lnrpc.PendingChannelsResponse_ForceClosedChannel {
×
598

×
599
        var channels []*lnrpc.PendingChannelsResponse_ForceClosedChannel
×
600
        oldForce := hn.State.CloseChannel.PendingForceClose
×
601

×
602
        err := wait.NoError(func() error {
×
603
                // TODO(yy): we should be able to use `hn.RPC.PendingChannels`
×
604
                // here to avoid checking the RPC error. However, we may get a
×
605
                // `unable to find arbitrator` error from the rpc point, due to
×
606
                // a timing issue in rpcserver,
×
607
                // 1. `r.server.chanStateDB.FetchClosedChannels` fetches
×
608
                //    the pending force close channel.
×
609
                // 2. `r.arbitratorPopulateForceCloseResp` relies on the
×
610
                //    channel arbitrator to get the report, and,
×
611
                // 3. the arbitrator may be deleted due to the force close
×
612
                //    channel being resolved.
×
613
                // Somewhere along the line is missing a lock to keep the data
×
614
                // consistent.
×
615
                req := &lnrpc.PendingChannelsRequest{}
×
616
                resp, err := hn.RPC.LN.PendingChannels(h.runCtx, req)
×
617
                if err != nil {
×
618
                        return fmt.Errorf("PendingChannels got: %w", err)
×
619
                }
×
620

621
                channels = resp.PendingForceClosingChannels
×
622
                total := len(channels)
×
623

×
624
                got := total - oldForce
×
625
                if got == num {
×
626
                        return nil
×
627
                }
×
628

629
                return errNumNotMatched(hn.Name(), "pending force close "+
×
630
                        "channels", num, got, total, oldForce)
×
631
        }, DefaultTimeout)
632

633
        require.NoErrorf(h, err, "%s: assert pending force close timeout",
×
634
                hn.Name())
×
635

×
636
        return channels
×
637
}
638

639
// AssertStreamChannelCoopClosed reads an update from the close channel client
640
// stream and asserts that the mempool state and node's topology match a coop
641
// close. In specific,
642
// - assert the channel is waiting close and has the expected ChanStatusFlags.
643
// - assert the mempool has the closing txes and anchor sweeps.
644
// - mine a block and assert the closing txid is mined.
645
// - assert the node has zero waiting close channels.
646
// - assert the node has seen the channel close update.
647
func (h *HarnessTest) AssertStreamChannelCoopClosed(hn *node.HarnessNode,
648
        cp *lnrpc.ChannelPoint, anchors bool,
649
        stream rpc.CloseChanClient) chainhash.Hash {
×
650

×
651
        // Assert the channel is waiting close.
×
652
        resp := h.AssertChannelWaitingClose(hn, cp)
×
653

×
654
        // Assert that the channel is in coop broadcasted.
×
655
        require.Contains(h, resp.Channel.ChanStatusFlags,
×
656
                channeldb.ChanStatusCoopBroadcasted.String(),
×
657
                "channel not coop broadcasted")
×
658

×
659
        // We'll now, generate a single block, wait for the final close status
×
660
        // update, then ensure that the closing transaction was included in the
×
661
        // block. If there are anchors, we also expect an anchor sweep.
×
662
        expectedTxes := 1
×
663
        if anchors {
×
664
                expectedTxes = 2
×
665
        }
×
666
        block := h.MineBlocksAndAssertNumTxes(1, expectedTxes)[0]
×
667

×
668
        // Consume one close event and assert the closing txid can be found in
×
669
        // the block.
×
670
        closingTxid := h.WaitForChannelCloseEvent(stream)
×
671
        h.AssertTxInBlock(block, closingTxid)
×
672

×
673
        // We should see zero waiting close channels now.
×
674
        h.AssertNumWaitingClose(hn, 0)
×
675

×
676
        // Finally, check that the node's topology graph has seen this channel
×
677
        // closed if it's a public channel.
×
678
        if !resp.Channel.Private {
×
679
                h.AssertTopologyChannelClosed(hn, cp)
×
680
        }
×
681

682
        return closingTxid
×
683
}
684

685
// AssertStreamChannelForceClosed reads an update from the close channel client
686
// stream and asserts that the mempool state and node's topology match a local
687
// force close. In specific,
688
//   - assert the channel is waiting close and has the expected ChanStatusFlags.
689
//   - assert the mempool has the closing txes.
690
//   - mine a block and assert the closing txid is mined.
691
//   - assert the channel is pending force close.
692
//   - assert the node has seen the channel close update.
693
//   - assert there's a pending anchor sweep request once the force close tx is
694
//     confirmed.
695
func (h *HarnessTest) AssertStreamChannelForceClosed(hn *node.HarnessNode,
696
        cp *lnrpc.ChannelPoint, anchorSweep bool,
697
        stream rpc.CloseChanClient) chainhash.Hash {
×
698

×
699
        // Assert the channel is waiting close.
×
700
        resp := h.AssertChannelWaitingClose(hn, cp)
×
701

×
702
        // Assert that the channel is in local force broadcasted.
×
703
        require.Contains(h, resp.Channel.ChanStatusFlags,
×
704
                channeldb.ChanStatusLocalCloseInitiator.String(),
×
705
                "channel not coop broadcasted")
×
706

×
707
        // Get the closing txid.
×
708
        closeTxid, err := chainhash.NewHashFromStr(resp.ClosingTxid)
×
709
        require.NoError(h, err)
×
710

×
711
        // We'll now, generate a single block, wait for the final close status
×
712
        // update, then ensure that the closing transaction was included in the
×
713
        // block.
×
714
        closeTx := h.AssertTxInMempool(*closeTxid)
×
715
        h.MineBlockWithTx(closeTx)
×
716

×
717
        // Consume one close event and assert the closing txid can be found in
×
718
        // the block.
×
719
        closingTxid := h.WaitForChannelCloseEvent(stream)
×
720

×
721
        // We should see zero waiting close channels and 1 pending force close
×
722
        // channels now.
×
723
        h.AssertNumWaitingClose(hn, 0)
×
724
        h.AssertNumPendingForceClose(hn, 1)
×
725

×
726
        // Finally, check that the node's topology graph has seen this channel
×
727
        // closed if it's a public channel.
×
728
        if !resp.Channel.Private {
×
729
                h.AssertTopologyChannelClosed(hn, cp)
×
730
        }
×
731

732
        // Assert there's a pending anchor sweep.
733
        //
734
        // NOTE: We may have a local sweep here, that's why we use
735
        // AssertAtLeastNumPendingSweeps instead of AssertNumPendingSweeps.
736
        if anchorSweep {
×
737
                h.AssertAtLeastNumPendingSweeps(hn, 1)
×
738
        }
×
739

740
        return closingTxid
×
741
}
742

743
// AssertChannelPolicyUpdate checks that the required policy update has
744
// happened on the given node.
745
func (h *HarnessTest) AssertChannelPolicyUpdate(hn *node.HarnessNode,
746
        advertisingNode *node.HarnessNode, policy *lnrpc.RoutingPolicy,
747
        chanPoint *lnrpc.ChannelPoint, includeUnannounced bool) {
×
748

×
749
        require.NoError(
×
750
                h, hn.Watcher.WaitForChannelPolicyUpdate(
×
751
                        advertisingNode, policy,
×
752
                        chanPoint, includeUnannounced,
×
753
                ), "%s: error while waiting for channel update", hn.Name(),
×
754
        )
×
755
}
×
756

757
// WaitForGraphSync waits until the node is synced to graph or times out.
758
func (h *HarnessTest) WaitForGraphSync(hn *node.HarnessNode) {
×
759
        err := wait.NoError(func() error {
×
760
                resp := hn.RPC.GetInfo()
×
761
                if resp.SyncedToGraph {
×
762
                        return nil
×
763
                }
×
764

765
                return fmt.Errorf("node not synced to graph")
×
766
        }, DefaultTimeout)
767
        require.NoError(h, err, "%s: timeout while sync to graph", hn.Name())
×
768
}
769

770
// AssertNumUTXOsWithConf waits for the given number of UTXOs with the
771
// specified confirmations range to be available or fails if that isn't the
772
// case before the default timeout.
773
func (h *HarnessTest) AssertNumUTXOsWithConf(hn *node.HarnessNode,
774
        expectedUtxos int, max, min int32) []*lnrpc.Utxo {
×
775

×
776
        var unconfirmed bool
×
777

×
778
        if max == 0 {
×
779
                unconfirmed = true
×
780
        }
×
781

782
        var utxos []*lnrpc.Utxo
×
783
        err := wait.NoError(func() error {
×
784
                req := &walletrpc.ListUnspentRequest{
×
785
                        Account:         "",
×
786
                        MaxConfs:        max,
×
787
                        MinConfs:        min,
×
788
                        UnconfirmedOnly: unconfirmed,
×
789
                }
×
790
                resp := hn.RPC.ListUnspent(req)
×
791
                total := len(resp.Utxos)
×
792

×
793
                if total == expectedUtxos {
×
794
                        utxos = resp.Utxos
×
795

×
796
                        return nil
×
797
                }
×
798

799
                desc := "has UTXOs:\n"
×
800
                for _, utxo := range resp.Utxos {
×
801
                        desc += fmt.Sprintf("%v\n", utxo)
×
802
                }
×
803

804
                return fmt.Errorf("%s: assert num of UTXOs failed: want %d, "+
×
805
                        "got: %d, %s", hn.Name(), expectedUtxos, total, desc)
×
806
        }, DefaultTimeout)
807
        require.NoError(h, err, "timeout waiting for UTXOs")
×
808

×
809
        return utxos
×
810
}
811

812
// AssertNumUTXOsUnconfirmed asserts the expected num of unconfirmed utxos are
813
// seen.
814
func (h *HarnessTest) AssertNumUTXOsUnconfirmed(hn *node.HarnessNode,
815
        num int) []*lnrpc.Utxo {
×
816

×
817
        return h.AssertNumUTXOsWithConf(hn, num, 0, 0)
×
818
}
×
819

820
// AssertNumUTXOsConfirmed asserts the expected num of confirmed utxos are
821
// seen, which means the returned utxos have at least one confirmation.
822
func (h *HarnessTest) AssertNumUTXOsConfirmed(hn *node.HarnessNode,
823
        num int) []*lnrpc.Utxo {
×
824

×
825
        return h.AssertNumUTXOsWithConf(hn, num, math.MaxInt32, 1)
×
826
}
×
827

828
// AssertNumUTXOs asserts the expected num of utxos are seen, including
829
// confirmed and unconfirmed outputs.
830
func (h *HarnessTest) AssertNumUTXOs(hn *node.HarnessNode,
831
        num int) []*lnrpc.Utxo {
×
832

×
833
        return h.AssertNumUTXOsWithConf(hn, num, math.MaxInt32, 0)
×
834
}
×
835

836
// getUTXOs gets the number of newly created UTOXs within the current test
837
// scope.
838
func (h *HarnessTest) getUTXOs(hn *node.HarnessNode, account string,
839
        max, min int32) []*lnrpc.Utxo {
×
840

×
841
        var unconfirmed bool
×
842

×
843
        if max == 0 {
×
844
                unconfirmed = true
×
845
        }
×
846

847
        req := &walletrpc.ListUnspentRequest{
×
848
                Account:         account,
×
849
                MaxConfs:        max,
×
850
                MinConfs:        min,
×
851
                UnconfirmedOnly: unconfirmed,
×
852
        }
×
853
        resp := hn.RPC.ListUnspent(req)
×
854

×
855
        return resp.Utxos
×
856
}
857

858
// GetUTXOs returns all the UTXOs for the given node's account, including
859
// confirmed and unconfirmed.
860
func (h *HarnessTest) GetUTXOs(hn *node.HarnessNode,
861
        account string) []*lnrpc.Utxo {
×
862

×
863
        return h.getUTXOs(hn, account, math.MaxInt32, 0)
×
864
}
×
865

866
// GetUTXOsConfirmed returns the confirmed UTXOs for the given node's account.
867
func (h *HarnessTest) GetUTXOsConfirmed(hn *node.HarnessNode,
868
        account string) []*lnrpc.Utxo {
×
869

×
870
        return h.getUTXOs(hn, account, math.MaxInt32, 1)
×
871
}
×
872

873
// GetUTXOsUnconfirmed returns the unconfirmed UTXOs for the given node's
874
// account.
875
func (h *HarnessTest) GetUTXOsUnconfirmed(hn *node.HarnessNode,
876
        account string) []*lnrpc.Utxo {
×
877

×
878
        return h.getUTXOs(hn, account, 0, 0)
×
879
}
×
880

881
// WaitForBalanceConfirmed waits until the node sees the expected confirmed
882
// balance in its wallet.
883
func (h *HarnessTest) WaitForBalanceConfirmed(hn *node.HarnessNode,
884
        expected btcutil.Amount) {
×
885

×
886
        var lastBalance btcutil.Amount
×
887
        err := wait.NoError(func() error {
×
888
                resp := hn.RPC.WalletBalance()
×
889

×
890
                lastBalance = btcutil.Amount(resp.ConfirmedBalance)
×
891
                if lastBalance == expected {
×
892
                        return nil
×
893
                }
×
894

895
                return fmt.Errorf("expected %v, only have %v", expected,
×
896
                        lastBalance)
×
897
        }, DefaultTimeout)
898

899
        require.NoError(h, err, "timeout waiting for confirmed balances")
×
900
}
901

902
// WaitForBalanceUnconfirmed waits until the node sees the expected unconfirmed
903
// balance in its wallet.
904
func (h *HarnessTest) WaitForBalanceUnconfirmed(hn *node.HarnessNode,
905
        expected btcutil.Amount) {
×
906

×
907
        var lastBalance btcutil.Amount
×
908
        err := wait.NoError(func() error {
×
909
                resp := hn.RPC.WalletBalance()
×
910

×
911
                lastBalance = btcutil.Amount(resp.UnconfirmedBalance)
×
912
                if lastBalance == expected {
×
913
                        return nil
×
914
                }
×
915

916
                return fmt.Errorf("expected %v, only have %v", expected,
×
917
                        lastBalance)
×
918
        }, DefaultTimeout)
919

920
        require.NoError(h, err, "timeout waiting for unconfirmed balances")
×
921
}
922

923
// Random32Bytes generates a random 32 bytes which can be used as a pay hash,
924
// preimage, etc.
925
func (h *HarnessTest) Random32Bytes() []byte {
×
926
        randBuf := make([]byte, lntypes.HashSize)
×
927

×
928
        _, err := rand.Read(randBuf)
×
929
        require.NoErrorf(h, err, "internal error, cannot generate random bytes")
×
930

×
931
        return randBuf
×
932
}
×
933

934
// RandomPreimage generates a random preimage which can be used as a payment
935
// preimage.
936
func (h *HarnessTest) RandomPreimage() lntypes.Preimage {
×
937
        var preimage lntypes.Preimage
×
938
        copy(preimage[:], h.Random32Bytes())
×
939

×
940
        return preimage
×
941
}
×
942

943
// DecodeAddress decodes a given address and asserts there's no error.
944
func (h *HarnessTest) DecodeAddress(addr string) btcutil.Address {
×
945
        resp, err := btcutil.DecodeAddress(addr, miner.HarnessNetParams)
×
946
        require.NoError(h, err, "DecodeAddress failed")
×
947

×
948
        return resp
×
949
}
×
950

951
// PayToAddrScript creates a new script from the given address and asserts
952
// there's no error.
953
func (h *HarnessTest) PayToAddrScript(addr btcutil.Address) []byte {
×
954
        addrScript, err := txscript.PayToAddrScript(addr)
×
955
        require.NoError(h, err, "PayToAddrScript failed")
×
956

×
957
        return addrScript
×
958
}
×
959

960
// AssertChannelBalanceResp makes a ChannelBalance request and checks the
961
// returned response matches the expected.
962
func (h *HarnessTest) AssertChannelBalanceResp(hn *node.HarnessNode,
963
        expected *lnrpc.ChannelBalanceResponse) {
×
964

×
965
        resp := hn.RPC.ChannelBalance()
×
966

×
967
        // Ignore custom channel data of both expected and actual responses.
×
968
        expected.CustomChannelData = nil
×
969
        resp.CustomChannelData = nil
×
970

×
971
        require.True(h, proto.Equal(expected, resp), "balance is incorrect "+
×
972
                "got: %v, want: %v", resp, expected)
×
973
}
×
974

975
// GetChannelByChanPoint tries to find a channel matching the channel point and
976
// asserts. It returns the channel found.
977
func (h *HarnessTest) GetChannelByChanPoint(hn *node.HarnessNode,
978
        chanPoint *lnrpc.ChannelPoint) *lnrpc.Channel {
×
979

×
980
        channel, err := h.findChannel(hn, chanPoint)
×
981
        require.NoErrorf(h, err, "channel not found using %v", chanPoint)
×
982

×
983
        return channel
×
984
}
×
985

986
// GetChannelCommitType retrieves the active channel commitment type for the
987
// given chan point.
988
func (h *HarnessTest) GetChannelCommitType(hn *node.HarnessNode,
989
        chanPoint *lnrpc.ChannelPoint) lnrpc.CommitmentType {
×
990

×
991
        c := h.GetChannelByChanPoint(hn, chanPoint)
×
992

×
993
        return c.CommitmentType
×
994
}
×
995

996
// AssertNumPendingOpenChannels asserts that a given node have the expected
997
// number of pending open channels.
998
func (h *HarnessTest) AssertNumPendingOpenChannels(hn *node.HarnessNode,
999
        expected int) []*lnrpc.PendingChannelsResponse_PendingOpenChannel {
×
1000

×
1001
        var channels []*lnrpc.PendingChannelsResponse_PendingOpenChannel
×
1002

×
1003
        oldNum := hn.State.OpenChannel.Pending
×
1004

×
1005
        err := wait.NoError(func() error {
×
1006
                resp := hn.RPC.PendingChannels()
×
1007
                channels = resp.PendingOpenChannels
×
1008
                total := len(channels)
×
1009

×
1010
                numChans := total - oldNum
×
1011

×
1012
                if numChans != expected {
×
1013
                        return errNumNotMatched(hn.Name(),
×
1014
                                "pending open channels", expected,
×
1015
                                numChans, total, oldNum)
×
1016
                }
×
1017

1018
                return nil
×
1019
        }, DefaultTimeout)
1020

1021
        require.NoError(h, err, "num of pending open channels not match")
×
1022

×
1023
        return channels
×
1024
}
1025

1026
// AssertNodesNumPendingOpenChannels asserts that both of the nodes have the
1027
// expected number of pending open channels.
1028
func (h *HarnessTest) AssertNodesNumPendingOpenChannels(a, b *node.HarnessNode,
1029
        expected int) {
×
1030

×
1031
        h.AssertNumPendingOpenChannels(a, expected)
×
1032
        h.AssertNumPendingOpenChannels(b, expected)
×
1033
}
×
1034

1035
// AssertPaymentStatusFromStream takes a client stream and asserts the payment
1036
// is in desired status before default timeout. The payment found is returned
1037
// once succeeded.
1038
func (h *HarnessTest) AssertPaymentStatusFromStream(stream rpc.PaymentClient,
1039
        status lnrpc.Payment_PaymentStatus) *lnrpc.Payment {
×
1040

×
1041
        return h.assertPaymentStatusWithTimeout(
×
1042
                stream, status, wait.PaymentTimeout,
×
1043
        )
×
1044
}
×
1045

1046
// AssertPaymentSucceedWithTimeout asserts that a payment is succeeded within
1047
// the specified timeout.
1048
func (h *HarnessTest) AssertPaymentSucceedWithTimeout(stream rpc.PaymentClient,
1049
        timeout time.Duration) *lnrpc.Payment {
×
1050

×
1051
        return h.assertPaymentStatusWithTimeout(
×
1052
                stream, lnrpc.Payment_SUCCEEDED, timeout,
×
1053
        )
×
1054
}
×
1055

1056
// assertPaymentStatusWithTimeout takes a client stream and asserts the payment
1057
// is in desired status before the specified timeout. The payment found is
1058
// returned once succeeded.
1059
func (h *HarnessTest) assertPaymentStatusWithTimeout(stream rpc.PaymentClient,
1060
        status lnrpc.Payment_PaymentStatus,
1061
        timeout time.Duration) *lnrpc.Payment {
×
1062

×
1063
        var target *lnrpc.Payment
×
1064
        err := wait.NoError(func() error {
×
1065
                // Consume one message. This will raise an error if the message
×
1066
                // is not received within DefaultTimeout.
×
1067
                payment, err := h.receivePaymentUpdateWithTimeout(
×
1068
                        stream, timeout,
×
1069
                )
×
1070
                if err != nil {
×
1071
                        return fmt.Errorf("received error from payment "+
×
1072
                                "stream: %s", err)
×
1073
                }
×
1074

1075
                // Return if the desired payment state is reached.
1076
                if payment.Status == status {
×
1077
                        target = payment
×
1078

×
1079
                        return nil
×
1080
                }
×
1081

1082
                // Return the err so that it can be used for debugging when
1083
                // timeout is reached.
1084
                return fmt.Errorf("payment %v status, got %v, want %v",
×
1085
                        payment.PaymentHash, payment.Status, status)
×
1086
        }, timeout)
1087

1088
        require.NoError(h, err, "timeout while waiting payment")
×
1089

×
1090
        return target
×
1091
}
1092

1093
// ReceivePaymentUpdate waits until a message is received on the payment client
1094
// stream or the timeout is reached.
1095
func (h *HarnessTest) ReceivePaymentUpdate(
1096
        stream rpc.PaymentClient) (*lnrpc.Payment, error) {
×
1097

×
1098
        return h.receivePaymentUpdateWithTimeout(stream, DefaultTimeout)
×
1099
}
×
1100

1101
// receivePaymentUpdateWithTimeout waits until a message is received on the
1102
// payment client stream or the timeout is reached.
1103
func (h *HarnessTest) receivePaymentUpdateWithTimeout(stream rpc.PaymentClient,
1104
        timeout time.Duration) (*lnrpc.Payment, error) {
×
1105

×
1106
        chanMsg := make(chan *lnrpc.Payment, 1)
×
1107
        errChan := make(chan error, 1)
×
1108

×
1109
        go func() {
×
1110
                // Consume one message. This will block until the message is
×
1111
                // received.
×
1112
                resp, err := stream.Recv()
×
1113
                if err != nil {
×
1114
                        errChan <- err
×
1115

×
1116
                        return
×
1117
                }
×
1118
                chanMsg <- resp
×
1119
        }()
1120

1121
        select {
×
1122
        case <-time.After(timeout):
×
1123
                require.Fail(h, "timeout", "timeout waiting for payment update")
×
1124
                return nil, nil
×
1125

1126
        case err := <-errChan:
×
1127
                return nil, err
×
1128

1129
        case updateMsg := <-chanMsg:
×
1130
                return updateMsg, nil
×
1131
        }
1132
}
1133

1134
// AssertInvoiceSettled asserts a given invoice specified by its payment
1135
// address is settled.
1136
func (h *HarnessTest) AssertInvoiceSettled(hn *node.HarnessNode, addr []byte) {
×
1137
        msg := &invoicesrpc.LookupInvoiceMsg{
×
1138
                InvoiceRef: &invoicesrpc.LookupInvoiceMsg_PaymentAddr{
×
1139
                        PaymentAddr: addr,
×
1140
                },
×
1141
        }
×
1142

×
1143
        err := wait.NoError(func() error {
×
1144
                invoice := hn.RPC.LookupInvoiceV2(msg)
×
1145
                if invoice.State == lnrpc.Invoice_SETTLED {
×
1146
                        return nil
×
1147
                }
×
1148

1149
                return fmt.Errorf("%s: invoice with payment address %x not "+
×
1150
                        "settled", hn.Name(), addr)
×
1151
        }, DefaultTimeout)
1152
        require.NoError(h, err, "timeout waiting for invoice settled state")
×
1153
}
1154

1155
// AssertNodeNumChannels polls the provided node's list channels rpc until it
1156
// reaches the desired number of total channels.
1157
func (h *HarnessTest) AssertNodeNumChannels(hn *node.HarnessNode,
1158
        numChannels int) {
×
1159

×
1160
        // Get the total number of channels.
×
1161
        old := hn.State.OpenChannel.Active + hn.State.OpenChannel.Inactive
×
1162

×
1163
        err := wait.NoError(func() error {
×
1164
                // We require the RPC call to be succeeded and won't wait for
×
1165
                // it as it's an unexpected behavior.
×
1166
                chanInfo := hn.RPC.ListChannels(&lnrpc.ListChannelsRequest{})
×
1167

×
1168
                // Return true if the query returned the expected number of
×
1169
                // channels.
×
1170
                num := len(chanInfo.Channels) - old
×
1171
                if num != numChannels {
×
1172
                        return fmt.Errorf("expected %v channels, got %v",
×
1173
                                numChannels, num)
×
1174
                }
×
1175

1176
                return nil
×
1177
        }, DefaultTimeout)
1178

1179
        require.NoError(h, err, "timeout checking node's num of channels")
×
1180
}
1181

1182
// AssertChannelLocalBalance checks the local balance of the given channel is
1183
// expected. The channel found using the specified channel point is returned.
1184
func (h *HarnessTest) AssertChannelLocalBalance(hn *node.HarnessNode,
1185
        cp *lnrpc.ChannelPoint, balance int64) *lnrpc.Channel {
×
1186

×
1187
        var result *lnrpc.Channel
×
1188

×
1189
        // Get the funding point.
×
1190
        err := wait.NoError(func() error {
×
1191
                // Find the target channel first.
×
1192
                target, err := h.findChannel(hn, cp)
×
1193

×
1194
                // Exit early if the channel is not found.
×
1195
                if err != nil {
×
1196
                        return fmt.Errorf("check balance failed: %w", err)
×
1197
                }
×
1198

1199
                result = target
×
1200

×
1201
                // Check local balance.
×
1202
                if target.LocalBalance == balance {
×
1203
                        return nil
×
1204
                }
×
1205

1206
                return fmt.Errorf("balance is incorrect, got %v, expected %v",
×
1207
                        target.LocalBalance, balance)
×
1208
        }, DefaultTimeout)
1209

1210
        require.NoError(h, err, "timeout while checking for balance")
×
1211

×
1212
        return result
×
1213
}
1214

1215
// AssertChannelNumUpdates checks the num of updates is expected from the given
1216
// channel.
1217
func (h *HarnessTest) AssertChannelNumUpdates(hn *node.HarnessNode,
1218
        num uint64, cp *lnrpc.ChannelPoint) {
×
1219

×
1220
        old := int(hn.State.OpenChannel.NumUpdates)
×
1221

×
1222
        // Find the target channel first.
×
1223
        target, err := h.findChannel(hn, cp)
×
1224
        require.NoError(h, err, "unable to find channel")
×
1225

×
1226
        err = wait.NoError(func() error {
×
1227
                total := int(target.NumUpdates)
×
1228
                if total-old == int(num) {
×
1229
                        return nil
×
1230
                }
×
1231

1232
                return errNumNotMatched(hn.Name(), "channel updates",
×
1233
                        int(num), total-old, total, old)
×
1234
        }, DefaultTimeout)
1235
        require.NoError(h, err, "timeout while checking for num of updates")
×
1236
}
1237

1238
// AssertNumActiveHtlcs asserts that a given number of HTLCs are seen in the
1239
// node's channels.
1240
func (h *HarnessTest) AssertNumActiveHtlcs(hn *node.HarnessNode, num int) {
×
1241
        old := hn.State.HTLC
×
1242

×
1243
        err := wait.NoError(func() error {
×
1244
                // pendingHTLCs is used to print unacked HTLCs, if found.
×
1245
                var pendingHTLCs []string
×
1246

×
1247
                // We require the RPC call to be succeeded and won't wait for
×
1248
                // it as it's an unexpected behavior.
×
1249
                req := &lnrpc.ListChannelsRequest{}
×
1250
                nodeChans := hn.RPC.ListChannels(req)
×
1251

×
1252
                total := 0
×
1253
                for _, channel := range nodeChans.Channels {
×
1254
                        for _, htlc := range channel.PendingHtlcs {
×
1255
                                if htlc.LockedIn {
×
1256
                                        total++
×
1257
                                }
×
1258

1259
                                rHash := fmt.Sprintf("%x", htlc.HashLock)
×
1260
                                pendingHTLCs = append(pendingHTLCs, rHash)
×
1261
                        }
1262
                }
1263
                if total-old != num {
×
1264
                        desc := fmt.Sprintf("active HTLCs: unacked HTLCs: %v",
×
1265
                                pendingHTLCs)
×
1266

×
1267
                        return errNumNotMatched(hn.Name(), desc,
×
1268
                                num, total-old, total, old)
×
1269
                }
×
1270

1271
                return nil
×
1272
        }, DefaultTimeout)
1273

1274
        require.NoErrorf(h, err, "%s timeout checking num active htlcs",
×
1275
                hn.Name())
×
1276
}
1277

1278
// AssertIncomingHTLCActive asserts the node has a pending incoming HTLC in the
1279
// given channel. Returns the HTLC if found and active.
1280
func (h *HarnessTest) AssertIncomingHTLCActive(hn *node.HarnessNode,
1281
        cp *lnrpc.ChannelPoint, payHash []byte) *lnrpc.HTLC {
×
1282

×
1283
        return h.assertHTLCActive(hn, cp, payHash, true)
×
1284
}
×
1285

1286
// AssertOutgoingHTLCActive asserts the node has a pending outgoing HTLC in the
1287
// given channel. Returns the HTLC if found and active.
1288
func (h *HarnessTest) AssertOutgoingHTLCActive(hn *node.HarnessNode,
1289
        cp *lnrpc.ChannelPoint, payHash []byte) *lnrpc.HTLC {
×
1290

×
1291
        return h.assertHTLCActive(hn, cp, payHash, false)
×
1292
}
×
1293

1294
// assertHLTCActive asserts the node has a pending HTLC in the given channel.
1295
// Returns the HTLC if found and active.
1296
func (h *HarnessTest) assertHTLCActive(hn *node.HarnessNode,
1297
        cp *lnrpc.ChannelPoint, payHash []byte, incoming bool) *lnrpc.HTLC {
×
1298

×
1299
        var result *lnrpc.HTLC
×
1300
        target := hex.EncodeToString(payHash)
×
1301

×
1302
        err := wait.NoError(func() error {
×
1303
                // We require the RPC call to be succeeded and won't wait for
×
1304
                // it as it's an unexpected behavior.
×
1305
                ch := h.GetChannelByChanPoint(hn, cp)
×
1306

×
1307
                // Check all payment hashes active for this channel.
×
1308
                for _, htlc := range ch.PendingHtlcs {
×
1309
                        rHash := hex.EncodeToString(htlc.HashLock)
×
1310
                        if rHash != target {
×
1311
                                continue
×
1312
                        }
1313

1314
                        // If the payment hash is found, check the incoming
1315
                        // field.
1316
                        if htlc.Incoming == incoming {
×
1317
                                // Return the result if it's locked in.
×
1318
                                if htlc.LockedIn {
×
1319
                                        result = htlc
×
1320
                                        return nil
×
1321
                                }
×
1322

1323
                                return fmt.Errorf("htlc(%x) not locked in",
×
1324
                                        payHash)
×
1325
                        }
1326

1327
                        // Otherwise we do have the HTLC but its direction is
1328
                        // not right.
1329
                        have, want := "outgoing", "incoming"
×
1330
                        if htlc.Incoming {
×
1331
                                have, want = "incoming", "outgoing"
×
1332
                        }
×
1333

1334
                        return fmt.Errorf("htlc(%x) has wrong direction - "+
×
1335
                                "want: %s, have: %s", payHash, want, have)
×
1336
                }
1337

1338
                return fmt.Errorf("htlc not found using payHash %x", payHash)
×
1339
        }, DefaultTimeout)
1340
        require.NoError(h, err, "%s: timeout checking pending HTLC", hn.Name())
×
1341

×
1342
        return result
×
1343
}
1344

1345
// AssertHLTCNotActive asserts the node doesn't have a pending HTLC in the
1346
// given channel, which mean either the HTLC never exists, or it was pending
1347
// and now settled. Returns the HTLC if found and active.
1348
//
1349
// NOTE: to check a pending HTLC becoming settled, first use AssertHLTCActive
1350
// then follow this check.
1351
func (h *HarnessTest) AssertHTLCNotActive(hn *node.HarnessNode,
1352
        cp *lnrpc.ChannelPoint, payHash []byte) *lnrpc.HTLC {
×
1353

×
1354
        var result *lnrpc.HTLC
×
1355
        target := hex.EncodeToString(payHash)
×
1356

×
1357
        err := wait.NoError(func() error {
×
1358
                // We require the RPC call to be succeeded and won't wait for
×
1359
                // it as it's an unexpected behavior.
×
1360
                ch := h.GetChannelByChanPoint(hn, cp)
×
1361

×
1362
                // Check all payment hashes active for this channel.
×
1363
                for _, htlc := range ch.PendingHtlcs {
×
1364
                        h := hex.EncodeToString(htlc.HashLock)
×
1365

×
1366
                        // Break if found the htlc.
×
1367
                        if h == target {
×
1368
                                result = htlc
×
1369
                                break
×
1370
                        }
1371
                }
1372

1373
                // If we've found nothing, we're done.
1374
                if result == nil {
×
1375
                        return nil
×
1376
                }
×
1377

1378
                // Otherwise return an error.
1379
                return fmt.Errorf("node [%s:%x] still has: the payHash %x",
×
1380
                        hn.Name(), hn.PubKey[:], payHash)
×
1381
        }, DefaultTimeout)
1382
        require.NoError(h, err, "timeout checking pending HTLC")
×
1383

×
1384
        return result
×
1385
}
1386

1387
// ReceiveSingleInvoice waits until a message is received on the subscribe
1388
// single invoice stream or the timeout is reached.
1389
func (h *HarnessTest) ReceiveSingleInvoice(
1390
        stream rpc.SingleInvoiceClient) *lnrpc.Invoice {
×
1391

×
1392
        chanMsg := make(chan *lnrpc.Invoice, 1)
×
1393
        errChan := make(chan error, 1)
×
1394
        go func() {
×
1395
                // Consume one message. This will block until the message is
×
1396
                // received.
×
1397
                resp, err := stream.Recv()
×
1398
                if err != nil {
×
1399
                        errChan <- err
×
1400

×
1401
                        return
×
1402
                }
×
1403
                chanMsg <- resp
×
1404
        }()
1405

1406
        select {
×
1407
        case <-time.After(DefaultTimeout):
×
1408
                require.Fail(h, "timeout", "timeout receiving single invoice")
×
1409

1410
        case err := <-errChan:
×
1411
                require.Failf(h, "err from stream",
×
1412
                        "received err from stream: %v", err)
×
1413

1414
        case updateMsg := <-chanMsg:
×
1415
                return updateMsg
×
1416
        }
1417

1418
        return nil
×
1419
}
1420

1421
// AssertInvoiceState takes a single invoice subscription stream and asserts
1422
// that a given invoice has became the desired state before timeout and returns
1423
// the invoice found.
1424
func (h *HarnessTest) AssertInvoiceState(stream rpc.SingleInvoiceClient,
1425
        state lnrpc.Invoice_InvoiceState) *lnrpc.Invoice {
×
1426

×
1427
        var invoice *lnrpc.Invoice
×
1428

×
1429
        err := wait.NoError(func() error {
×
1430
                invoice = h.ReceiveSingleInvoice(stream)
×
1431
                if invoice.State == state {
×
1432
                        return nil
×
1433
                }
×
1434

1435
                return fmt.Errorf("mismatched invoice state, want %v, got %v",
×
1436
                        state, invoice.State)
×
1437
        }, DefaultTimeout)
1438
        require.NoError(h, err, "timeout waiting for invoice state: %v", state)
×
1439

×
1440
        return invoice
×
1441
}
1442

1443
// assertAllTxesSpendFrom asserts that all txes in the list spend from the
1444
// given tx.
1445
func (h *HarnessTest) AssertAllTxesSpendFrom(txes []*wire.MsgTx,
1446
        prevTxid chainhash.Hash) {
×
1447

×
1448
        for _, tx := range txes {
×
1449
                if tx.TxIn[0].PreviousOutPoint.Hash != prevTxid {
×
1450
                        require.Failf(h, "", "tx %v did not spend from %v",
×
1451
                                tx.TxHash(), prevTxid)
×
1452
                }
×
1453
        }
1454
}
1455

1456
// AssertTxSpendFrom asserts that a given tx is spent from a previous tx.
1457
func (h *HarnessTest) AssertTxSpendFrom(tx *wire.MsgTx,
1458
        prevTxid chainhash.Hash) {
×
1459

×
1460
        if tx.TxIn[0].PreviousOutPoint.Hash != prevTxid {
×
1461
                require.Failf(h, "", "tx %v did not spend from %v",
×
1462
                        tx.TxHash(), prevTxid)
×
1463
        }
×
1464
}
1465

1466
type PendingForceClose *lnrpc.PendingChannelsResponse_ForceClosedChannel
1467

1468
// AssertChannelPendingForceClose asserts that the given channel found in the
1469
// node is pending force close. Returns the PendingForceClose if found.
1470
func (h *HarnessTest) AssertChannelPendingForceClose(hn *node.HarnessNode,
1471
        chanPoint *lnrpc.ChannelPoint) PendingForceClose {
×
1472

×
1473
        var target PendingForceClose
×
1474

×
1475
        op := h.OutPointFromChannelPoint(chanPoint)
×
1476

×
1477
        err := wait.NoError(func() error {
×
1478
                resp := hn.RPC.PendingChannels()
×
1479

×
1480
                forceCloseChans := resp.PendingForceClosingChannels
×
1481
                for _, ch := range forceCloseChans {
×
1482
                        if ch.Channel.ChannelPoint == op.String() {
×
1483
                                target = ch
×
1484

×
1485
                                return nil
×
1486
                        }
×
1487
                }
1488

1489
                return fmt.Errorf("%v: channel %s not found in pending "+
×
1490
                        "force close", hn.Name(), chanPoint)
×
1491
        }, DefaultTimeout)
1492
        require.NoError(h, err, "assert pending force close timed out")
×
1493

×
1494
        return target
×
1495
}
1496

1497
// AssertNumHTLCsAndStage takes a pending force close channel's channel point
1498
// and asserts the expected number of pending HTLCs and HTLC stage are matched.
1499
func (h *HarnessTest) AssertNumHTLCsAndStage(hn *node.HarnessNode,
1500
        chanPoint *lnrpc.ChannelPoint, num int, stage uint32) {
×
1501

×
1502
        // Get the channel output point.
×
1503
        cp := h.OutPointFromChannelPoint(chanPoint)
×
1504

×
1505
        var target PendingForceClose
×
1506
        checkStage := func() error {
×
1507
                resp := hn.RPC.PendingChannels()
×
1508
                if len(resp.PendingForceClosingChannels) == 0 {
×
1509
                        return fmt.Errorf("zero pending force closing channels")
×
1510
                }
×
1511

1512
                for _, ch := range resp.PendingForceClosingChannels {
×
1513
                        if ch.Channel.ChannelPoint == cp.String() {
×
1514
                                target = ch
×
1515

×
1516
                                break
×
1517
                        }
1518
                }
1519

1520
                if target == nil {
×
1521
                        return fmt.Errorf("cannot find pending force closing "+
×
1522
                                "channel using %v", cp)
×
1523
                }
×
1524

1525
                if target.LimboBalance == 0 {
×
1526
                        return fmt.Errorf("zero limbo balance")
×
1527
                }
×
1528

1529
                if len(target.PendingHtlcs) != num {
×
1530
                        return fmt.Errorf("got %d pending htlcs, want %d, %s",
×
1531
                                len(target.PendingHtlcs), num,
×
1532
                                lnutils.SpewLogClosure(target.PendingHtlcs)())
×
1533
                }
×
1534

1535
                for _, htlc := range target.PendingHtlcs {
×
1536
                        if htlc.Stage == stage {
×
1537
                                continue
×
1538
                        }
1539

1540
                        return fmt.Errorf("HTLC %s got stage: %v, "+
×
1541
                                "want stage: %v", htlc.Outpoint, htlc.Stage,
×
1542
                                stage)
×
1543
                }
1544

1545
                return nil
×
1546
        }
1547

1548
        require.NoErrorf(h, wait.NoError(checkStage, DefaultTimeout),
×
1549
                "timeout waiting for htlc stage")
×
1550
}
1551

1552
// findPayment queries the payment from the node's ListPayments which matches
1553
// the specified preimage hash.
1554
func (h *HarnessTest) findPayment(hn *node.HarnessNode,
1555
        paymentHash string) (*lnrpc.Payment, error) {
×
1556

×
1557
        req := &lnrpc.ListPaymentsRequest{IncludeIncomplete: true}
×
1558
        paymentsResp := hn.RPC.ListPayments(req)
×
1559

×
1560
        for _, p := range paymentsResp.Payments {
×
1561
                if p.PaymentHash == paymentHash {
×
1562
                        return p, nil
×
1563
                }
×
1564
        }
1565

1566
        return nil, fmt.Errorf("payment %v cannot be found", paymentHash)
×
1567
}
1568

1569
// PaymentCheck is a function that checks a payment for a specific condition.
1570
type PaymentCheck func(*lnrpc.Payment) error
1571

1572
// AssertPaymentStatus asserts that the given node list a payment with the given
1573
// payment hash has the expected status. It also checks that the payment has the
1574
// expected preimage, which is empty when it's not settled and matches the given
1575
// preimage when it's succeeded.
1576
func (h *HarnessTest) AssertPaymentStatus(hn *node.HarnessNode,
1577
        payHash lntypes.Hash, status lnrpc.Payment_PaymentStatus,
1578
        checks ...PaymentCheck) *lnrpc.Payment {
×
1579

×
1580
        var target *lnrpc.Payment
×
1581

×
1582
        err := wait.NoError(func() error {
×
1583
                p, err := h.findPayment(hn, payHash.String())
×
1584
                if err != nil {
×
1585
                        return err
×
1586
                }
×
1587

1588
                if status == p.Status {
×
1589
                        target = p
×
1590
                        return nil
×
1591
                }
×
1592

1593
                return fmt.Errorf("payment: %v status not match, want %s "+
×
1594
                        "got %s", payHash, status, p.Status)
×
1595
        }, DefaultTimeout)
1596
        require.NoError(h, err, "timeout checking payment status")
×
1597

×
1598
        switch status {
×
1599
        // If this expected status is SUCCEEDED, we expect the final
1600
        // preimage.
1601
        case lnrpc.Payment_SUCCEEDED:
×
1602
                preimage, err := lntypes.MakePreimageFromStr(
×
1603
                        target.PaymentPreimage,
×
1604
                )
×
1605
                require.NoError(h, err, "fail to make preimage")
×
1606
                require.Equal(h, payHash, preimage.Hash(), "preimage not match")
×
1607

1608
        // Otherwise we expect an all-zero preimage.
1609
        default:
×
1610
                require.Equal(h, (lntypes.Preimage{}).String(),
×
1611
                        target.PaymentPreimage, "expected zero preimage")
×
1612
        }
1613

1614
        // Perform any additional checks on the payment.
1615
        for _, check := range checks {
×
1616
                require.NoError(h, check(target))
×
1617
        }
×
1618

1619
        return target
×
1620
}
1621

1622
// AssertPaymentFailureReason asserts that the given node lists a payment with
1623
// the given preimage which has the expected failure reason.
1624
func (h *HarnessTest) AssertPaymentFailureReason(
1625
        hn *node.HarnessNode, preimage lntypes.Preimage,
1626
        reason lnrpc.PaymentFailureReason) *lnrpc.Payment {
×
1627

×
1628
        var payment *lnrpc.Payment
×
1629

×
1630
        payHash := preimage.Hash()
×
1631
        err := wait.NoError(func() error {
×
1632
                p, err := h.findPayment(hn, payHash.String())
×
1633
                if err != nil {
×
1634
                        return err
×
1635
                }
×
1636

1637
                payment = p
×
1638

×
1639
                if reason == p.FailureReason {
×
1640
                        return nil
×
1641
                }
×
1642

1643
                return fmt.Errorf("payment: %v failure reason not match, "+
×
1644
                        "want %s(%d) got %s(%d)", payHash, reason, reason,
×
1645
                        p.FailureReason, p.FailureReason)
×
1646
        }, DefaultTimeout)
1647
        require.NoError(h, err, "timeout checking payment failure reason")
×
1648

×
1649
        return payment
×
1650
}
1651

1652
// AssertActiveNodesSynced asserts all active nodes have synced to the chain.
1653
func (h *HarnessTest) AssertActiveNodesSynced() {
×
1654
        for _, node := range h.manager.activeNodes {
×
1655
                h.WaitForBlockchainSync(node)
×
1656
        }
×
1657
}
1658

1659
// AssertActiveNodesSyncedTo asserts all active nodes have synced to the
1660
// provided bestBlock.
1661
func (h *HarnessTest) AssertActiveNodesSyncedTo(bestBlock chainhash.Hash) {
×
1662
        for _, node := range h.manager.activeNodes {
×
1663
                h.WaitForBlockchainSyncTo(node, bestBlock)
×
1664
        }
×
1665
}
1666

1667
// AssertPeerNotConnected asserts that the given node b is not connected to a.
1668
func (h *HarnessTest) AssertPeerNotConnected(a, b *node.HarnessNode) {
×
1669
        err := wait.NoError(func() error {
×
1670
                // We require the RPC call to be succeeded and won't wait for
×
1671
                // it as it's an unexpected behavior.
×
1672
                resp := a.RPC.ListPeers()
×
1673

×
1674
                // If node B is seen in the ListPeers response from node A,
×
1675
                // then we return false as the connection has been fully
×
1676
                // established.
×
1677
                for _, peer := range resp.Peers {
×
1678
                        if peer.PubKey == b.PubKeyStr {
×
1679
                                return fmt.Errorf("peers %s and %s still "+
×
1680
                                        "connected", a.Name(), b.Name())
×
1681
                        }
×
1682
                }
1683

1684
                return nil
×
1685
        }, DefaultTimeout)
1686
        require.NoError(h, err, "timeout checking peers not connected")
×
1687
}
1688

1689
// AssertNotConnected asserts that two peers are not connected.
1690
func (h *HarnessTest) AssertNotConnected(a, b *node.HarnessNode) {
×
1691
        // Sleep one second before the assertion to make sure that when there's
×
1692
        // a RPC call to connect, that RPC call is finished before the
×
1693
        // assertion.
×
1694
        time.Sleep(1 * time.Second)
×
1695

×
1696
        h.AssertPeerNotConnected(a, b)
×
1697
        h.AssertPeerNotConnected(b, a)
×
1698
}
×
1699

1700
// AssertConnected asserts that two peers are connected.
1701
func (h *HarnessTest) AssertConnected(a, b *node.HarnessNode) {
×
1702
        h.AssertPeerConnected(a, b)
×
1703
        h.AssertPeerConnected(b, a)
×
1704
}
×
1705

1706
// AssertAmountPaid checks that the ListChannels command of the provided
1707
// node list the total amount sent and received as expected for the
1708
// provided channel.
1709
func (h *HarnessTest) AssertAmountPaid(channelName string, hn *node.HarnessNode,
1710
        chanPoint *lnrpc.ChannelPoint, amountSent, amountReceived int64) {
×
1711

×
1712
        checkAmountPaid := func() error {
×
1713
                // Find the targeted channel.
×
1714
                channel, err := h.findChannel(hn, chanPoint)
×
1715
                if err != nil {
×
1716
                        return fmt.Errorf("assert amount failed: %w", err)
×
1717
                }
×
1718

1719
                if channel.TotalSatoshisSent != amountSent {
×
1720
                        return fmt.Errorf("%v: incorrect amount"+
×
1721
                                " sent: %v != %v", channelName,
×
1722
                                channel.TotalSatoshisSent,
×
1723
                                amountSent)
×
1724
                }
×
1725
                if channel.TotalSatoshisReceived !=
×
1726
                        amountReceived {
×
1727

×
1728
                        return fmt.Errorf("%v: incorrect amount"+
×
1729
                                " received: %v != %v",
×
1730
                                channelName,
×
1731
                                channel.TotalSatoshisReceived,
×
1732
                                amountReceived)
×
1733
                }
×
1734

1735
                return nil
×
1736
        }
1737

1738
        // As far as HTLC inclusion in commitment transaction might be
1739
        // postponed we will try to check the balance couple of times,
1740
        // and then if after some period of time we receive wrong
1741
        // balance return the error.
1742
        err := wait.NoError(checkAmountPaid, DefaultTimeout)
×
1743
        require.NoError(h, err, "timeout while checking amount paid")
×
1744
}
1745

1746
// AssertLastHTLCError checks that the last sent HTLC of the last payment sent
1747
// by the given node failed with the expected failure code.
1748
func (h *HarnessTest) AssertLastHTLCError(hn *node.HarnessNode,
1749
        code lnrpc.Failure_FailureCode) {
×
1750

×
1751
        // Use -1 to specify the last HTLC.
×
1752
        h.assertHTLCError(hn, code, -1)
×
1753
}
×
1754

1755
// AssertFirstHTLCError checks that the first HTLC of the last payment sent
1756
// by the given node failed with the expected failure code.
1757
func (h *HarnessTest) AssertFirstHTLCError(hn *node.HarnessNode,
1758
        code lnrpc.Failure_FailureCode) {
×
1759

×
1760
        // Use 0 to specify the first HTLC.
×
1761
        h.assertHTLCError(hn, code, 0)
×
1762
}
×
1763

1764
// assertLastHTLCError checks that the HTLC at the specified index of the last
1765
// payment sent by the given node failed with the expected failure code.
1766
func (h *HarnessTest) assertHTLCError(hn *node.HarnessNode,
1767
        code lnrpc.Failure_FailureCode, index int) {
×
1768

×
1769
        req := &lnrpc.ListPaymentsRequest{
×
1770
                IncludeIncomplete: true,
×
1771
        }
×
1772

×
1773
        err := wait.NoError(func() error {
×
1774
                paymentsResp := hn.RPC.ListPayments(req)
×
1775

×
1776
                payments := paymentsResp.Payments
×
1777
                if len(payments) == 0 {
×
1778
                        return fmt.Errorf("no payments found")
×
1779
                }
×
1780

1781
                payment := payments[len(payments)-1]
×
1782
                htlcs := payment.Htlcs
×
1783
                if len(htlcs) == 0 {
×
1784
                        return fmt.Errorf("no htlcs found")
×
1785
                }
×
1786

1787
                // If the index is greater than 0, check we have enough htlcs.
1788
                if index > 0 && len(htlcs) <= index {
×
1789
                        return fmt.Errorf("not enough htlcs")
×
1790
                }
×
1791

1792
                // If index is less than or equal to 0, we will read the last
1793
                // htlc.
1794
                if index <= 0 {
×
1795
                        index = len(htlcs) - 1
×
1796
                }
×
1797

1798
                htlc := htlcs[index]
×
1799

×
1800
                // The htlc must have a status of failed.
×
1801
                if htlc.Status != lnrpc.HTLCAttempt_FAILED {
×
1802
                        return fmt.Errorf("htlc should be failed")
×
1803
                }
×
1804
                // The failure field must not be empty.
1805
                if htlc.Failure == nil {
×
1806
                        return fmt.Errorf("expected htlc failure")
×
1807
                }
×
1808

1809
                // Exit if the expected code is found.
1810
                if htlc.Failure.Code == code {
×
1811
                        return nil
×
1812
                }
×
1813

1814
                return fmt.Errorf("unexpected failure code")
×
1815
        }, DefaultTimeout)
1816

1817
        require.NoError(h, err, "timeout checking HTLC error")
×
1818
}
1819

1820
// AssertZombieChannel asserts that a given channel found using the chanID is
1821
// marked as zombie.
1822
func (h *HarnessTest) AssertZombieChannel(hn *node.HarnessNode, chanID uint64) {
×
1823
        ctxt, cancel := context.WithTimeout(h.runCtx, DefaultTimeout)
×
1824
        defer cancel()
×
1825

×
1826
        err := wait.NoError(func() error {
×
1827
                _, err := hn.RPC.LN.GetChanInfo(
×
1828
                        ctxt, &lnrpc.ChanInfoRequest{ChanId: chanID},
×
1829
                )
×
1830
                if err == nil {
×
1831
                        return fmt.Errorf("expected error but got nil")
×
1832
                }
×
1833

1834
                if !strings.Contains(err.Error(), "marked as zombie") {
×
1835
                        return fmt.Errorf("expected error to contain '%s' but "+
×
1836
                                "was '%v'", "marked as zombie", err)
×
1837
                }
×
1838

1839
                return nil
×
1840
        }, DefaultTimeout)
1841
        require.NoError(h, err, "timeout while checking zombie channel")
×
1842
}
1843

1844
// AssertNotInGraph asserts that a given channel is either not found at all in
1845
// the graph or that it has been marked as a zombie.
1846
func (h *HarnessTest) AssertNotInGraph(hn *node.HarnessNode, chanID uint64) {
×
1847
        ctxt, cancel := context.WithTimeout(h.runCtx, DefaultTimeout)
×
1848
        defer cancel()
×
1849

×
1850
        err := wait.NoError(func() error {
×
1851
                _, err := hn.RPC.LN.GetChanInfo(
×
1852
                        ctxt, &lnrpc.ChanInfoRequest{ChanId: chanID},
×
1853
                )
×
1854
                if err == nil {
×
1855
                        return fmt.Errorf("expected error but got nil")
×
1856
                }
×
1857

1858
                switch {
×
1859
                case strings.Contains(err.Error(), "marked as zombie"):
×
1860
                        return nil
×
1861

1862
                case strings.Contains(err.Error(), "edge not found"):
×
1863
                        return nil
×
1864

1865
                default:
×
1866
                        return fmt.Errorf("expected error to contain either "+
×
1867
                                "'%s' or '%s' but was: '%v'", "marked as i"+
×
1868
                                "zombie", "edge not found", err)
×
1869
                }
1870
        }, DefaultTimeout)
1871
        require.NoError(h, err, "timeout while checking that channel is not "+
×
1872
                "found in graph")
×
1873
}
1874

1875
// AssertChannelInGraphDB asserts that a given channel is found in the graph db.
1876
func (h *HarnessTest) AssertChannelInGraphDB(hn *node.HarnessNode,
1877
        chanPoint *lnrpc.ChannelPoint) *lnrpc.ChannelEdge {
×
1878

×
1879
        ctxt, cancel := context.WithCancel(h.runCtx)
×
1880
        defer cancel()
×
1881

×
1882
        var edge *lnrpc.ChannelEdge
×
1883

×
1884
        op := h.OutPointFromChannelPoint(chanPoint)
×
1885
        err := wait.NoError(func() error {
×
1886
                resp, err := hn.RPC.LN.GetChanInfo(
×
1887
                        ctxt, &lnrpc.ChanInfoRequest{
×
1888
                                ChanPoint: op.String(),
×
1889
                        },
×
1890
                )
×
1891
                if err != nil {
×
1892
                        return fmt.Errorf("channel %s not found in graph: %w",
×
1893
                                op, err)
×
1894
                }
×
1895

1896
                // Make sure the policies are populated, otherwise this edge
1897
                // cannot be used for routing.
1898
                if resp.Node1Policy == nil {
×
1899
                        return fmt.Errorf("channel %s has no policy1", op)
×
1900
                }
×
1901

1902
                if resp.Node2Policy == nil {
×
1903
                        return fmt.Errorf("channel %s has no policy2", op)
×
1904
                }
×
1905

1906
                edge = resp
×
1907

×
1908
                return nil
×
1909
        }, DefaultTimeout)
1910

1911
        require.NoError(h, err, "%s: timeout finding channel in graph",
×
1912
                hn.Name())
×
1913

×
1914
        return edge
×
1915
}
1916

1917
// AssertChannelInGraphCache asserts a given channel is found in the graph
1918
// cache.
1919
func (h *HarnessTest) AssertChannelInGraphCache(hn *node.HarnessNode,
1920
        chanPoint *lnrpc.ChannelPoint) *lnrpc.ChannelEdge {
×
1921

×
1922
        var edge *lnrpc.ChannelEdge
×
1923

×
1924
        req := &lnrpc.ChannelGraphRequest{IncludeUnannounced: true}
×
1925
        cpStr := channelPointStr(chanPoint)
×
1926

×
1927
        err := wait.NoError(func() error {
×
1928
                chanGraph := hn.RPC.DescribeGraph(req)
×
1929

×
1930
                // Iterate all the known edges, and make sure the edge policies
×
1931
                // are populated when a matched edge is found.
×
1932
                for _, e := range chanGraph.Edges {
×
1933
                        if e.ChanPoint != cpStr {
×
1934
                                continue
×
1935
                        }
1936

1937
                        if e.Node1Policy == nil {
×
1938
                                return fmt.Errorf("no policy for node1 %v",
×
1939
                                        e.Node1Pub)
×
1940
                        }
×
1941

1942
                        if e.Node2Policy == nil {
×
1943
                                return fmt.Errorf("no policy for node2 %v",
×
1944
                                        e.Node1Pub)
×
1945
                        }
×
1946

1947
                        edge = e
×
1948

×
1949
                        return nil
×
1950
                }
1951

1952
                // If we've iterated over all the known edges and we weren't
1953
                // able to find this specific one, then we'll fail.
1954
                return fmt.Errorf("no edge found for channel point: %s", cpStr)
×
1955
        }, DefaultTimeout)
1956

1957
        require.NoError(h, err, "%s: timeout finding channel %v in graph cache",
×
1958
                cpStr, hn.Name())
×
1959

×
1960
        return edge
×
1961
}
1962

1963
// AssertChannelInGraphDB asserts that a given channel is found both in the
1964
// graph db (GetChanInfo) and the graph cache (DescribeGraph).
1965
func (h *HarnessTest) AssertChannelInGraph(hn *node.HarnessNode,
1966
        chanPoint *lnrpc.ChannelPoint) *lnrpc.ChannelEdge {
×
1967

×
1968
        // Make sure the channel is found in the db first.
×
1969
        h.AssertChannelInGraphDB(hn, chanPoint)
×
1970

×
1971
        // Assert the channel is also found in the graph cache, which refreshes
×
1972
        // every `--caches.rpc-graph-cache-duration`.
×
1973
        return h.AssertChannelInGraphCache(hn, chanPoint)
×
1974
}
×
1975

1976
// AssertTxAtHeight gets all of the transactions that a node's wallet has a
1977
// record of at the target height, and finds and returns the tx with the target
1978
// txid, failing if it is not found.
1979
func (h *HarnessTest) AssertTxAtHeight(hn *node.HarnessNode, height int32,
1980
        txid *chainhash.Hash) *lnrpc.Transaction {
×
1981

×
1982
        req := &lnrpc.GetTransactionsRequest{
×
1983
                StartHeight: height,
×
1984
                EndHeight:   height,
×
1985
        }
×
1986
        txns := hn.RPC.GetTransactions(req)
×
1987

×
1988
        for _, tx := range txns.Transactions {
×
1989
                if tx.TxHash == txid.String() {
×
1990
                        return tx
×
1991
                }
×
1992
        }
1993

1994
        require.Failf(h, "fail to find tx", "tx:%v not found at height:%v",
×
1995
                txid, height)
×
1996

×
1997
        return nil
×
1998
}
1999

2000
// getChannelPolicies queries the channel graph and retrieves the current edge
2001
// policies for the provided channel point.
2002
func (h *HarnessTest) getChannelPolicies(hn *node.HarnessNode,
2003
        advertisingNode string,
2004
        cp *lnrpc.ChannelPoint) (*lnrpc.RoutingPolicy, error) {
×
2005

×
2006
        req := &lnrpc.ChannelGraphRequest{IncludeUnannounced: true}
×
2007
        chanGraph := hn.RPC.DescribeGraph(req)
×
2008

×
2009
        cpStr := channelPointStr(cp)
×
2010
        for _, e := range chanGraph.Edges {
×
2011
                if e.ChanPoint != cpStr {
×
2012
                        continue
×
2013
                }
2014

2015
                if e.Node1Pub == advertisingNode {
×
2016
                        return e.Node1Policy, nil
×
2017
                }
×
2018

2019
                return e.Node2Policy, nil
×
2020
        }
2021

2022
        // If we've iterated over all the known edges and we weren't
2023
        // able to find this specific one, then we'll fail.
2024
        return nil, fmt.Errorf("did not find edge with advertisingNode: %s"+
×
2025
                ", channel point: %s", advertisingNode, cpStr)
×
2026
}
2027

2028
// AssertChannelPolicy asserts that the passed node's known channel policy for
2029
// the passed chanPoint is consistent with the expected policy values.
2030
func (h *HarnessTest) AssertChannelPolicy(hn *node.HarnessNode,
2031
        advertisingNode string, expectedPolicy *lnrpc.RoutingPolicy,
2032
        chanPoint *lnrpc.ChannelPoint) {
×
2033

×
2034
        policy, err := h.getChannelPolicies(hn, advertisingNode, chanPoint)
×
2035
        require.NoErrorf(h, err, "%s: failed to find policy", hn.Name())
×
2036

×
2037
        err = node.CheckChannelPolicy(policy, expectedPolicy)
×
2038
        require.NoErrorf(h, err, "%s: check policy failed", hn.Name())
×
2039
}
×
2040

2041
// AssertNumPolicyUpdates asserts that a given number of channel policy updates
2042
// has been seen in the specified node.
2043
func (h *HarnessTest) AssertNumPolicyUpdates(hn *node.HarnessNode,
2044
        chanPoint *lnrpc.ChannelPoint,
2045
        advertisingNode *node.HarnessNode, num int) {
×
2046

×
2047
        op := h.OutPointFromChannelPoint(chanPoint)
×
2048

×
2049
        var policies []*node.PolicyUpdateInfo
×
2050

×
2051
        err := wait.NoError(func() error {
×
2052
                policyMap := hn.Watcher.GetPolicyUpdates(op)
×
2053
                nodePolicy, ok := policyMap[advertisingNode.PubKeyStr]
×
2054
                if ok {
×
2055
                        policies = nodePolicy
×
2056
                }
×
2057

2058
                if len(policies) == num {
×
2059
                        return nil
×
2060
                }
×
2061

2062
                p, err := json.MarshalIndent(policies, "", "\t")
×
2063
                require.NoError(h, err, "encode policy err")
×
2064

×
2065
                return fmt.Errorf("expected to find %d policy updates, "+
×
2066
                        "instead got: %d, chanPoint: %v, "+
×
2067
                        "advertisingNode: %s:%s, policy: %s", num,
×
2068
                        len(policies), op, advertisingNode.Name(),
×
2069
                        advertisingNode.PubKeyStr, p)
×
2070
        }, DefaultTimeout)
2071

2072
        require.NoError(h, err, "%s: timeout waiting for num of policy updates",
×
2073
                hn.Name())
×
2074
}
2075

2076
// AssertNumPayments asserts that the number of payments made within the test
2077
// scope is as expected, including the incomplete ones.
2078
func (h *HarnessTest) AssertNumPayments(hn *node.HarnessNode,
2079
        num int) []*lnrpc.Payment {
×
2080

×
2081
        // Get the number of payments we already have from the previous test.
×
2082
        have := hn.State.Payment.Total
×
2083

×
2084
        req := &lnrpc.ListPaymentsRequest{
×
2085
                IncludeIncomplete: true,
×
2086
                IndexOffset:       hn.State.Payment.LastIndexOffset,
×
2087
        }
×
2088

×
2089
        var payments []*lnrpc.Payment
×
2090
        err := wait.NoError(func() error {
×
2091
                resp := hn.RPC.ListPayments(req)
×
2092

×
2093
                payments = resp.Payments
×
2094
                if len(payments) == num {
×
2095
                        return nil
×
2096
                }
×
2097

2098
                return errNumNotMatched(hn.Name(), "num of payments",
×
2099
                        num, len(payments), have+len(payments), have)
×
2100
        }, DefaultTimeout)
2101
        require.NoError(h, err, "%s: timeout checking num of payments",
×
2102
                hn.Name())
×
2103

×
2104
        return payments
×
2105
}
2106

2107
// AssertNumNodeAnns asserts that a given number of node announcements has been
2108
// seen in the specified node.
2109
func (h *HarnessTest) AssertNumNodeAnns(hn *node.HarnessNode,
2110
        pubkey string, num int) []*lnrpc.NodeUpdate {
×
2111

×
2112
        // We will get the current number of channel updates first and add it
×
2113
        // to our expected number of newly created channel updates.
×
2114
        anns, err := hn.Watcher.WaitForNumNodeUpdates(pubkey, num)
×
2115
        require.NoError(h, err, "%s: failed to assert num of node anns",
×
2116
                hn.Name())
×
2117

×
2118
        return anns
×
2119
}
×
2120

2121
// AssertNumChannelUpdates asserts that a given number of channel updates has
2122
// been seen in the specified node's network topology.
2123
func (h *HarnessTest) AssertNumChannelUpdates(hn *node.HarnessNode,
2124
        chanPoint *lnrpc.ChannelPoint, num int) {
×
2125

×
2126
        op := h.OutPointFromChannelPoint(chanPoint)
×
2127
        err := hn.Watcher.WaitForNumChannelUpdates(op, num)
×
2128
        require.NoError(h, err, "%s: failed to assert num of channel updates",
×
2129
                hn.Name())
×
2130
}
×
2131

2132
// CreateBurnAddr creates a random burn address of the given type.
2133
func (h *HarnessTest) CreateBurnAddr(addrType lnrpc.AddressType) ([]byte,
2134
        btcutil.Address) {
×
2135

×
2136
        randomPrivKey, err := btcec.NewPrivateKey()
×
2137
        require.NoError(h, err)
×
2138

×
2139
        randomKeyBytes := randomPrivKey.PubKey().SerializeCompressed()
×
2140
        harnessNetParams := miner.HarnessNetParams
×
2141

×
2142
        var addr btcutil.Address
×
2143
        switch addrType {
×
2144
        case lnrpc.AddressType_WITNESS_PUBKEY_HASH:
×
2145
                addr, err = btcutil.NewAddressWitnessPubKeyHash(
×
2146
                        btcutil.Hash160(randomKeyBytes), harnessNetParams,
×
2147
                )
×
2148

2149
        case lnrpc.AddressType_TAPROOT_PUBKEY:
×
2150
                taprootKey := txscript.ComputeTaprootKeyNoScript(
×
2151
                        randomPrivKey.PubKey(),
×
2152
                )
×
2153
                addr, err = btcutil.NewAddressPubKey(
×
2154
                        schnorr.SerializePubKey(taprootKey), harnessNetParams,
×
2155
                )
×
2156

2157
        case lnrpc.AddressType_NESTED_PUBKEY_HASH:
×
2158
                var witnessAddr btcutil.Address
×
2159
                witnessAddr, err = btcutil.NewAddressWitnessPubKeyHash(
×
2160
                        btcutil.Hash160(randomKeyBytes), harnessNetParams,
×
2161
                )
×
2162
                require.NoError(h, err)
×
2163

×
2164
                addr, err = btcutil.NewAddressScriptHash(
×
2165
                        h.PayToAddrScript(witnessAddr), harnessNetParams,
×
2166
                )
×
2167

2168
        default:
×
2169
                h.Fatalf("Unsupported burn address type: %v", addrType)
×
2170
        }
2171
        require.NoError(h, err)
×
2172

×
2173
        return h.PayToAddrScript(addr), addr
×
2174
}
2175

2176
// ReceiveTrackPayment waits until a message is received on the track payment
2177
// stream or the timeout is reached.
2178
func (h *HarnessTest) ReceiveTrackPayment(
2179
        stream rpc.TrackPaymentClient) *lnrpc.Payment {
×
2180

×
2181
        chanMsg := make(chan *lnrpc.Payment)
×
2182
        errChan := make(chan error)
×
2183
        go func() {
×
2184
                // Consume one message. This will block until the message is
×
2185
                // received.
×
2186
                resp, err := stream.Recv()
×
2187
                if err != nil {
×
2188
                        errChan <- err
×
2189
                        return
×
2190
                }
×
2191
                chanMsg <- resp
×
2192
        }()
2193

2194
        select {
×
2195
        case <-time.After(DefaultTimeout):
×
2196
                require.Fail(h, "timeout", "timeout trakcing payment")
×
2197

2198
        case err := <-errChan:
×
2199
                require.Failf(h, "err from stream",
×
2200
                        "received err from stream: %v", err)
×
2201

2202
        case updateMsg := <-chanMsg:
×
2203
                return updateMsg
×
2204
        }
2205

2206
        return nil
×
2207
}
2208

2209
// ReceiveHtlcEvent waits until a message is received on the subscribe
2210
// htlc event stream or the timeout is reached.
2211
func (h *HarnessTest) ReceiveHtlcEvent(
2212
        stream rpc.HtlcEventsClient) *routerrpc.HtlcEvent {
×
2213

×
2214
        chanMsg := make(chan *routerrpc.HtlcEvent)
×
2215
        errChan := make(chan error)
×
2216
        go func() {
×
2217
                // Consume one message. This will block until the message is
×
2218
                // received.
×
2219
                resp, err := stream.Recv()
×
2220
                if err != nil {
×
2221
                        errChan <- err
×
2222
                        return
×
2223
                }
×
2224
                chanMsg <- resp
×
2225
        }()
2226

2227
        select {
×
2228
        case <-time.After(DefaultTimeout):
×
2229
                require.Fail(h, "timeout", "timeout receiving htlc "+
×
2230
                        "event update")
×
2231

2232
        case err := <-errChan:
×
2233
                require.Failf(h, "err from stream",
×
2234
                        "received err from stream: %v", err)
×
2235

2236
        case updateMsg := <-chanMsg:
×
2237
                return updateMsg
×
2238
        }
2239

2240
        return nil
×
2241
}
2242

2243
// AssertHtlcEventType consumes one event from a client and asserts the event
2244
// type is matched.
2245
func (h *HarnessTest) AssertHtlcEventType(client rpc.HtlcEventsClient,
2246
        userType routerrpc.HtlcEvent_EventType) *routerrpc.HtlcEvent {
×
2247

×
2248
        event := h.ReceiveHtlcEvent(client)
×
2249
        require.Equalf(h, userType, event.EventType, "wrong event type, "+
×
2250
                "want %v got %v", userType, event.EventType)
×
2251

×
2252
        return event
×
2253
}
×
2254

2255
// HtlcEvent maps the series of event types used in `*routerrpc.HtlcEvent_*`.
2256
type HtlcEvent int
2257

2258
const (
2259
        HtlcEventForward HtlcEvent = iota
2260
        HtlcEventForwardFail
2261
        HtlcEventSettle
2262
        HtlcEventLinkFail
2263
        HtlcEventFinal
2264
)
2265

2266
// AssertHtlcEventType consumes one event from a client and asserts both the
2267
// user event type the event.Event type is matched.
2268
func (h *HarnessTest) AssertHtlcEventTypes(client rpc.HtlcEventsClient,
2269
        userType routerrpc.HtlcEvent_EventType,
2270
        eventType HtlcEvent) *routerrpc.HtlcEvent {
×
2271

×
2272
        event := h.ReceiveHtlcEvent(client)
×
2273
        require.Equalf(h, userType, event.EventType, "wrong event type, "+
×
2274
                "want %v got %v", userType, event.EventType)
×
2275

×
2276
        var ok bool
×
2277

×
2278
        switch eventType {
×
2279
        case HtlcEventForward:
×
2280
                _, ok = event.Event.(*routerrpc.HtlcEvent_ForwardEvent)
×
2281

2282
        case HtlcEventForwardFail:
×
2283
                _, ok = event.Event.(*routerrpc.HtlcEvent_ForwardFailEvent)
×
2284

2285
        case HtlcEventSettle:
×
2286
                _, ok = event.Event.(*routerrpc.HtlcEvent_SettleEvent)
×
2287

2288
        case HtlcEventLinkFail:
×
2289
                _, ok = event.Event.(*routerrpc.HtlcEvent_LinkFailEvent)
×
2290

2291
        case HtlcEventFinal:
×
2292
                _, ok = event.Event.(*routerrpc.HtlcEvent_FinalHtlcEvent)
×
2293
        }
2294

2295
        require.Truef(h, ok, "wrong event type: %T, want %T", event.Event,
×
2296
                eventType)
×
2297

×
2298
        return event
×
2299
}
2300

2301
// AssertFeeReport checks that the fee report from the given node has the
2302
// desired day, week, and month sum values.
2303
func (h *HarnessTest) AssertFeeReport(hn *node.HarnessNode,
2304
        day, week, month int) {
×
2305

×
2306
        err := wait.NoError(func() error {
×
2307
                feeReport, err := hn.RPC.LN.FeeReport(
×
2308
                        h.runCtx, &lnrpc.FeeReportRequest{},
×
2309
                )
×
2310
                require.NoError(h, err, "unable to query for fee report")
×
2311

×
2312
                if uint64(day) != feeReport.DayFeeSum {
×
2313
                        return fmt.Errorf("day fee mismatch, want %d, got %d",
×
2314
                                day, feeReport.DayFeeSum)
×
2315
                }
×
2316

2317
                if uint64(week) != feeReport.WeekFeeSum {
×
2318
                        return fmt.Errorf("week fee mismatch, want %d, got %d",
×
2319
                                week, feeReport.WeekFeeSum)
×
2320
                }
×
2321
                if uint64(month) != feeReport.MonthFeeSum {
×
2322
                        return fmt.Errorf("month fee mismatch, want %d, got %d",
×
2323
                                month, feeReport.MonthFeeSum)
×
2324
                }
×
2325

2326
                return nil
×
2327
        }, wait.DefaultTimeout)
2328
        require.NoErrorf(h, err, "%s: time out checking fee report", hn.Name())
×
2329
}
2330

2331
// AssertHtlcEvents consumes events from a client and ensures that they are of
2332
// the expected type and contain the expected number of forwards, forward
2333
// failures and settles.
2334
//
2335
// TODO(yy): needs refactor to reduce its complexity.
2336
func (h *HarnessTest) AssertHtlcEvents(client rpc.HtlcEventsClient,
2337
        fwdCount, fwdFailCount, settleCount, linkFailCount int,
2338
        userType routerrpc.HtlcEvent_EventType) []*routerrpc.HtlcEvent {
×
2339

×
2340
        var forwards, forwardFails, settles, linkFails int
×
2341

×
2342
        numEvents := fwdCount + fwdFailCount + settleCount + linkFailCount
×
2343
        events := make([]*routerrpc.HtlcEvent, 0)
×
2344

×
2345
        // It's either the userType or the unknown type.
×
2346
        //
×
2347
        // TODO(yy): maybe the FinalHtlcEvent shouldn't be in UNKNOWN type?
×
2348
        eventTypes := []routerrpc.HtlcEvent_EventType{
×
2349
                userType, routerrpc.HtlcEvent_UNKNOWN,
×
2350
        }
×
2351

×
2352
        for i := 0; i < numEvents; i++ {
×
2353
                event := h.ReceiveHtlcEvent(client)
×
2354

×
2355
                require.Containsf(h, eventTypes, event.EventType,
×
2356
                        "wrong event type, want %v, got %v", userType,
×
2357
                        event.EventType)
×
2358

×
2359
                events = append(events, event)
×
2360

×
2361
                switch e := event.Event.(type) {
×
2362
                case *routerrpc.HtlcEvent_ForwardEvent:
×
2363
                        forwards++
×
2364

2365
                case *routerrpc.HtlcEvent_ForwardFailEvent:
×
2366
                        forwardFails++
×
2367

2368
                case *routerrpc.HtlcEvent_SettleEvent:
×
2369
                        settles++
×
2370

2371
                case *routerrpc.HtlcEvent_FinalHtlcEvent:
×
2372
                        if e.FinalHtlcEvent.Settled {
×
2373
                                settles++
×
2374
                        }
×
2375

2376
                case *routerrpc.HtlcEvent_LinkFailEvent:
×
2377
                        linkFails++
×
2378

2379
                default:
×
2380
                        require.Fail(h, "assert event fail",
×
2381
                                "unexpected event: %T", event.Event)
×
2382
                }
2383
        }
2384

2385
        require.Equal(h, fwdCount, forwards, "num of forwards mismatch")
×
2386
        require.Equal(h, fwdFailCount, forwardFails,
×
2387
                "num of forward fails mismatch")
×
2388
        require.Equal(h, settleCount, settles, "num of settles mismatch")
×
2389
        require.Equal(h, linkFailCount, linkFails, "num of link fails mismatch")
×
2390

×
2391
        return events
×
2392
}
2393

2394
// AssertTransactionInWallet asserts a given txid can be found in the node's
2395
// wallet.
2396
func (h *HarnessTest) AssertTransactionInWallet(hn *node.HarnessNode,
2397
        txid chainhash.Hash) {
×
2398

×
2399
        req := &lnrpc.GetTransactionsRequest{}
×
2400
        err := wait.NoError(func() error {
×
2401
                txResp := hn.RPC.GetTransactions(req)
×
2402
                for _, txn := range txResp.Transactions {
×
2403
                        if txn.TxHash == txid.String() {
×
2404
                                return nil
×
2405
                        }
×
2406
                }
2407

2408
                return fmt.Errorf("%s: expected txid=%v not found in wallet",
×
2409
                        hn.Name(), txid)
×
2410
        }, DefaultTimeout)
2411

2412
        require.NoError(h, err, "failed to find tx")
×
2413
}
2414

2415
// AssertTransactionNotInWallet asserts a given txid can NOT be found in the
2416
// node's wallet.
2417
func (h *HarnessTest) AssertTransactionNotInWallet(hn *node.HarnessNode,
2418
        txid chainhash.Hash) {
×
2419

×
2420
        req := &lnrpc.GetTransactionsRequest{}
×
2421
        err := wait.NoError(func() error {
×
2422
                txResp := hn.RPC.GetTransactions(req)
×
2423
                for _, txn := range txResp.Transactions {
×
2424
                        if txn.TxHash == txid.String() {
×
2425
                                return fmt.Errorf("expected txid=%v to be "+
×
2426
                                        "not found", txid)
×
2427
                        }
×
2428
                }
2429

2430
                return nil
×
2431
        }, DefaultTimeout)
2432

2433
        require.NoErrorf(h, err, "%s: failed to assert tx not found", hn.Name())
×
2434
}
2435

2436
// WaitForNodeBlockHeight queries the node for its current block height until
2437
// it reaches the passed height.
2438
func (h *HarnessTest) WaitForNodeBlockHeight(hn *node.HarnessNode,
2439
        height int32) {
×
2440

×
2441
        err := wait.NoError(func() error {
×
2442
                info := hn.RPC.GetInfo()
×
2443
                if int32(info.BlockHeight) != height {
×
2444
                        return fmt.Errorf("expected block height to "+
×
2445
                                "be %v, was %v", height, info.BlockHeight)
×
2446
                }
×
2447

2448
                return nil
×
2449
        }, DefaultTimeout)
2450

2451
        require.NoErrorf(h, err, "%s: timeout while waiting for height",
×
2452
                hn.Name())
×
2453
}
2454

2455
// AssertChannelCommitHeight asserts the given channel for the node has the
2456
// expected commit height(`NumUpdates`).
2457
func (h *HarnessTest) AssertChannelCommitHeight(hn *node.HarnessNode,
2458
        cp *lnrpc.ChannelPoint, height int) {
×
2459

×
2460
        err := wait.NoError(func() error {
×
2461
                c, err := h.findChannel(hn, cp)
×
2462
                if err != nil {
×
2463
                        return err
×
2464
                }
×
2465

2466
                if int(c.NumUpdates) == height {
×
2467
                        return nil
×
2468
                }
×
2469

2470
                return fmt.Errorf("expected commit height to be %v, was %v",
×
2471
                        height, c.NumUpdates)
×
2472
        }, DefaultTimeout)
2473

2474
        require.NoError(h, err, "timeout while waiting for commit height")
×
2475
}
2476

2477
// AssertNumInvoices asserts that the number of invoices made within the test
2478
// scope is as expected.
2479
func (h *HarnessTest) AssertNumInvoices(hn *node.HarnessNode,
2480
        num int) []*lnrpc.Invoice {
×
2481

×
2482
        have := hn.State.Invoice.Total
×
2483
        req := &lnrpc.ListInvoiceRequest{
×
2484
                NumMaxInvoices: math.MaxUint64,
×
2485
                IndexOffset:    hn.State.Invoice.LastIndexOffset,
×
2486
        }
×
2487

×
2488
        var invoices []*lnrpc.Invoice
×
2489
        err := wait.NoError(func() error {
×
2490
                resp := hn.RPC.ListInvoices(req)
×
2491

×
2492
                invoices = resp.Invoices
×
2493
                if len(invoices) == num {
×
2494
                        return nil
×
2495
                }
×
2496

2497
                return errNumNotMatched(hn.Name(), "num of invoices",
×
2498
                        num, len(invoices), have+len(invoices), have)
×
2499
        }, DefaultTimeout)
2500
        require.NoError(h, err, "timeout checking num of invoices")
×
2501

×
2502
        return invoices
×
2503
}
2504

2505
// ReceiveSendToRouteUpdate waits until a message is received on the
2506
// SendToRoute client stream or the timeout is reached.
2507
func (h *HarnessTest) ReceiveSendToRouteUpdate(
2508
        stream rpc.SendToRouteClient) (*lnrpc.SendResponse, error) {
×
2509

×
2510
        chanMsg := make(chan *lnrpc.SendResponse, 1)
×
2511
        errChan := make(chan error, 1)
×
2512
        go func() {
×
2513
                // Consume one message. This will block until the message is
×
2514
                // received.
×
2515
                resp, err := stream.Recv()
×
2516
                if err != nil {
×
2517
                        errChan <- err
×
2518

×
2519
                        return
×
2520
                }
×
2521
                chanMsg <- resp
×
2522
        }()
2523

2524
        select {
×
2525
        case <-time.After(DefaultTimeout):
×
2526
                require.Fail(h, "timeout", "timeout waiting for send resp")
×
2527
                return nil, nil
×
2528

2529
        case err := <-errChan:
×
2530
                return nil, err
×
2531

2532
        case updateMsg := <-chanMsg:
×
2533
                return updateMsg, nil
×
2534
        }
2535
}
2536

2537
// AssertInvoiceEqual asserts that two lnrpc.Invoices are equivalent. A custom
2538
// comparison function is defined for these tests, since proto message returned
2539
// from unary and streaming RPCs (as of protobuf 1.23.0 and grpc 1.29.1) aren't
2540
// consistent with the private fields set on the messages. As a result, we
2541
// avoid using require.Equal and test only the actual data members.
2542
func (h *HarnessTest) AssertInvoiceEqual(a, b *lnrpc.Invoice) {
×
2543
        // Ensure the HTLCs are sorted properly before attempting to compare.
×
2544
        sort.Slice(a.Htlcs, func(i, j int) bool {
×
2545
                return a.Htlcs[i].ChanId < a.Htlcs[j].ChanId
×
2546
        })
×
2547
        sort.Slice(b.Htlcs, func(i, j int) bool {
×
2548
                return b.Htlcs[i].ChanId < b.Htlcs[j].ChanId
×
2549
        })
×
2550

2551
        require.Equal(h, a.Memo, b.Memo)
×
2552
        require.Equal(h, a.RPreimage, b.RPreimage)
×
2553
        require.Equal(h, a.RHash, b.RHash)
×
2554
        require.Equal(h, a.Value, b.Value)
×
2555
        require.Equal(h, a.ValueMsat, b.ValueMsat)
×
2556
        require.Equal(h, a.CreationDate, b.CreationDate)
×
2557
        require.Equal(h, a.SettleDate, b.SettleDate)
×
2558
        require.Equal(h, a.PaymentRequest, b.PaymentRequest)
×
2559
        require.Equal(h, a.DescriptionHash, b.DescriptionHash)
×
2560
        require.Equal(h, a.Expiry, b.Expiry)
×
2561
        require.Equal(h, a.FallbackAddr, b.FallbackAddr)
×
2562
        require.Equal(h, a.CltvExpiry, b.CltvExpiry)
×
2563
        require.Equal(h, a.RouteHints, b.RouteHints)
×
2564
        require.Equal(h, a.Private, b.Private)
×
2565
        require.Equal(h, a.AddIndex, b.AddIndex)
×
2566
        require.Equal(h, a.SettleIndex, b.SettleIndex)
×
2567
        require.Equal(h, a.AmtPaidSat, b.AmtPaidSat)
×
2568
        require.Equal(h, a.AmtPaidMsat, b.AmtPaidMsat)
×
2569
        require.Equal(h, a.State, b.State)
×
2570
        require.Equal(h, a.Features, b.Features)
×
2571
        require.Equal(h, a.IsKeysend, b.IsKeysend)
×
2572
        require.Equal(h, a.PaymentAddr, b.PaymentAddr)
×
2573
        require.Equal(h, a.IsAmp, b.IsAmp)
×
2574

×
2575
        require.Equal(h, len(a.Htlcs), len(b.Htlcs))
×
2576
        for i := range a.Htlcs {
×
2577
                htlcA, htlcB := a.Htlcs[i], b.Htlcs[i]
×
2578
                require.Equal(h, htlcA.ChanId, htlcB.ChanId)
×
2579
                require.Equal(h, htlcA.HtlcIndex, htlcB.HtlcIndex)
×
2580
                require.Equal(h, htlcA.AmtMsat, htlcB.AmtMsat)
×
2581
                require.Equal(h, htlcA.AcceptHeight, htlcB.AcceptHeight)
×
2582
                require.Equal(h, htlcA.AcceptTime, htlcB.AcceptTime)
×
2583
                require.Equal(h, htlcA.ResolveTime, htlcB.ResolveTime)
×
2584
                require.Equal(h, htlcA.ExpiryHeight, htlcB.ExpiryHeight)
×
2585
                require.Equal(h, htlcA.State, htlcB.State)
×
2586
                require.Equal(h, htlcA.CustomRecords, htlcB.CustomRecords)
×
2587
                require.Equal(h, htlcA.MppTotalAmtMsat, htlcB.MppTotalAmtMsat)
×
2588
                require.Equal(h, htlcA.Amp, htlcB.Amp)
×
2589
        }
×
2590
}
2591

2592
// AssertUTXOInWallet asserts that a given UTXO can be found in the node's
2593
// wallet.
2594
func (h *HarnessTest) AssertUTXOInWallet(hn *node.HarnessNode,
2595
        op *lnrpc.OutPoint, account string) {
×
2596

×
2597
        err := wait.NoError(func() error {
×
2598
                utxos := h.GetUTXOs(hn, account)
×
2599

×
2600
                err := fmt.Errorf("tx with hash %x not found", op.TxidBytes)
×
2601
                for _, utxo := range utxos {
×
2602
                        if !bytes.Equal(utxo.Outpoint.TxidBytes, op.TxidBytes) {
×
2603
                                continue
×
2604
                        }
2605

2606
                        err = fmt.Errorf("tx with output index %v not found",
×
2607
                                op.OutputIndex)
×
2608
                        if utxo.Outpoint.OutputIndex != op.OutputIndex {
×
2609
                                continue
×
2610
                        }
2611

2612
                        return nil
×
2613
                }
2614

2615
                return err
×
2616
        }, DefaultTimeout)
2617

2618
        require.NoErrorf(h, err, "outpoint %v not found in %s's wallet",
×
2619
                op, hn.Name())
×
2620
}
2621

2622
// AssertWalletAccountBalance asserts that the unconfirmed and confirmed
2623
// balance for the given account is satisfied by the WalletBalance and
2624
// ListUnspent RPCs. The unconfirmed balance is not checked for neutrino nodes.
2625
func (h *HarnessTest) AssertWalletAccountBalance(hn *node.HarnessNode,
2626
        account string, confirmedBalance, unconfirmedBalance int64) {
×
2627

×
2628
        err := wait.NoError(func() error {
×
2629
                balanceResp := hn.RPC.WalletBalance()
×
2630
                require.Contains(h, balanceResp.AccountBalance, account)
×
2631
                accountBalance := balanceResp.AccountBalance[account]
×
2632

×
2633
                // Check confirmed balance.
×
2634
                if accountBalance.ConfirmedBalance != confirmedBalance {
×
2635
                        return fmt.Errorf("expected confirmed balance %v, "+
×
2636
                                "got %v", confirmedBalance,
×
2637
                                accountBalance.ConfirmedBalance)
×
2638
                }
×
2639

2640
                utxos := h.GetUTXOsConfirmed(hn, account)
×
2641
                var totalConfirmedVal int64
×
2642
                for _, utxo := range utxos {
×
2643
                        totalConfirmedVal += utxo.AmountSat
×
2644
                }
×
2645
                if totalConfirmedVal != confirmedBalance {
×
2646
                        return fmt.Errorf("expected total confirmed utxo "+
×
2647
                                "balance %v, got %v", confirmedBalance,
×
2648
                                totalConfirmedVal)
×
2649
                }
×
2650

2651
                // Skip unconfirmed balance checks for neutrino nodes.
2652
                if h.IsNeutrinoBackend() {
×
2653
                        return nil
×
2654
                }
×
2655

2656
                // Check unconfirmed balance.
2657
                if accountBalance.UnconfirmedBalance != unconfirmedBalance {
×
2658
                        return fmt.Errorf("expected unconfirmed balance %v, "+
×
2659
                                "got %v", unconfirmedBalance,
×
2660
                                accountBalance.UnconfirmedBalance)
×
2661
                }
×
2662

2663
                utxos = h.GetUTXOsUnconfirmed(hn, account)
×
2664
                var totalUnconfirmedVal int64
×
2665
                for _, utxo := range utxos {
×
2666
                        totalUnconfirmedVal += utxo.AmountSat
×
2667
                }
×
2668
                if totalUnconfirmedVal != unconfirmedBalance {
×
2669
                        return fmt.Errorf("expected total unconfirmed utxo "+
×
2670
                                "balance %v, got %v", unconfirmedBalance,
×
2671
                                totalUnconfirmedVal)
×
2672
                }
×
2673

2674
                return nil
×
2675
        }, DefaultTimeout)
2676
        require.NoError(h, err, "timeout checking wallet account balance")
×
2677
}
2678

2679
// AssertClosingTxInMempool assert that the closing transaction of the given
2680
// channel point can be found in the mempool. If the channel has anchors, it
2681
// will assert the anchor sweep tx is also in the mempool.
2682
func (h *HarnessTest) AssertClosingTxInMempool(cp *lnrpc.ChannelPoint,
2683
        c lnrpc.CommitmentType) *wire.MsgTx {
×
2684

×
2685
        // Get expected number of txes to be found in the mempool.
×
2686
        expectedTxes := 1
×
2687
        hasAnchors := CommitTypeHasAnchors(c)
×
2688
        if hasAnchors {
×
2689
                expectedTxes = 2
×
2690
        }
×
2691

2692
        // Wait for the expected txes to be found in the mempool.
2693
        h.AssertNumTxsInMempool(expectedTxes)
×
2694

×
2695
        // Get the closing tx from the mempool.
×
2696
        op := h.OutPointFromChannelPoint(cp)
×
2697
        closeTx := h.AssertOutpointInMempool(op)
×
2698

×
2699
        return closeTx
×
2700
}
2701

2702
// AssertClosingTxInMempool assert that the closing transaction of the given
2703
// channel point can be found in the mempool. If the channel has anchors, it
2704
// will assert the anchor sweep tx is also in the mempool.
2705
func (h *HarnessTest) MineClosingTx(cp *lnrpc.ChannelPoint) *wire.MsgTx {
×
2706
        // Wait for the expected txes to be found in the mempool.
×
2707
        h.AssertNumTxsInMempool(1)
×
2708

×
2709
        // Get the closing tx from the mempool.
×
2710
        op := h.OutPointFromChannelPoint(cp)
×
2711
        closeTx := h.AssertOutpointInMempool(op)
×
2712

×
2713
        // Mine a block to confirm the closing transaction and potential anchor
×
2714
        // sweep.
×
2715
        h.MineBlocksAndAssertNumTxes(1, 1)
×
2716

×
2717
        return closeTx
×
2718
}
×
2719

2720
// AssertWalletLockedBalance asserts the expected amount has been marked as
2721
// locked in the node's WalletBalance response.
2722
func (h *HarnessTest) AssertWalletLockedBalance(hn *node.HarnessNode,
2723
        balance int64) {
×
2724

×
2725
        err := wait.NoError(func() error {
×
2726
                balanceResp := hn.RPC.WalletBalance()
×
2727
                got := balanceResp.LockedBalance
×
2728

×
2729
                if got != balance {
×
2730
                        return fmt.Errorf("want %d, got %d", balance, got)
×
2731
                }
×
2732

2733
                return nil
×
2734
        }, wait.DefaultTimeout)
2735
        require.NoError(h, err, "%s: timeout checking locked balance",
×
2736
                hn.Name())
×
2737
}
2738

2739
// AssertNumPendingSweeps asserts the number of pending sweeps for the given
2740
// node.
2741
func (h *HarnessTest) AssertNumPendingSweeps(hn *node.HarnessNode,
2742
        n int) []*walletrpc.PendingSweep {
×
2743

×
2744
        results := make([]*walletrpc.PendingSweep, 0, n)
×
2745

×
2746
        err := wait.NoError(func() error {
×
2747
                resp := hn.RPC.PendingSweeps()
×
2748
                num := len(resp.PendingSweeps)
×
2749

×
2750
                numDesc := "\n"
×
2751
                for _, s := range resp.PendingSweeps {
×
2752
                        desc := fmt.Sprintf("op=%v:%v, amt=%v, type=%v, "+
×
2753
                                "deadline=%v, maturityHeight=%v\n",
×
2754
                                s.Outpoint.TxidStr, s.Outpoint.OutputIndex,
×
2755
                                s.AmountSat, s.WitnessType, s.DeadlineHeight,
×
2756
                                s.MaturityHeight)
×
2757
                        numDesc += desc
×
2758

×
2759
                        // The deadline height must be set, otherwise the
×
2760
                        // pending input response is not update-to-date.
×
2761
                        if s.DeadlineHeight == 0 {
×
2762
                                return fmt.Errorf("input not updated: %s", desc)
×
2763
                        }
×
2764
                }
2765

2766
                if num == n {
×
2767
                        results = resp.PendingSweeps
×
2768
                        return nil
×
2769
                }
×
2770

2771
                return fmt.Errorf("want %d , got %d, sweeps: %s", n, num,
×
2772
                        numDesc)
×
2773
        }, DefaultTimeout)
2774

2775
        require.NoErrorf(h, err, "%s: check pending sweeps timeout", hn.Name())
×
2776

×
2777
        return results
×
2778
}
2779

2780
// AssertAtLeastNumPendingSweeps asserts there are at least n pending sweeps for
2781
// the given node.
2782
func (h *HarnessTest) AssertAtLeastNumPendingSweeps(hn *node.HarnessNode,
2783
        n int) []*walletrpc.PendingSweep {
×
2784

×
2785
        results := make([]*walletrpc.PendingSweep, 0, n)
×
2786

×
2787
        err := wait.NoError(func() error {
×
2788
                resp := hn.RPC.PendingSweeps()
×
2789
                num := len(resp.PendingSweeps)
×
2790

×
2791
                numDesc := "\n"
×
2792
                for _, s := range resp.PendingSweeps {
×
2793
                        desc := fmt.Sprintf("op=%v:%v, amt=%v, type=%v, "+
×
2794
                                "deadline=%v, maturityHeight=%v\n",
×
2795
                                s.Outpoint.TxidStr, s.Outpoint.OutputIndex,
×
2796
                                s.AmountSat, s.WitnessType, s.DeadlineHeight,
×
2797
                                s.MaturityHeight)
×
2798
                        numDesc += desc
×
2799

×
2800
                        // The deadline height must be set, otherwise the
×
2801
                        // pending input response is not update-to-date.
×
2802
                        if s.DeadlineHeight == 0 {
×
2803
                                return fmt.Errorf("input not updated: %s", desc)
×
2804
                        }
×
2805
                }
2806

2807
                if num >= n {
×
2808
                        results = resp.PendingSweeps
×
2809
                        return nil
×
2810
                }
×
2811

2812
                return fmt.Errorf("want %d , got %d, sweeps: %s", n, num,
×
2813
                        numDesc)
×
2814
        }, DefaultTimeout)
2815

2816
        require.NoErrorf(h, err, "%s: check pending sweeps timeout", hn.Name())
×
2817

×
2818
        return results
×
2819
}
2820

2821
// AssertNumSweeps asserts the number of sweeps for the given node.
2822
func (h *HarnessTest) AssertNumSweeps(hn *node.HarnessNode,
2823
        req *walletrpc.ListSweepsRequest,
2824
        n int) *walletrpc.ListSweepsResponse {
×
2825

×
2826
        var result *walletrpc.ListSweepsResponse
×
2827

×
2828
        // The ListSweeps call is wrapped in wait.NoError to handle potential
×
2829
        // timing issues. Sweep transactions might not be immediately reflected
×
2830
        // or processed by the node after an event (e.g., channel closure or
×
2831
        // block mining) due to propagation or processing delays. This ensures
×
2832
        // the system retries the call until the expected sweep is found,
×
2833
        // preventing test flakes caused by race conditions.
×
2834
        err := wait.NoError(func() error {
×
2835
                resp := hn.RPC.ListSweeps(req)
×
2836

×
2837
                var txIDs []string
×
2838
                if req.Verbose {
×
2839
                        details := resp.GetTransactionDetails()
×
2840
                        if details != nil {
×
2841
                                for _, tx := range details.Transactions {
×
2842
                                        txIDs = append(txIDs, tx.TxHash)
×
2843
                                }
×
2844
                        }
2845
                } else {
×
2846
                        ids := resp.GetTransactionIds()
×
2847
                        if ids != nil {
×
2848
                                txIDs = ids.TransactionIds
×
2849
                        }
×
2850
                }
2851

2852
                num := len(txIDs)
×
2853

×
2854
                // Exit early if the num matches.
×
2855
                if num == n {
×
2856
                        result = resp
×
2857
                        return nil
×
2858
                }
×
2859

2860
                return fmt.Errorf("want %d, got %d, sweeps: %v, req: %v", n,
×
2861
                        num, txIDs, req)
×
2862
        }, DefaultTimeout)
2863

2864
        require.NoErrorf(h, err, "%s: check num of sweeps timeout", hn.Name())
×
2865

×
2866
        return result
×
2867
}
2868

2869
// FindSweepingTxns asserts the expected number of sweeping txns are found in
2870
// the txns specified and return them.
2871
func (h *HarnessTest) FindSweepingTxns(txns []*wire.MsgTx,
2872
        expectedNumSweeps int, closeTxid chainhash.Hash) []*wire.MsgTx {
×
2873

×
2874
        var sweepTxns []*wire.MsgTx
×
2875

×
2876
        for _, tx := range txns {
×
2877
                if tx.TxIn[0].PreviousOutPoint.Hash == closeTxid {
×
2878
                        sweepTxns = append(sweepTxns, tx)
×
2879
                }
×
2880
        }
2881
        require.Len(h, sweepTxns, expectedNumSweeps, "unexpected num of sweeps")
×
2882

×
2883
        return sweepTxns
×
2884
}
2885

2886
// AssertForceCloseAndAnchorTxnsInMempool asserts that the force close and
2887
// anchor sweep txns are found in the mempool and returns the force close tx
2888
// and the anchor sweep tx.
2889
func (h *HarnessTest) AssertForceCloseAndAnchorTxnsInMempool() (*wire.MsgTx,
2890
        *wire.MsgTx) {
×
2891

×
2892
        // Assert there are two txns in the mempool.
×
2893
        txns := h.GetNumTxsFromMempool(2)
×
2894

×
2895
        // isParentAndChild checks whether there is an input used in the
×
2896
        // assumed child tx by checking every input's previous outpoint against
×
2897
        // the assumed parentTxid.
×
2898
        isParentAndChild := func(parent, child *wire.MsgTx) bool {
×
2899
                parentTxid := parent.TxHash()
×
2900

×
2901
                for _, inp := range child.TxIn {
×
2902
                        if inp.PreviousOutPoint.Hash == parentTxid {
×
2903
                                // Found a match, this is indeed the anchor
×
2904
                                // sweeping tx so we return it here.
×
2905
                                return true
×
2906
                        }
×
2907
                }
2908

2909
                return false
×
2910
        }
2911

2912
        switch {
×
2913
        // Assume the first one is the closing tx and the second one is the
2914
        // anchor sweeping tx.
2915
        case isParentAndChild(txns[0], txns[1]):
×
2916
                return txns[0], txns[1]
×
2917

2918
        // Assume the first one is the anchor sweeping tx and the second one is
2919
        // the closing tx.
2920
        case isParentAndChild(txns[1], txns[0]):
×
2921
                return txns[1], txns[0]
×
2922

2923
        // Unrelated txns found, fail the test.
2924
        default:
×
2925
                h.Fatalf("the two txns not related: %v", txns)
×
2926

×
2927
                return nil, nil
×
2928
        }
2929
}
2930

2931
// ReceiveSendToRouteUpdate waits until a message is received on the
2932
// PeerEventsClient stream or the timeout is reached.
2933
func (h *HarnessTest) ReceivePeerEvent(
2934
        stream rpc.PeerEventsClient) (*lnrpc.PeerEvent, error) {
×
2935

×
2936
        eventChan := make(chan *lnrpc.PeerEvent, 1)
×
2937
        errChan := make(chan error, 1)
×
2938
        go func() {
×
2939
                // Consume one message. This will block until the message is
×
2940
                // received.
×
2941
                resp, err := stream.Recv()
×
2942
                if err != nil {
×
2943
                        errChan <- err
×
2944

×
2945
                        return
×
2946
                }
×
2947
                eventChan <- resp
×
2948
        }()
2949

2950
        select {
×
2951
        case <-time.After(DefaultTimeout):
×
2952
                require.Fail(h, "timeout", "timeout waiting for peer event")
×
2953
                return nil, nil
×
2954

2955
        case err := <-errChan:
×
2956
                return nil, err
×
2957

2958
        case event := <-eventChan:
×
2959
                return event, nil
×
2960
        }
2961
}
2962

2963
// AssertPeerOnlineEvent reads an event from the PeerEventsClient stream and
2964
// asserts it's an online event.
2965
func (h HarnessTest) AssertPeerOnlineEvent(stream rpc.PeerEventsClient) {
×
2966
        event, err := h.ReceivePeerEvent(stream)
×
2967
        require.NoError(h, err)
×
2968

×
2969
        require.Equal(h, lnrpc.PeerEvent_PEER_ONLINE, event.Type)
×
2970
}
×
2971

2972
// AssertPeerOfflineEvent reads an event from the PeerEventsClient stream and
2973
// asserts it's an offline event.
2974
func (h HarnessTest) AssertPeerOfflineEvent(stream rpc.PeerEventsClient) {
×
2975
        event, err := h.ReceivePeerEvent(stream)
×
2976
        require.NoError(h, err)
×
2977

×
2978
        require.Equal(h, lnrpc.PeerEvent_PEER_OFFLINE, event.Type)
×
2979
}
×
2980

2981
// AssertPeerReconnected reads two events from the PeerEventsClient stream. The
2982
// first event must be an offline event, and the second event must be an online
2983
// event. This is a typical reconnection scenario, where the peer is
2984
// disconnected then connected again.
2985
//
2986
// NOTE: It's important to make the subscription before the disconnection
2987
// happens, otherwise the events can be missed.
2988
func (h HarnessTest) AssertPeerReconnected(stream rpc.PeerEventsClient) {
×
2989
        h.AssertPeerOfflineEvent(stream)
×
2990
        h.AssertPeerOnlineEvent(stream)
×
2991
}
×
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