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

lightningnetwork / lnd / 10207481183

01 Aug 2024 11:52PM UTC coverage: 58.679% (+0.09%) from 58.591%
10207481183

push

github

web-flow
Merge pull request #8836 from hieblmi/payment-failure-reason-cancel

routing: add payment failure reason `FailureReasonCancel`

7 of 30 new or added lines in 5 files covered. (23.33%)

1662 existing lines in 21 files now uncovered.

125454 of 213798 relevant lines covered (58.68%)

28679.1 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/lnrpc"
23
        "github.com/lightningnetwork/lnd/lnrpc/invoicesrpc"
24
        "github.com/lightningnetwork/lnd/lnrpc/routerrpc"
25
        "github.com/lightningnetwork/lnd/lnrpc/walletrpc"
26
        "github.com/lightningnetwork/lnd/lntest/miner"
27
        "github.com/lightningnetwork/lnd/lntest/node"
28
        "github.com/lightningnetwork/lnd/lntest/rpc"
29
        "github.com/lightningnetwork/lnd/lntest/wait"
30
        "github.com/lightningnetwork/lnd/lntypes"
31
        "github.com/stretchr/testify/require"
32
        "google.golang.org/protobuf/proto"
33
)
34

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

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

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

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

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

61
// WaitForBlockchainSyncTo waits until the node is synced to bestBlock.
62
func (h *HarnessTest) WaitForBlockchainSyncTo(hn *node.HarnessNode,
63
        bestBlock *wire.MsgBlock) {
×
64

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

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

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

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

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

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

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

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

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

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

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

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

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

×
147
        // Assert disconnected.
×
148
        h.AssertPeerNotConnected(a, b)
×
149
}
×
150

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

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

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

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

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

×
181
                _, err := a.RPC.LN.ConnectPeer(ctxt, req)
×
182

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

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

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

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

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

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

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

220
                return err
×
221
        }
222

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

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

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

242
// AssertNumEdges checks that an expected number of edges can be found in the
243
// node specified.
244
func (h *HarnessTest) AssertNumEdges(hn *node.HarnessNode,
245
        expected int, includeUnannounced bool) []*lnrpc.ChannelEdge {
×
246

×
247
        var edges []*lnrpc.ChannelEdge
×
248

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

254
        err := wait.NoError(func() error {
×
255
                req := &lnrpc.ChannelGraphRequest{
×
256
                        IncludeUnannounced: includeUnannounced,
×
257
                }
×
258
                chanGraph := hn.RPC.DescribeGraph(req)
×
259
                total := len(chanGraph.Edges)
×
260

×
261
                if total-old == expected {
×
262
                        if expected != 0 {
×
263
                                // NOTE: assume edges come in ascending order
×
264
                                // that the old edges are at the front of the
×
265
                                // slice.
×
266
                                edges = chanGraph.Edges[old:]
×
267
                        }
×
268

269
                        return nil
×
270
                }
271

272
                return errNumNotMatched(hn.Name(), "num of channel edges",
×
273
                        expected, total-old, total, old)
×
274
        }, DefaultTimeout)
275

276
        require.NoError(h, err, "timeout while checking for edges")
×
277

×
278
        return edges
×
279
}
280

281
// ReceiveOpenChannelUpdate waits until a message is received on the stream or
282
// the timeout is reached.
283
func (h *HarnessTest) ReceiveOpenChannelUpdate(
284
        stream rpc.OpenChanClient) *lnrpc.OpenStatusUpdate {
×
285

×
286
        update, err := h.receiveOpenChannelUpdate(stream)
×
287
        require.NoError(h, err, "received err from open channel stream")
×
288

×
289
        return update
×
290
}
×
291

292
// ReceiveOpenChannelError waits for the expected error during the open channel
293
// flow from the peer or times out.
294
func (h *HarnessTest) ReceiveOpenChannelError(
295
        stream rpc.OpenChanClient, expectedErr error) {
×
296

×
297
        _, err := h.receiveOpenChannelUpdate(stream)
×
298
        require.Contains(h, err.Error(), expectedErr.Error(),
×
299
                "error not matched")
×
300
}
×
301

302
// receiveOpenChannelUpdate waits until a message or an error is received on
303
// the stream or the timeout is reached.
304
//
305
// TODO(yy): use generics to unify all receiving stream update once go@1.18 is
306
// used.
307
func (h *HarnessTest) receiveOpenChannelUpdate(
308
        stream rpc.OpenChanClient) (*lnrpc.OpenStatusUpdate, error) {
×
309

×
310
        chanMsg := make(chan *lnrpc.OpenStatusUpdate)
×
311
        errChan := make(chan error)
×
312
        go func() {
×
313
                // Consume one message. This will block until the message is
×
314
                // received.
×
315
                resp, err := stream.Recv()
×
316
                if err != nil {
×
317
                        errChan <- err
×
318
                        return
×
319
                }
×
320
                chanMsg <- resp
×
321
        }()
322

323
        select {
×
324
        case <-time.After(DefaultTimeout):
×
325
                require.Fail(h, "timeout", "timeout waiting for open channel "+
×
326
                        "update sent")
×
327
                return nil, nil
×
328

329
        case err := <-errChan:
×
330
                return nil, err
×
331

332
        case updateMsg := <-chanMsg:
×
333
                return updateMsg, nil
×
334
        }
335
}
336

337
// WaitForChannelOpenEvent waits for a notification that a channel is open by
338
// consuming a message from the passed open channel stream.
339
func (h HarnessTest) WaitForChannelOpenEvent(
340
        stream rpc.OpenChanClient) *lnrpc.ChannelPoint {
×
341

×
342
        // Consume one event.
×
343
        event := h.ReceiveOpenChannelUpdate(stream)
×
344

×
345
        resp, ok := event.Update.(*lnrpc.OpenStatusUpdate_ChanOpen)
×
346
        require.Truef(h, ok, "expected channel open update, instead got %v",
×
347
                resp)
×
348

×
349
        return resp.ChanOpen.ChannelPoint
×
350
}
×
351

352
// AssertTopologyChannelOpen asserts that a given channel outpoint is seen by
353
// the passed node's network topology.
354
func (h *HarnessTest) AssertTopologyChannelOpen(hn *node.HarnessNode,
355
        chanPoint *lnrpc.ChannelPoint) {
×
356

×
357
        err := hn.Watcher.WaitForChannelOpen(chanPoint)
×
358
        require.NoErrorf(h, err, "%s didn't report channel", hn.Name())
×
359
}
×
360

361
// AssertChannelExists asserts that an active channel identified by the
362
// specified channel point exists from the point-of-view of the node.
363
func (h *HarnessTest) AssertChannelExists(hn *node.HarnessNode,
364
        cp *lnrpc.ChannelPoint) *lnrpc.Channel {
×
365

×
366
        return h.assertChannelStatus(hn, cp, true)
×
367
}
×
368

369
// AssertChannelActive checks if a channel identified by the specified channel
370
// point is active.
371
func (h *HarnessTest) AssertChannelActive(hn *node.HarnessNode,
372
        cp *lnrpc.ChannelPoint) *lnrpc.Channel {
×
373

×
374
        return h.assertChannelStatus(hn, cp, true)
×
375
}
×
376

377
// AssertChannelInactive checks if a channel identified by the specified channel
378
// point is inactive.
379
func (h *HarnessTest) AssertChannelInactive(hn *node.HarnessNode,
380
        cp *lnrpc.ChannelPoint) *lnrpc.Channel {
×
381

×
382
        return h.assertChannelStatus(hn, cp, false)
×
383
}
×
384

385
// assertChannelStatus asserts that a channel identified by the specified
386
// channel point exists from the point-of-view of the node and that it is either
387
// active or inactive depending on the value of the active parameter.
388
func (h *HarnessTest) assertChannelStatus(hn *node.HarnessNode,
389
        cp *lnrpc.ChannelPoint, active bool) *lnrpc.Channel {
×
390

×
391
        var (
×
392
                channel *lnrpc.Channel
×
393
                err     error
×
394
        )
×
395

×
396
        err = wait.NoError(func() error {
×
397
                channel, err = h.findChannel(hn, cp)
×
398
                if err != nil {
×
399
                        return err
×
400
                }
×
401

402
                // Check whether the channel is active, exit early if it is.
403
                if channel.Active == active {
×
404
                        return nil
×
405
                }
×
406

407
                return fmt.Errorf("expected channel_active=%v, got %v",
×
408
                        active, channel.Active)
×
409
        }, DefaultTimeout)
410

411
        require.NoErrorf(h, err, "%s: timeout checking for channel point: %v",
×
412
                hn.Name(), cp)
×
413

×
414
        return channel
×
415
}
416

417
// AssertOutputScriptClass checks that the specified transaction output has the
418
// expected script class.
419
func (h *HarnessTest) AssertOutputScriptClass(tx *btcutil.Tx,
420
        outputIndex uint32, scriptClass txscript.ScriptClass) {
×
421

×
422
        require.Greater(h, len(tx.MsgTx().TxOut), int(outputIndex))
×
423

×
424
        txOut := tx.MsgTx().TxOut[outputIndex]
×
425

×
426
        pkScript, err := txscript.ParsePkScript(txOut.PkScript)
×
427
        require.NoError(h, err)
×
428
        require.Equal(h, scriptClass, pkScript.Class())
×
429
}
×
430

431
// findChannel tries to find a target channel in the node using the given
432
// channel point.
433
func (h *HarnessTest) findChannel(hn *node.HarnessNode,
434
        chanPoint *lnrpc.ChannelPoint,
435
        opts ...ListChannelOption) (*lnrpc.Channel, error) {
×
436

×
437
        // Get the funding point.
×
438
        fp := h.OutPointFromChannelPoint(chanPoint)
×
439

×
440
        req := &lnrpc.ListChannelsRequest{}
×
441

×
442
        for _, opt := range opts {
×
443
                opt(req)
×
444
        }
×
445

446
        channelInfo := hn.RPC.ListChannels(req)
×
447

×
448
        // Find the target channel.
×
449
        for _, channel := range channelInfo.Channels {
×
450
                if channel.ChannelPoint == fp.String() {
×
451
                        return channel, nil
×
452
                }
×
453
        }
454

455
        return nil, fmt.Errorf("channel not found using %s", chanPoint)
×
456
}
457

