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

lightningnetwork / lnd / 12430538171

20 Dec 2024 11:21AM UTC coverage: 58.716% (+0.1%) from 58.576%
12430538171

push

github

web-flow
Merge pull request #9381 from yyforyongyu/fix-no-space-left

workflows: fix no space left error

135265 of 230373 relevant lines covered (58.72%)

19174.52 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/lightningnetwork/lnd/channeldb"
22
        "github.com/lightningnetwork/lnd/fn/v2"
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 *wire.MsgBlock) {
×
66

×
67
        bestBlockHash := bestBlock.BlockHash().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.AssertPeerConnected(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
// AssertNumActiveEdges checks that an expected number of active edges can be
245
// found in the node specified.
246
func (h *HarnessTest) AssertNumActiveEdges(hn *node.HarnessNode,
247
        expected int, includeUnannounced bool) []*lnrpc.ChannelEdge {
×
248

×
249
        var edges []*lnrpc.ChannelEdge
×
250

×
251
        old := hn.State.Edge.Public
×
252
        if includeUnannounced {
×
253
                old = hn.State.Edge.Total
×
254
        }
×
255

256
        // filterDisabled is a helper closure that filters out disabled
257
        // channels.
258
        filterDisabled := func(edge *lnrpc.ChannelEdge) bool {
×
259
                if edge.Node1Policy != nil && edge.Node1Policy.Disabled {
×
260
                        return false
×
261
                }
×
262
                if edge.Node2Policy != nil && edge.Node2Policy.Disabled {
×
263
                        return false
×
264
                }
×
265

266
                return true
×
267
        }
268

269
        err := wait.NoError(func() error {
×
270
                req := &lnrpc.ChannelGraphRequest{
×
271
                        IncludeUnannounced: includeUnannounced,
×
272
                }
×
273
                resp := hn.RPC.DescribeGraph(req)
×
274
                activeEdges := fn.Filter(resp.Edges, filterDisabled)
×
275
                total := len(activeEdges)
×
276

×
277
                if total-old == expected {
×
278
                        if expected != 0 {
×
279
                                // NOTE: assume edges come in ascending order
×
280
                                // that the old edges are at the front of the
×
281
                                // slice.
×
282
                                edges = activeEdges[old:]
×
283
                        }
×
284

285
                        return nil
×
286
                }
287

288
                return errNumNotMatched(hn.Name(), "num of channel edges",
×
289
                        expected, total-old, total, old)
×
290
        }, DefaultTimeout)
291

292
        require.NoError(h, err, "timeout while checking for edges")
×
293

×
294
        return edges
×
295
}
296

297
// AssertNumEdges checks that an expected number of edges can be found in the
298
// node specified.
299
func (h *HarnessTest) AssertNumEdges(hn *node.HarnessNode,
300
        expected int, includeUnannounced bool) []*lnrpc.ChannelEdge {
×
301

×
302
        var edges []*lnrpc.ChannelEdge
×
303

×
304
        old := hn.State.Edge.Public
×
305
        if includeUnannounced {
×
306
                old = hn.State.Edge.Total
×
307
        }
×
308

309
        err := wait.NoError(func() error {
×
310
                req := &lnrpc.ChannelGraphRequest{
×
311
                        IncludeUnannounced: includeUnannounced,
×
312
                }
×
313
                resp := hn.RPC.DescribeGraph(req)
×
314
                total := len(resp.Edges)
×
315

×
316
                if total-old == expected {
×
317
                        if expected != 0 {
×
318
                                // NOTE: assume edges come in ascending order
×
319
                                // that the old edges are at the front of the
×
320
                                // slice.
×
321
                                edges = resp.Edges[old:]
×
322
                        }
×
323

324
                        return nil
×
325
                }
326

327
                return errNumNotMatched(hn.Name(), "num of channel edges",
×
328
                        expected, total-old, total, old)
×
329
        }, DefaultTimeout)
330

331
        require.NoError(h, err, "timeout while checking for edges")
×
332

×
333
        return edges
×
334
}
335

336
// ReceiveOpenChannelUpdate waits until a message is received on the stream or
337
// the timeout is reached.
338
func (h *HarnessTest) ReceiveOpenChannelUpdate(
339
        stream rpc.OpenChanClient) *lnrpc.OpenStatusUpdate {
×
340

×
341
        update, err := h.receiveOpenChannelUpdate(stream)
×
342
        require.NoError(h, err, "received err from open channel stream")
×
343

×
344
        return update
×
345
}
×
346

347
// ReceiveOpenChannelError waits for the expected error during the open channel
348
// flow from the peer or times out.
349
func (h *HarnessTest) ReceiveOpenChannelError(
350
        stream rpc.OpenChanClient, expectedErr error) {
×
351

×
352
        _, err := h.receiveOpenChannelUpdate(stream)
×
353
        require.Contains(h, err.Error(), expectedErr.Error(),
×
354
                "error not matched")
×
355
}
×
356

357
// receiveOpenChannelUpdate waits until a message or an error is received on
358
// the stream or the timeout is reached.
359
//
360
// TODO(yy): use generics to unify all receiving stream update once go@1.18 is
361
// used.
362
func (h *HarnessTest) receiveOpenChannelUpdate(
363
        stream rpc.OpenChanClient) (*lnrpc.OpenStatusUpdate, error) {
×
364

×
365
        chanMsg := make(chan *lnrpc.OpenStatusUpdate)
×
366
        errChan := make(chan error)
×
367
        go func() {
×
368
                // Consume one message. This will block until the message is
×
369
                // received.
×
370
                resp, err := stream.Recv()
×
371
                if err != nil {
×
372
                        errChan <- err
×
373
                        return
×
374
                }
×
375
                chanMsg <- resp
×
376
        }()
377

378
        select {
×
379
        case <-time.After(DefaultTimeout):
×
380
                require.Fail(h, "timeout", "timeout waiting for open channel "+
×
381
                        "update sent")
×
382
                return nil, nil
×
383

384
        case err := <-errChan:
×
385
                return nil, err
×
386

387
        case updateMsg := <-chanMsg:
×
388
                return updateMsg, nil
×
389
        }
390
}
391

392
// WaitForChannelOpenEvent waits for a notification that a channel is open by
393
// consuming a message from the passed open channel stream.
394
func (h HarnessTest) WaitForChannelOpenEvent(
395
        stream rpc.OpenChanClient) *lnrpc.ChannelPoint {
×
396

×
397
        // Consume one event.
×
398
        event := h.ReceiveOpenChannelUpdate(stream)
×
399

×
400
        resp, ok := event.Update.(*lnrpc.OpenStatusUpdate_ChanOpen)
×
401
        require.Truef(h, ok, "expected channel open update, instead got %v",
×
402
                resp)
×
403

×
404
        return resp.ChanOpen.ChannelPoint
×
405
}
×
406

407
// AssertChannelExists asserts that an active channel identified by the
408
// specified channel point exists from the point-of-view of the node.
409
func (h *HarnessTest) AssertChannelExists(hn *node.HarnessNode,
410
        cp *lnrpc.ChannelPoint) *lnrpc.Channel {
×
411

×
412
        return h.assertChannelStatus(hn, cp, true)
×
413
}
×
414

415
// AssertChannelActive checks if a channel identified by the specified channel
416
// point is active.
417
func (h *HarnessTest) AssertChannelActive(hn *node.HarnessNode,
418
        cp *lnrpc.ChannelPoint) *lnrpc.Channel {
×
419

×
420
        return h.assertChannelStatus(hn, cp, true)
×
421
}
×
422

423
// AssertChannelInactive checks if a channel identified by the specified channel
424
// point is inactive.
425
func (h *HarnessTest) AssertChannelInactive(hn *node.HarnessNode,
426
        cp *lnrpc.ChannelPoint) *lnrpc.Channel {
×
427

×
428
        return h.assertChannelStatus(hn, cp, false)
×
429
}
×
430

431
// assertChannelStatus asserts that a channel identified by the specified
432
// channel point exists from the point-of-view of the node and that it is either
433
// active or inactive depending on the value of the active parameter.
434
func (h *HarnessTest) assertChannelStatus(hn *node.HarnessNode,
435
        cp *lnrpc.ChannelPoint, active bool) *lnrpc.Channel {
×
436

×
437
        var (
×
438
                channel *lnrpc.Channel
×
439
                err     error
×
440
        )
×
441

×
442
        err = wait.NoError(func() error {
×
443
                channel, err = h.findChannel(hn, cp)
×
444
                if err != nil {
×
445
                        return err
×
446
                }
×
447

448
                // Check whether the channel is active, exit early if it is.
449
                if channel.Active == active {
×
450
                        return nil
×
451
                }
×
452

453
                return fmt.Errorf("expected channel_active=%v, got %v",
×
454
                        active, channel.Active)
×
455
        }, DefaultTimeout)
456

457
        require.NoErrorf(h, err, "%s: timeout checking for channel point: %v",
×
458
                hn.Name(), cp)
×
459

×
460
        return channel
×
461
}
462

463
// AssertOutputScriptClass checks that the specified transaction output has the
464
// expected script class.
465
func (h *HarnessTest) AssertOutputScriptClass(tx *btcutil.Tx,
466
        outputIndex uint32, scriptClass txscript.ScriptClass) {
×
467

×
468
        require.Greater(h, len(tx.MsgTx().TxOut), int(outputIndex))
×
469

×
470
        txOut := tx.MsgTx().TxOut[outputIndex]
×
471

×
472
        pkScript, err := txscript.ParsePkScript(txOut.PkScript)
×
473
        require.NoError(h, err)
×
474
        require.Equal(h, scriptClass, pkScript.Class())
×
475
}
×
476

477
// findChannel tries to find a target channel in the node using the given
478
// channel point.
479
func (h *HarnessTest) findChannel(hn *node.HarnessNode,
480
        chanPoint *lnrpc.ChannelPoint,
481
        opts ...ListChannelOption) (*lnrpc.Channel, error) {
×
482

×
483
        // Get the funding point.
×
484
        fp := h.OutPointFromChannelPoint(chanPoint)
×
485

×
486
        req := &lnrpc.ListChannelsRequest{}
×
487

×
488
        for _, opt := range opts {
×
489
                opt(req)
×
490
        }
×
491

492
        channelInfo := hn.RPC.ListChannels(req)
×
493

×
494
        // Find the target channel.
×
495
        for _, channel := range channelInfo.Channels {
×
496
                if channel.ChannelPoint == fp.String() {
×
497
                        return channel, nil
×
498
                }
×
499
        }
500

501
        return nil, fmt.Errorf("%s: channel not found using %s", hn.Name(),
×
502
                fp.String())
×
503
}
504

505
// ReceiveCloseChannelUpdate waits until a message or an error is received on
506
// the subscribe channel close stream or the timeout is reached.
507
func (h *HarnessTest) ReceiveCloseChannelUpdate(
508
        stream rpc.CloseChanClient) (*lnrpc.CloseStatusUpdate, error) {
×
509

×
510
        chanMsg := make(chan *lnrpc.CloseStatusUpdate)
×
511
        errChan := make(chan error)
×
512
        go func() {
×
513
                // Consume one message. This will block until the message is
×
514
                // received.
×
515
                resp, err := stream.Recv()
×
516
                if err != nil {
×
517
                        errChan <- err
×
518
                        return
×
519
                }
×
520
                chanMsg <- resp
×
521
        }()
522

523
        select {
×
524
        case <-time.After(DefaultTimeout):
×
525
                require.Fail(h, "timeout", "timeout waiting for close channel "+
×
526
                        "update sent")
×
527

×
528
                return nil, nil
×
529

530
        case err := <-errChan:
×
531
                return nil, fmt.Errorf("received err from close channel "+
×
532
                        "stream: %v", err)
×
533

534
        case updateMsg := <-chanMsg:
×
535
                return updateMsg, nil
×
536
        }
537
}
538

539
type WaitingCloseChannel *lnrpc.PendingChannelsResponse_WaitingCloseChannel
540

541
// AssertChannelWaitingClose asserts that the given channel found in the node
542
// is waiting close. Returns the WaitingCloseChannel if found.
543
func (h *HarnessTest) AssertChannelWaitingClose(hn *node.HarnessNode,
544
        chanPoint *lnrpc.ChannelPoint) WaitingCloseChannel {
×
545

×
546
        var target WaitingCloseChannel
×
547

×
548
        op := h.OutPointFromChannelPoint(chanPoint)
×
549

×
550
        err := wait.NoError(func() error {
×
551
                resp := hn.RPC.PendingChannels()
×
552

×
553
                for _, waitingClose := range resp.WaitingCloseChannels {
×
554
                        if waitingClose.Channel.ChannelPoint == op.String() {
×
555
                                target = waitingClose
×
556
                                return nil
×
557
                        }
×
558
                }
559

560
                return fmt.Errorf("%v: channel %s not found in waiting close",
×
561
                        hn.Name(), op)
×
562
        }, DefaultTimeout)
563
        require.NoError(h, err, "assert channel waiting close timed out")
×
564

×
565
        return target
×
566
}
567

568
// AssertTopologyChannelClosed asserts a given channel is closed by checking
569
// the graph topology subscription of the specified node. Returns the closed
570
// channel update if found.
571
func (h *HarnessTest) AssertTopologyChannelClosed(hn *node.HarnessNode,
572
        chanPoint *lnrpc.ChannelPoint) *lnrpc.ClosedChannelUpdate {
×
573

×
574
        closedChan, err := hn.Watcher.WaitForChannelClose(chanPoint)
×
575
        require.NoError(h, err, "failed to wait for channel close")
×
576

×
577
        return closedChan
×
578
}
×
579

580
// WaitForChannelCloseEvent waits for a notification that a channel is closed
581
// by consuming a message from the passed close channel stream. Returns the
582
// closing txid if found.
583
func (h HarnessTest) WaitForChannelCloseEvent(
584
        stream rpc.CloseChanClient) chainhash.Hash {
×
585

×
586
        // Consume one event.
×
587
        event, err := h.ReceiveCloseChannelUpdate(stream)
×
588
        require.NoError(h, err)
×
589

×
590
        resp, ok := event.Update.(*lnrpc.CloseStatusUpdate_ChanClose)
×
591
        require.Truef(h, ok, "expected channel open update, instead got %v",
×
592
                resp)
×
593

×
594
        txid, err := chainhash.NewHash(resp.ChanClose.ClosingTxid)
×
595
        require.NoErrorf(h, err, "wrong format found in closing txid: %v",
×
596
                resp.ChanClose.ClosingTxid)
×
597

×
598
        return *txid
×
599
}
×
600

601
// AssertNumWaitingClose checks that a PendingChannels response from the node
602
// reports the expected number of waiting close channels.
603
func (h *HarnessTest) AssertNumWaitingClose(hn *node.HarnessNode,
604
        num int) []*lnrpc.PendingChannelsResponse_WaitingCloseChannel {
×
605

×
606
        var channels []*lnrpc.PendingChannelsResponse_WaitingCloseChannel
×
607
        oldWaiting := hn.State.CloseChannel.WaitingClose
×
608

×
609
        err := wait.NoError(func() error {
×
610
                resp := hn.RPC.PendingChannels()
×
611
                channels = resp.WaitingCloseChannels
×
612
                total := len(channels)
×
613

×
614
                got := total - oldWaiting
×
615
                if got == num {
×
616
                        return nil
×
617
                }
×
618

619
                return errNumNotMatched(hn.Name(), "waiting close channels",
×
620
                        num, got, total, oldWaiting)
×
621
        }, DefaultTimeout)
622

623
        require.NoErrorf(h, err, "%s: assert waiting close timeout",
×
624
                hn.Name())
×
625

×
626
        return channels
×
627
}
628

629
// AssertNumPendingForceClose checks that a PendingChannels response from the
630
// node reports the expected number of pending force close channels.
631
func (h *HarnessTest) AssertNumPendingForceClose(hn *node.HarnessNode,
632
        num int) []*lnrpc.PendingChannelsResponse_ForceClosedChannel {
×
633

×
634
        var channels []*lnrpc.PendingChannelsResponse_ForceClosedChannel
×
635
        oldForce := hn.State.CloseChannel.PendingForceClose
×
636

×
637
        err := wait.NoError(func() error {
×
638
                // TODO(yy): we should be able to use `hn.RPC.PendingChannels`
×
639
                // here to avoid checking the RPC error. However, we may get a
×
640
                // `unable to find arbitrator` error from the rpc point, due to
×
641
                // a timing issue in rpcserver,
×
642
                // 1. `r.server.chanStateDB.FetchClosedChannels` fetches
×
643
                //    the pending force close channel.
×
644
                // 2. `r.arbitratorPopulateForceCloseResp` relies on the
×
645
                //    channel arbitrator to get the report, and,
×
646
                // 3. the arbitrator may be deleted due to the force close
×
647
                //    channel being resolved.
×
648
                // Somewhere along the line is missing a lock to keep the data
×
649
                // consistent.
×
650
                req := &lnrpc.PendingChannelsRequest{}
×
651
                resp, err := hn.RPC.LN.PendingChannels(h.runCtx, req)
×
652
                if err != nil {
×
653
                        return fmt.Errorf("PendingChannels got: %w", err)
×
654
                }
×
655

656
                channels = resp.PendingForceClosingChannels
×
657
                total := len(channels)
×
658

×
659
                got := total - oldForce
×
660
                if got == num {
×
661
                        return nil
×
662
                }
×
663

664
                return errNumNotMatched(hn.Name(), "pending force close "+
×
665
                        "channels", num, got, total, oldForce)
×
666
        }, DefaultTimeout)
667

668
        require.NoErrorf(h, err, "%s: assert pending force close timeout",
×
669
                hn.Name())
×
670

×
671
        return channels
×
672
}
673

674
// AssertStreamChannelCoopClosed reads an update from the close channel client
675
// stream and asserts that the mempool state and node's topology match a coop
676
// close. In specific,
677
// - assert the channel is waiting close and has the expected ChanStatusFlags.
678
// - assert the mempool has the closing txes and anchor sweeps.
679
// - mine a block and assert the closing txid is mined.
680
// - assert the node has zero waiting close channels.
681
// - assert the node has seen the channel close update.
682
func (h *HarnessTest) AssertStreamChannelCoopClosed(hn *node.HarnessNode,
683
        cp *lnrpc.ChannelPoint, anchors bool,
684
        stream rpc.CloseChanClient) chainhash.Hash {
×
685

×
686
        // Assert the channel is waiting close.
×
687
        resp := h.AssertChannelWaitingClose(hn, cp)
×
688

×
689
        // Assert that the channel is in coop broadcasted.
×
690
        require.Contains(h, resp.Channel.ChanStatusFlags,
×
691
                channeldb.ChanStatusCoopBroadcasted.String(),
×
692
                "channel not coop broadcasted")
×
693

×
694
        // We'll now, generate a single block, wait for the final close status
×
695
        // update, then ensure that the closing transaction was included in the
×
696
        // block. If there are anchors, we also expect an anchor sweep.
×
697
        expectedTxes := 1
×
698
        if anchors {
×
699
                expectedTxes = 2
×
700
        }
×
701
        block := h.MineBlocksAndAssertNumTxes(1, expectedTxes)[0]
×
702

×
703
        // Consume one close event and assert the closing txid can be found in
×
704
        // the block.
×
705
        closingTxid := h.WaitForChannelCloseEvent(stream)
×
706
        h.AssertTxInBlock(block, closingTxid)
×
707

×
708
        // We should see zero waiting close channels now.
×
709
        h.AssertNumWaitingClose(hn, 0)
×
710

×
711
        // Finally, check that the node's topology graph has seen this channel
×
712
        // closed if it's a public channel.
×
713
        if !resp.Channel.Private {
×
714
                h.AssertTopologyChannelClosed(hn, cp)
×
715
        }
×
716

717
        return closingTxid
×
718
}
719

720
// AssertStreamChannelForceClosed reads an update from the close channel client
721
// stream and asserts that the mempool state and node's topology match a local
722
// force close. In specific,
723
//   - assert the channel is waiting close and has the expected ChanStatusFlags.
724
//   - assert the mempool has the closing txes.
725
//   - mine a block and assert the closing txid is mined.
726
//   - assert the channel is pending force close.
727
//   - assert the node has seen the channel close update.
728
//   - assert there's a pending anchor sweep request once the force close tx is
729
//     confirmed.
730
func (h *HarnessTest) AssertStreamChannelForceClosed(hn *node.HarnessNode,
731
        cp *lnrpc.ChannelPoint, anchorSweep bool,
732
        stream rpc.CloseChanClient) chainhash.Hash {
×
733

×
734
        // Assert the channel is waiting close.
×
735
        resp := h.AssertChannelWaitingClose(hn, cp)
×
736

×
737
        // Assert that the channel is in local force broadcasted.
×
738
        require.Contains(h, resp.Channel.ChanStatusFlags,
×
739
                channeldb.ChanStatusLocalCloseInitiator.String(),
×
740
                "channel not coop broadcasted")
×
741

×
742
        // Get the closing txid.
×
743
        closeTxid, err := chainhash.NewHashFromStr(resp.ClosingTxid)
×
744
        require.NoError(h, err)
×
745

×
746
        // We'll now, generate a single block, wait for the final close status
×
747
        // update, then ensure that the closing transaction was included in the
×
748
        // block.
×
749
        closeTx := h.AssertTxInMempool(*closeTxid)
×
750
        h.MineBlockWithTx(closeTx)
×
751

×
752
        // Consume one close event and assert the closing txid can be found in
×
753
        // the block.
×
754
        closingTxid := h.WaitForChannelCloseEvent(stream)
×
755

×
756
        // We should see zero waiting close channels and 1 pending force close
×
757
        // channels now.
×
758
        h.AssertNumWaitingClose(hn, 0)
×
759
        h.AssertNumPendingForceClose(hn, 1)
×
760

×
761
        // Finally, check that the node's topology graph has seen this channel
×
762
        // closed if it's a public channel.
×
763
        if !resp.Channel.Private {
×
764
                h.AssertTopologyChannelClosed(hn, cp)
×
765
        }
×
766

767
        // Assert there's a pending anchor sweep.
768
        if anchorSweep {
×
769
                h.AssertNumPendingSweeps(hn, 1)
×
770
        }
×
771

772
        return closingTxid
×
773
}
774

775
// AssertChannelPolicyUpdate checks that the required policy update has
776
// happened on the given node.
777
func (h *HarnessTest) AssertChannelPolicyUpdate(hn *node.HarnessNode,
778
        advertisingNode *node.HarnessNode, policy *lnrpc.RoutingPolicy,
779
        chanPoint *lnrpc.ChannelPoint, includeUnannounced bool) {
×
780

×
781
        require.NoError(
×
782
                h, hn.Watcher.WaitForChannelPolicyUpdate(
×
783
                        advertisingNode, policy,
×
784
                        chanPoint, includeUnannounced,
×
785
                ), "%s: error while waiting for channel update", hn.Name(),
×
786
        )
×
787
}
×
788

789
// WaitForGraphSync waits until the node is synced to graph or times out.
790
func (h *HarnessTest) WaitForGraphSync(hn *node.HarnessNode) {
×
791
        err := wait.NoError(func() error {
×
792
                resp := hn.RPC.GetInfo()
×
793
                if resp.SyncedToGraph {
×
794
                        return nil
×
795
                }
×
796

797
                return fmt.Errorf("node not synced to graph")
×
798
        }, DefaultTimeout)
799
        require.NoError(h, err, "%s: timeout while sync to graph", hn.Name())
×
800
}
801

802
// AssertNumUTXOsWithConf waits for the given number of UTXOs with the
803
// specified confirmations range to be available or fails if that isn't the
804
// case before the default timeout.
805
//
806
// NOTE: for standby nodes(Alice and Bob), this method takes account of the
807
// previous state of the node's UTXOs. The previous state is snapshotted when
808
// finishing a previous test case via the cleanup function in `Subtest`. In
809
// other words, this assertion only checks the new changes made in the current
810
// test.
811
func (h *HarnessTest) AssertNumUTXOsWithConf(hn *node.HarnessNode,
812
        expectedUtxos int, max, min int32) []*lnrpc.Utxo {
×
813

×
814
        var unconfirmed bool
×
815

×
816
        old := hn.State.UTXO.Confirmed
×
817
        if max == 0 {
×
818
                old = hn.State.UTXO.Unconfirmed
×
819
                unconfirmed = true
×
820
        }
×
821

822
        var utxos []*lnrpc.Utxo
×
823
        err := wait.NoError(func() error {
×
824
                req := &walletrpc.ListUnspentRequest{
×
825
                        Account:         "",
×
826
                        MaxConfs:        max,
×
827
                        MinConfs:        min,
×
828
                        UnconfirmedOnly: unconfirmed,
×
829
                }
×
830
                resp := hn.RPC.ListUnspent(req)
×
831
                total := len(resp.Utxos)
×
832

×
833
                if total-old == expectedUtxos {
×
834
                        utxos = resp.Utxos[old:]
×
835

×
836
                        return nil
×
837
                }
×
838

839
                desc := "has UTXOs:\n"
×
840
                for _, utxo := range resp.Utxos {
×
841
                        desc += fmt.Sprintf("%v\n", utxo)
×
842
                }
×
843

844
                return errNumNotMatched(hn.Name(), "num of UTXOs",
×
845
                        expectedUtxos, total-old, total, old, desc)
×
846
        }, DefaultTimeout)
847
        require.NoError(h, err, "timeout waiting for UTXOs")
×
848

×
849
        return utxos
×
850
}
851

852
// AssertNumUTXOsUnconfirmed asserts the expected num of unconfirmed utxos are
853
// seen.
854
//
855
// NOTE: for standby nodes(Alice and Bob), this method takes account of the
856
// previous state of the node's UTXOs. Check `AssertNumUTXOsWithConf` for
857
// details.
858
func (h *HarnessTest) AssertNumUTXOsUnconfirmed(hn *node.HarnessNode,
859
        num int) []*lnrpc.Utxo {
×
860

×
861
        return h.AssertNumUTXOsWithConf(hn, num, 0, 0)
×
862
}
×
863

864
// AssertNumUTXOsConfirmed asserts the expected num of confirmed utxos are
865
// seen, which means the returned utxos have at least one confirmation.
866
//
867
// NOTE: for standby nodes(Alice and Bob), this method takes account of the
868
// previous state of the node's UTXOs. Check `AssertNumUTXOsWithConf` for
869
// details.
870
func (h *HarnessTest) AssertNumUTXOsConfirmed(hn *node.HarnessNode,
871
        num int) []*lnrpc.Utxo {
×
872

×
873
        return h.AssertNumUTXOsWithConf(hn, num, math.MaxInt32, 1)
×
874
}
×
875

876
// AssertNumUTXOs asserts the expected num of utxos are seen, including
877
// confirmed and unconfirmed outputs.
878
//
879
// NOTE: for standby nodes(Alice and Bob), this method takes account of the
880
// previous state of the node's UTXOs. Check `AssertNumUTXOsWithConf` for
881
// details.
882
func (h *HarnessTest) AssertNumUTXOs(hn *node.HarnessNode,
883
        num int) []*lnrpc.Utxo {
×
884

×
885
        return h.AssertNumUTXOsWithConf(hn, num, math.MaxInt32, 0)
×
886
}
×
887

888
// getUTXOs gets the number of newly created UTOXs within the current test
889
// scope.
890
func (h *HarnessTest) getUTXOs(hn *node.HarnessNode, account string,
891
        max, min int32) []*lnrpc.Utxo {
×
892

×
893
        var unconfirmed bool
×
894

×
895
        if max == 0 {
×
896
                unconfirmed = true
×
897
        }
×
898

899
        req := &walletrpc.ListUnspentRequest{
×
900
                Account:         account,
×
901
                MaxConfs:        max,
×
902
                MinConfs:        min,
×
903
                UnconfirmedOnly: unconfirmed,
×
904
        }
×
905
        resp := hn.RPC.ListUnspent(req)
×
906

×
907
        return resp.Utxos
×
908
}
909

910
// GetUTXOs returns all the UTXOs for the given node's account, including
911
// confirmed and unconfirmed.
912
func (h *HarnessTest) GetUTXOs(hn *node.HarnessNode,
913
        account string) []*lnrpc.Utxo {
×
914

×
915
        return h.getUTXOs(hn, account, math.MaxInt32, 0)
×
916
}
×
917

918
// GetUTXOsConfirmed returns the confirmed UTXOs for the given node's account.
919
func (h *HarnessTest) GetUTXOsConfirmed(hn *node.HarnessNode,
920
        account string) []*lnrpc.Utxo {
×
921

×
922
        return h.getUTXOs(hn, account, math.MaxInt32, 1)
×
923
}
×
924

925
// GetUTXOsUnconfirmed returns the unconfirmed UTXOs for the given node's
926
// account.
927
func (h *HarnessTest) GetUTXOsUnconfirmed(hn *node.HarnessNode,
928
        account string) []*lnrpc.Utxo {
×
929

×
930
        return h.getUTXOs(hn, account, 0, 0)
×
931
}
×
932

933
// WaitForBalanceConfirmed waits until the node sees the expected confirmed
934
// balance in its wallet.
935
func (h *HarnessTest) WaitForBalanceConfirmed(hn *node.HarnessNode,
936
        expected btcutil.Amount) {
×
937

×
938
        var lastBalance btcutil.Amount
×
939
        err := wait.NoError(func() error {
×
940
                resp := hn.RPC.WalletBalance()
×
941

×
942
                lastBalance = btcutil.Amount(resp.ConfirmedBalance)
×
943
                if lastBalance == expected {
×
944
                        return nil
×
945
                }
×
946

947
                return fmt.Errorf("expected %v, only have %v", expected,
×
948
                        lastBalance)
×
949
        }, DefaultTimeout)
950

951
        require.NoError(h, err, "timeout waiting for confirmed balances")
×
952
}
953

954
// WaitForBalanceUnconfirmed waits until the node sees the expected unconfirmed
955
// balance in its wallet.
956
func (h *HarnessTest) WaitForBalanceUnconfirmed(hn *node.HarnessNode,
957
        expected btcutil.Amount) {
×
958

×
959
        var lastBalance btcutil.Amount
×
960
        err := wait.NoError(func() error {
×
961
                resp := hn.RPC.WalletBalance()
×
962

×
963
                lastBalance = btcutil.Amount(resp.UnconfirmedBalance)
×
964
                if lastBalance == expected {
×
965
                        return nil
×
966
                }
×
967

968
                return fmt.Errorf("expected %v, only have %v", expected,
×
969
                        lastBalance)
×
970
        }, DefaultTimeout)
971

972
        require.NoError(h, err, "timeout waiting for unconfirmed balances")
×
973
}
974

975
// Random32Bytes generates a random 32 bytes which can be used as a pay hash,
976
// preimage, etc.
977
func (h *HarnessTest) Random32Bytes() []byte {
×
978
        randBuf := make([]byte, lntypes.HashSize)
×
979

×
980
        _, err := rand.Read(randBuf)
×
981
        require.NoErrorf(h, err, "internal error, cannot generate random bytes")
×
982

×
983
        return randBuf
×
984
}
×
985

986
// RandomPreimage generates a random preimage which can be used as a payment
987
// preimage.
988
func (h *HarnessTest) RandomPreimage() lntypes.Preimage {
×
989
        var preimage lntypes.Preimage
×
990
        copy(preimage[:], h.Random32Bytes())
×
991

×
992
        return preimage
×
993
}
×
994

995
// DecodeAddress decodes a given address and asserts there's no error.
996
func (h *HarnessTest) DecodeAddress(addr string) btcutil.Address {
×
997
        resp, err := btcutil.DecodeAddress(addr, miner.HarnessNetParams)
×
998
        require.NoError(h, err, "DecodeAddress failed")
×
999

×
1000
        return resp
×
1001
}
×
1002

1003
// PayToAddrScript creates a new script from the given address and asserts
1004
// there's no error.
1005
func (h *HarnessTest) PayToAddrScript(addr btcutil.Address) []byte {
×
1006
        addrScript, err := txscript.PayToAddrScript(addr)
×
1007
        require.NoError(h, err, "PayToAddrScript failed")
×
1008

×
1009
        return addrScript
×
1010
}
×
1011

1012
// AssertChannelBalanceResp makes a ChannelBalance request and checks the
1013
// returned response matches the expected.
1014
func (h *HarnessTest) AssertChannelBalanceResp(hn *node.HarnessNode,
1015
        expected *lnrpc.ChannelBalanceResponse) {
×
1016

×
1017
        resp := hn.RPC.ChannelBalance()
×
1018

×
1019
        // Ignore custom channel data of both expected and actual responses.
×
1020
        expected.CustomChannelData = nil
×
1021
        resp.CustomChannelData = nil
×
1022

×
1023
        require.True(h, proto.Equal(expected, resp), "balance is incorrect "+
×
1024
                "got: %v, want: %v", resp, expected)
×
1025
}
×
1026

1027
// GetChannelByChanPoint tries to find a channel matching the channel point and
1028
// asserts. It returns the channel found.
1029
func (h *HarnessTest) GetChannelByChanPoint(hn *node.HarnessNode,
1030
        chanPoint *lnrpc.ChannelPoint) *lnrpc.Channel {
×
1031

×
1032
        channel, err := h.findChannel(hn, chanPoint)
×
1033
        require.NoErrorf(h, err, "channel not found using %v", chanPoint)
×
1034

×
1035
        return channel
×
1036
}
×
1037

1038
// GetChannelCommitType retrieves the active channel commitment type for the
1039
// given chan point.
1040
func (h *HarnessTest) GetChannelCommitType(hn *node.HarnessNode,
1041
        chanPoint *lnrpc.ChannelPoint) lnrpc.CommitmentType {
×
1042

×
1043
        c := h.GetChannelByChanPoint(hn, chanPoint)
×
1044

×
1045
        return c.CommitmentType
×
1046
}
×
1047

1048
// AssertNumPendingOpenChannels asserts that a given node have the expected
1049
// number of pending open channels.
1050
func (h *HarnessTest) AssertNumPendingOpenChannels(hn *node.HarnessNode,
1051
        expected int) []*lnrpc.PendingChannelsResponse_PendingOpenChannel {
×
1052

×
1053
        var channels []*lnrpc.PendingChannelsResponse_PendingOpenChannel
×
1054

×
1055
        oldNum := hn.State.OpenChannel.Pending
×
1056

×
1057
        err := wait.NoError(func() error {
×
1058
                resp := hn.RPC.PendingChannels()
×
1059
                channels = resp.PendingOpenChannels
×
1060
                total := len(channels)
×
1061

×
1062
                numChans := total - oldNum
×
1063

×
1064
                if numChans != expected {
×
1065
                        return errNumNotMatched(hn.Name(),
×
1066
                                "pending open channels", expected,
×
1067
                                numChans, total, oldNum)
×
1068
                }
×
1069

1070
                return nil
×
1071
        }, DefaultTimeout)
1072

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

×
1075
        return channels
×
1076
}
1077

1078
// AssertNodesNumPendingOpenChannels asserts that both of the nodes have the
1079
// expected number of pending open channels.
1080
func (h *HarnessTest) AssertNodesNumPendingOpenChannels(a, b *node.HarnessNode,
1081
        expected int) {
×
1082

×
1083
        h.AssertNumPendingOpenChannels(a, expected)
×
1084
        h.AssertNumPendingOpenChannels(b, expected)
×
1085
}
×
1086

1087
// AssertPaymentStatusFromStream takes a client stream and asserts the payment
1088
// is in desired status before default timeout. The payment found is returned
1089
// once succeeded.
1090
func (h *HarnessTest) AssertPaymentStatusFromStream(stream rpc.PaymentClient,
1091
        status lnrpc.Payment_PaymentStatus) *lnrpc.Payment {
×
1092

×
1093
        return h.assertPaymentStatusWithTimeout(
×
1094
                stream, status, wait.PaymentTimeout,
×
1095
        )
×
1096
}
×
1097

1098
// AssertPaymentSucceedWithTimeout asserts that a payment is succeeded within
1099
// the specified timeout.
1100
func (h *HarnessTest) AssertPaymentSucceedWithTimeout(stream rpc.PaymentClient,
1101
        timeout time.Duration) *lnrpc.Payment {
×
1102

×
1103
        return h.assertPaymentStatusWithTimeout(
×
1104
                stream, lnrpc.Payment_SUCCEEDED, timeout,
×
1105
        )
×
1106
}
×
1107

1108
// assertPaymentStatusWithTimeout takes a client stream and asserts the payment
1109
// is in desired status before the specified timeout. The payment found is
1110
// returned once succeeded.
1111
func (h *HarnessTest) assertPaymentStatusWithTimeout(stream rpc.PaymentClient,
1112
        status lnrpc.Payment_PaymentStatus,
1113
        timeout time.Duration) *lnrpc.Payment {
×
1114

×
1115
        var target *lnrpc.Payment
×
1116
        err := wait.NoError(func() error {
×
1117
                // Consume one message. This will raise an error if the message
×
1118
                // is not received within DefaultTimeout.
×
1119
                payment, err := h.receivePaymentUpdateWithTimeout(
×
1120
                        stream, timeout,
×
1121
                )
×
1122
                if err != nil {
×
1123
                        return fmt.Errorf("received error from payment "+
×
1124
                                "stream: %s", err)
×
1125
                }
×
1126

1127
                // Return if the desired payment state is reached.
1128
                if payment.Status == status {
×
1129
                        target = payment
×
1130

×
1131
                        return nil
×
1132
                }
×
1133

1134
                // Return the err so that it can be used for debugging when
1135
                // timeout is reached.
1136
                return fmt.Errorf("payment %v status, got %v, want %v",
×
1137
                        payment.PaymentHash, payment.Status, status)
×
1138
        }, timeout)
1139

1140
        require.NoError(h, err, "timeout while waiting payment")
×
1141

×
1142
        return target
×
1143
}
1144

1145
// ReceivePaymentUpdate waits until a message is received on the payment client
1146
// stream or the timeout is reached.
1147
func (h *HarnessTest) ReceivePaymentUpdate(
1148
        stream rpc.PaymentClient) (*lnrpc.Payment, error) {
×
1149

×
1150
        return h.receivePaymentUpdateWithTimeout(stream, DefaultTimeout)
×
1151
}
×
1152

1153
// receivePaymentUpdateWithTimeout waits until a message is received on the
1154
// payment client stream or the timeout is reached.
1155
func (h *HarnessTest) receivePaymentUpdateWithTimeout(stream rpc.PaymentClient,
1156
        timeout time.Duration) (*lnrpc.Payment, error) {
×
1157

×
1158
        chanMsg := make(chan *lnrpc.Payment, 1)
×
1159
        errChan := make(chan error, 1)
×
1160

×
1161
        go func() {
×
1162
                // Consume one message. This will block until the message is
×
1163
                // received.
×
1164
                resp, err := stream.Recv()
×
1165
                if err != nil {
×
1166
                        errChan <- err
×
1167

×
1168
                        return
×
1169
                }
×
1170
                chanMsg <- resp
×
1171
        }()
1172

1173
        select {
×
1174
        case <-time.After(timeout):
×
1175
                require.Fail(h, "timeout", "timeout waiting for payment update")
×
1176
                return nil, nil
×
1177

1178
        case err := <-errChan:
×
1179
                return nil, err
×
1180

1181
        case updateMsg := <-chanMsg:
×
1182
                return updateMsg, nil
×
1183
        }
1184
}
1185

1186
// AssertInvoiceSettled asserts a given invoice specified by its payment
1187
// address is settled.
1188
func (h *HarnessTest) AssertInvoiceSettled(hn *node.HarnessNode, addr []byte) {
×
1189
        msg := &invoicesrpc.LookupInvoiceMsg{
×
1190
                InvoiceRef: &invoicesrpc.LookupInvoiceMsg_PaymentAddr{
×
1191
                        PaymentAddr: addr,
×
1192
                },
×
1193
        }
×
1194

×
1195
        err := wait.NoError(func() error {
×
1196
                invoice := hn.RPC.LookupInvoiceV2(msg)
×
1197
                if invoice.State == lnrpc.Invoice_SETTLED {
×
1198
                        return nil
×
1199
                }
×
1200

1201
                return fmt.Errorf("%s: invoice with payment address %x not "+
×
1202
                        "settled", hn.Name(), addr)
×
1203
        }, DefaultTimeout)
1204
        require.NoError(h, err, "timeout waiting for invoice settled state")
×
1205
}
1206

1207
// AssertNodeNumChannels polls the provided node's list channels rpc until it
1208
// reaches the desired number of total channels.
1209
func (h *HarnessTest) AssertNodeNumChannels(hn *node.HarnessNode,
1210
        numChannels int) {
×
1211

×
1212
        // Get the total number of channels.
×
1213
        old := hn.State.OpenChannel.Active + hn.State.OpenChannel.Inactive
×
1214

×
1215
        err := wait.NoError(func() error {
×
1216
                // We require the RPC call to be succeeded and won't wait for
×
1217
                // it as it's an unexpected behavior.
×
1218
                chanInfo := hn.RPC.ListChannels(&lnrpc.ListChannelsRequest{})
×
1219

×
1220
                // Return true if the query returned the expected number of
×
1221
                // channels.
×
1222
                num := len(chanInfo.Channels) - old
×
1223
                if num != numChannels {
×
1224
                        return fmt.Errorf("expected %v channels, got %v",
×
1225
                                numChannels, num)
×
1226
                }
×
1227

1228
                return nil
×
1229
        }, DefaultTimeout)
1230

1231
        require.NoError(h, err, "timeout checking node's num of channels")
×
1232
}
1233

1234
// AssertChannelLocalBalance checks the local balance of the given channel is
1235
// expected. The channel found using the specified channel point is returned.
1236
func (h *HarnessTest) AssertChannelLocalBalance(hn *node.HarnessNode,
1237
        cp *lnrpc.ChannelPoint, balance int64) *lnrpc.Channel {
×
1238

×
1239
        var result *lnrpc.Channel
×
1240

×
1241
        // Get the funding point.
×
1242
        err := wait.NoError(func() error {
×
1243
                // Find the target channel first.
×
1244
                target, err := h.findChannel(hn, cp)
×
1245

×
1246
                // Exit early if the channel is not found.
×
1247
                if err != nil {
×
1248
                        return fmt.Errorf("check balance failed: %w", err)
×
1249
                }
×
1250

1251
                result = target
×
1252

×
1253
                // Check local balance.
×
1254
                if target.LocalBalance == balance {
×
1255
                        return nil
×
1256
                }
×
1257

1258
                return fmt.Errorf("balance is incorrect, got %v, expected %v",
×
1259
                        target.LocalBalance, balance)
×
1260
        }, DefaultTimeout)
1261

1262
        require.NoError(h, err, "timeout while checking for balance")
×
1263

×
1264
        return result
×
1265
}
1266

1267
// AssertChannelNumUpdates checks the num of updates is expected from the given
1268
// channel.
1269
func (h *HarnessTest) AssertChannelNumUpdates(hn *node.HarnessNode,
1270
        num uint64, cp *lnrpc.ChannelPoint) {
×
1271

×
1272
        old := int(hn.State.OpenChannel.NumUpdates)
×
1273

×
1274
        // Find the target channel first.
×
1275
        target, err := h.findChannel(hn, cp)
×
1276
        require.NoError(h, err, "unable to find channel")
×
1277

×
1278
        err = wait.NoError(func() error {
×
1279
                total := int(target.NumUpdates)
×
1280
                if total-old == int(num) {
×
1281
                        return nil
×
1282
                }
×
1283

1284
                return errNumNotMatched(hn.Name(), "channel updates",
×
1285
                        int(num), total-old, total, old)
×
1286
        }, DefaultTimeout)
1287
        require.NoError(h, err, "timeout while checking for num of updates")
×
1288
}
1289

1290
// AssertNumActiveHtlcs asserts that a given number of HTLCs are seen in the
1291
// node's channels.
1292
func (h *HarnessTest) AssertNumActiveHtlcs(hn *node.HarnessNode, num int) {
×
1293
        old := hn.State.HTLC
×
1294

×
1295
        err := wait.NoError(func() error {
×
1296
                // We require the RPC call to be succeeded and won't wait for
×
1297
                // it as it's an unexpected behavior.
×
1298
                req := &lnrpc.ListChannelsRequest{}
×
1299
                nodeChans := hn.RPC.ListChannels(req)
×
1300

×
1301
                total := 0
×
1302
                for _, channel := range nodeChans.Channels {
×
1303
                        total += len(channel.PendingHtlcs)
×
1304
                }
×
1305
                if total-old != num {
×
1306
                        return errNumNotMatched(hn.Name(), "active HTLCs",
×
1307
                                num, total-old, total, old)
×
1308
                }
×
1309

1310
                return nil
×
1311
        }, DefaultTimeout)
1312

1313
        require.NoErrorf(h, err, "%s timeout checking num active htlcs",
×
1314
                hn.Name())
×
1315
}
1316

1317
// AssertIncomingHTLCActive asserts the node has a pending incoming HTLC in the
1318
// given channel. Returns the HTLC if found and active.
1319
func (h *HarnessTest) AssertIncomingHTLCActive(hn *node.HarnessNode,
1320
        cp *lnrpc.ChannelPoint, payHash []byte) *lnrpc.HTLC {
×
1321

×
1322
        return h.assertHTLCActive(hn, cp, payHash, true)
×
1323
}
×
1324

1325
// AssertOutgoingHTLCActive asserts the node has a pending outgoing HTLC in the
1326
// given channel. Returns the HTLC if found and active.
1327
func (h *HarnessTest) AssertOutgoingHTLCActive(hn *node.HarnessNode,
1328
        cp *lnrpc.ChannelPoint, payHash []byte) *lnrpc.HTLC {
×
1329

×
1330
        return h.assertHTLCActive(hn, cp, payHash, false)
×
1331
}
×
1332

1333
// assertHLTCActive asserts the node has a pending HTLC in the given channel.
1334
// Returns the HTLC if found and active.
1335
func (h *HarnessTest) assertHTLCActive(hn *node.HarnessNode,
1336
        cp *lnrpc.ChannelPoint, payHash []byte, incoming bool) *lnrpc.HTLC {
×
1337

×
1338
        var result *lnrpc.HTLC
×
1339
        target := hex.EncodeToString(payHash)
×
1340

×
1341
        err := wait.NoError(func() error {
×
1342
                // We require the RPC call to be succeeded and won't wait for
×
1343
                // it as it's an unexpected behavior.
×
1344
                ch := h.GetChannelByChanPoint(hn, cp)
×
1345

×
1346
                // Check all payment hashes active for this channel.
×
1347
                for _, htlc := range ch.PendingHtlcs {
×
1348
                        h := hex.EncodeToString(htlc.HashLock)
×
1349
                        if h != target {
×
1350
                                continue
×
1351
                        }
1352

1353
                        // If the payment hash is found, check the incoming
1354
                        // field.
1355
                        if htlc.Incoming == incoming {
×
1356
                                // Found it and return.
×
1357
                                result = htlc
×
1358
                                return nil
×
1359
                        }
×
1360

1361
                        // Otherwise we do have the HTLC but its direction is
1362
                        // not right.
1363
                        have, want := "outgoing", "incoming"
×
1364
                        if htlc.Incoming {
×
1365
                                have, want = "incoming", "outgoing"
×
1366
                        }
×
1367

1368
                        return fmt.Errorf("node[%s] have htlc(%v), want: %s, "+
×
1369
                                "have: %s", hn.Name(), payHash, want, have)
×
1370
                }
1371

1372
                return fmt.Errorf("node [%s:%x] didn't have: the payHash %x",
×
1373
                        hn.Name(), hn.PubKey[:], payHash)
×
1374
        }, DefaultTimeout)
1375
        require.NoError(h, err, "timeout checking pending HTLC")
×
1376

×
1377
        return result
×
1378
}
1379

1380
// AssertHLTCNotActive asserts the node doesn't have a pending HTLC in the
1381
// given channel, which mean either the HTLC never exists, or it was pending
1382
// and now settled. Returns the HTLC if found and active.
1383
//
1384
// NOTE: to check a pending HTLC becoming settled, first use AssertHLTCActive
1385
// then follow this check.
1386
func (h *HarnessTest) AssertHTLCNotActive(hn *node.HarnessNode,
1387
        cp *lnrpc.ChannelPoint, payHash []byte) *lnrpc.HTLC {
×
1388

×
1389
        var result *lnrpc.HTLC
×
1390
        target := hex.EncodeToString(payHash)
×
1391

×
1392
        err := wait.NoError(func() error {
×
1393
                // We require the RPC call to be succeeded and won't wait for
×
1394
                // it as it's an unexpected behavior.
×
1395
                ch := h.GetChannelByChanPoint(hn, cp)
×
1396

×
1397
                // Check all payment hashes active for this channel.
×
1398
                for _, htlc := range ch.PendingHtlcs {
×
1399
                        h := hex.EncodeToString(htlc.HashLock)
×
1400

×
1401
                        // Break if found the htlc.
×
1402
                        if h == target {
×
1403
                                result = htlc
×
1404
                                break
×
1405
                        }
1406
                }
1407

1408
                // If we've found nothing, we're done.
1409
                if result == nil {
×
1410
                        return nil
×
1411
                }
×
1412

1413
                // Otherwise return an error.
1414
                return fmt.Errorf("node [%s:%x] still has: the payHash %x",
×
1415
                        hn.Name(), hn.PubKey[:], payHash)
×
1416
        }, DefaultTimeout)
1417
        require.NoError(h, err, "timeout checking pending HTLC")
×
1418

×
1419
        return result
×
1420
}
1421

1422
// ReceiveSingleInvoice waits until a message is received on the subscribe
1423
// single invoice stream or the timeout is reached.
1424
func (h *HarnessTest) ReceiveSingleInvoice(
1425
        stream rpc.SingleInvoiceClient) *lnrpc.Invoice {
×
1426

×
1427
        chanMsg := make(chan *lnrpc.Invoice, 1)
×
1428
        errChan := make(chan error, 1)
×
1429
        go func() {
×
1430
                // Consume one message. This will block until the message is
×
1431
                // received.
×
1432
                resp, err := stream.Recv()
×
1433
                if err != nil {
×
1434
                        errChan <- err
×
1435

×
1436
                        return
×
1437
                }
×
1438
                chanMsg <- resp
×
1439
        }()
1440

1441
        select {
×
1442
        case <-time.After(DefaultTimeout):
×
1443
                require.Fail(h, "timeout", "timeout receiving single invoice")
×
1444

1445
        case err := <-errChan:
×
1446
                require.Failf(h, "err from stream",
×
1447
                        "received err from stream: %v", err)
×
1448

1449
        case updateMsg := <-chanMsg:
×
1450
                return updateMsg
×
1451
        }
1452

1453
        return nil
×
1454
}
1455

1456
// AssertInvoiceState takes a single invoice subscription stream and asserts
1457
// that a given invoice has became the desired state before timeout and returns
1458
// the invoice found.
1459
func (h *HarnessTest) AssertInvoiceState(stream rpc.SingleInvoiceClient,
1460
        state lnrpc.Invoice_InvoiceState) *lnrpc.Invoice {
×
1461

×
1462
        var invoice *lnrpc.Invoice
×
1463

×
1464
        err := wait.NoError(func() error {
×
1465
                invoice = h.ReceiveSingleInvoice(stream)
×
1466
                if invoice.State == state {
×
1467
                        return nil
×
1468
                }
×
1469

1470
                return fmt.Errorf("mismatched invoice state, want %v, got %v",
×
1471
                        state, invoice.State)
×
1472
        }, DefaultTimeout)
1473
        require.NoError(h, err, "timeout waiting for invoice state: %v", state)
×
1474

×
1475
        return invoice
×
1476
}
1477

1478
// assertAllTxesSpendFrom asserts that all txes in the list spend from the
1479
// given tx.
1480
func (h *HarnessTest) AssertAllTxesSpendFrom(txes []*wire.MsgTx,
1481
        prevTxid chainhash.Hash) {
×
1482

×
1483
        for _, tx := range txes {
×
1484
                if tx.TxIn[0].PreviousOutPoint.Hash != prevTxid {
×
1485
                        require.Failf(h, "", "tx %v did not spend from %v",
×
1486
                                tx.TxHash(), prevTxid)
×
1487
                }
×
1488
        }
1489
}
1490

1491
// AssertTxSpendFrom asserts that a given tx is spent from a previous tx.
1492
func (h *HarnessTest) AssertTxSpendFrom(tx *wire.MsgTx,
1493
        prevTxid chainhash.Hash) {
×
1494

×
1495
        if tx.TxIn[0].PreviousOutPoint.Hash != prevTxid {
×
1496
                require.Failf(h, "", "tx %v did not spend from %v",
×
1497
                        tx.TxHash(), prevTxid)
×
1498
        }
×
1499
}
1500

1501
type PendingForceClose *lnrpc.PendingChannelsResponse_ForceClosedChannel
1502

1503
// AssertChannelPendingForceClose asserts that the given channel found in the
1504
// node is pending force close. Returns the PendingForceClose if found.
1505
func (h *HarnessTest) AssertChannelPendingForceClose(hn *node.HarnessNode,
1506
        chanPoint *lnrpc.ChannelPoint) PendingForceClose {
×
1507

×
1508
        var target PendingForceClose
×
1509

×
1510
        op := h.OutPointFromChannelPoint(chanPoint)
×
1511

×
1512
        err := wait.NoError(func() error {
×
1513
                resp := hn.RPC.PendingChannels()
×
1514

×
1515
                forceCloseChans := resp.PendingForceClosingChannels
×
1516
                for _, ch := range forceCloseChans {
×
1517
                        if ch.Channel.ChannelPoint == op.String() {
×
1518
                                target = ch
×
1519

×
1520
                                return nil
×
1521
                        }
×
1522
                }
1523

1524
                return fmt.Errorf("%v: channel %s not found in pending "+
×
1525
                        "force close", hn.Name(), chanPoint)
×
1526
        }, DefaultTimeout)
1527
        require.NoError(h, err, "assert pending force close timed out")
×
1528

×
1529
        return target
×
1530
}
1531

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

×
1537
        // Get the channel output point.
×
1538
        cp := h.OutPointFromChannelPoint(chanPoint)
×
1539

×
1540
        var target PendingForceClose
×
1541
        checkStage := func() error {
×
1542
                resp := hn.RPC.PendingChannels()
×
1543
                if len(resp.PendingForceClosingChannels) == 0 {
×
1544
                        return fmt.Errorf("zero pending force closing channels")
×
1545
                }
×
1546

1547
                for _, ch := range resp.PendingForceClosingChannels {
×
1548
                        if ch.Channel.ChannelPoint == cp.String() {
×
1549
                                target = ch
×
1550

×
1551
                                break
×
1552
                        }
1553
                }
1554

1555
                if target == nil {
×
1556
                        return fmt.Errorf("cannot find pending force closing "+
×
1557
                                "channel using %v", cp)
×
1558
                }
×
1559

1560
                if target.LimboBalance == 0 {
×
1561
                        return fmt.Errorf("zero limbo balance")
×
1562
                }
×
1563

1564
                if len(target.PendingHtlcs) != num {
×
1565
                        return fmt.Errorf("got %d pending htlcs, want %d, %s",
×
1566
                                len(target.PendingHtlcs), num,
×
1567
                                lnutils.SpewLogClosure(target.PendingHtlcs)())
×
1568
                }
×
1569

1570
                for i, htlc := range target.PendingHtlcs {
×
1571
                        if htlc.Stage == stage {
×
1572
                                continue
×
1573
                        }
1574

1575
                        return fmt.Errorf("HTLC %d got stage: %v, "+
×
1576
                                "want stage: %v", i, htlc.Stage, stage)
×
1577
                }
1578

1579
                return nil
×
1580
        }
1581

1582
        require.NoErrorf(h, wait.NoError(checkStage, DefaultTimeout),
×
1583
                "timeout waiting for htlc stage")
×
1584
}
1585

1586
// findPayment queries the payment from the node's ListPayments which matches
1587
// the specified preimage hash.
1588
func (h *HarnessTest) findPayment(hn *node.HarnessNode,
1589
        paymentHash string) (*lnrpc.Payment, error) {
×
1590

×
1591
        req := &lnrpc.ListPaymentsRequest{IncludeIncomplete: true}
×
1592
        paymentsResp := hn.RPC.ListPayments(req)
×
1593

×
1594
        for _, p := range paymentsResp.Payments {
×
1595
                if p.PaymentHash == paymentHash {
×
1596
                        return p, nil
×
1597
                }
×
1598
        }
1599

1600
        return nil, fmt.Errorf("payment %v cannot be found", paymentHash)
×
1601
}
1602

1603
// PaymentCheck is a function that checks a payment for a specific condition.
1604
type PaymentCheck func(*lnrpc.Payment) error
1605

1606
// AssertPaymentStatus asserts that the given node list a payment with the
1607
// given preimage has the expected status. It also checks that the payment has
1608
// the expected preimage, which is empty when it's not settled and matches the
1609
// given preimage when it's succeeded.
1610
func (h *HarnessTest) AssertPaymentStatus(hn *node.HarnessNode,
1611
        preimage lntypes.Preimage, status lnrpc.Payment_PaymentStatus,
1612
        checks ...PaymentCheck) *lnrpc.Payment {
×
1613

×
1614
        var target *lnrpc.Payment
×
1615
        payHash := preimage.Hash()
×
1616

×
1617
        err := wait.NoError(func() error {
×
1618
                p, err := h.findPayment(hn, payHash.String())
×
1619
                if err != nil {
×
1620
                        return err
×
1621
                }
×
1622

1623
                if status == p.Status {
×
1624
                        target = p
×
1625
                        return nil
×
1626
                }
×
1627

1628
                return fmt.Errorf("payment: %v status not match, want %s "+
×
1629
                        "got %s", payHash, status, p.Status)
×
1630
        }, DefaultTimeout)
1631
        require.NoError(h, err, "timeout checking payment status")
×
1632

×
1633
        switch status {
×
1634
        // If this expected status is SUCCEEDED, we expect the final
1635
        // preimage.
1636
        case lnrpc.Payment_SUCCEEDED:
×
1637
                require.Equal(h, preimage.String(), target.PaymentPreimage,
×
1638
                        "preimage not match")
×
1639

1640
        // Otherwise we expect an all-zero preimage.
1641
        default:
×
1642
                require.Equal(h, (lntypes.Preimage{}).String(),
×
1643
                        target.PaymentPreimage, "expected zero preimage")
×
1644
        }
1645

1646
        // Perform any additional checks on the payment.
1647
        for _, check := range checks {
×
1648
                require.NoError(h, check(target))
×
1649
        }
×
1650

1651
        return target
×
1652
}
1653

1654
// AssertPaymentFailureReason asserts that the given node lists a payment with
1655
// the given preimage which has the expected failure reason.
1656
func (h *HarnessTest) AssertPaymentFailureReason(hn *node.HarnessNode,
1657
        preimage lntypes.Preimage, reason lnrpc.PaymentFailureReason) {
×
1658

×
1659
        payHash := preimage.Hash()
×
1660
        err := wait.NoError(func() error {
×
1661
                p, err := h.findPayment(hn, payHash.String())
×
1662
                if err != nil {
×
1663
                        return err
×
1664
                }
×
1665

1666
                if reason == p.FailureReason {
×
1667
                        return nil
×
1668
                }
×
1669

1670
                return fmt.Errorf("payment: %v failure reason not match, "+
×
1671
                        "want %s got %s", payHash, reason, p.Status)
×
1672
        }, DefaultTimeout)
1673
        require.NoError(h, err, "timeout checking payment failure reason")
×
1674
}
1675

1676
// AssertActiveNodesSynced asserts all active nodes have synced to the chain.
1677
func (h *HarnessTest) AssertActiveNodesSynced() {
×
1678
        for _, node := range h.manager.activeNodes {
×
1679
                h.WaitForBlockchainSync(node)
×
1680
        }
×
1681
}
1682

1683
// AssertActiveNodesSyncedTo asserts all active nodes have synced to the
1684
// provided bestBlock.
1685
func (h *HarnessTest) AssertActiveNodesSyncedTo(bestBlock *wire.MsgBlock) {
×
1686
        for _, node := range h.manager.activeNodes {
×
1687
                h.WaitForBlockchainSyncTo(node, bestBlock)
×
1688
        }
×
1689
}
1690

1691
// AssertPeerNotConnected asserts that the given node b is not connected to a.
1692
func (h *HarnessTest) AssertPeerNotConnected(a, b *node.HarnessNode) {
×
1693
        err := wait.NoError(func() error {
×
1694
                // We require the RPC call to be succeeded and won't wait for
×
1695
                // it as it's an unexpected behavior.
×
1696
                resp := a.RPC.ListPeers()
×
1697

×
1698
                // If node B is seen in the ListPeers response from node A,
×
1699
                // then we return false as the connection has been fully
×
1700
                // established.
×
1701
                for _, peer := range resp.Peers {
×
1702
                        if peer.PubKey == b.PubKeyStr {
×
1703
                                return fmt.Errorf("peers %s and %s still "+
×
1704
                                        "connected", a.Name(), b.Name())
×
1705
                        }
×
1706
                }
1707

1708
                return nil
×
1709
        }, DefaultTimeout)
1710
        require.NoError(h, err, "timeout checking peers not connected")
×
1711
}
1712

1713
// AssertNotConnected asserts that two peers are not connected.
1714
func (h *HarnessTest) AssertNotConnected(a, b *node.HarnessNode) {
×
1715
        h.AssertPeerNotConnected(a, b)
×
1716
        h.AssertPeerNotConnected(b, a)
×
1717
}
×
1718

1719
// AssertConnected asserts that two peers are connected.
1720
func (h *HarnessTest) AssertConnected(a, b *node.HarnessNode) {
×
1721
        h.AssertPeerConnected(a, b)
×
1722
        h.AssertPeerConnected(b, a)
×
1723
}
×
1724

1725
// AssertAmountPaid checks that the ListChannels command of the provided
1726
// node list the total amount sent and received as expected for the
1727
// provided channel.
1728
func (h *HarnessTest) AssertAmountPaid(channelName string, hn *node.HarnessNode,
1729
        chanPoint *lnrpc.ChannelPoint, amountSent, amountReceived int64) {
×
1730

×
1731
        checkAmountPaid := func() error {
×
1732
                // Find the targeted channel.
×
1733
                channel, err := h.findChannel(hn, chanPoint)
×
1734
                if err != nil {
×
1735
                        return fmt.Errorf("assert amount failed: %w", err)
×
1736
                }
×
1737

1738
                if channel.TotalSatoshisSent != amountSent {
×
1739
                        return fmt.Errorf("%v: incorrect amount"+
×
1740
                                " sent: %v != %v", channelName,
×
1741
                                channel.TotalSatoshisSent,
×
1742
                                amountSent)
×
1743
                }
×
1744
                if channel.TotalSatoshisReceived !=
×
1745
                        amountReceived {
×
1746

×
1747
                        return fmt.Errorf("%v: incorrect amount"+
×
1748
                                " received: %v != %v",
×
1749
                                channelName,
×
1750
                                channel.TotalSatoshisReceived,
×
1751
                                amountReceived)
×
1752
                }
×
1753

1754
                return nil
×
1755
        }
1756

1757
        // As far as HTLC inclusion in commitment transaction might be
1758
        // postponed we will try to check the balance couple of times,
1759
        // and then if after some period of time we receive wrong
1760
        // balance return the error.
1761
        err := wait.NoError(checkAmountPaid, DefaultTimeout)
×
1762
        require.NoError(h, err, "timeout while checking amount paid")
×
1763
}
1764

1765
// AssertLastHTLCError checks that the last sent HTLC of the last payment sent
1766
// by the given node failed with the expected failure code.
1767
func (h *HarnessTest) AssertLastHTLCError(hn *node.HarnessNode,
1768
        code lnrpc.Failure_FailureCode) {
×
1769

×
1770
        // Use -1 to specify the last HTLC.
×
1771
        h.assertHTLCError(hn, code, -1)
×
1772
}
×
1773

1774
// AssertFirstHTLCError checks that the first HTLC of the last payment sent
1775
// by the given node failed with the expected failure code.
1776
func (h *HarnessTest) AssertFirstHTLCError(hn *node.HarnessNode,
1777
        code lnrpc.Failure_FailureCode) {
×
1778

×
1779
        // Use 0 to specify the first HTLC.
×
1780
        h.assertHTLCError(hn, code, 0)
×
1781
}
×
1782

1783
// assertLastHTLCError checks that the HTLC at the specified index of the last
1784
// payment sent by the given node failed with the expected failure code.
1785
func (h *HarnessTest) assertHTLCError(hn *node.HarnessNode,
1786
        code lnrpc.Failure_FailureCode, index int) {
×
1787

×
1788
        req := &lnrpc.ListPaymentsRequest{
×
1789
                IncludeIncomplete: true,
×
1790
        }
×
1791

×
1792
        err := wait.NoError(func() error {
×
1793
                paymentsResp := hn.RPC.ListPayments(req)
×
1794

×
1795
                payments := paymentsResp.Payments
×
1796
                if len(payments) == 0 {
×
1797
                        return fmt.Errorf("no payments found")
×
1798
                }
×
1799

1800
                payment := payments[len(payments)-1]
×
1801
                htlcs := payment.Htlcs
×
1802
                if len(htlcs) == 0 {
×
1803
                        return fmt.Errorf("no htlcs found")
×
1804
                }
×
1805

1806
                // If the index is greater than 0, check we have enough htlcs.
1807
                if index > 0 && len(htlcs) <= index {
×
1808
                        return fmt.Errorf("not enough htlcs")
×
1809
                }
×
1810

1811
                // If index is less than or equal to 0, we will read the last
1812
                // htlc.
1813
                if index <= 0 {
×
1814
                        index = len(htlcs) - 1
×
1815
                }
×
1816

1817
                htlc := htlcs[index]
×
1818

×
1819
                // The htlc must have a status of failed.
×
1820
                if htlc.Status != lnrpc.HTLCAttempt_FAILED {
×
1821
                        return fmt.Errorf("htlc should be failed")
×
1822
                }
×
1823
                // The failure field must not be empty.
1824
                if htlc.Failure == nil {
×
1825
                        return fmt.Errorf("expected htlc failure")
×
1826
                }
×
1827

1828
                // Exit if the expected code is found.
1829
                if htlc.Failure.Code == code {
×
1830
                        return nil
×
1831
                }
×
1832

1833
                return fmt.Errorf("unexpected failure code")
×
1834
        }, DefaultTimeout)
1835

1836
        require.NoError(h, err, "timeout checking HTLC error")
×
1837
}
1838

1839
// AssertZombieChannel asserts that a given channel found using the chanID is
1840
// marked as zombie.
1841
func (h *HarnessTest) AssertZombieChannel(hn *node.HarnessNode, chanID uint64) {
×
1842
        ctxt, cancel := context.WithTimeout(h.runCtx, DefaultTimeout)
×
1843
        defer cancel()
×
1844

×
1845
        err := wait.NoError(func() error {
×
1846
                _, err := hn.RPC.LN.GetChanInfo(
×
1847
                        ctxt, &lnrpc.ChanInfoRequest{ChanId: chanID},
×
1848
                )
×
1849
                if err == nil {
×
1850
                        return fmt.Errorf("expected error but got nil")
×
1851
                }
×
1852

1853
                if !strings.Contains(err.Error(), "marked as zombie") {
×
1854
                        return fmt.Errorf("expected error to contain '%s' but "+
×
1855
                                "was '%v'", "marked as zombie", err)
×
1856
                }
×
1857

1858
                return nil
×
1859
        }, DefaultTimeout)
1860
        require.NoError(h, err, "timeout while checking zombie channel")
×
1861
}
1862

1863
// AssertNotInGraph asserts that a given channel is either not found at all in
1864
// the graph or that it has been marked as a zombie.
1865
func (h *HarnessTest) AssertNotInGraph(hn *node.HarnessNode, chanID uint64) {
×
1866
        ctxt, cancel := context.WithTimeout(h.runCtx, DefaultTimeout)
×
1867
        defer cancel()
×
1868

×
1869
        err := wait.NoError(func() error {
×
1870
                _, err := hn.RPC.LN.GetChanInfo(
×
1871
                        ctxt, &lnrpc.ChanInfoRequest{ChanId: chanID},
×
1872
                )
×
1873
                if err == nil {
×
1874
                        return fmt.Errorf("expected error but got nil")
×
1875
                }
×
1876

1877
                switch {
×
1878
                case strings.Contains(err.Error(), "marked as zombie"):
×
1879
                        return nil
×
1880

1881
                case strings.Contains(err.Error(), "edge not found"):
×
1882
                        return nil
×
1883

1884
                default:
×
1885
                        return fmt.Errorf("expected error to contain either "+
×
1886
                                "'%s' or '%s' but was: '%v'", "marked as i"+
×
1887
                                "zombie", "edge not found", err)
×
1888
                }
1889
        }, DefaultTimeout)
1890
        require.NoError(h, err, "timeout while checking that channel is not "+
×
1891
                "found in graph")
×
1892
}
1893

1894
// AssertChannelInGraph asserts that a given channel is found in the graph.
1895
func (h *HarnessTest) AssertChannelInGraph(hn *node.HarnessNode,
1896
        chanPoint *lnrpc.ChannelPoint) *lnrpc.ChannelEdge {
×
1897

×
1898
        ctxt, cancel := context.WithCancel(h.runCtx)
×
1899
        defer cancel()
×
1900

×
1901
        var edge *lnrpc.ChannelEdge
×
1902

×
1903
        op := h.OutPointFromChannelPoint(chanPoint)
×
1904
        err := wait.NoError(func() error {
×
1905
                resp, err := hn.RPC.LN.GetChanInfo(
×
1906
                        ctxt, &lnrpc.ChanInfoRequest{
×
1907
                                ChanPoint: op.String(),
×
1908
                        },
×
1909
                )
×
1910
                if err != nil {
×
1911
                        return fmt.Errorf("channel %s not found in graph: %w",
×
1912
                                op, err)
×
1913
                }
×
1914

1915
                edge = resp
×
1916

×
1917
                return nil
×
1918
        }, DefaultTimeout)
1919
        require.NoError(h, err, "%s: timeout finding channel in graph",
×
1920
                hn.Name())
×
1921

×
1922
        return edge
×
1923
}
1924

1925
// AssertTxAtHeight gets all of the transactions that a node's wallet has a
1926
// record of at the target height, and finds and returns the tx with the target
1927
// txid, failing if it is not found.
1928
func (h *HarnessTest) AssertTxAtHeight(hn *node.HarnessNode, height int32,
1929
        txid *chainhash.Hash) *lnrpc.Transaction {
×
1930

×
1931
        req := &lnrpc.GetTransactionsRequest{
×
1932
                StartHeight: height,
×
1933
                EndHeight:   height,
×
1934
        }
×
1935
        txns := hn.RPC.GetTransactions(req)
×
1936

×
1937
        for _, tx := range txns.Transactions {
×
1938
                if tx.TxHash == txid.String() {
×
1939
                        return tx
×
1940
                }
×
1941
        }
1942

1943
        require.Failf(h, "fail to find tx", "tx:%v not found at height:%v",
×
1944
                txid, height)
×
1945

×
1946
        return nil
×
1947
}
1948

1949
// getChannelPolicies queries the channel graph and retrieves the current edge
1950
// policies for the provided channel point.
1951
func (h *HarnessTest) getChannelPolicies(hn *node.HarnessNode,
1952
        advertisingNode string,
1953
        cp *lnrpc.ChannelPoint) (*lnrpc.RoutingPolicy, error) {
×
1954

×
1955
        req := &lnrpc.ChannelGraphRequest{IncludeUnannounced: true}
×
1956
        chanGraph := hn.RPC.DescribeGraph(req)
×
1957

×
1958
        cpStr := channelPointStr(cp)
×
1959
        for _, e := range chanGraph.Edges {
×
1960
                if e.ChanPoint != cpStr {
×
1961
                        continue
×
1962
                }
1963

1964
                if e.Node1Pub == advertisingNode {
×
1965
                        return e.Node1Policy, nil
×
1966
                }
×
1967

1968
                return e.Node2Policy, nil
×
1969
        }
1970

1971
        // If we've iterated over all the known edges and we weren't
1972
        // able to find this specific one, then we'll fail.
1973
        return nil, fmt.Errorf("did not find edge with advertisingNode: %s"+
×
1974
                ", channel point: %s", advertisingNode, cpStr)
×
1975
}
1976

1977
// AssertChannelPolicy asserts that the passed node's known channel policy for
1978
// the passed chanPoint is consistent with the expected policy values.
1979
func (h *HarnessTest) AssertChannelPolicy(hn *node.HarnessNode,
1980
        advertisingNode string, expectedPolicy *lnrpc.RoutingPolicy,
1981
        chanPoint *lnrpc.ChannelPoint) {
×
1982

×
1983
        policy, err := h.getChannelPolicies(hn, advertisingNode, chanPoint)
×
1984
        require.NoErrorf(h, err, "%s: failed to find policy", hn.Name())
×
1985

×
1986
        err = node.CheckChannelPolicy(policy, expectedPolicy)
×
1987
        require.NoErrorf(h, err, "%s: check policy failed", hn.Name())
×
1988
}
×
1989

1990
// AssertNumPolicyUpdates asserts that a given number of channel policy updates
1991
// has been seen in the specified node.
1992
func (h *HarnessTest) AssertNumPolicyUpdates(hn *node.HarnessNode,
1993
        chanPoint *lnrpc.ChannelPoint,
1994
        advertisingNode *node.HarnessNode, num int) {
×
1995

×
1996
        op := h.OutPointFromChannelPoint(chanPoint)
×
1997

×
1998
        var policies []*node.PolicyUpdateInfo
×
1999

×
2000
        err := wait.NoError(func() error {
×
2001
                policyMap := hn.Watcher.GetPolicyUpdates(op)
×
2002
                nodePolicy, ok := policyMap[advertisingNode.PubKeyStr]
×
2003
                if ok {
×
2004
                        policies = nodePolicy
×
2005
                }
×
2006

2007
                if len(policies) == num {
×
2008
                        return nil
×
2009
                }
×
2010

2011
                p, err := json.MarshalIndent(policies, "", "\t")
×
2012
                require.NoError(h, err, "encode policy err")
×
2013

×
2014
                return fmt.Errorf("expected to find %d policy updates, "+
×
2015
                        "instead got: %d, chanPoint: %v, "+
×
2016
                        "advertisingNode: %s:%s, policy: %s", num,
×
2017
                        len(policies), op, advertisingNode.Name(),
×
2018
                        advertisingNode.PubKeyStr, p)
×
2019
        }, DefaultTimeout)
2020

2021
        require.NoError(h, err, "%s: timeout waiting for num of policy updates",
×
2022
                hn.Name())
×
2023
}
2024

2025
// AssertNumPayments asserts that the number of payments made within the test
2026
// scope is as expected, including the incomplete ones.
2027
func (h *HarnessTest) AssertNumPayments(hn *node.HarnessNode,
2028
        num int) []*lnrpc.Payment {
×
2029

×
2030
        // Get the number of payments we already have from the previous test.
×
2031
        have := hn.State.Payment.Total
×
2032

×
2033
        req := &lnrpc.ListPaymentsRequest{
×
2034
                IncludeIncomplete: true,
×
2035
                IndexOffset:       hn.State.Payment.LastIndexOffset,
×
2036
        }
×
2037

×
2038
        var payments []*lnrpc.Payment
×
2039
        err := wait.NoError(func() error {
×
2040
                resp := hn.RPC.ListPayments(req)
×
2041

×
2042
                payments = resp.Payments
×
2043
                if len(payments) == num {
×
2044
                        return nil
×
2045
                }
×
2046

2047
                return errNumNotMatched(hn.Name(), "num of payments",
×
2048
                        num, len(payments), have+len(payments), have)
×
2049
        }, DefaultTimeout)
2050
        require.NoError(h, err, "%s: timeout checking num of payments",
×
2051
                hn.Name())
×
2052

×
2053
        return payments
×
2054
}
2055

2056
// AssertNumNodeAnns asserts that a given number of node announcements has been
2057
// seen in the specified node.
2058
func (h *HarnessTest) AssertNumNodeAnns(hn *node.HarnessNode,
2059
        pubkey string, num int) []*lnrpc.NodeUpdate {
×
2060

×
2061
        // We will get the current number of channel updates first and add it
×
2062
        // to our expected number of newly created channel updates.
×
2063
        anns, err := hn.Watcher.WaitForNumNodeUpdates(pubkey, num)
×
2064
        require.NoError(h, err, "%s: failed to assert num of node anns",
×
2065
                hn.Name())
×
2066

×
2067
        return anns
×
2068
}
×
2069

2070
// AssertNumChannelUpdates asserts that a given number of channel updates has
2071
// been seen in the specified node's network topology.
2072
func (h *HarnessTest) AssertNumChannelUpdates(hn *node.HarnessNode,
2073
        chanPoint *lnrpc.ChannelPoint, num int) {
×
2074

×
2075
        op := h.OutPointFromChannelPoint(chanPoint)
×
2076
        err := hn.Watcher.WaitForNumChannelUpdates(op, num)
×
2077
        require.NoError(h, err, "%s: failed to assert num of channel updates",
×
2078
                hn.Name())
×
2079
}
×
2080

2081
// CreateBurnAddr creates a random burn address of the given type.
2082
func (h *HarnessTest) CreateBurnAddr(addrType lnrpc.AddressType) ([]byte,
2083
        btcutil.Address) {
×
2084

×
2085
        randomPrivKey, err := btcec.NewPrivateKey()
×
2086
        require.NoError(h, err)
×
2087

×
2088
        randomKeyBytes := randomPrivKey.PubKey().SerializeCompressed()
×
2089
        harnessNetParams := miner.HarnessNetParams
×
2090

×
2091
        var addr btcutil.Address
×
2092
        switch addrType {
×
2093
        case lnrpc.AddressType_WITNESS_PUBKEY_HASH:
×
2094
                addr, err = btcutil.NewAddressWitnessPubKeyHash(
×
2095
                        btcutil.Hash160(randomKeyBytes), harnessNetParams,
×
2096
                )
×
2097

2098
        case lnrpc.AddressType_TAPROOT_PUBKEY:
×
2099
                taprootKey := txscript.ComputeTaprootKeyNoScript(
×
2100
                        randomPrivKey.PubKey(),
×
2101
                )
×
2102
                addr, err = btcutil.NewAddressPubKey(
×
2103
                        schnorr.SerializePubKey(taprootKey), harnessNetParams,
×
2104
                )
×
2105

2106
        case lnrpc.AddressType_NESTED_PUBKEY_HASH:
×
2107
                var witnessAddr btcutil.Address
×
2108
                witnessAddr, err = btcutil.NewAddressWitnessPubKeyHash(
×
2109
                        btcutil.Hash160(randomKeyBytes), harnessNetParams,
×
2110
                )
×
2111
                require.NoError(h, err)
×
2112

×
2113
                addr, err = btcutil.NewAddressScriptHash(
×
2114
                        h.PayToAddrScript(witnessAddr), harnessNetParams,
×
2115
                )
×
2116

2117
        default:
×
2118
                h.Fatalf("Unsupported burn address type: %v", addrType)
×
2119
        }
2120
        require.NoError(h, err)
×
2121

×
2122
        return h.PayToAddrScript(addr), addr
×
2123
}
2124

2125
// ReceiveTrackPayment waits until a message is received on the track payment
2126
// stream or the timeout is reached.
2127
func (h *HarnessTest) ReceiveTrackPayment(
2128
        stream rpc.TrackPaymentClient) *lnrpc.Payment {
×
2129

×
2130
        chanMsg := make(chan *lnrpc.Payment)
×
2131
        errChan := make(chan error)
×
2132
        go func() {
×
2133
                // Consume one message. This will block until the message is
×
2134
                // received.
×
2135
                resp, err := stream.Recv()
×
2136
                if err != nil {
×
2137
                        errChan <- err
×
2138
                        return
×
2139
                }
×
2140
                chanMsg <- resp
×
2141
        }()
2142

2143
        select {
×
2144
        case <-time.After(DefaultTimeout):
×
2145
                require.Fail(h, "timeout", "timeout trakcing payment")
×
2146

2147
        case err := <-errChan:
×
2148
                require.Failf(h, "err from stream",
×
2149
                        "received err from stream: %v", err)
×
2150

2151
        case updateMsg := <-chanMsg:
×
2152
                return updateMsg
×
2153
        }
2154

2155
        return nil
×
2156
}
2157

2158
// ReceiveHtlcEvent waits until a message is received on the subscribe
2159
// htlc event stream or the timeout is reached.
2160
func (h *HarnessTest) ReceiveHtlcEvent(
2161
        stream rpc.HtlcEventsClient) *routerrpc.HtlcEvent {
×
2162

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

2176
        select {
×
2177
        case <-time.After(DefaultTimeout):
×
2178
                require.Fail(h, "timeout", "timeout receiving htlc "+
×
2179
                        "event update")
×
2180

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

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

2189
        return nil
×
2190
}
2191

2192
// AssertHtlcEventType consumes one event from a client and asserts the event
2193
// type is matched.
2194
func (h *HarnessTest) AssertHtlcEventType(client rpc.HtlcEventsClient,
2195
        userType routerrpc.HtlcEvent_EventType) *routerrpc.HtlcEvent {
×
2196

×
2197
        event := h.ReceiveHtlcEvent(client)
×
2198
        require.Equalf(h, userType, event.EventType, "wrong event type, "+
×
2199
                "want %v got %v", userType, event.EventType)
×
2200

×
2201
        return event
×
2202
}
×
2203

2204
// HtlcEvent maps the series of event types used in `*routerrpc.HtlcEvent_*`.
2205
type HtlcEvent int
2206

2207
const (
2208
        HtlcEventForward HtlcEvent = iota
2209
        HtlcEventForwardFail
2210
        HtlcEventSettle
2211
        HtlcEventLinkFail
2212
        HtlcEventFinal
2213
)
2214

2215
// AssertHtlcEventType consumes one event from a client and asserts both the
2216
// user event type the event.Event type is matched.
2217
func (h *HarnessTest) AssertHtlcEventTypes(client rpc.HtlcEventsClient,
2218
        userType routerrpc.HtlcEvent_EventType,
2219
        eventType HtlcEvent) *routerrpc.HtlcEvent {
×
2220

×
2221
        event := h.ReceiveHtlcEvent(client)
×
2222
        require.Equalf(h, userType, event.EventType, "wrong event type, "+
×
2223
                "want %v got %v", userType, event.EventType)
×
2224

×
2225
        var ok bool
×
2226

×
2227
        switch eventType {
×
2228
        case HtlcEventForward:
×
2229
                _, ok = event.Event.(*routerrpc.HtlcEvent_ForwardEvent)
×
2230

2231
        case HtlcEventForwardFail:
×
2232
                _, ok = event.Event.(*routerrpc.HtlcEvent_ForwardFailEvent)
×
2233

2234
        case HtlcEventSettle:
×
2235
                _, ok = event.Event.(*routerrpc.HtlcEvent_SettleEvent)
×
2236

2237
        case HtlcEventLinkFail:
×
2238
                _, ok = event.Event.(*routerrpc.HtlcEvent_LinkFailEvent)
×
2239

2240
        case HtlcEventFinal:
×
2241
                _, ok = event.Event.(*routerrpc.HtlcEvent_FinalHtlcEvent)
×
2242
        }
2243

2244
        require.Truef(h, ok, "wrong event type: %T, want %T", event.Event,
×
2245
                eventType)
×
2246

×
2247
        return event
×
2248
}
2249

2250
// AssertFeeReport checks that the fee report from the given node has the
2251
// desired day, week, and month sum values.
2252
func (h *HarnessTest) AssertFeeReport(hn *node.HarnessNode,
2253
        day, week, month int) {
×
2254

×
2255
        err := wait.NoError(func() error {
×
2256
                feeReport, err := hn.RPC.LN.FeeReport(
×
2257
                        h.runCtx, &lnrpc.FeeReportRequest{},
×
2258
                )
×
2259
                require.NoError(h, err, "unable to query for fee report")
×
2260

×
2261
                if uint64(day) != feeReport.DayFeeSum {
×
2262
                        return fmt.Errorf("day fee mismatch, want %d, got %d",
×
2263
                                day, feeReport.DayFeeSum)
×
2264
                }
×
2265

2266
                if uint64(week) != feeReport.WeekFeeSum {
×
2267
                        return fmt.Errorf("week fee mismatch, want %d, got %d",
×
2268
                                week, feeReport.WeekFeeSum)
×
2269
                }
×
2270
                if uint64(month) != feeReport.MonthFeeSum {
×
2271
                        return fmt.Errorf("month fee mismatch, want %d, got %d",
×
2272
                                month, feeReport.MonthFeeSum)
×
2273
                }
×
2274

2275
                return nil
×
2276
        }, wait.DefaultTimeout)
2277
        require.NoErrorf(h, err, "%s: time out checking fee report", hn.Name())
×
2278
}
2279

2280
// AssertHtlcEvents consumes events from a client and ensures that they are of
2281
// the expected type and contain the expected number of forwards, forward
2282
// failures and settles.
2283
//
2284
// TODO(yy): needs refactor to reduce its complexity.
2285
func (h *HarnessTest) AssertHtlcEvents(client rpc.HtlcEventsClient,
2286
        fwdCount, fwdFailCount, settleCount, linkFailCount int,
2287
        userType routerrpc.HtlcEvent_EventType) []*routerrpc.HtlcEvent {
×
2288

×
2289
        var forwards, forwardFails, settles, linkFails int
×
2290

×
2291
        numEvents := fwdCount + fwdFailCount + settleCount + linkFailCount
×
2292
        events := make([]*routerrpc.HtlcEvent, 0)
×
2293

×
2294
        // It's either the userType or the unknown type.
×
2295
        //
×
2296
        // TODO(yy): maybe the FinalHtlcEvent shouldn't be in UNKNOWN type?
×
2297
        eventTypes := []routerrpc.HtlcEvent_EventType{
×
2298
                userType, routerrpc.HtlcEvent_UNKNOWN,
×
2299
        }
×
2300

×
2301
        for i := 0; i < numEvents; i++ {
×
2302
                event := h.ReceiveHtlcEvent(client)
×
2303

×
2304
                require.Containsf(h, eventTypes, event.EventType,
×
2305
                        "wrong event type, got %v", userType, event.EventType)
×
2306

×
2307
                events = append(events, event)
×
2308

×
2309
                switch e := event.Event.(type) {
×
2310
                case *routerrpc.HtlcEvent_ForwardEvent:
×
2311
                        forwards++
×
2312

2313
                case *routerrpc.HtlcEvent_ForwardFailEvent:
×
2314
                        forwardFails++
×
2315

2316
                case *routerrpc.HtlcEvent_SettleEvent:
×
2317
                        settles++
×
2318

2319
                case *routerrpc.HtlcEvent_FinalHtlcEvent:
×
2320
                        if e.FinalHtlcEvent.Settled {
×
2321
                                settles++
×
2322
                        }
×
2323

2324
                case *routerrpc.HtlcEvent_LinkFailEvent:
×
2325
                        linkFails++
×
2326

2327
                default:
×
2328
                        require.Fail(h, "assert event fail",
×
2329
                                "unexpected event: %T", event.Event)
×
2330
                }
2331
        }
2332

2333
        require.Equal(h, fwdCount, forwards, "num of forwards mismatch")
×
2334
        require.Equal(h, fwdFailCount, forwardFails,
×
2335
                "num of forward fails mismatch")
×
2336
        require.Equal(h, settleCount, settles, "num of settles mismatch")
×
2337
        require.Equal(h, linkFailCount, linkFails, "num of link fails mismatch")
×
2338

×
2339
        return events
×
2340
}
2341

2342
// AssertTransactionInWallet asserts a given txid can be found in the node's
2343
// wallet.
2344
func (h *HarnessTest) AssertTransactionInWallet(hn *node.HarnessNode,
2345
        txid chainhash.Hash) {
×
2346

×
2347
        req := &lnrpc.GetTransactionsRequest{}
×
2348
        err := wait.NoError(func() error {
×
2349
                txResp := hn.RPC.GetTransactions(req)
×
2350
                for _, txn := range txResp.Transactions {
×
2351
                        if txn.TxHash == txid.String() {
×
2352
                                return nil
×
2353
                        }
×
2354
                }
2355

2356
                return fmt.Errorf("%s: expected txid=%v not found in wallet",
×
2357
                        hn.Name(), txid)
×
2358
        }, DefaultTimeout)
2359

2360
        require.NoError(h, err, "failed to find tx")
×
2361
}
2362

2363
// AssertTransactionNotInWallet asserts a given txid can NOT be found in the
2364
// node's wallet.
2365
func (h *HarnessTest) AssertTransactionNotInWallet(hn *node.HarnessNode,
2366
        txid chainhash.Hash) {
×
2367

×
2368
        req := &lnrpc.GetTransactionsRequest{}
×
2369
        err := wait.NoError(func() error {
×
2370
                txResp := hn.RPC.GetTransactions(req)
×
2371
                for _, txn := range txResp.Transactions {
×
2372
                        if txn.TxHash == txid.String() {
×
2373
                                return fmt.Errorf("expected txid=%v to be "+
×
2374
                                        "not found", txid)
×
2375
                        }
×
2376
                }
2377

2378
                return nil
×
2379
        }, DefaultTimeout)
2380

2381
        require.NoErrorf(h, err, "%s: failed to assert tx not found", hn.Name())
×
2382
}
2383

2384
// WaitForNodeBlockHeight queries the node for its current block height until
2385
// it reaches the passed height.
2386
func (h *HarnessTest) WaitForNodeBlockHeight(hn *node.HarnessNode,
2387
        height int32) {
×
2388

×
2389
        err := wait.NoError(func() error {
×
2390
                info := hn.RPC.GetInfo()
×
2391
                if int32(info.BlockHeight) != height {
×
2392
                        return fmt.Errorf("expected block height to "+
×
2393
                                "be %v, was %v", height, info.BlockHeight)
×
2394
                }
×
2395

2396
                return nil
×
2397
        }, DefaultTimeout)
2398

2399
        require.NoErrorf(h, err, "%s: timeout while waiting for height",
×
2400
                hn.Name())
×
2401
}
2402

2403
// AssertChannelCommitHeight asserts the given channel for the node has the
2404
// expected commit height(`NumUpdates`).
2405
func (h *HarnessTest) AssertChannelCommitHeight(hn *node.HarnessNode,
2406
        cp *lnrpc.ChannelPoint, height int) {
×
2407

×
2408
        err := wait.NoError(func() error {
×
2409
                c, err := h.findChannel(hn, cp)
×
2410
                if err != nil {
×
2411
                        return err
×
2412
                }
×
2413

2414
                if int(c.NumUpdates) == height {
×
2415
                        return nil
×
2416
                }
×
2417

2418
                return fmt.Errorf("expected commit height to be %v, was %v",
×
2419
                        height, c.NumUpdates)
×
2420
        }, DefaultTimeout)
2421

2422
        require.NoError(h, err, "timeout while waiting for commit height")
×
2423
}
2424

2425
// AssertNumInvoices asserts that the number of invoices made within the test
2426
// scope is as expected.
2427
func (h *HarnessTest) AssertNumInvoices(hn *node.HarnessNode,
2428
        num int) []*lnrpc.Invoice {
×
2429

×
2430
        have := hn.State.Invoice.Total
×
2431
        req := &lnrpc.ListInvoiceRequest{
×
2432
                NumMaxInvoices: math.MaxUint64,
×
2433
                IndexOffset:    hn.State.Invoice.LastIndexOffset,
×
2434
        }
×
2435

×
2436
        var invoices []*lnrpc.Invoice
×
2437
        err := wait.NoError(func() error {
×
2438
                resp := hn.RPC.ListInvoices(req)
×
2439

×
2440
                invoices = resp.Invoices
×
2441
                if len(invoices) == num {
×
2442
                        return nil
×
2443
                }
×
2444

2445
                return errNumNotMatched(hn.Name(), "num of invoices",
×
2446
                        num, len(invoices), have+len(invoices), have)
×
2447
        }, DefaultTimeout)
2448
        require.NoError(h, err, "timeout checking num of invoices")
×
2449

×
2450
        return invoices
×
2451
}
2452

2453
// ReceiveSendToRouteUpdate waits until a message is received on the
2454
// SendToRoute client stream or the timeout is reached.
2455
func (h *HarnessTest) ReceiveSendToRouteUpdate(
2456
        stream rpc.SendToRouteClient) (*lnrpc.SendResponse, error) {
×
2457

×
2458
        chanMsg := make(chan *lnrpc.SendResponse, 1)
×
2459
        errChan := make(chan error, 1)
×
2460
        go func() {
×
2461
                // Consume one message. This will block until the message is
×
2462
                // received.
×
2463
                resp, err := stream.Recv()
×
2464
                if err != nil {
×
2465
                        errChan <- err
×
2466

×
2467
                        return
×
2468
                }
×
2469
                chanMsg <- resp
×
2470
        }()
2471

2472
        select {
×
2473
        case <-time.After(DefaultTimeout):
×
2474
                require.Fail(h, "timeout", "timeout waiting for send resp")
×
2475
                return nil, nil
×
2476

2477
        case err := <-errChan:
×
2478
                return nil, err
×
2479

2480
        case updateMsg := <-chanMsg:
×
2481
                return updateMsg, nil
×
2482
        }
2483
}
2484

2485
// AssertInvoiceEqual asserts that two lnrpc.Invoices are equivalent. A custom
2486
// comparison function is defined for these tests, since proto message returned
2487
// from unary and streaming RPCs (as of protobuf 1.23.0 and grpc 1.29.1) aren't
2488
// consistent with the private fields set on the messages. As a result, we
2489
// avoid using require.Equal and test only the actual data members.
2490
func (h *HarnessTest) AssertInvoiceEqual(a, b *lnrpc.Invoice) {
×
2491
        // Ensure the HTLCs are sorted properly before attempting to compare.
×
2492
        sort.Slice(a.Htlcs, func(i, j int) bool {
×
2493
                return a.Htlcs[i].ChanId < a.Htlcs[j].ChanId
×
2494
        })
×
2495
        sort.Slice(b.Htlcs, func(i, j int) bool {
×
2496
                return b.Htlcs[i].ChanId < b.Htlcs[j].ChanId
×
2497
        })
×
2498

2499
        require.Equal(h, a.Memo, b.Memo)
×
2500
        require.Equal(h, a.RPreimage, b.RPreimage)
×
2501
        require.Equal(h, a.RHash, b.RHash)
×
2502
        require.Equal(h, a.Value, b.Value)
×
2503
        require.Equal(h, a.ValueMsat, b.ValueMsat)
×
2504
        require.Equal(h, a.CreationDate, b.CreationDate)
×
2505
        require.Equal(h, a.SettleDate, b.SettleDate)
×
2506
        require.Equal(h, a.PaymentRequest, b.PaymentRequest)
×
2507
        require.Equal(h, a.DescriptionHash, b.DescriptionHash)
×
2508
        require.Equal(h, a.Expiry, b.Expiry)
×
2509
        require.Equal(h, a.FallbackAddr, b.FallbackAddr)
×
2510
        require.Equal(h, a.CltvExpiry, b.CltvExpiry)
×
2511
        require.Equal(h, a.RouteHints, b.RouteHints)
×
2512
        require.Equal(h, a.Private, b.Private)
×
2513
        require.Equal(h, a.AddIndex, b.AddIndex)
×
2514
        require.Equal(h, a.SettleIndex, b.SettleIndex)
×
2515
        require.Equal(h, a.AmtPaidSat, b.AmtPaidSat)
×
2516
        require.Equal(h, a.AmtPaidMsat, b.AmtPaidMsat)
×
2517
        require.Equal(h, a.State, b.State)
×
2518
        require.Equal(h, a.Features, b.Features)
×
2519
        require.Equal(h, a.IsKeysend, b.IsKeysend)
×
2520
        require.Equal(h, a.PaymentAddr, b.PaymentAddr)
×
2521
        require.Equal(h, a.IsAmp, b.IsAmp)
×
2522

×
2523
        require.Equal(h, len(a.Htlcs), len(b.Htlcs))
×
2524
        for i := range a.Htlcs {
×
2525
                htlcA, htlcB := a.Htlcs[i], b.Htlcs[i]
×
2526
                require.Equal(h, htlcA.ChanId, htlcB.ChanId)
×
2527
                require.Equal(h, htlcA.HtlcIndex, htlcB.HtlcIndex)
×
2528
                require.Equal(h, htlcA.AmtMsat, htlcB.AmtMsat)
×
2529
                require.Equal(h, htlcA.AcceptHeight, htlcB.AcceptHeight)
×
2530
                require.Equal(h, htlcA.AcceptTime, htlcB.AcceptTime)
×
2531
                require.Equal(h, htlcA.ResolveTime, htlcB.ResolveTime)
×
2532
                require.Equal(h, htlcA.ExpiryHeight, htlcB.ExpiryHeight)
×
2533
                require.Equal(h, htlcA.State, htlcB.State)
×
2534
                require.Equal(h, htlcA.CustomRecords, htlcB.CustomRecords)
×
2535
                require.Equal(h, htlcA.MppTotalAmtMsat, htlcB.MppTotalAmtMsat)
×
2536
                require.Equal(h, htlcA.Amp, htlcB.Amp)
×
2537
        }
×
2538
}
2539

2540
// AssertUTXOInWallet asserts that a given UTXO can be found in the node's
2541
// wallet.
2542
func (h *HarnessTest) AssertUTXOInWallet(hn *node.HarnessNode,
2543
        op *lnrpc.OutPoint, account string) {
×
2544

×
2545
        err := wait.NoError(func() error {
×
2546
                utxos := h.GetUTXOs(hn, account)
×
2547

×
2548
                err := fmt.Errorf("tx with hash %x not found", op.TxidBytes)
×
2549
                for _, utxo := range utxos {
×
2550
                        if !bytes.Equal(utxo.Outpoint.TxidBytes, op.TxidBytes) {
×
2551
                                continue
×
2552
                        }
2553

2554
                        err = fmt.Errorf("tx with output index %v not found",
×
2555
                                op.OutputIndex)
×
2556
                        if utxo.Outpoint.OutputIndex != op.OutputIndex {
×
2557
                                continue
×
2558
                        }
2559

2560
                        return nil
×
2561
                }
2562

2563
                return err
×
2564
        }, DefaultTimeout)
2565

2566
        require.NoErrorf(h, err, "outpoint %v not found in %s's wallet",
×
2567
                op, hn.Name())
×
2568
}
2569

2570
// AssertWalletAccountBalance asserts that the unconfirmed and confirmed
2571
// balance for the given account is satisfied by the WalletBalance and
2572
// ListUnspent RPCs. The unconfirmed balance is not checked for neutrino nodes.
2573
func (h *HarnessTest) AssertWalletAccountBalance(hn *node.HarnessNode,
2574
        account string, confirmedBalance, unconfirmedBalance int64) {
×
2575

×
2576
        err := wait.NoError(func() error {
×
2577
                balanceResp := hn.RPC.WalletBalance()
×
2578
                require.Contains(h, balanceResp.AccountBalance, account)
×
2579
                accountBalance := balanceResp.AccountBalance[account]
×
2580

×
2581
                // Check confirmed balance.
×
2582
                if accountBalance.ConfirmedBalance != confirmedBalance {
×
2583
                        return fmt.Errorf("expected confirmed balance %v, "+
×
2584
                                "got %v", confirmedBalance,
×
2585
                                accountBalance.ConfirmedBalance)
×
2586
                }
×
2587

2588
                utxos := h.GetUTXOsConfirmed(hn, account)
×
2589
                var totalConfirmedVal int64
×
2590
                for _, utxo := range utxos {
×
2591
                        totalConfirmedVal += utxo.AmountSat
×
2592
                }
×
2593
                if totalConfirmedVal != confirmedBalance {
×
2594
                        return fmt.Errorf("expected total confirmed utxo "+
×
2595
                                "balance %v, got %v", confirmedBalance,
×
2596
                                totalConfirmedVal)
×
2597
                }
×
2598

2599
                // Skip unconfirmed balance checks for neutrino nodes.
2600
                if h.IsNeutrinoBackend() {
×
2601
                        return nil
×
2602
                }
×
2603

2604
                // Check unconfirmed balance.
2605
                if accountBalance.UnconfirmedBalance != unconfirmedBalance {
×
2606
                        return fmt.Errorf("expected unconfirmed balance %v, "+
×
2607
                                "got %v", unconfirmedBalance,
×
2608
                                accountBalance.UnconfirmedBalance)
×
2609
                }
×
2610

2611
                utxos = h.GetUTXOsUnconfirmed(hn, account)
×
2612
                var totalUnconfirmedVal int64
×
2613
                for _, utxo := range utxos {
×
2614
                        totalUnconfirmedVal += utxo.AmountSat
×
2615
                }
×
2616
                if totalUnconfirmedVal != unconfirmedBalance {
×
2617
                        return fmt.Errorf("expected total unconfirmed utxo "+
×
2618
                                "balance %v, got %v", unconfirmedBalance,
×
2619
                                totalUnconfirmedVal)
×
2620
                }
×
2621

2622
                return nil
×
2623
        }, DefaultTimeout)
2624
        require.NoError(h, err, "timeout checking wallet account balance")
×
2625
}
2626

2627
// AssertClosingTxInMempool assert that the closing transaction of the given
2628
// channel point can be found in the mempool. If the channel has anchors, it
2629
// will assert the anchor sweep tx is also in the mempool.
2630
func (h *HarnessTest) AssertClosingTxInMempool(cp *lnrpc.ChannelPoint,
2631
        c lnrpc.CommitmentType) *wire.MsgTx {
×
2632

×
2633
        // Get expected number of txes to be found in the mempool.
×
2634
        expectedTxes := 1
×
2635
        hasAnchors := CommitTypeHasAnchors(c)
×
2636
        if hasAnchors {
×
2637
                expectedTxes = 2
×
2638
        }
×
2639

2640
        // Wait for the expected txes to be found in the mempool.
2641
        h.AssertNumTxsInMempool(expectedTxes)
×
2642

×
2643
        // Get the closing tx from the mempool.
×
2644
        op := h.OutPointFromChannelPoint(cp)
×
2645
        closeTx := h.AssertOutpointInMempool(op)
×
2646

×
2647
        return closeTx
×
2648
}
2649

2650
// AssertClosingTxInMempool assert that the closing transaction of the given
2651
// channel point can be found in the mempool. If the channel has anchors, it
2652
// will assert the anchor sweep tx is also in the mempool.
2653
func (h *HarnessTest) MineClosingTx(cp *lnrpc.ChannelPoint) *wire.MsgTx {
×
2654
        // Wait for the expected txes to be found in the mempool.
×
2655
        h.AssertNumTxsInMempool(1)
×
2656

×
2657
        // Get the closing tx from the mempool.
×
2658
        op := h.OutPointFromChannelPoint(cp)
×
2659
        closeTx := h.AssertOutpointInMempool(op)
×
2660

×
2661
        // Mine a block to confirm the closing transaction and potential anchor
×
2662
        // sweep.
×
2663
        h.MineBlocksAndAssertNumTxes(1, 1)
×
2664

×
2665
        return closeTx
×
2666
}
×
2667

2668
// AssertWalletLockedBalance asserts the expected amount has been marked as
2669
// locked in the node's WalletBalance response.
2670
func (h *HarnessTest) AssertWalletLockedBalance(hn *node.HarnessNode,
2671
        balance int64) {
×
2672

×
2673
        err := wait.NoError(func() error {
×
2674
                balanceResp := hn.RPC.WalletBalance()
×
2675
                got := balanceResp.LockedBalance
×
2676

×
2677
                if got != balance {
×
2678
                        return fmt.Errorf("want %d, got %d", balance, got)
×
2679
                }
×
2680

2681
                return nil
×
2682
        }, wait.DefaultTimeout)
2683
        require.NoError(h, err, "%s: timeout checking locked balance",
×
2684
                hn.Name())
×
2685
}
2686

2687
// AssertNumPendingSweeps asserts the number of pending sweeps for the given
2688
// node.
2689
func (h *HarnessTest) AssertNumPendingSweeps(hn *node.HarnessNode,
2690
        n int) []*walletrpc.PendingSweep {
×
2691

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

×
2694
        err := wait.NoError(func() error {
×
2695
                resp := hn.RPC.PendingSweeps()
×
2696
                num := len(resp.PendingSweeps)
×
2697

×
2698
                numDesc := "\n"
×
2699
                for _, s := range resp.PendingSweeps {
×
2700
                        desc := fmt.Sprintf("op=%v:%v, amt=%v, type=%v, "+
×
2701
                                "deadline=%v\n", s.Outpoint.TxidStr,
×
2702
                                s.Outpoint.OutputIndex, s.AmountSat,
×
2703
                                s.WitnessType, s.DeadlineHeight)
×
2704
                        numDesc += desc
×
2705

×
2706
                        // The deadline height must be set, otherwise the
×
2707
                        // pending input response is not update-to-date.
×
2708
                        if s.DeadlineHeight == 0 {
×
2709
                                return fmt.Errorf("input not updated: %s", desc)
×
2710
                        }
×
2711
                }
2712

2713
                if num == n {
×
2714
                        results = resp.PendingSweeps
×
2715
                        return nil
×
2716
                }
×
2717

2718
                return fmt.Errorf("want %d , got %d, sweeps: %s", n, num,
×
2719
                        numDesc)
×
2720
        }, DefaultTimeout)
2721

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

×
2724
        return results
×
2725
}
2726

2727
// FindSweepingTxns asserts the expected number of sweeping txns are found in
2728
// the txns specified and return them.
2729
func (h *HarnessTest) FindSweepingTxns(txns []*wire.MsgTx,
2730
        expectedNumSweeps int, closeTxid chainhash.Hash) []*wire.MsgTx {
×
2731

×
2732
        var sweepTxns []*wire.MsgTx
×
2733

×
2734
        for _, tx := range txns {
×
2735
                if tx.TxIn[0].PreviousOutPoint.Hash == closeTxid {
×
2736
                        sweepTxns = append(sweepTxns, tx)
×
2737
                }
×
2738
        }
2739
        require.Len(h, sweepTxns, expectedNumSweeps, "unexpected num of sweeps")
×
2740

×
2741
        return sweepTxns
×
2742
}
2743

2744
// AssertForceCloseAndAnchorTxnsInMempool asserts that the force close and
2745
// anchor sweep txns are found in the mempool and returns the force close tx
2746
// and the anchor sweep tx.
2747
func (h *HarnessTest) AssertForceCloseAndAnchorTxnsInMempool() (*wire.MsgTx,
2748
        *wire.MsgTx) {
×
2749

×
2750
        // Assert there are two txns in the mempool.
×
2751
        txns := h.GetNumTxsFromMempool(2)
×
2752

×
2753
        // isParentAndChild checks whether there is an input used in the
×
2754
        // assumed child tx by checking every input's previous outpoint against
×
2755
        // the assumed parentTxid.
×
2756
        isParentAndChild := func(parent, child *wire.MsgTx) bool {
×
2757
                parentTxid := parent.TxHash()
×
2758

×
2759
                for _, inp := range child.TxIn {
×
2760
                        if inp.PreviousOutPoint.Hash == parentTxid {
×
2761
                                // Found a match, this is indeed the anchor
×
2762
                                // sweeping tx so we return it here.
×
2763
                                return true
×
2764
                        }
×
2765
                }
2766

2767
                return false
×
2768
        }
2769

2770
        switch {
×
2771
        // Assume the first one is the closing tx and the second one is the
2772
        // anchor sweeping tx.
2773
        case isParentAndChild(txns[0], txns[1]):
×
2774
                return txns[0], txns[1]
×
2775

2776
        // Assume the first one is the anchor sweeping tx and the second one is
2777
        // the closing tx.
2778
        case isParentAndChild(txns[1], txns[0]):
×
2779
                return txns[1], txns[0]
×
2780

2781
        // Unrelated txns found, fail the test.
2782
        default:
×
2783
                h.Fatalf("the two txns not related: %v", txns)
×
2784

×
2785
                return nil, nil
×
2786
        }
2787
}
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