458
// ReceiveCloseChannelUpdate waits until a message or an error is received on
459
// the subscribe channel close stream or the timeout is reached.
460
func (h *HarnessTest) ReceiveCloseChannelUpdate(
461
        stream rpc.CloseChanClient) (*lnrpc.CloseStatusUpdate, error) {
×
462

×
463
        chanMsg := make(chan *lnrpc.CloseStatusUpdate)
×
464
        errChan := make(chan error)
×
465
        go func() {
×
466
                // Consume one message. This will block until the message is
×
467
                // received.
×
468
                resp, err := stream.Recv()
×
469
                if err != nil {
×
470
                        errChan <- err
×
471
                        return
×
472
                }
×
473
                chanMsg <- resp
×
474
        }()
475

476
        select {
×
477
        case <-time.After(DefaultTimeout):
×
478
                require.Fail(h, "timeout", "timeout waiting for close channel "+
×
479
                        "update sent")
×
480

×
481
                return nil, nil
×
482

483
        case err := <-errChan:
×
484
                return nil, fmt.Errorf("received err from close channel "+
×
485
                        "stream: %v", err)
×
486

487
        case updateMsg := <-chanMsg:
×
488
                return updateMsg, nil
×
489
        }
490
}
491

492
type WaitingCloseChannel *lnrpc.PendingChannelsResponse_WaitingCloseChannel
493

494
// AssertChannelWaitingClose asserts that the given channel found in the node
495
// is waiting close. Returns the WaitingCloseChannel if found.
496
func (h *HarnessTest) AssertChannelWaitingClose(hn *node.HarnessNode,
497
        chanPoint *lnrpc.ChannelPoint) WaitingCloseChannel {
×
498

×
499
        var target WaitingCloseChannel
×
500

×
501
        op := h.OutPointFromChannelPoint(chanPoint)
×
502

×
503
        err := wait.NoError(func() error {
×
504
                resp := hn.RPC.PendingChannels()
×
505

×
506
                for _, waitingClose := range resp.WaitingCloseChannels {
×
507
                        if waitingClose.Channel.ChannelPoint == op.String() {
×
508
                                target = waitingClose
×
509
                                return nil
×
510
                        }
×
511
                }
512

513
                return fmt.Errorf("%v: channel %s not found in waiting close",
×
514
                        hn.Name(), op)
×
515
        }, DefaultTimeout)
516
        require.NoError(h, err, "assert channel waiting close timed out")
×
517

×
518
        return target
×
519
}
520

521
// AssertTopologyChannelClosed asserts a given channel is closed by checking
522
// the graph topology subscription of the specified node. Returns the closed
523
// channel update if found.
524
func (h *HarnessTest) AssertTopologyChannelClosed(hn *node.HarnessNode,
525
        chanPoint *lnrpc.ChannelPoint) *lnrpc.ClosedChannelUpdate {
×
526

×
527
        closedChan, err := hn.Watcher.WaitForChannelClose(chanPoint)
×
528
        require.NoError(h, err, "failed to wait for channel close")
×
529

×
530
        return closedChan
×
531
}
×
532

533
// WaitForChannelCloseEvent waits for a notification that a channel is closed
534
// by consuming a message from the passed close channel stream. Returns the
535
// closing txid if found.
536
func (h HarnessTest) WaitForChannelCloseEvent(
537
        stream rpc.CloseChanClient) *chainhash.Hash {
×
538

×
539
        // Consume one event.
×
540
        event, err := h.ReceiveCloseChannelUpdate(stream)
×
541
        require.NoError(h, err)
×
542

×
543
        resp, ok := event.Update.(*lnrpc.CloseStatusUpdate_ChanClose)
×
544
        require.Truef(h, ok, "expected channel open update, instead got %v",
×
545
                resp)
×
546

×
547
        txid, err := chainhash.NewHash(resp.ChanClose.ClosingTxid)
×
548
        require.NoErrorf(h, err, "wrong format found in closing txid: %v",
×
549
                resp.ChanClose.ClosingTxid)
×
550

×
551
        return txid
×
552
}
×
553

554
// AssertNumWaitingClose checks that a PendingChannels response from the node
555
// reports the expected number of waiting close channels.
556
func (h *HarnessTest) AssertNumWaitingClose(hn *node.HarnessNode,
557
        num int) []*lnrpc.PendingChannelsResponse_WaitingCloseChannel {
×
558

×
559
        var channels []*lnrpc.PendingChannelsResponse_WaitingCloseChannel
×
560
        oldWaiting := hn.State.CloseChannel.WaitingClose
×
561

×
562
        err := wait.NoError(func() error {
×
563
                resp := hn.RPC.PendingChannels()
×
564
                channels = resp.WaitingCloseChannels
×
565
                total := len(channels)
×
566

×
567
                got := total - oldWaiting
×
568
                if got == num {
×
569
                        return nil
×
570
                }
×
571

572
                return errNumNotMatched(hn.Name(), "waiting close channels",
×
573
                        num, got, total, oldWaiting)
×
574
        }, DefaultTimeout)
575

576
        require.NoErrorf(h, err, "%s: assert waiting close timeout",
×
577
                hn.Name())
×
578

×
579
        return channels
×
580
}
581

582
// AssertNumPendingForceClose checks that a PendingChannels response from the
583
// node reports the expected number of pending force close channels.
584
func (h *HarnessTest) AssertNumPendingForceClose(hn *node.HarnessNode,
585
        num int) []*lnrpc.PendingChannelsResponse_ForceClosedChannel {
×
586

×
587
        var channels []*lnrpc.PendingChannelsResponse_ForceClosedChannel
×
588
        oldForce := hn.State.CloseChannel.PendingForceClose
×
589

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

609
                channels = resp.PendingForceClosingChannels
×
610
                total := len(channels)
×
611

×
612
                got := total - oldForce
×
613
                if got == num {
×
614
                        return nil
×
615
                }
×
616

617
                return errNumNotMatched(hn.Name(), "pending force close "+
×
618
                        "channels", num, got, total, oldForce)
×
619
        }, DefaultTimeout)
620

621
        require.NoErrorf(h, err, "%s: assert pending force close timeout",
×
622
                hn.Name())
×
623

×
624
        return channels
×
625
}
626

627
// AssertStreamChannelCoopClosed reads an update from the close channel client
628
// stream and asserts that the mempool state and node's topology match a coop
629
// close. In specific,
630
// - assert the channel is waiting close and has the expected ChanStatusFlags.
631
// - assert the mempool has the closing txes and anchor sweeps.
632
// - mine a block and assert the closing txid is mined.
633
// - assert the node has zero waiting close channels.
634
// - assert the node has seen the channel close update.
635
func (h *HarnessTest) AssertStreamChannelCoopClosed(hn *node.HarnessNode,
636
        cp *lnrpc.ChannelPoint, anchors bool,
637
        stream rpc.CloseChanClient) *chainhash.Hash {
×
638

×
639
        // Assert the channel is waiting close.
×
640
        resp := h.AssertChannelWaitingClose(hn, cp)
×
641

×
642
        // Assert that the channel is in coop broadcasted.
×
643
        require.Contains(h, resp.Channel.ChanStatusFlags,
×
644
                channeldb.ChanStatusCoopBroadcasted.String(),
×
645
                "channel not coop broadcasted")
×
646

×
647
        // We'll now, generate a single block, wait for the final close status
×
648
        // update, then ensure that the closing transaction was included in the
×
649
        // block. If there are anchors, we also expect an anchor sweep.
×
650
        expectedTxes := 1
×
651
        if anchors {
×
652
                expectedTxes = 2
×
653
        }
×
654
        block := h.MineBlocksAndAssertNumTxes(1, expectedTxes)[0]
×
655

×
656
        // Consume one close event and assert the closing txid can be found in
×
657
        // the block.
×
658
        closingTxid := h.WaitForChannelCloseEvent(stream)
×
659
        h.AssertTxInBlock(block, closingTxid)
×
660

×
661
        // We should see zero waiting close channels now.
×
662
        h.AssertNumWaitingClose(hn, 0)
×
663

×
664
        // Finally, check that the node's topology graph has seen this channel
×
665
        // closed if it's a public channel.
×
666
        if !resp.Channel.Private {
×
667
                h.AssertTopologyChannelClosed(hn, cp)
×
668
        }
×
669

670
        return closingTxid
×
671
}
672

673
// AssertStreamChannelForceClosed reads an update from the close channel client
674
// stream and asserts that the mempool state and node's topology match a local
675
// force close. In specific,
676
//   - assert the channel is waiting close and has the expected ChanStatusFlags.
677
//   - assert the mempool has the closing txes.
678
//   - mine a block and assert the closing txid is mined.
679
//   - assert the channel is pending force close.
680
//   - assert the node has seen the channel close update.
681
//   - assert there's a pending anchor sweep request once the force close tx is
682
//     confirmed.
683
func (h *HarnessTest) AssertStreamChannelForceClosed(hn *node.HarnessNode,
684
        cp *lnrpc.ChannelPoint, anchorSweep bool,
685
        stream rpc.CloseChanClient) *chainhash.Hash {
×
686

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

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

×
695
        // We'll now, generate a single block, wait for the final close status
×
696
        // update, then ensure that the closing transaction was included in the
×
697
        // block.
×
698
        block := h.MineBlocksAndAssertNumTxes(1, 1)[0]
×
699

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

×
705
        // We should see zero waiting close channels and 1 pending force close
×
706
        // channels now.
×
707
        h.AssertNumWaitingClose(hn, 0)
×
708
        h.AssertNumPendingForceClose(hn, 1)
×
709

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

716
        // Assert there's a pending anchor sweep.
717
        if anchorSweep {
×
718
                h.AssertNumPendingSweeps(hn, 1)
×
719
        }
×
720

721
        return closingTxid
×
722
}
723

724
// AssertChannelPolicyUpdate checks that the required policy update has
725
// happened on the given node.
726
func (h *HarnessTest) AssertChannelPolicyUpdate(hn *node.HarnessNode,
727
        advertisingNode *node.HarnessNode, policy *lnrpc.RoutingPolicy,
728
        chanPoint *lnrpc.ChannelPoint, includeUnannounced bool) {
×
729

×
730
        require.NoError(
×
731
                h, hn.Watcher.WaitForChannelPolicyUpdate(
×
732
                        advertisingNode, policy,
×
733
                        chanPoint, includeUnannounced,
×
734
                ), "%s: error while waiting for channel update", hn.Name(),
×
735
        )
×
736
}
×
737

738
// WaitForGraphSync waits until the node is synced to graph or times out.
739
func (h *HarnessTest) WaitForGraphSync(hn *node.HarnessNode) {
×
740
        err := wait.NoError(func() error {
×
741
                resp := hn.RPC.GetInfo()
×
742
                if resp.SyncedToGraph {
×
743
                        return nil
×
744
                }
×
745

746
                return fmt.Errorf("node not synced to graph")
×
747
        }, DefaultTimeout)
748
        require.NoError(h, err, "%s: timeout while sync to graph", hn.Name())
×
749
}
750

751
// AssertNumUTXOsWithConf waits for the given number of UTXOs with the
752
// specified confirmations range to be available or fails if that isn't the
753
// case before the default timeout.
754
//
755
// NOTE: for standby nodes(Alice and Bob), this method takes account of the
756
// previous state of the node's UTXOs. The previous state is snapshotted when
757
// finishing a previous test case via the cleanup function in `Subtest`. In
758
// other words, this assertion only checks the new changes made in the current
759
// test.
760
func (h *HarnessTest) AssertNumUTXOsWithConf(hn *node.HarnessNode,
761
        expectedUtxos int, max, min int32) []*lnrpc.Utxo {
×
762

×
763
        var unconfirmed bool
×
764

×
765
        old := hn.State.UTXO.Confirmed
×
766
        if max == 0 {
×
767
                old = hn.State.UTXO.Unconfirmed
×
768
                unconfirmed = true
×
769
        }
×
770

771
        var utxos []*lnrpc.Utxo
×
772
        err := wait.NoError(func() error {
×
773
                req := &walletrpc.ListUnspentRequest{
×
774
                        Account:         "",
×
775
                        MaxConfs:        max,
×
776
                        MinConfs:        min,
×
777
                        UnconfirmedOnly: unconfirmed,
×
778
                }
×
779
                resp := hn.RPC.ListUnspent(req)
×
780
                total := len(resp.Utxos)
×
781

×
782
                if total-old == expectedUtxos {
×
783
                        utxos = resp.Utxos[old:]
×
784

×
785
                        return nil
×
786
                }
×
787

788
                desc := "has UTXOs:\n"
×
789
                for _, utxo := range resp.Utxos {
×
790
                        desc += fmt.Sprintf("%v\n", utxo)
×
791
                }
×
792

793
                return errNumNotMatched(hn.Name(), "num of UTXOs",
×
794
                        expectedUtxos, total-old, total, old, desc)
×
795
        }, DefaultTimeout)
796
        require.NoError(h, err, "timeout waiting for UTXOs")
×
797

×
798
        return utxos
×
799
}
800

801
// AssertNumUTXOsUnconfirmed asserts the expected num of unconfirmed utxos are
802
// seen.
803
//
804
// NOTE: for standby nodes(Alice and Bob), this method takes account of the
805
// previous state of the node's UTXOs. Check `AssertNumUTXOsWithConf` for
806
// details.
807
func (h *HarnessTest) AssertNumUTXOsUnconfirmed(hn *node.HarnessNode,
808
        num int) []*lnrpc.Utxo {
×
809

×
810
        return h.AssertNumUTXOsWithConf(hn, num, 0, 0)
×
811
}
×
812

813
// AssertNumUTXOsConfirmed asserts the expected num of confirmed utxos are
814
// seen, which means the returned utxos have at least one confirmation.
815
//
816
// NOTE: for standby nodes(Alice and Bob), this method takes account of the
817
// previous state of the node's UTXOs. Check `AssertNumUTXOsWithConf` for
818
// details.
819
func (h *HarnessTest) AssertNumUTXOsConfirmed(hn *node.HarnessNode,
820
        num int) []*lnrpc.Utxo {
×
821

×
822
        return h.AssertNumUTXOsWithConf(hn, num, math.MaxInt32, 1)
×
823
}
×
824

825
// AssertNumUTXOs asserts the expected num of utxos are seen, including
826
// confirmed and unconfirmed outputs.
827
//
828
// NOTE: for standby nodes(Alice and Bob), this method takes account of the
829
// previous state of the node's UTXOs. Check `AssertNumUTXOsWithConf` for
830
// details.
831
func (h *HarnessTest) AssertNumUTXOs(hn *node.HarnessNode,
832
        num int) []*lnrpc.Utxo {
×
833

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

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

×
842
        var unconfirmed bool
×
843

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

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

×
856
        return resp.Utxos
×
857
}
858

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
932
        return randBuf
×
933
}
×
934

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

×
941
        return preimage
×
942
}
×
943

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

×
949
        return resp
×
950
}
×
951

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

×
958
        return addrScript
×
959
}
×
960

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

×
966
        resp := hn.RPC.ChannelBalance()
×
967
        require.True(h, proto.Equal(expected, resp), "balance is incorrect "+
×
968
                "got: %v, want: %v", resp, expected)
×
969
}
×
970

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

×
976
        channel, err := h.findChannel(hn, chanPoint)
×
977
        require.NoErrorf(h, err, "channel not found using %v", chanPoint)
×
978

×
979
        return channel
×
980
}
×
981

982
// GetChannelCommitType retrieves the active channel commitment type for the
983
// given chan point.
984
func (h *HarnessTest) GetChannelCommitType(hn *node.HarnessNode,
985
        chanPoint *lnrpc.ChannelPoint) lnrpc.CommitmentType {
×
986

×
987
        c := h.GetChannelByChanPoint(hn, chanPoint)
×
988

×
989
        return c.CommitmentType
×
990
}
×
991

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

×
997
        var channels []*lnrpc.PendingChannelsResponse_PendingOpenChannel
×
998

×
999
        oldNum := hn.State.OpenChannel.Pending
×
1000

×
1001
        err := wait.NoError(func() error {
×
1002
                resp := hn.RPC.PendingChannels()
×
1003
                channels = resp.PendingOpenChannels
×
1004
                total := len(channels)
×
1005

×
1006
                numChans := total - oldNum
×
1007

×
1008
                if numChans != expected {
×
1009
                        return errNumNotMatched(hn.Name(),
×
1010
                                "pending open channels", expected,
×
1011
                                numChans, total, oldNum)
×
1012
                }
×
1013

1014
                return nil
×
1015
        }, DefaultTimeout)
1016

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

×
1019
        return channels
×
1020
}
1021

1022
// AssertNodesNumPendingOpenChannels asserts that both of the nodes have the
1023
// expected number of pending open channels.
1024
func (h *HarnessTest) AssertNodesNumPendingOpenChannels(a, b *node.HarnessNode,
1025
        expected int) {
×
1026

×
1027
        h.AssertNumPendingOpenChannels(a, expected)
×
1028
        h.AssertNumPendingOpenChannels(b, expected)
×
1029
}
×
1030

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

×
1037
        return h.assertPaymentStatusWithTimeout(
×
1038
                stream, status, wait.PaymentTimeout,
×
1039
        )
×
1040
}
×
1041

1042
// AssertPaymentSucceedWithTimeout asserts that a payment is succeeded within
1043
// the specified timeout.
1044
func (h *HarnessTest) AssertPaymentSucceedWithTimeout(stream rpc.PaymentClient,
1045
        timeout time.Duration) *lnrpc.Payment {
×
1046

×
1047
        return h.assertPaymentStatusWithTimeout(
×
1048
                stream, lnrpc.Payment_SUCCEEDED, timeout,
×
1049
        )
×
1050
}
×
1051

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

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

1071
                // Return if the desired payment state is reached.
1072
                if payment.Status == status {
×
1073
                        target = payment
×
1074

×
1075
                        return nil
×
1076
                }
×
1077

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

1084
        require.NoError(h, err, "timeout while waiting payment")
×
1085

×
1086
        return target
×
1087
}
1088

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

×
1094
        return h.receivePaymentUpdateWithTimeout(stream, DefaultTimeout)
×
1095
}
×
1096

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

×
1102
        chanMsg := make(chan *lnrpc.Payment, 1)
×
1103
        errChan := make(chan error, 1)
×
1104

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

×
1112
                        return
×
1113
                }
×
1114
                chanMsg <- resp
×
1115
        }()
1116

1117
        select {
×
1118
        case <-time.After(timeout):
×
1119
                require.Fail(h, "timeout", "timeout waiting for payment update")
×
1120
                return nil, nil
×
1121

1122
        case err := <-errChan:
×
1123
                return nil, err
×
1124

1125
        case updateMsg := <-chanMsg:
×
1126
                return updateMsg, nil
×
1127
        }
1128
}
1129

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

×
1139
        err := wait.NoError(func() error {
×
1140
                invoice := hn.RPC.LookupInvoiceV2(msg)
×
1141
                if invoice.State == lnrpc.Invoice_SETTLED {
×
1142
                        return nil
×
1143
                }
×
1144

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

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

×
1156
        // Get the total number of channels.
×
1157
        old := hn.State.OpenChannel.Active + hn.State.OpenChannel.Inactive
×
1158

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

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

1172
                return nil
×
1173
        }, DefaultTimeout)
1174

1175
        require.NoError(h, err, "timeout checking node's num of channels")
×
1176
}
1177

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

×
1183
        var result *lnrpc.Channel
×
1184

×
1185
        // Get the funding point.
×
1186
        err := wait.NoError(func() error {
×
1187
                // Find the target channel first.
×
1188
                target, err := h.findChannel(hn, cp)
×
1189

×
1190
                // Exit early if the channel is not found.
×
1191
                if err != nil {
×
1192
                        return fmt.Errorf("check balance failed: %w", err)
×
1193
                }
×
1194

1195
                result = target
×
1196

×
1197
                // Check local balance.
×
1198
                if target.LocalBalance == balance {
×
1199
                        return nil
×
1200
                }
×
1201

1202
                return fmt.Errorf("balance is incorrect, got %v, expected %v",
×
1203
                        target.LocalBalance, balance)
×
1204
        }, DefaultTimeout)
1205

1206
        require.NoError(h, err, "timeout while checking for balance")
×
1207

×
1208
        return result
×
1209
}
1210

1211
// AssertChannelNumUpdates checks the num of updates is expected from the given
1212
// channel.
1213
func (h *HarnessTest) AssertChannelNumUpdates(hn *node.HarnessNode,
1214
        num uint64, cp *lnrpc.ChannelPoint) {
×
1215

×
1216
        old := int(hn.State.OpenChannel.NumUpdates)
×
1217

×
1218
        // Find the target channel first.
×
1219
        target, err := h.findChannel(hn, cp)
×
1220
        require.NoError(h, err, "unable to find channel")
×
1221

×
1222
        err = wait.NoError(func() error {
×
1223
                total := int(target.NumUpdates)
×
1224
                if total-old == int(num) {
×
1225
                        return nil
×
1226
                }
×
1227

1228
                return errNumNotMatched(hn.Name(), "channel updates",
×
1229
                        int(num), total-old, total, old)
×
1230
        }, DefaultTimeout)
1231
        require.NoError(h, err, "timeout while checking for num of updates")
×
1232
}
1233

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

×
1239
        err := wait.NoError(func() error {
×
1240
                // We require the RPC call to be succeeded and won't wait for
×
1241
                // it as it's an unexpected behavior.
×
1242
                req := &lnrpc.ListChannelsRequest{}
×
1243
                nodeChans := hn.RPC.ListChannels(req)
×
1244

×
1245
                total := 0
×
1246
                for _, channel := range nodeChans.Channels {
×
1247
                        total += len(channel.PendingHtlcs)
×
1248
                }
×
1249
                if total-old != num {
×
1250
                        return errNumNotMatched(hn.Name(), "active HTLCs",
×
1251
                                num, total-old, total, old)
×
1252
                }
×
1253

1254
                return nil
×
1255
        }, DefaultTimeout)
1256

1257
        require.NoErrorf(h, err, "%s timeout checking num active htlcs",
×
1258
                hn.Name())
×
1259
}
1260

1261
// AssertActiveHtlcs makes sure the node has the _exact_ HTLCs matching
1262
// payHashes on _all_ their channels.
1263
func (h *HarnessTest) AssertActiveHtlcs(hn *node.HarnessNode,
1264
        payHashes ...[]byte) {
×
1265

×
1266
        err := wait.NoError(func() error {
×
1267
                // We require the RPC call to be succeeded and won't wait for
×
1268
                // it as it's an unexpected behavior.
×
1269
                req := &lnrpc.ListChannelsRequest{}
×
1270
                nodeChans := hn.RPC.ListChannels(req)
×
1271

×
1272
                for _, ch := range nodeChans.Channels {
×
1273
                        // Record all payment hashes active for this channel.
×
1274
                        htlcHashes := make(map[string]struct{})
×
1275

×
1276
                        for _, htlc := range ch.PendingHtlcs {
×
1277
                                h := hex.EncodeToString(htlc.HashLock)
×
1278
                                _, ok := htlcHashes[h]
×
1279
                                if ok {
×
1280
                                        return fmt.Errorf("duplicate HashLock "+
×
1281
                                                "in PendingHtlcs: %v",
×
1282
                                                ch.PendingHtlcs)
×
1283
                                }
×
1284
                                htlcHashes[h] = struct{}{}
×
1285
                        }
1286

1287
                        // Channel should have exactly the payHashes active.
1288
                        if len(payHashes) != len(htlcHashes) {
×
1289
                                return fmt.Errorf("node [%s:%x] had %v "+
×
1290
                                        "htlcs active, expected %v",
×
1291
                                        hn.Name(), hn.PubKey[:],
×
1292
                                        len(htlcHashes), len(payHashes))
×
1293
                        }
×
1294

1295
                        // Make sure all the payHashes are active.
1296
                        for _, payHash := range payHashes {
×
1297
                                h := hex.EncodeToString(payHash)
×
1298
                                if _, ok := htlcHashes[h]; ok {
×
1299
                                        continue
×
1300
                                }
1301

1302
                                return fmt.Errorf("node [%s:%x] didn't have: "+
×
1303
                                        "the payHash %v active", hn.Name(),
×
1304
                                        hn.PubKey[:], h)
×
1305
                        }
1306
                }
1307

1308
                return nil
×
1309
        }, DefaultTimeout)
1310
        require.NoError(h, err, "timeout checking active HTLCs")
×
1311
}
1312

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

×
1318
        return h.assertHTLCActive(hn, cp, payHash, true)
×
1319
}
×
1320

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

×
1326
        return h.assertHTLCActive(hn, cp, payHash, false)
×
1327
}
×
1328

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

×
1334
        var result *lnrpc.HTLC
×
1335
        target := hex.EncodeToString(payHash)
×
1336

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

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

1349
                        // If the payment hash is found, check the incoming
1350
                        // field.
1351
                        if htlc.Incoming == incoming {
×
1352
                                // Found it and return.
×
1353
                                result = htlc
×
1354
                                return nil
×
1355
                        }
×
1356

1357
                        // Otherwise we do have the HTLC but its direction is
1358
                        // not right.
1359
                        have, want := "outgoing", "incoming"
×
1360
                        if htlc.Incoming {
×
1361
                                have, want = "incoming", "outgoing"
×
1362
                        }
×
1363

1364
                        return fmt.Errorf("node[%s] have htlc(%v), want: %s, "+
×
1365
                                "have: %s", hn.Name(), payHash, want, have)
×
1366
                }
1367

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

×
1373
        return result
×
1374
}
1375

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

×
1385
        var result *lnrpc.HTLC
×
1386
        target := hex.EncodeToString(payHash)
×
1387

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

×
1393
                // Check all payment hashes active for this channel.
×
1394
                for _, htlc := range ch.PendingHtlcs {
×
1395
                        h := hex.EncodeToString(htlc.HashLock)
×
1396

×
1397
                        // Break if found the htlc.
×
1398
                        if h == target {
×
1399
                                result = htlc
×
1400
                                break
×
1401
                        }
1402
                }
1403

1404
                // If we've found nothing, we're done.
1405
                if result == nil {
×
1406
                        return nil
×
1407
                }
×
1408

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

×
1415
        return result
×
1416
}
1417

1418
// ReceiveSingleInvoice waits until a message is received on the subscribe
1419
// single invoice stream or the timeout is reached.
1420
func (h *HarnessTest) ReceiveSingleInvoice(
1421
        stream rpc.SingleInvoiceClient) *lnrpc.Invoice {
×
1422

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

×
1432
                        return
×
1433
                }
×
1434
                chanMsg <- resp
×
1435
        }()
1436

1437
        select {
×
1438
        case <-time.After(DefaultTimeout):
×
1439
                require.Fail(h, "timeout", "timeout receiving single invoice")
×
1440

1441
        case err := <-errChan:
×
1442
                require.Failf(h, "err from stream",
×
1443
                        "received err from stream: %v", err)
×
1444

1445
        case updateMsg := <-chanMsg:
×
1446
                return updateMsg
×
1447
        }
1448

1449
        return nil
×
1450
}
1451

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

×
1458
        var invoice *lnrpc.Invoice
×
1459

×
1460
        err := wait.NoError(func() error {
×
1461
                invoice = h.ReceiveSingleInvoice(stream)
×
1462
                if invoice.State == state {
×
1463
                        return nil
×
1464
                }
×
1465

1466
                return fmt.Errorf("mismatched invoice state, want %v, got %v",
×
1467
                        state, invoice.State)
×
1468
        }, DefaultTimeout)
1469
        require.NoError(h, err, "timeout waiting for invoice state: %v", state)
×
1470

×
1471
        return invoice
×
1472
}
1473

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

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

1487
// AssertTxSpendFrom asserts that a given tx is spent from a previous tx.
1488
func (h *HarnessTest) AssertTxSpendFrom(tx *wire.MsgTx,
1489
        prevTxid chainhash.Hash) {
×
1490

×
1491
        if tx.TxIn[0].PreviousOutPoint.Hash != prevTxid {
×
1492
                require.Failf(h, "", "tx %v did not spend from %v",
×
1493
                        tx.TxHash(), prevTxid)
×
1494
        }
×
1495
}
1496

1497
type PendingForceClose *lnrpc.PendingChannelsResponse_ForceClosedChannel
1498

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

×
1504
        var target PendingForceClose
×
1505

×
1506
        op := h.OutPointFromChannelPoint(chanPoint)
×
1507

×
1508
        err := wait.NoError(func() error {
×
1509
                resp := hn.RPC.PendingChannels()
×
1510

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

×
1516
                                return nil
×
1517
                        }
×
1518
                }
1519

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

×
1525
        return target
×
1526
}
1527

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

×
1533
        // Get the channel output point.
×
1534
        cp := h.OutPointFromChannelPoint(chanPoint)
×
1535

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

1543
                for _, ch := range resp.PendingForceClosingChannels {
×
1544
                        if ch.Channel.ChannelPoint == cp.String() {
×
1545
                                target = ch
×
1546

×
1547
                                break
×
1548
                        }
1549
                }
1550

1551
                if target == nil {
×
1552
                        return fmt.Errorf("cannot find pending force closing "+
×
1553
                                "channel using %v", cp)
×
1554
                }
×
1555

1556
                if target.LimboBalance == 0 {
×
1557
                        return fmt.Errorf("zero limbo balance")
×
1558
                }
×
1559

1560
                if len(target.PendingHtlcs) != num {
×
1561
                        return fmt.Errorf("got %d pending htlcs, want %d",
×
1562
                                len(target.PendingHtlcs), num)
×
1563
                }
×
1564

1565
                for i, htlc := range target.PendingHtlcs {
×
1566
                        if htlc.Stage == stage {
×
1567
                                continue
×
1568
                        }
1569

1570
                        return fmt.Errorf("HTLC %d got stage: %v, "+
×
1571
                                "want stage: %v", i, htlc.Stage, stage)
×
1572
                }
1573

1574
                return nil
×
1575
        }
1576

1577
        require.NoErrorf(h, wait.NoError(checkStage, DefaultTimeout),
×
1578
                "timeout waiting for htlc stage")
×
1579
}
1580

1581
// findPayment queries the payment from the node's ListPayments which matches
1582
// the specified preimage hash.
1583
func (h *HarnessTest) findPayment(hn *node.HarnessNode,
1584
        paymentHash string) *lnrpc.Payment {
×
1585

×
1586
        req := &lnrpc.ListPaymentsRequest{IncludeIncomplete: true}
×
1587
        paymentsResp := hn.RPC.ListPayments(req)
×
1588

×
1589
        for _, p := range paymentsResp.Payments {
×
1590
                if p.PaymentHash != paymentHash {
×
1591
                        continue
×
1592
                }
1593

1594
                return p
×
1595
        }
1596

1597
        require.Failf(h, "payment not found", "payment %v cannot be found",
×
1598
                paymentHash)
×
1599

×
1600
        return nil
×
1601
}
1602

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

×
1611
        var target *lnrpc.Payment
×
1612
        payHash := preimage.Hash()
×
1613

×
1614
        err := wait.NoError(func() error {
×
1615
                p := h.findPayment(hn, payHash.String())
×
1616
                if status == p.Status {
×
1617
                        target = p
×
1618
                        return nil
×
1619
                }
×
1620

1621
                return fmt.Errorf("payment: %v status not match, want %s "+
×
1622
                        "got %s", payHash, status, p.Status)
×
1623
        }, DefaultTimeout)
1624
        require.NoError(h, err, "timeout checking payment status")
×
1625

×
1626
        switch status {
×
1627
        // If this expected status is SUCCEEDED, we expect the final
1628
        // preimage.
1629
        case lnrpc.Payment_SUCCEEDED:
×
1630
                require.Equal(h, preimage.String(), target.PaymentPreimage,
×
1631
                        "preimage not match")
×
1632

1633
        // Otherwise we expect an all-zero preimage.
1634
        default:
×
1635
                require.Equal(h, (lntypes.Preimage{}).String(),
×
1636
                        target.PaymentPreimage, "expected zero preimage")
×
1637
        }
1638

1639
        return target
×
1640
}
1641

1642
// AssertPaymentFailureReason asserts that the given node lists a payment with
1643
// the given preimage which has the expected failure reason.
1644
func (h *HarnessTest) AssertPaymentFailureReason(hn *node.HarnessNode,
NEW
1645
        preimage lntypes.Preimage, reason lnrpc.PaymentFailureReason) {
×
NEW
1646

×
NEW
1647
        payHash := preimage.Hash()
×
NEW
1648
        err := wait.NoError(func() error {
×
NEW
1649
                p := h.findPayment(hn, payHash.String())
×
NEW
1650
                if reason == p.FailureReason {
×
NEW
1651
                        return nil
×
NEW
1652
                }
×
1653

NEW
1654
                return fmt.Errorf("payment: %v failure reason not match, "+
×
NEW
1655
                        "want %s got %s", payHash, reason, p.Status)
×
1656
        }, DefaultTimeout)
NEW
1657
        require.NoError(h, err, "timeout checking payment failure reason")
×
1658
}
1659

1660
// AssertActiveNodesSynced asserts all active nodes have synced to the chain.
1661
func (h *HarnessTest) AssertActiveNodesSynced() {
×
1662
        for _, node := range h.manager.activeNodes {
×
1663
                h.WaitForBlockchainSync(node)
×
1664
        }
×
1665
}
1666

1667
// AssertActiveNodesSyncedTo asserts all active nodes have synced to the
1668
// provided bestBlock.
1669
func (h *HarnessTest) AssertActiveNodesSyncedTo(bestBlock *wire.MsgBlock) {
×
1670
        for _, node := range h.manager.activeNodes {
×
1671
                h.WaitForBlockchainSyncTo(node, bestBlock)
×
1672
        }
×
1673
}
1674

1675
// AssertPeerNotConnected asserts that the given node b is not connected to a.
1676
func (h *HarnessTest) AssertPeerNotConnected(a, b *node.HarnessNode) {
×
1677
        err := wait.NoError(func() error {
×
1678
                // We require the RPC call to be succeeded and won't wait for
×
1679
                // it as it's an unexpected behavior.
×
1680
                resp := a.RPC.ListPeers()
×
1681

×
1682
                // If node B is seen in the ListPeers response from node A,
×
1683
                // then we return false as the connection has been fully
×
1684
                // established.
×
1685
                for _, peer := range resp.Peers {
×
1686
                        if peer.PubKey == b.PubKeyStr {
×
1687
                                return fmt.Errorf("peers %s and %s still "+
×
1688
                                        "connected", a.Name(), b.Name())
×
1689
                        }
×
1690
                }
1691

1692
                return nil
×
1693
        }, DefaultTimeout)
1694
        require.NoError(h, err, "timeout checking peers not connected")
×
1695
}
1696

1697
// AssertNotConnected asserts that two peers are not connected.
1698
func (h *HarnessTest) AssertNotConnected(a, b *node.HarnessNode) {
×
1699
        h.AssertPeerNotConnected(a, b)
×
1700
        h.AssertPeerNotConnected(b, a)
×
1701
}
×
1702

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

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

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

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

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

1738
                return nil
×
1739
        }
1740

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

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

×
1754
        // Use -1 to specify the last HTLC.
×
1755
        h.assertHTLCError(hn, code, -1)
×
1756
}
×
1757

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

×
1763
        // Use 0 to specify the first HTLC.
×
1764
        h.assertHTLCError(hn, code, 0)
×
1765
}
×
1766

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

×
1772
        req := &lnrpc.ListPaymentsRequest{
×
1773
                IncludeIncomplete: true,
×
1774
        }
×
1775

×
1776
        err := wait.NoError(func() error {
×
1777
                paymentsResp := hn.RPC.ListPayments(req)
×
1778

×
1779
                payments := paymentsResp.Payments
×
1780
                if len(payments) == 0 {
×
1781
                        return fmt.Errorf("no payments found")
×
1782
                }
×
1783

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

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

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

1801
                htlc := htlcs[index]
×
1802

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

1812
                // Exit if the expected code is found.
1813
                if htlc.Failure.Code == code {
×
1814
                        return nil
×
1815
                }
×
1816

1817
                return fmt.Errorf("unexpected failure code")
×
1818
        }, DefaultTimeout)
1819

1820
        require.NoError(h, err, "timeout checking HTLC error")
×
1821
}
1822

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

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

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

1842
                return nil
×
1843
        }, DefaultTimeout)
1844
        require.NoError(h, err, "timeout while checking zombie channel")
×
1845
}
1846

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

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

1861
                switch {
×
1862
                case strings.Contains(err.Error(), "marked as zombie"):
×
1863
                        return nil
×
1864

1865
                case strings.Contains(err.Error(), "edge not found"):
×
1866
                        return nil
×
1867

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

1878
// AssertTxAtHeight gets all of the transactions that a node's wallet has a
1879
// record of at the target height, and finds and returns the tx with the target
1880
// txid, failing if it is not found.
1881
func (h *HarnessTest) AssertTxAtHeight(hn *node.HarnessNode, height int32,
1882
        txid *chainhash.Hash) *lnrpc.Transaction {
×
1883

×
1884
        req := &lnrpc.GetTransactionsRequest{
×
1885
                StartHeight: height,
×
1886
                EndHeight:   height,
×
1887
        }
×
1888
        txns := hn.RPC.GetTransactions(req)
×
1889

×
1890
        for _, tx := range txns.Transactions {
×
1891
                if tx.TxHash == txid.String() {
×
1892
                        return tx
×
1893
                }
×
1894
        }
1895

1896
        require.Failf(h, "fail to find tx", "tx:%v not found at height:%v",
×
1897
                txid, height)
×
1898

×
1899
        return nil
×
1900
}
1901

1902
// getChannelPolicies queries the channel graph and retrieves the current edge
1903
// policies for the provided channel point.
1904
func (h *HarnessTest) getChannelPolicies(hn *node.HarnessNode,
1905
        advertisingNode string,
1906
        cp *lnrpc.ChannelPoint) (*lnrpc.RoutingPolicy, error) {
×
1907

×
1908
        req := &lnrpc.ChannelGraphRequest{IncludeUnannounced: true}
×
1909
        chanGraph := hn.RPC.DescribeGraph(req)
×
1910

×
1911
        cpStr := channelPointStr(cp)
×
1912
        for _, e := range chanGraph.Edges {
×
1913
                if e.ChanPoint != cpStr {
×
1914
                        continue
×
1915
                }
1916

1917
                if e.Node1Pub == advertisingNode {
×
1918
                        return e.Node1Policy, nil
×
1919
                }
×
1920

1921
                return e.Node2Policy, nil
×
1922
        }
1923

1924
        // If we've iterated over all the known edges and we weren't
1925
        // able to find this specific one, then we'll fail.
1926
        return nil, fmt.Errorf("did not find edge with advertisingNode: %s"+
×
1927
                ", channel point: %s", advertisingNode, cpStr)
×
1928
}
1929

1930
// AssertChannelPolicy asserts that the passed node's known channel policy for
1931
// the passed chanPoint is consistent with the expected policy values.
1932
func (h *HarnessTest) AssertChannelPolicy(hn *node.HarnessNode,
1933
        advertisingNode string, expectedPolicy *lnrpc.RoutingPolicy,
1934
        chanPoint *lnrpc.ChannelPoint) {
×
1935

×
1936
        policy, err := h.getChannelPolicies(hn, advertisingNode, chanPoint)
×
1937
        require.NoErrorf(h, err, "%s: failed to find policy", hn.Name())
×
1938

×
1939
        err = node.CheckChannelPolicy(policy, expectedPolicy)
×
1940
        require.NoErrorf(h, err, "%s: check policy failed", hn.Name())
×
1941
}
×
1942

1943
// AssertNumPolicyUpdates asserts that a given number of channel policy updates
1944
// has been seen in the specified node.
1945
func (h *HarnessTest) AssertNumPolicyUpdates(hn *node.HarnessNode,
1946
        chanPoint *lnrpc.ChannelPoint,
1947
        advertisingNode *node.HarnessNode, num int) {
×
1948

×
1949
        op := h.OutPointFromChannelPoint(chanPoint)
×
1950

×
1951
        var policies []*node.PolicyUpdateInfo
×
1952

×
1953
        err := wait.NoError(func() error {
×
1954
                policyMap := hn.Watcher.GetPolicyUpdates(op)
×
1955
                nodePolicy, ok := policyMap[advertisingNode.PubKeyStr]
×
1956
                if ok {
×
1957
                        policies = nodePolicy
×
1958
                }
×
1959

1960
                if len(policies) == num {
×
1961
                        return nil
×
1962
                }
×
1963

1964
                p, err := json.MarshalIndent(policies, "", "\t")
×
1965
                require.NoError(h, err, "encode policy err")
×
1966

×
1967
                return fmt.Errorf("expected to find %d policy updates, "+
×
1968
                        "instead got: %d, chanPoint: %v, "+
×
1969
                        "advertisingNode: %s:%s, policy: %s", num,
×
1970
                        len(policies), op, advertisingNode.Name(),
×
1971
                        advertisingNode.PubKeyStr, p)
×
1972
        }, DefaultTimeout)
1973

1974
        require.NoError(h, err, "%s: timeout waiting for num of policy updates",
×
1975
                hn.Name())
×
1976
}
1977

1978
// AssertNumPayments asserts that the number of payments made within the test
1979
// scope is as expected, including the incomplete ones.
1980
func (h *HarnessTest) AssertNumPayments(hn *node.HarnessNode,
1981
        num int) []*lnrpc.Payment {
×
1982

×
1983
        // Get the number of payments we already have from the previous test.
×
1984
        have := hn.State.Payment.Total
×
1985

×
1986
        req := &lnrpc.ListPaymentsRequest{
×
1987
                IncludeIncomplete: true,
×
1988
                IndexOffset:       hn.State.Payment.LastIndexOffset,
×
1989
        }
×
1990

×
1991
        var payments []*lnrpc.Payment
×
1992
        err := wait.NoError(func() error {
×
1993
                resp := hn.RPC.ListPayments(req)
×
1994

×
1995
                payments = resp.Payments
×
1996
                if len(payments) == num {
×
1997
                        return nil
×
1998
                }
×
1999

2000
                return errNumNotMatched(hn.Name(), "num of payments",
×
2001
                        num, len(payments), have+len(payments), have)
×
2002
        }, DefaultTimeout)
2003
        require.NoError(h, err, "%s: timeout checking num of payments",
×
2004
                hn.Name())
×
2005

×
2006
        return payments
×
2007
}
2008

2009
// AssertNumNodeAnns asserts that a given number of node announcements has been
2010
// seen in the specified node.
2011
func (h *HarnessTest) AssertNumNodeAnns(hn *node.HarnessNode,
2012
        pubkey string, num int) []*lnrpc.NodeUpdate {
×
2013

×
2014
        // We will get the current number of channel updates first and add it
×
2015
        // to our expected number of newly created channel updates.
×
2016
        anns, err := hn.Watcher.WaitForNumNodeUpdates(pubkey, num)
×
2017
        require.NoError(h, err, "%s: failed to assert num of node anns",
×
2018
                hn.Name())
×
2019

×
2020
        return anns
×
2021
}
×
2022

2023
// AssertNumChannelUpdates asserts that a given number of channel updates has
2024
// been seen in the specified node's network topology.
2025
func (h *HarnessTest) AssertNumChannelUpdates(hn *node.HarnessNode,
2026
        chanPoint *lnrpc.ChannelPoint, num int) {
×
2027

×
2028
        op := h.OutPointFromChannelPoint(chanPoint)
×
2029
        err := hn.Watcher.WaitForNumChannelUpdates(op, num)
×
2030
        require.NoError(h, err, "%s: failed to assert num of channel updates",
×
2031
                hn.Name())
×
2032
}
×
2033

2034
// CreateBurnAddr creates a random burn address of the given type.
2035
func (h *HarnessTest) CreateBurnAddr(addrType lnrpc.AddressType) ([]byte,
2036
        btcutil.Address) {
×
2037

×
2038
        randomPrivKey, err := btcec.NewPrivateKey()
×
2039
        require.NoError(h, err)
×
2040

×
2041
        randomKeyBytes := randomPrivKey.PubKey().SerializeCompressed()
×
2042
        harnessNetParams := miner.HarnessNetParams
×
2043

×
2044
        var addr btcutil.Address
×
2045
        switch addrType {
×
2046
        case lnrpc.AddressType_WITNESS_PUBKEY_HASH:
×
2047
                addr, err = btcutil.NewAddressWitnessPubKeyHash(
×
2048
                        btcutil.Hash160(randomKeyBytes), harnessNetParams,
×
2049
                )
×
2050

2051
        case lnrpc.AddressType_TAPROOT_PUBKEY:
×
2052
                taprootKey := txscript.ComputeTaprootKeyNoScript(
×
2053
                        randomPrivKey.PubKey(),
×
2054
                )
×
2055
                addr, err = btcutil.NewAddressPubKey(
×
2056
                        schnorr.SerializePubKey(taprootKey), harnessNetParams,
×
2057
                )
×
2058

2059
        case lnrpc.AddressType_NESTED_PUBKEY_HASH:
×
2060
                var witnessAddr btcutil.Address
×
2061
                witnessAddr, err = btcutil.NewAddressWitnessPubKeyHash(
×
2062
                        btcutil.Hash160(randomKeyBytes), harnessNetParams,
×
2063
                )
×
2064
                require.NoError(h, err)
×
2065

×
2066
                addr, err = btcutil.NewAddressScriptHash(
×
2067
                        h.PayToAddrScript(witnessAddr), harnessNetParams,
×
2068
                )
×
2069

2070
        default:
×
2071
                h.Fatalf("Unsupported burn address type: %v", addrType)
×
2072
        }
2073
        require.NoError(h, err)
×
2074

×
2075
        return h.PayToAddrScript(addr), addr
×
2076
}
2077

2078
// ReceiveTrackPayment waits until a message is received on the track payment
2079
// stream or the timeout is reached.
2080
func (h *HarnessTest) ReceiveTrackPayment(
2081
        stream rpc.TrackPaymentClient) *lnrpc.Payment {
×
2082

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

2096
        select {
×
2097
        case <-time.After(DefaultTimeout):
×
2098
                require.Fail(h, "timeout", "timeout trakcing payment")
×
2099

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

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

2108
        return nil
×
2109
}
2110

2111
// ReceiveHtlcEvent waits until a message is received on the subscribe
2112
// htlc event stream or the timeout is reached.
2113
func (h *HarnessTest) ReceiveHtlcEvent(
2114
        stream rpc.HtlcEventsClient) *routerrpc.HtlcEvent {
×
2115

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

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

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

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

2142
        return nil
×
2143
}
2144

2145
// AssertHtlcEventType consumes one event from a client and asserts the event
2146
// type is matched.
2147
func (h *HarnessTest) AssertHtlcEventType(client rpc.HtlcEventsClient,
2148
        userType routerrpc.HtlcEvent_EventType) *routerrpc.HtlcEvent {
×
2149

×
2150
        event := h.ReceiveHtlcEvent(client)
×
2151
        require.Equalf(h, userType, event.EventType, "wrong event type, "+
×
2152
                "want %v got %v", userType, event.EventType)
×
2153

×
2154
        return event
×
2155
}
×
2156

2157
// HtlcEvent maps the series of event types used in `*routerrpc.HtlcEvent_*`.
2158
type HtlcEvent int
2159

2160
const (
2161
        HtlcEventForward HtlcEvent = iota
2162
        HtlcEventForwardFail
2163
        HtlcEventSettle
2164
        HtlcEventLinkFail
2165
        HtlcEventFinal
2166
)
2167

2168
// AssertHtlcEventType consumes one event from a client and asserts both the
2169
// user event type the event.Event type is matched.
2170
func (h *HarnessTest) AssertHtlcEventTypes(client rpc.HtlcEventsClient,
2171
        userType routerrpc.HtlcEvent_EventType,
2172
        eventType HtlcEvent) *routerrpc.HtlcEvent {
×
2173

×
2174
        event := h.ReceiveHtlcEvent(client)
×
2175
        require.Equalf(h, userType, event.EventType, "wrong event type, "+
×
2176
                "want %v got %v", userType, event.EventType)
×
2177

×
2178
        var ok bool
×
2179

×
2180
        switch eventType {
×
2181
        case HtlcEventForward:
×
2182
                _, ok = event.Event.(*routerrpc.HtlcEvent_ForwardEvent)
×
2183

2184
        case HtlcEventForwardFail:
×
2185
                _, ok = event.Event.(*routerrpc.HtlcEvent_ForwardFailEvent)
×
2186

2187
        case HtlcEventSettle:
×
2188
                _, ok = event.Event.(*routerrpc.HtlcEvent_SettleEvent)
×
2189

2190
        case HtlcEventLinkFail:
×
2191
                _, ok = event.Event.(*routerrpc.HtlcEvent_LinkFailEvent)
×
2192

2193
        case HtlcEventFinal:
×
2194
                _, ok = event.Event.(*routerrpc.HtlcEvent_FinalHtlcEvent)
×
2195
        }
2196

2197
        require.Truef(h, ok, "wrong event type: %T, want %T", event.Event,
×
2198
                eventType)
×
2199

×
2200
        return event
×
2201
}
2202

2203
// AssertFeeReport checks that the fee report from the given node has the
2204
// desired day, week, and month sum values.
2205
func (h *HarnessTest) AssertFeeReport(hn *node.HarnessNode,
2206
        day, week, month int) {
×
2207

×
2208
        err := wait.NoError(func() error {
×
2209
                feeReport, err := hn.RPC.LN.FeeReport(
×
2210
                        h.runCtx, &lnrpc.FeeReportRequest{},
×
2211
                )
×
2212
                require.NoError(h, err, "unable to query for fee report")
×
2213

×
2214
                if uint64(day) != feeReport.DayFeeSum {
×
2215
                        return fmt.Errorf("day fee mismatch, want %d, got %d",
×
2216
                                day, feeReport.DayFeeSum)
×
2217
                }
×
2218

2219
                if uint64(week) != feeReport.WeekFeeSum {
×
2220
                        return fmt.Errorf("week fee mismatch, want %d, got %d",
×
2221
                                week, feeReport.WeekFeeSum)
×
2222
                }
×
2223
                if uint64(month) != feeReport.MonthFeeSum {
×
2224
                        return fmt.Errorf("month fee mismatch, want %d, got %d",
×
2225
                                month, feeReport.MonthFeeSum)
×
2226
                }
×
2227

2228
                return nil
×
2229
        }, wait.DefaultTimeout)
2230
        require.NoErrorf(h, err, "%s: time out checking fee report", hn.Name())
×
2231
}
2232

2233
// AssertHtlcEvents consumes events from a client and ensures that they are of
2234
// the expected type and contain the expected number of forwards, forward
2235
// failures and settles.
2236
//
2237
// TODO(yy): needs refactor to reduce its complexity.
2238
func (h *HarnessTest) AssertHtlcEvents(client rpc.HtlcEventsClient,
2239
        fwdCount, fwdFailCount, settleCount, linkFailCount int,
2240
        userType routerrpc.HtlcEvent_EventType) []*routerrpc.HtlcEvent {
×
2241

×
2242
        var forwards, forwardFails, settles, linkFails int
×
2243

×
2244
        numEvents := fwdCount + fwdFailCount + settleCount + linkFailCount
×
2245
        events := make([]*routerrpc.HtlcEvent, 0)
×
2246

×
2247
        // It's either the userType or the unknown type.
×
2248
        //
×
2249
        // TODO(yy): maybe the FinalHtlcEvent shouldn't be in UNKNOWN type?
×
2250
        eventTypes := []routerrpc.HtlcEvent_EventType{
×
2251
                userType, routerrpc.HtlcEvent_UNKNOWN,
×
2252
        }
×
2253

×
2254
        for i := 0; i < numEvents; i++ {
×
2255
                event := h.ReceiveHtlcEvent(client)
×
2256

×
2257
                require.Containsf(h, eventTypes, event.EventType,
×
2258
                        "wrong event type, got %v", userType, event.EventType)
×
2259

×
2260
                events = append(events, event)
×
2261

×
2262
                switch e := event.Event.(type) {
×
2263
                case *routerrpc.HtlcEvent_ForwardEvent:
×
2264
                        forwards++
×
2265

2266
                case *routerrpc.HtlcEvent_ForwardFailEvent:
×
2267
                        forwardFails++
×
2268

2269
                case *routerrpc.HtlcEvent_SettleEvent:
×
2270
                        settles++
×
2271

2272
                case *routerrpc.HtlcEvent_FinalHtlcEvent:
×
2273
                        if e.FinalHtlcEvent.Settled {
×
2274
                                settles++
×
2275
                        }
×
2276

2277
                case *routerrpc.HtlcEvent_LinkFailEvent:
×
2278
                        linkFails++
×
2279

2280
                default:
×
2281
                        require.Fail(h, "assert event fail",
×
2282
                                "unexpected event: %T", event.Event)
×
2283
                }
2284
        }
2285

2286
        require.Equal(h, fwdCount, forwards, "num of forwards mismatch")
×
2287
        require.Equal(h, fwdFailCount, forwardFails,
×
2288
                "num of forward fails mismatch")
×
2289
        require.Equal(h, settleCount, settles, "num of settles mismatch")
×
2290
        require.Equal(h, linkFailCount, linkFails, "num of link fails mismatch")
×
2291

×
2292
        return events
×
2293
}
2294

2295
// AssertTransactionInWallet asserts a given txid can be found in the node's
2296
// wallet.
2297
func (h *HarnessTest) AssertTransactionInWallet(hn *node.HarnessNode,
2298
        txid chainhash.Hash) {
×
2299

×
2300
        req := &lnrpc.GetTransactionsRequest{}
×
2301
        err := wait.NoError(func() error {
×
2302
                txResp := hn.RPC.GetTransactions(req)
×
2303
                for _, txn := range txResp.Transactions {
×
2304
                        if txn.TxHash == txid.String() {
×
2305
                                return nil
×
2306
                        }
×
2307
                }
2308

2309
                return fmt.Errorf("%s: expected txid=%v not found in wallet",
×
2310
                        hn.Name(), txid)
×
2311
        }, DefaultTimeout)
2312

2313
        require.NoError(h, err, "failed to find tx")
×
2314
}
2315

2316
// AssertTransactionNotInWallet asserts a given txid can NOT be found in the
2317
// node's wallet.
2318
func (h *HarnessTest) AssertTransactionNotInWallet(hn *node.HarnessNode,
2319
        txid chainhash.Hash) {
×
2320

×
2321
        req := &lnrpc.GetTransactionsRequest{}
×
2322
        err := wait.NoError(func() error {
×
2323
                txResp := hn.RPC.GetTransactions(req)
×
2324
                for _, txn := range txResp.Transactions {
×
2325
                        if txn.TxHash == txid.String() {
×
2326
                                return fmt.Errorf("expected txid=%v to be "+
×
2327
                                        "not found", txid)
×
2328
                        }
×
2329
                }
2330

2331
                return nil
×
2332
        }, DefaultTimeout)
2333

2334
        require.NoErrorf(h, err, "%s: failed to assert tx not found", hn.Name())
×
2335
}
2336

2337
// WaitForNodeBlockHeight queries the node for its current block height until
2338
// it reaches the passed height.
2339
func (h *HarnessTest) WaitForNodeBlockHeight(hn *node.HarnessNode,
2340
        height int32) {
×
2341

×
2342
        err := wait.NoError(func() error {
×
2343
                info := hn.RPC.GetInfo()
×
2344
                if int32(info.BlockHeight) != height {
×
2345
                        return fmt.Errorf("expected block height to "+
×
2346
                                "be %v, was %v", height, info.BlockHeight)
×
2347
                }
×
2348

2349
                return nil
×
2350
        }, DefaultTimeout)
2351

2352
        require.NoErrorf(h, err, "%s: timeout while waiting for height",
×
2353
                hn.Name())
×
2354
}
2355

2356
// AssertChannelCommitHeight asserts the given channel for the node has the
2357
// expected commit height(`NumUpdates`).
2358
func (h *HarnessTest) AssertChannelCommitHeight(hn *node.HarnessNode,
2359
        cp *lnrpc.ChannelPoint, height int) {
×
2360

×
2361
        err := wait.NoError(func() error {
×
2362
                c, err := h.findChannel(hn, cp)
×
2363
                if err != nil {
×
2364
                        return err
×
2365
                }
×
2366

2367
                if int(c.NumUpdates) == height {
×
2368
                        return nil
×
2369
                }
×
2370

2371
                return fmt.Errorf("expected commit height to be %v, was %v",
×
2372
                        height, c.NumUpdates)
×
2373
        }, DefaultTimeout)
2374

2375
        require.NoError(h, err, "timeout while waiting for commit height")
×
2376
}
2377

2378
// AssertNumInvoices asserts that the number of invoices made within the test
2379
// scope is as expected.
2380
func (h *HarnessTest) AssertNumInvoices(hn *node.HarnessNode,
2381
        num int) []*lnrpc.Invoice {
×
2382

×
2383
        have := hn.State.Invoice.Total
×
2384
        req := &lnrpc.ListInvoiceRequest{
×
2385
                NumMaxInvoices: math.MaxUint64,
×
2386
                IndexOffset:    hn.State.Invoice.LastIndexOffset,
×
2387
        }
×
2388

×
2389
        var invoices []*lnrpc.Invoice
×
2390
        err := wait.NoError(func() error {
×
2391
                resp := hn.RPC.ListInvoices(req)
×
2392

×
2393
                invoices = resp.Invoices
×
2394
                if len(invoices) == num {
×
2395
                        return nil
×
2396
                }
×
2397

2398
                return errNumNotMatched(hn.Name(), "num of invoices",
×
2399
                        num, len(invoices), have+len(invoices), have)
×
2400
        }, DefaultTimeout)
2401
        require.NoError(h, err, "timeout checking num of invoices")
×
2402

×
2403
        return invoices
×
2404
}
2405

2406
// ReceiveSendToRouteUpdate waits until a message is received on the
2407
// SendToRoute client stream or the timeout is reached.
2408
func (h *HarnessTest) ReceiveSendToRouteUpdate(
2409
        stream rpc.SendToRouteClient) (*lnrpc.SendResponse, error) {
×
2410

×
2411
        chanMsg := make(chan *lnrpc.SendResponse, 1)
×
2412
        errChan := make(chan error, 1)
×
2413
        go func() {
×
2414
                // Consume one message. This will block until the message is
×
2415
                // received.
×
2416
                resp, err := stream.Recv()
×
2417
                if err != nil {
×
2418
                        errChan <- err
×
2419

×
2420
                        return
×
2421
                }
×
2422
                chanMsg <- resp
×
2423
        }()
2424

2425
        select {
×
2426
        case <-time.After(DefaultTimeout):
×
2427
                require.Fail(h, "timeout", "timeout waiting for send resp")
×
2428
                return nil, nil
×
2429

2430
        case err := <-errChan:
×
2431
                return nil, err
×
2432

2433
        case updateMsg := <-chanMsg:
×
2434
                return updateMsg, nil
×
2435
        }
2436
}
2437

2438
// AssertInvoiceEqual asserts that two lnrpc.Invoices are equivalent. A custom
2439
// comparison function is defined for these tests, since proto message returned
2440
// from unary and streaming RPCs (as of protobuf 1.23.0 and grpc 1.29.1) aren't
2441
// consistent with the private fields set on the messages. As a result, we
2442
// avoid using require.Equal and test only the actual data members.
2443
func (h *HarnessTest) AssertInvoiceEqual(a, b *lnrpc.Invoice) {
×
2444
        // Ensure the HTLCs are sorted properly before attempting to compare.
×
2445
        sort.Slice(a.Htlcs, func(i, j int) bool {
×
2446
                return a.Htlcs[i].ChanId < a.Htlcs[j].ChanId
×
2447
        })
×
2448
        sort.Slice(b.Htlcs, func(i, j int) bool {
×
2449
                return b.Htlcs[i].ChanId < b.Htlcs[j].ChanId
×
2450
        })
×
2451

2452
        require.Equal(h, a.Memo, b.Memo)
×
2453
        require.Equal(h, a.RPreimage, b.RPreimage)
×
2454
        require.Equal(h, a.RHash, b.RHash)
×
2455
        require.Equal(h, a.Value, b.Value)
×
2456
        require.Equal(h, a.ValueMsat, b.ValueMsat)
×
2457
        require.Equal(h, a.CreationDate, b.CreationDate)
×
2458
        require.Equal(h, a.SettleDate, b.SettleDate)
×
2459
        require.Equal(h, a.PaymentRequest, b.PaymentRequest)
×
2460
        require.Equal(h, a.DescriptionHash, b.DescriptionHash)
×
2461
        require.Equal(h, a.Expiry, b.Expiry)
×
2462
        require.Equal(h, a.FallbackAddr, b.FallbackAddr)
×
2463
        require.Equal(h, a.CltvExpiry, b.CltvExpiry)
×
2464
        require.Equal(h, a.RouteHints, b.RouteHints)
×
2465
        require.Equal(h, a.Private, b.Private)
×
2466
        require.Equal(h, a.AddIndex, b.AddIndex)
×
2467
        require.Equal(h, a.SettleIndex, b.SettleIndex)
×
2468
        require.Equal(h, a.AmtPaidSat, b.AmtPaidSat)
×
2469
        require.Equal(h, a.AmtPaidMsat, b.AmtPaidMsat)
×
2470
        require.Equal(h, a.State, b.State)
×
2471
        require.Equal(h, a.Features, b.Features)
×
2472
        require.Equal(h, a.IsKeysend, b.IsKeysend)
×
2473
        require.Equal(h, a.PaymentAddr, b.PaymentAddr)
×
2474
        require.Equal(h, a.IsAmp, b.IsAmp)
×
2475

×
2476
        require.Equal(h, len(a.Htlcs), len(b.Htlcs))
×
2477
        for i := range a.Htlcs {
×
2478
                htlcA, htlcB := a.Htlcs[i], b.Htlcs[i]
×
2479
                require.Equal(h, htlcA.ChanId, htlcB.ChanId)
×
2480
                require.Equal(h, htlcA.HtlcIndex, htlcB.HtlcIndex)
×
2481
                require.Equal(h, htlcA.AmtMsat, htlcB.AmtMsat)
×
2482
                require.Equal(h, htlcA.AcceptHeight, htlcB.AcceptHeight)
×
2483
                require.Equal(h, htlcA.AcceptTime, htlcB.AcceptTime)
×
2484
                require.Equal(h, htlcA.ResolveTime, htlcB.ResolveTime)
×
2485
                require.Equal(h, htlcA.ExpiryHeight, htlcB.ExpiryHeight)
×
2486
                require.Equal(h, htlcA.State, htlcB.State)
×
2487
                require.Equal(h, htlcA.CustomRecords, htlcB.CustomRecords)
×
2488
                require.Equal(h, htlcA.MppTotalAmtMsat, htlcB.MppTotalAmtMsat)
×
2489
                require.Equal(h, htlcA.Amp, htlcB.Amp)
×
2490
        }
×
2491
}
2492

2493
// AssertUTXOInWallet asserts that a given UTXO can be found in the node's
2494
// wallet.
2495
func (h *HarnessTest) AssertUTXOInWallet(hn *node.HarnessNode,
2496
        op *lnrpc.OutPoint, account string) {
×
2497

×
2498
        err := wait.NoError(func() error {
×
2499
                utxos := h.GetUTXOs(hn, account)
×
2500

×
2501
                err := fmt.Errorf("tx with hash %x not found", op.TxidBytes)
×
2502
                for _, utxo := range utxos {
×
2503
                        if !bytes.Equal(utxo.Outpoint.TxidBytes, op.TxidBytes) {
×
2504
                                continue
×
2505
                        }
2506

2507
                        err = fmt.Errorf("tx with output index %v not found",
×
2508
                                op.OutputIndex)
×
2509
                        if utxo.Outpoint.OutputIndex != op.OutputIndex {
×
2510
                                continue
×
2511
                        }
2512

2513
                        return nil
×
2514
                }
2515

2516
                return err
×
2517
        }, DefaultTimeout)
2518

2519
        require.NoErrorf(h, err, "outpoint %v not found in %s's wallet",
×
2520
                op, hn.Name())
×
2521
}
2522

2523
// AssertWalletAccountBalance asserts that the unconfirmed and confirmed
2524
// balance for the given account is satisfied by the WalletBalance and
2525
// ListUnspent RPCs. The unconfirmed balance is not checked for neutrino nodes.
2526
func (h *HarnessTest) AssertWalletAccountBalance(hn *node.HarnessNode,
2527
        account string, confirmedBalance, unconfirmedBalance int64) {
×
2528

×
2529
        err := wait.NoError(func() error {
×
2530
                balanceResp := hn.RPC.WalletBalance()
×
2531
                require.Contains(h, balanceResp.AccountBalance, account)
×
2532
                accountBalance := balanceResp.AccountBalance[account]
×
2533

×
2534
                // Check confirmed balance.
×
2535
                if accountBalance.ConfirmedBalance != confirmedBalance {
×
2536
                        return fmt.Errorf("expected confirmed balance %v, "+
×
2537
                                "got %v", confirmedBalance,
×
2538
                                accountBalance.ConfirmedBalance)
×
2539
                }
×
2540

2541
                utxos := h.GetUTXOsConfirmed(hn, account)
×
2542
                var totalConfirmedVal int64
×
2543
                for _, utxo := range utxos {
×
2544
                        totalConfirmedVal += utxo.AmountSat
×
2545
                }
×
2546
                if totalConfirmedVal != confirmedBalance {
×
2547
                        return fmt.Errorf("expected total confirmed utxo "+
×
2548
                                "balance %v, got %v", confirmedBalance,
×
2549
                                totalConfirmedVal)
×
2550
                }
×
2551

2552
                // Skip unconfirmed balance checks for neutrino nodes.
2553
                if h.IsNeutrinoBackend() {
×
2554
                        return nil
×
2555
                }
×
2556

2557
                // Check unconfirmed balance.
2558
                if accountBalance.UnconfirmedBalance != unconfirmedBalance {
×
2559
                        return fmt.Errorf("expected unconfirmed balance %v, "+
×
2560
                                "got %v", unconfirmedBalance,
×
2561
                                accountBalance.UnconfirmedBalance)
×
2562
                }
×
2563

2564
                utxos = h.GetUTXOsUnconfirmed(hn, account)
×
2565
                var totalUnconfirmedVal int64
×
2566
                for _, utxo := range utxos {
×
2567
                        totalUnconfirmedVal += utxo.AmountSat
×
2568
                }
×
2569
                if totalUnconfirmedVal != unconfirmedBalance {
×
2570
                        return fmt.Errorf("expected total unconfirmed utxo "+
×
2571
                                "balance %v, got %v", unconfirmedBalance,
×
2572
                                totalUnconfirmedVal)
×
2573
                }
×
2574

2575
                return nil
×
2576
        }, DefaultTimeout)
2577
        require.NoError(h, err, "timeout checking wallet account balance")
×
2578
}
2579

2580
// AssertClosingTxInMempool assert that the closing transaction of the given
2581
// channel point can be found in the mempool. If the channel has anchors, it
2582
// will assert the anchor sweep tx is also in the mempool.
2583
func (h *HarnessTest) AssertClosingTxInMempool(cp *lnrpc.ChannelPoint,
2584
        c lnrpc.CommitmentType) *wire.MsgTx {
×
2585

×
2586
        // Get expected number of txes to be found in the mempool.
×
2587
        expectedTxes := 1
×
2588
        hasAnchors := CommitTypeHasAnchors(c)
×
2589
        if hasAnchors {
×
2590
                expectedTxes = 2
×
2591
        }
×
2592

2593
        // Wait for the expected txes to be found in the mempool.
2594
        h.AssertNumTxsInMempool(expectedTxes)
×
2595

×
2596
        // Get the closing tx from the mempool.
×
2597
        op := h.OutPointFromChannelPoint(cp)
×
2598
        closeTx := h.AssertOutpointInMempool(op)
×
2599

×
2600
        return closeTx
×
2601
}
2602

2603
// AssertClosingTxInMempool assert that the closing transaction of the given
2604
// channel point can be found in the mempool. If the channel has anchors, it
2605
// will assert the anchor sweep tx is also in the mempool.
2606
func (h *HarnessTest) MineClosingTx(cp *lnrpc.ChannelPoint) *wire.MsgTx {
×
2607
        // Wait for the expected txes to be found in the mempool.
×
2608
        h.AssertNumTxsInMempool(1)
×
2609

×
2610
        // Get the closing tx from the mempool.
×
2611
        op := h.OutPointFromChannelPoint(cp)
×
2612
        closeTx := h.AssertOutpointInMempool(op)
×
2613

×
2614
        // Mine a block to confirm the closing transaction and potential anchor
×
2615
        // sweep.
×
2616
        h.MineBlocksAndAssertNumTxes(1, 1)
×
2617

×
2618
        return closeTx
×
2619
}
×
2620

2621
// AssertWalletLockedBalance asserts the expected amount has been marked as
2622
// locked in the node's WalletBalance response.
2623
func (h *HarnessTest) AssertWalletLockedBalance(hn *node.HarnessNode,
2624
        balance int64) {
×
2625

×
2626
        err := wait.NoError(func() error {
×
2627
                balanceResp := hn.RPC.WalletBalance()
×
2628
                got := balanceResp.LockedBalance
×
2629

×
2630
                if got != balance {
×
2631
                        return fmt.Errorf("want %d, got %d", balance, got)
×
2632
                }
×
2633

2634
                return nil
×
2635
        }, wait.DefaultTimeout)
2636
        require.NoError(h, err, "%s: timeout checking locked balance",
×
2637
                hn.Name())
×
2638
}
2639

2640
// AssertNumPendingSweeps asserts the number of pending sweeps for the given
2641
// node.
2642
func (h *HarnessTest) AssertNumPendingSweeps(hn *node.HarnessNode,
2643
        n int) []*walletrpc.PendingSweep {
×
2644

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

×
2647
        err := wait.NoError(func() error {
×
2648
                resp := hn.RPC.PendingSweeps()
×
2649
                num := len(resp.PendingSweeps)
×
2650

×
2651
                numDesc := "\n"
×
2652
                for _, s := range resp.PendingSweeps {
×
2653
                        desc := fmt.Sprintf("op=%v:%v, amt=%v, type=%v, "+
×
2654
                                "deadline=%v\n", s.Outpoint.TxidStr,
×
2655
                                s.Outpoint.OutputIndex, s.AmountSat,
×
2656
                                s.WitnessType, s.DeadlineHeight)
×
2657
                        numDesc += desc
×
2658

×
2659
                        // The deadline height must be set, otherwise the
×
2660
                        // pending input response is not update-to-date.
×
2661
                        if s.DeadlineHeight == 0 {
×
2662
                                return fmt.Errorf("input not updated: %s", desc)
×
2663
                        }
×
2664
                }
2665

2666
                if num == n {
×
2667
                        results = resp.PendingSweeps
×
2668
                        return nil
×
2669
                }
×
2670

2671
                return fmt.Errorf("want %d , got %d, sweeps: %s", n, num,
×
2672
                        numDesc)
×
2673
        }, DefaultTimeout)
2674

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

×
2677
        return results
×
2678
}
2679

2680
// FindSweepingTxns asserts the expected number of sweeping txns are found in
2681
// the txns specified and return them.
2682
func (h *HarnessTest) FindSweepingTxns(txns []*wire.MsgTx,
2683
        expectedNumSweeps int, closeTxid chainhash.Hash) []*wire.MsgTx {
×
2684

×
2685
        var sweepTxns []*wire.MsgTx
×
2686

×
2687
        for _, tx := range txns {
×
2688
                if tx.TxIn[0].PreviousOutPoint.Hash == closeTxid {
×
2689
                        sweepTxns = append(sweepTxns, tx)
×
2690
                }
×
2691
        }
2692
        require.Len(h, sweepTxns, expectedNumSweeps, "unexpected num of sweeps")
×
2693

×
2694
        return sweepTxns
×
2695
}
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