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

lightningnetwork / lnd / 14474220508

15 Apr 2025 04:10PM UTC coverage: 69.094% (+0.006%) from 69.088%
14474220508

Pull #9721

github

web-flow
Merge 9be650f86 into 014706cc3
Pull Request #9721: feat(lncli): Add --route_hints flag to sendpayment and queryroutes

0 of 36 new or added lines in 1 file covered. (0.0%)

129 existing lines in 13 files now uncovered.

133654 of 193437 relevant lines covered (69.09%)

22203.07 hits per line

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

86.97
/routing/router.go
1
package routing
2

3
import (
4
        "context"
5
        "fmt"
6
        "math"
7
        "math/big"
8
        "sort"
9
        "sync"
10
        "sync/atomic"
11
        "time"
12

13
        "github.com/btcsuite/btcd/btcec/v2"
14
        "github.com/btcsuite/btcd/btcutil"
15
        "github.com/davecgh/go-spew/spew"
16
        "github.com/go-errors/errors"
17
        "github.com/lightningnetwork/lnd/amp"
18
        "github.com/lightningnetwork/lnd/channeldb"
19
        "github.com/lightningnetwork/lnd/clock"
20
        "github.com/lightningnetwork/lnd/fn/v2"
21
        "github.com/lightningnetwork/lnd/graph/db/models"
22
        "github.com/lightningnetwork/lnd/htlcswitch"
23
        "github.com/lightningnetwork/lnd/lntypes"
24
        "github.com/lightningnetwork/lnd/lnutils"
25
        "github.com/lightningnetwork/lnd/lnwallet"
26
        "github.com/lightningnetwork/lnd/lnwire"
27
        "github.com/lightningnetwork/lnd/record"
28
        "github.com/lightningnetwork/lnd/routing/route"
29
        "github.com/lightningnetwork/lnd/routing/shards"
30
        "github.com/lightningnetwork/lnd/tlv"
31
        "github.com/lightningnetwork/lnd/zpay32"
32
)
33

34
const (
35
        // DefaultPayAttemptTimeout is the default payment attempt timeout. The
36
        // payment attempt timeout defines the duration after which we stop
37
        // trying more routes for a payment.
38
        DefaultPayAttemptTimeout = time.Second * 60
39

40
        // MinCLTVDelta is the minimum CLTV value accepted by LND for all
41
        // timelock deltas. This includes both forwarding CLTV deltas set on
42
        // channel updates, as well as final CLTV deltas used to create BOLT 11
43
        // payment requests.
44
        //
45
        // NOTE: For payment requests, BOLT 11 stipulates that a final CLTV
46
        // delta of 9 should be used when no value is decoded. This however
47
        // leads to inflexibility in upgrading this default parameter, since it
48
        // can create inconsistencies around the assumed value between sender
49
        // and receiver. Specifically, if the receiver assumes a higher value
50
        // than the sender, the receiver will always see the received HTLCs as
51
        // invalid due to their timelock not meeting the required delta.
52
        //
53
        // We skirt this by always setting an explicit CLTV delta when creating
54
        // invoices. This allows LND nodes to freely update the minimum without
55
        // creating incompatibilities during the upgrade process. For some time
56
        // LND has used an explicit default final CLTV delta of 40 blocks for
57
        // bitcoin, though we now clamp the lower end of this
58
        // range for user-chosen deltas to 18 blocks to be conservative.
59
        MinCLTVDelta = 18
60

61
        // MaxCLTVDelta is the maximum CLTV value accepted by LND for all
62
        // timelock deltas.
63
        MaxCLTVDelta = math.MaxUint16
64
)
65

66
var (
67
        // ErrRouterShuttingDown is returned if the router is in the process of
68
        // shutting down.
69
        ErrRouterShuttingDown = fmt.Errorf("router shutting down")
70

71
        // ErrSelfIntro is a failure returned when the source node of a
72
        // route request is also the introduction node. This is not yet
73
        // supported because LND does not support blinded forwardingg.
74
        ErrSelfIntro = errors.New("introduction point as own node not " +
75
                "supported")
76

77
        // ErrHintsAndBlinded is returned if a route request has both
78
        // bolt 11 route hints and a blinded path set.
79
        ErrHintsAndBlinded = errors.New("bolt 11 route hints and blinded " +
80
                "paths are mutually exclusive")
81

82
        // ErrExpiryAndBlinded is returned if a final cltv and a blinded path
83
        // are provided, as the cltv should be provided within the blinded
84
        // path.
85
        ErrExpiryAndBlinded = errors.New("final cltv delta and blinded " +
86
                "paths are mutually exclusive")
87

88
        // ErrTargetAndBlinded is returned is a target destination and a
89
        // blinded path are both set (as the target is inferred from the
90
        // blinded path).
91
        ErrTargetAndBlinded = errors.New("target node and blinded paths " +
92
                "are mutually exclusive")
93

94
        // ErrNoTarget is returned when the target node for a route is not
95
        // provided by either a blinded route or a cleartext pubkey.
96
        ErrNoTarget = errors.New("destination not set in target or blinded " +
97
                "path")
98

99
        // ErrSkipTempErr is returned when a non-MPP is made yet the
100
        // skipTempErr flag is set.
101
        ErrSkipTempErr = errors.New("cannot skip temp error for non-MPP")
102
)
103

104
// PaymentAttemptDispatcher is used by the router to send payment attempts onto
105
// the network, and receive their results.
106
type PaymentAttemptDispatcher interface {
107
        // SendHTLC is a function that directs a link-layer switch to
108
        // forward a fully encoded payment to the first hop in the route
109
        // denoted by its public key. A non-nil error is to be returned if the
110
        // payment was unsuccessful.
111
        SendHTLC(firstHop lnwire.ShortChannelID,
112
                attemptID uint64,
113
                htlcAdd *lnwire.UpdateAddHTLC) error
114

115
        // GetAttemptResult returns the result of the payment attempt with
116
        // the given attemptID. The paymentHash should be set to the payment's
117
        // overall hash, or in case of AMP payments the payment's unique
118
        // identifier.
119
        //
120
        // The method returns a channel where the payment result will be sent
121
        // when available, or an error is encountered during forwarding. When a
122
        // result is received on the channel, the HTLC is guaranteed to no
123
        // longer be in flight.  The switch shutting down is signaled by
124
        // closing the channel. If the attemptID is unknown,
125
        // ErrPaymentIDNotFound will be returned.
126
        GetAttemptResult(attemptID uint64, paymentHash lntypes.Hash,
127
                deobfuscator htlcswitch.ErrorDecrypter) (
128
                <-chan *htlcswitch.PaymentResult, error)
129

130
        // CleanStore calls the underlying result store, telling it is safe to
131
        // delete all entries except the ones in the keepPids map. This should
132
        // be called periodically to let the switch clean up payment results
133
        // that we have handled.
134
        // NOTE: New payment attempts MUST NOT be made after the keepPids map
135
        // has been created and this method has returned.
136
        CleanStore(keepPids map[uint64]struct{}) error
137

138
        // HasAttemptResult reads the network result store to fetch the
139
        // specified attempt. Returns true if the attempt result exists.
140
        //
141
        // NOTE: This method is used and should only be used by the router to
142
        // resume payments during startup. It can be viewed as a subset of
143
        // `GetAttemptResult` in terms of its functionality, and can be removed
144
        // once we move the construction of `UpdateAddHTLC` and
145
        // `ErrorDecrypter` into `htlcswitch`.
146
        HasAttemptResult(attemptID uint64) (bool, error)
147
}
148

149
// PaymentSessionSource is an interface that defines a source for the router to
150
// retrieve new payment sessions.
151
type PaymentSessionSource interface {
152
        // NewPaymentSession creates a new payment session that will produce
153
        // routes to the given target. An optional set of routing hints can be
154
        // provided in order to populate additional edges to explore when
155
        // finding a path to the payment's destination.
156
        NewPaymentSession(p *LightningPayment,
157
                firstHopBlob fn.Option[tlv.Blob],
158
                ts fn.Option[htlcswitch.AuxTrafficShaper]) (PaymentSession,
159
                error)
160

161
        // NewPaymentSessionEmpty creates a new paymentSession instance that is
162
        // empty, and will be exhausted immediately. Used for failure reporting
163
        // to missioncontrol for resumed payment we don't want to make more
164
        // attempts for.
165
        NewPaymentSessionEmpty() PaymentSession
166
}
167

168
// MissionControlQuerier is an interface that exposes failure reporting and
169
// probability estimation.
170
type MissionControlQuerier interface {
171
        // ReportPaymentFail reports a failed payment to mission control as
172
        // input for future probability estimates. It returns a bool indicating
173
        // whether this error is a final error and no further payment attempts
174
        // need to be made.
175
        ReportPaymentFail(attemptID uint64, rt *route.Route,
176
                failureSourceIdx *int, failure lnwire.FailureMessage) (
177
                *channeldb.FailureReason, error)
178

179
        // ReportPaymentSuccess reports a successful payment to mission control
180
        // as input for future probability estimates.
181
        ReportPaymentSuccess(attemptID uint64, rt *route.Route) error
182

183
        // GetProbability is expected to return the success probability of a
184
        // payment from fromNode along edge.
185
        GetProbability(fromNode, toNode route.Vertex,
186
                amt lnwire.MilliSatoshi, capacity btcutil.Amount) float64
187
}
188

189
// FeeSchema is the set fee configuration for a Lightning Node on the network.
190
// Using the coefficients described within the schema, the required fee to
191
// forward outgoing payments can be derived.
192
type FeeSchema struct {
193
        // BaseFee is the base amount of milli-satoshis that will be chained
194
        // for ANY payment forwarded.
195
        BaseFee lnwire.MilliSatoshi
196

197
        // FeeRate is the rate that will be charged for forwarding payments.
198
        // This value should be interpreted as the numerator for a fraction
199
        // (fixed point arithmetic) whose denominator is 1 million. As a result
200
        // the effective fee rate charged per mSAT will be: (amount *
201
        // FeeRate/1,000,000).
202
        FeeRate uint32
203

204
        // InboundFee is the inbound fee schedule that applies to forwards
205
        // coming in through a channel to which this FeeSchema pertains.
206
        InboundFee fn.Option[models.InboundFee]
207
}
208

209
// ChannelPolicy holds the parameters that determine the policy we enforce
210
// when forwarding payments on a channel. These parameters are communicated
211
// to the rest of the network in ChannelUpdate messages.
212
type ChannelPolicy struct {
213
        // FeeSchema holds the fee configuration for a channel.
214
        FeeSchema
215

216
        // TimeLockDelta is the required HTLC timelock delta to be used
217
        // when forwarding payments.
218
        TimeLockDelta uint32
219

220
        // MaxHTLC is the maximum HTLC size including fees we are allowed to
221
        // forward over this channel.
222
        MaxHTLC lnwire.MilliSatoshi
223

224
        // MinHTLC is the minimum HTLC size including fees we are allowed to
225
        // forward over this channel.
226
        MinHTLC *lnwire.MilliSatoshi
227
}
228

229
// Config defines the configuration for the ChannelRouter. ALL elements within
230
// the configuration MUST be non-nil for the ChannelRouter to carry out its
231
// duties.
232
type Config struct {
233
        // SelfNode is the public key of the node that this channel router
234
        // belongs to.
235
        SelfNode route.Vertex
236

237
        // RoutingGraph is a graph source that will be used for pathfinding.
238
        RoutingGraph Graph
239

240
        // Chain is the router's source to the most up-to-date blockchain data.
241
        // All incoming advertised channels will be checked against the chain
242
        // to ensure that the channels advertised are still open.
243
        Chain lnwallet.BlockChainIO
244

245
        // Payer is an instance of a PaymentAttemptDispatcher and is used by
246
        // the router to send payment attempts onto the network, and receive
247
        // their results.
248
        Payer PaymentAttemptDispatcher
249

250
        // Control keeps track of the status of ongoing payments, ensuring we
251
        // can properly resume them across restarts.
252
        Control ControlTower
253

254
        // MissionControl is a shared memory of sorts that executions of
255
        // payment path finding use in order to remember which vertexes/edges
256
        // were pruned from prior attempts. During SendPayment execution,
257
        // errors sent by nodes are mapped into a vertex or edge to be pruned.
258
        // Each run will then take into account this set of pruned
259
        // vertexes/edges to reduce route failure and pass on graph information
260
        // gained to the next execution.
261
        MissionControl MissionControlQuerier
262

263
        // SessionSource defines a source for the router to retrieve new payment
264
        // sessions.
265
        SessionSource PaymentSessionSource
266

267
        // GetLink is a method that allows the router to query the lower link
268
        // layer to determine the up-to-date available bandwidth at a
269
        // prospective link to be traversed. If the link isn't available, then
270
        // a value of zero should be returned. Otherwise, the current up-to-
271
        // date knowledge of the available bandwidth of the link should be
272
        // returned.
273
        GetLink getLinkQuery
274

275
        // NextPaymentID is a method that guarantees to return a new, unique ID
276
        // each time it is called. This is used by the router to generate a
277
        // unique payment ID for each payment it attempts to send, such that
278
        // the switch can properly handle the HTLC.
279
        NextPaymentID func() (uint64, error)
280

281
        // PathFindingConfig defines global path finding parameters.
282
        PathFindingConfig PathFindingConfig
283

284
        // Clock is mockable time provider.
285
        Clock clock.Clock
286

287
        // ApplyChannelUpdate can be called to apply a new channel update to the
288
        // graph that we received from a payment failure.
289
        ApplyChannelUpdate func(msg *lnwire.ChannelUpdate1) bool
290

291
        // ClosedSCIDs is used by the router to fetch closed channels.
292
        //
293
        // TODO(yy): remove it once the root cause of stuck payments is found.
294
        ClosedSCIDs map[lnwire.ShortChannelID]struct{}
295

296
        // TrafficShaper is an optional traffic shaper that can be used to
297
        // control the outgoing channel of a payment.
298
        TrafficShaper fn.Option[htlcswitch.AuxTrafficShaper]
299
}
300

301
// EdgeLocator is a struct used to identify a specific edge.
302
type EdgeLocator struct {
303
        // ChannelID is the channel of this edge.
304
        ChannelID uint64
305

306
        // Direction takes the value of 0 or 1 and is identical in definition to
307
        // the channel direction flag. A value of 0 means the direction from the
308
        // lower node pubkey to the higher.
309
        Direction uint8
310
}
311

312
// String returns a human-readable version of the edgeLocator values.
313
func (e *EdgeLocator) String() string {
×
314
        return fmt.Sprintf("%v:%v", e.ChannelID, e.Direction)
×
315
}
×
316

317
// ChannelRouter is the layer 3 router within the Lightning stack. Below the
318
// ChannelRouter is the HtlcSwitch, and below that is the Bitcoin blockchain
319
// itself. The primary role of the ChannelRouter is to respond to queries for
320
// potential routes that can support a payment amount, and also general graph
321
// reachability questions. The router will prune the channel graph
322
// automatically as new blocks are discovered which spend certain known funding
323
// outpoints, thereby closing their respective channels.
324
type ChannelRouter struct {
325
        started uint32 // To be used atomically.
326
        stopped uint32 // To be used atomically.
327

328
        // cfg is a copy of the configuration struct that the ChannelRouter was
329
        // initialized with.
330
        cfg *Config
331

332
        quit chan struct{}
333
        wg   sync.WaitGroup
334
}
335

336
// New creates a new instance of the ChannelRouter with the specified
337
// configuration parameters. As part of initialization, if the router detects
338
// that the channel graph isn't fully in sync with the latest UTXO (since the
339
// channel graph is a subset of the UTXO set) set, then the router will proceed
340
// to fully sync to the latest state of the UTXO set.
341
func New(cfg Config) (*ChannelRouter, error) {
20✔
342
        return &ChannelRouter{
20✔
343
                cfg:  &cfg,
20✔
344
                quit: make(chan struct{}),
20✔
345
        }, nil
20✔
346
}
20✔
347

348
// Start launches all the goroutines the ChannelRouter requires to carry out
349
// its duties. If the router has already been started, then this method is a
350
// noop.
351
func (r *ChannelRouter) Start() error {
20✔
352
        if !atomic.CompareAndSwapUint32(&r.started, 0, 1) {
20✔
353
                return nil
×
354
        }
×
355

356
        log.Info("Channel Router starting")
20✔
357

20✔
358
        // If any payments are still in flight, we resume, to make sure their
20✔
359
        // results are properly handled.
20✔
360
        if err := r.resumePayments(); err != nil {
20✔
361
                log.Error("Failed to resume payments during startup")
×
362
        }
×
363

364
        return nil
20✔
365
}
366

367
// Stop signals the ChannelRouter to gracefully halt all routines. This method
368
// will *block* until all goroutines have excited. If the channel router has
369
// already stopped then this method will return immediately.
370
func (r *ChannelRouter) Stop() error {
20✔
371
        if !atomic.CompareAndSwapUint32(&r.stopped, 0, 1) {
20✔
372
                return nil
×
373
        }
×
374

375
        log.Info("Channel Router shutting down...")
20✔
376
        defer log.Debug("Channel Router shutdown complete")
20✔
377

20✔
378
        close(r.quit)
20✔
379
        r.wg.Wait()
20✔
380

20✔
381
        return nil
20✔
382
}
383

384
// RouteRequest contains the parameters for a pathfinding request. It may
385
// describe a request to make a regular payment or one to a blinded path
386
// (incdicated by a non-nil BlindedPayment field).
387
type RouteRequest struct {
388
        // Source is the node that the path originates from.
389
        Source route.Vertex
390

391
        // Target is the node that the path terminates at. If the route
392
        // includes a blinded path, target will be the blinded node id of the
393
        // final hop in the blinded route.
394
        Target route.Vertex
395

396
        // Amount is the Amount in millisatoshis to be delivered to the target
397
        // node.
398
        Amount lnwire.MilliSatoshi
399

400
        // TimePreference expresses the caller's time preference for
401
        // pathfinding.
402
        TimePreference float64
403

404
        // Restrictions provides a set of additional Restrictions that the
405
        // route must adhere to.
406
        Restrictions *RestrictParams
407

408
        // CustomRecords is a set of custom tlv records to include for the
409
        // final hop.
410
        CustomRecords record.CustomSet
411

412
        // RouteHints contains an additional set of edges to include in our
413
        // view of the graph. This may either be a set of hints for private
414
        // channels or a "virtual" hop hint that represents a blinded route.
415
        RouteHints RouteHints
416

417
        // FinalExpiry is the cltv delta for the final hop. If paying to a
418
        // blinded path, this value is a duplicate of the delta provided
419
        // in blinded payment.
420
        FinalExpiry uint16
421

422
        // BlindedPathSet contains a set of optional blinded paths and
423
        // parameters used to reach a target node blinded paths. This field is
424
        // mutually exclusive with the Target field.
425
        BlindedPathSet *BlindedPaymentPathSet
426
}
427

428
// RouteHints is an alias type for a set of route hints, with the source node
429
// as the map's key and the details of the hint(s) in the edge policy.
430
type RouteHints map[route.Vertex][]AdditionalEdge
431

432
// NewRouteRequest produces a new route request for a regular payment or one
433
// to a blinded route, validating that the target, routeHints and finalExpiry
434
// parameters are mutually exclusive with the blindedPayment parameter (which
435
// contains these values for blinded payments).
436
func NewRouteRequest(source route.Vertex, target *route.Vertex,
437
        amount lnwire.MilliSatoshi, timePref float64,
438
        restrictions *RestrictParams, customRecords record.CustomSet,
439
        routeHints RouteHints, blindedPathSet *BlindedPaymentPathSet,
440
        finalExpiry uint16) (*RouteRequest, error) {
18✔
441

18✔
442
        var (
18✔
443
                // Assume that we're starting off with a regular payment.
18✔
444
                requestHints  = routeHints
18✔
445
                requestExpiry = finalExpiry
18✔
446
                err           error
18✔
447
        )
18✔
448

18✔
449
        if blindedPathSet != nil {
27✔
450
                if blindedPathSet.IsIntroNode(source) {
10✔
451
                        return nil, ErrSelfIntro
1✔
452
                }
1✔
453

454
                // Check that the values for a clear path have not been set,
455
                // as this is an ambiguous signal from the caller.
456
                if routeHints != nil {
9✔
457
                        return nil, ErrHintsAndBlinded
1✔
458
                }
1✔
459

460
                if finalExpiry != 0 {
8✔
461
                        return nil, ErrExpiryAndBlinded
1✔
462
                }
1✔
463

464
                requestExpiry = blindedPathSet.FinalCLTVDelta()
6✔
465

6✔
466
                requestHints, err = blindedPathSet.ToRouteHints()
6✔
467
                if err != nil {
6✔
468
                        return nil, err
×
469
                }
×
470
        }
471

472
        requestTarget, err := getTargetNode(target, blindedPathSet)
15✔
473
        if err != nil {
16✔
474
                return nil, err
1✔
475
        }
1✔
476

477
        return &RouteRequest{
14✔
478
                Source:         source,
14✔
479
                Target:         requestTarget,
14✔
480
                Amount:         amount,
14✔
481
                TimePreference: timePref,
14✔
482
                Restrictions:   restrictions,
14✔
483
                CustomRecords:  customRecords,
14✔
484
                RouteHints:     requestHints,
14✔
485
                FinalExpiry:    requestExpiry,
14✔
486
                BlindedPathSet: blindedPathSet,
14✔
487
        }, nil
14✔
488
}
489

490
func getTargetNode(target *route.Vertex,
491
        blindedPathSet *BlindedPaymentPathSet) (route.Vertex, error) {
15✔
492

15✔
493
        var (
15✔
494
                blinded   = blindedPathSet != nil
15✔
495
                targetSet = target != nil
15✔
496
        )
15✔
497

15✔
498
        switch {
15✔
499
        case blinded && targetSet:
1✔
500
                return route.Vertex{}, ErrTargetAndBlinded
1✔
501

502
        case blinded:
5✔
503
                return route.NewVertex(blindedPathSet.TargetPubKey()), nil
5✔
504

505
        case targetSet:
12✔
506
                return *target, nil
12✔
507

508
        default:
×
509
                return route.Vertex{}, ErrNoTarget
×
510
        }
511
}
512

513
// FindRoute attempts to query the ChannelRouter for the optimum path to a
514
// particular target destination to which it is able to send `amt` after
515
// factoring in channel capacities and cumulative fees along the route.
516
func (r *ChannelRouter) FindRoute(req *RouteRequest) (*route.Route, float64,
517
        error) {
8✔
518

8✔
519
        log.Debugf("Searching for path to %v, sending %v", req.Target,
8✔
520
                req.Amount)
8✔
521

8✔
522
        // We'll attempt to obtain a set of bandwidth hints that can help us
8✔
523
        // eliminate certain routes early on in the path finding process.
8✔
524
        bandwidthHints, err := newBandwidthManager(
8✔
525
                r.cfg.RoutingGraph, r.cfg.SelfNode, r.cfg.GetLink,
8✔
526
                fn.None[tlv.Blob](), r.cfg.TrafficShaper,
8✔
527
        )
8✔
528
        if err != nil {
8✔
529
                return nil, 0, err
×
530
        }
×
531

532
        // We'll fetch the current block height, so we can properly calculate
533
        // the required HTLC time locks within the route.
534
        _, currentHeight, err := r.cfg.Chain.GetBestBlock()
8✔
535
        if err != nil {
8✔
536
                return nil, 0, err
×
537
        }
×
538

539
        // Now that we know the destination is reachable within the graph, we'll
540
        // execute our path finding algorithm.
541
        finalHtlcExpiry := currentHeight + int32(req.FinalExpiry)
8✔
542

8✔
543
        // Validate time preference.
8✔
544
        timePref := req.TimePreference
8✔
545
        if timePref < -1 || timePref > 1 {
8✔
546
                return nil, 0, errors.New("time preference out of range")
×
547
        }
×
548

549
        path, probability, err := findPath(
8✔
550
                &graphParams{
8✔
551
                        additionalEdges: req.RouteHints,
8✔
552
                        bandwidthHints:  bandwidthHints,
8✔
553
                        graph:           r.cfg.RoutingGraph,
8✔
554
                },
8✔
555
                req.Restrictions, &r.cfg.PathFindingConfig,
8✔
556
                r.cfg.SelfNode, req.Source, req.Target, req.Amount,
8✔
557
                req.TimePreference, finalHtlcExpiry,
8✔
558
        )
8✔
559
        if err != nil {
11✔
560
                return nil, 0, err
3✔
561
        }
3✔
562

563
        // Create the route with absolute time lock values.
564
        route, err := newRoute(
8✔
565
                req.Source, path, uint32(currentHeight),
8✔
566
                finalHopParams{
8✔
567
                        amt:         req.Amount,
8✔
568
                        totalAmt:    req.Amount,
8✔
569
                        cltvDelta:   req.FinalExpiry,
8✔
570
                        records:     req.CustomRecords,
8✔
571
                        paymentAddr: req.Restrictions.PaymentAddr,
8✔
572
                        metadata:    req.Restrictions.Metadata,
8✔
573
                }, req.BlindedPathSet,
8✔
574
        )
8✔
575
        if err != nil {
8✔
UNCOV
576
                return nil, 0, err
×
UNCOV
577
        }
×
578

579
        go log.Tracef("Obtained path to send %v to %x: %v",
8✔
580
                req.Amount, req.Target, lnutils.SpewLogClosure(route))
8✔
581

8✔
582
        return route, probability, nil
8✔
583
}
584

585
// probabilitySource defines the signature of a function that can be used to
586
// query the success probability of sending a given amount between the two
587
// given vertices.
588
type probabilitySource func(route.Vertex, route.Vertex, lnwire.MilliSatoshi,
589
        btcutil.Amount) float64
590

591
// BlindedPathRestrictions are a set of constraints to adhere to when
592
// choosing a set of blinded paths to this node.
593
type BlindedPathRestrictions struct {
594
        // MinDistanceFromIntroNode is the minimum number of _real_ (non-dummy)
595
        // hops to include in a blinded path. Since we post-fix dummy hops, this
596
        // is the minimum distance between our node and the introduction node
597
        // of the path. This doesn't include our node, so if the minimum is 1,
598
        // then the path will contain at minimum our node along with an
599
        // introduction node hop.
600
        MinDistanceFromIntroNode uint8
601

602
        // NumHops is the number of hops that each blinded path should consist
603
        // of. If paths are found with a number of hops less that NumHops, then
604
        // dummy hops will be padded on to the route. This value doesn't
605
        // include our node, so if the maximum is 1, then the path will contain
606
        // our node along with an introduction node hop.
607
        NumHops uint8
608

609
        // MaxNumPaths is the maximum number of blinded paths to select.
610
        MaxNumPaths uint8
611

612
        // NodeOmissionSet is a set of nodes that should not be used within any
613
        // of the blinded paths that we generate.
614
        NodeOmissionSet fn.Set[route.Vertex]
615
}
616

617
// FindBlindedPaths finds a selection of paths to the destination node that can
618
// be used in blinded payment paths.
619
func (r *ChannelRouter) FindBlindedPaths(destination route.Vertex,
620
        amt lnwire.MilliSatoshi, probabilitySrc probabilitySource,
621
        restrictions *BlindedPathRestrictions) ([]*route.Route, error) {
10✔
622

10✔
623
        // First, find a set of candidate paths given the destination node and
10✔
624
        // path length restrictions.
10✔
625
        paths, err := findBlindedPaths(
10✔
626
                r.cfg.RoutingGraph, destination, &blindedPathRestrictions{
10✔
627
                        minNumHops:      restrictions.MinDistanceFromIntroNode,
10✔
628
                        maxNumHops:      restrictions.NumHops,
10✔
629
                        nodeOmissionSet: restrictions.NodeOmissionSet,
10✔
630
                },
10✔
631
        )
10✔
632
        if err != nil {
10✔
UNCOV
633
                return nil, err
×
UNCOV
634
        }
×
635

636
        // routeWithProbability groups a route with the probability of a
637
        // payment of the given amount succeeding on that path.
638
        type routeWithProbability struct {
10✔
639
                route       *route.Route
10✔
640
                probability float64
10✔
641
        }
10✔
642

10✔
643
        // Iterate over all the candidate paths and determine the success
10✔
644
        // probability of each path given the data we have about forwards
10✔
645
        // between any two nodes on a path.
10✔
646
        routes := make([]*routeWithProbability, 0, len(paths))
10✔
647
        for _, path := range paths {
31✔
648
                if len(path) < 1 {
21✔
649
                        return nil, fmt.Errorf("a blinded path must have at " +
×
UNCOV
650
                                "least one hop")
×
UNCOV
651
                }
×
652

653
                var (
21✔
654
                        introNode = path[0].vertex
21✔
655
                        prevNode  = introNode
21✔
656
                        hops      = make(
21✔
657
                                []*route.Hop, 0, len(path)-1,
21✔
658
                        )
21✔
659
                        totalRouteProbability = float64(1)
21✔
660
                )
21✔
661

21✔
662
                // For each set of hops on the path, get the success probability
21✔
663
                // of a forward between those two vertices and use that to
21✔
664
                // update the overall route probability.
21✔
665
                for j := 1; j < len(path); j++ {
58✔
666
                        probability := probabilitySrc(
37✔
667
                                prevNode, path[j].vertex, amt,
37✔
668
                                path[j-1].edgeCapacity,
37✔
669
                        )
37✔
670

37✔
671
                        totalRouteProbability *= probability
37✔
672

37✔
673
                        hops = append(hops, &route.Hop{
37✔
674
                                PubKeyBytes: path[j].vertex,
37✔
675
                                ChannelID:   path[j-1].channelID,
37✔
676
                        })
37✔
677

37✔
678
                        prevNode = path[j].vertex
37✔
679
                }
37✔
680

681
                // Don't bother adding a route if its success probability less
682
                // minimum that can be assigned to any single pair.
683
                if totalRouteProbability <= DefaultMinRouteProbability {
23✔
684
                        continue
2✔
685
                }
686

687
                routes = append(routes, &routeWithProbability{
19✔
688
                        route: &route.Route{
19✔
689
                                SourcePubKey: introNode,
19✔
690
                                Hops:         hops,
19✔
691
                        },
19✔
692
                        probability: totalRouteProbability,
19✔
693
                })
19✔
694
        }
695

696
        // Sort the routes based on probability.
697
        sort.Slice(routes, func(i, j int) bool {
23✔
698
                return routes[i].probability > routes[j].probability
13✔
699
        })
13✔
700

701
        // Now just choose the best paths up until the maximum number of allowed
702
        // paths.
703
        bestRoutes := make([]*route.Route, 0, restrictions.MaxNumPaths)
10✔
704
        for _, route := range routes {
28✔
705
                if len(bestRoutes) >= int(restrictions.MaxNumPaths) {
19✔
706
                        break
1✔
707
                }
708

709
                bestRoutes = append(bestRoutes, route.route)
17✔
710
        }
711

712
        return bestRoutes, nil
10✔
713
}
714

715
// generateNewSessionKey generates a new ephemeral private key to be used for a
716
// payment attempt.
717
func generateNewSessionKey() (*btcec.PrivateKey, error) {
39✔
718
        // Generate a new random session key to ensure that we don't trigger
39✔
719
        // any replay.
39✔
720
        //
39✔
721
        // TODO(roasbeef): add more sources of randomness?
39✔
722
        return btcec.NewPrivateKey()
39✔
723
}
39✔
724

725
// LightningPayment describes a payment to be sent through the network to the
726
// final destination.
727
type LightningPayment struct {
728
        // Target is the node in which the payment should be routed towards.
729
        Target route.Vertex
730

731
        // Amount is the value of the payment to send through the network in
732
        // milli-satoshis.
733
        Amount lnwire.MilliSatoshi
734

735
        // FeeLimit is the maximum fee in millisatoshis that the payment should
736
        // accept when sending it through the network. The payment will fail
737
        // if there isn't a route with lower fees than this limit.
738
        FeeLimit lnwire.MilliSatoshi
739

740
        // CltvLimit is the maximum time lock that is allowed for attempts to
741
        // complete this payment.
742
        CltvLimit uint32
743

744
        // paymentHash is the r-hash value to use within the HTLC extended to
745
        // the first hop. This won't be set for AMP payments.
746
        paymentHash *lntypes.Hash
747

748
        // amp is an optional field that is set if and only if this is am AMP
749
        // payment.
750
        amp *AMPOptions
751

752
        // FinalCLTVDelta is the CTLV expiry delta to use for the _final_ hop
753
        // in the route. This means that the final hop will have a CLTV delta
754
        // of at least: currentHeight + FinalCLTVDelta.
755
        FinalCLTVDelta uint16
756

757
        // PayAttemptTimeout is a timeout value that we'll use to determine
758
        // when we should should abandon the payment attempt after consecutive
759
        // payment failure. This prevents us from attempting to send a payment
760
        // indefinitely. A zero value means the payment will never time out.
761
        //
762
        // TODO(halseth): make wallclock time to allow resume after startup.
763
        PayAttemptTimeout time.Duration
764

765
        // RouteHints represents the different routing hints that can be used to
766
        // assist a payment in reaching its destination successfully. These
767
        // hints will act as intermediate hops along the route.
768
        //
769
        // NOTE: This is optional unless required by the payment. When providing
770
        // multiple routes, ensure the hop hints within each route are chained
771
        // together and sorted in forward order in order to reach the
772
        // destination successfully. This is mutually exclusive to the
773
        // BlindedPayment field.
774
        RouteHints [][]zpay32.HopHint
775

776
        // BlindedPathSet holds the information about a set of blinded paths to
777
        // the payment recipient. This is mutually exclusive to the RouteHints
778
        // field.
779
        BlindedPathSet *BlindedPaymentPathSet
780

781
        // OutgoingChannelIDs is the list of channels that are allowed for the
782
        // first hop. If nil, any channel may be used.
783
        OutgoingChannelIDs []uint64
784

785
        // LastHop is the pubkey of the last node before the final destination
786
        // is reached. If nil, any node may be used.
787
        LastHop *route.Vertex
788

789
        // DestFeatures specifies the set of features we assume the final node
790
        // has for pathfinding. Typically, these will be taken directly from an
791
        // invoice, but they can also be manually supplied or assumed by the
792
        // sender. If a nil feature vector is provided, the router will try to
793
        // fall back to the graph in order to load a feature vector for a node
794
        // in the public graph.
795
        DestFeatures *lnwire.FeatureVector
796

797
        // PaymentAddr is the payment address specified by the receiver. This
798
        // field should be a random 32-byte nonce presented in the receiver's
799
        // invoice to prevent probing of the destination.
800
        PaymentAddr fn.Option[[32]byte]
801

802
        // PaymentRequest is an optional payment request that this payment is
803
        // attempting to complete.
804
        PaymentRequest []byte
805

806
        // DestCustomRecords are TLV records that are to be sent to the final
807
        // hop in the new onion payload format. If the destination does not
808
        // understand this new onion payload format, then the payment will
809
        // fail.
810
        DestCustomRecords record.CustomSet
811

812
        // FirstHopCustomRecords are the TLV records that are to be sent to the
813
        // first hop of this payment. These records will be transmitted via the
814
        // wire message and therefore do not affect the onion payload size.
815
        FirstHopCustomRecords lnwire.CustomRecords
816

817
        // MaxParts is the maximum number of partial payments that may be used
818
        // to complete the full amount.
819
        MaxParts uint32
820

821
        // MaxShardAmt is the largest shard that we'll attempt to split using.
822
        // If this field is set, and we need to split, rather than attempting
823
        // half of the original payment amount, we'll use this value if half
824
        // the payment amount is greater than it.
825
        //
826
        // NOTE: This field is _optional_.
827
        MaxShardAmt *lnwire.MilliSatoshi
828

829
        // TimePref is the time preference for this payment. Set to -1 to
830
        // optimize for fees only, to 1 to optimize for reliability only or a
831
        // value in between for a mix.
832
        TimePref float64
833

834
        // Metadata is additional data that is sent along with the payment to
835
        // the payee.
836
        Metadata []byte
837
}
838

839
// AMPOptions houses information that must be known in order to send an AMP
840
// payment.
841
type AMPOptions struct {
842
        SetID     [32]byte
843
        RootShare [32]byte
844
}
845

846
// SetPaymentHash sets the given hash as the payment's overall hash. This
847
// should only be used for non-AMP payments.
848
func (l *LightningPayment) SetPaymentHash(hash lntypes.Hash) error {
16✔
849
        if l.amp != nil {
16✔
UNCOV
850
                return fmt.Errorf("cannot set payment hash for AMP payment")
×
UNCOV
851
        }
×
852

853
        l.paymentHash = &hash
16✔
854
        return nil
16✔
855
}
856

857
// SetAMP sets the given AMP options for the payment.
858
func (l *LightningPayment) SetAMP(amp *AMPOptions) error {
3✔
859
        if l.paymentHash != nil {
3✔
860
                return fmt.Errorf("cannot set amp options for payment " +
×
UNCOV
861
                        "with payment hash")
×
UNCOV
862
        }
×
863

864
        l.amp = amp
3✔
865
        return nil
3✔
866
}
867

868
// Identifier returns a 32-byte slice that uniquely identifies this single
869
// payment. For non-AMP payments this will be the payment hash, for AMP
870
// payments this will be the used SetID.
871
func (l *LightningPayment) Identifier() [32]byte {
74✔
872
        if l.amp != nil {
77✔
873
                return l.amp.SetID
3✔
874
        }
3✔
875

876
        return *l.paymentHash
74✔
877
}
878

879
// SendPayment attempts to send a payment as described within the passed
880
// LightningPayment. This function is blocking and will return either: when the
881
// payment is successful, or all candidates routes have been attempted and
882
// resulted in a failed payment. If the payment succeeds, then a non-nil Route
883
// will be returned which describes the path the successful payment traversed
884
// within the network to reach the destination. Additionally, the payment
885
// preimage will also be returned.
886
func (r *ChannelRouter) SendPayment(payment *LightningPayment) ([32]byte,
887
        *route.Route, error) {
12✔
888

12✔
889
        paySession, shardTracker, err := r.PreparePayment(payment)
12✔
890
        if err != nil {
12✔
UNCOV
891
                return [32]byte{}, nil, err
×
UNCOV
892
        }
×
893

894
        log.Tracef("Dispatching SendPayment for lightning payment: %v",
12✔
895
                spewPayment(payment))
12✔
896

12✔
897
        return r.sendPayment(
12✔
898
                context.Background(), payment.FeeLimit, payment.Identifier(),
12✔
899
                payment.PayAttemptTimeout, paySession, shardTracker,
12✔
900
                payment.FirstHopCustomRecords,
12✔
901
        )
12✔
902
}
903

904
// SendPaymentAsync is the non-blocking version of SendPayment. The payment
905
// result needs to be retrieved via the control tower.
906
func (r *ChannelRouter) SendPaymentAsync(ctx context.Context,
907
        payment *LightningPayment, ps PaymentSession, st shards.ShardTracker) {
3✔
908

3✔
909
        // Since this is the first time this payment is being made, we pass nil
3✔
910
        // for the existing attempt.
3✔
911
        r.wg.Add(1)
3✔
912
        go func() {
6✔
913
                defer r.wg.Done()
3✔
914

3✔
915
                log.Tracef("Dispatching SendPayment for lightning payment: %v",
3✔
916
                        spewPayment(payment))
3✔
917

3✔
918
                _, _, err := r.sendPayment(
3✔
919
                        ctx, payment.FeeLimit, payment.Identifier(),
3✔
920
                        payment.PayAttemptTimeout, ps, st,
3✔
921
                        payment.FirstHopCustomRecords,
3✔
922
                )
3✔
923
                if err != nil {
6✔
924
                        log.Errorf("Payment %x failed: %v",
3✔
925
                                payment.Identifier(), err)
3✔
926
                }
3✔
927
        }()
928
}
929

930
// spewPayment returns a log closures that provides a spewed string
931
// representation of the passed payment.
932
func spewPayment(payment *LightningPayment) lnutils.LogClosure {
15✔
933
        return lnutils.NewLogClosure(func() string {
15✔
934
                // Make a copy of the payment with a nilled Curve
×
935
                // before spewing.
×
936
                var routeHints [][]zpay32.HopHint
×
937
                for _, routeHint := range payment.RouteHints {
×
938
                        var hopHints []zpay32.HopHint
×
939
                        for _, hopHint := range routeHint {
×
940
                                h := hopHint.Copy()
×
941
                                hopHints = append(hopHints, h)
×
UNCOV
942
                        }
×
943
                        routeHints = append(routeHints, hopHints)
×
944
                }
945
                p := *payment
×
UNCOV
946
                p.RouteHints = routeHints
×
UNCOV
947
                return spew.Sdump(p)
×
948
        })
949
}
950

951
// PreparePayment creates the payment session and registers the payment with the
952
// control tower.
953
func (r *ChannelRouter) PreparePayment(payment *LightningPayment) (
954
        PaymentSession, shards.ShardTracker, error) {
15✔
955

15✔
956
        // Assemble any custom data we want to send to the first hop only.
15✔
957
        var firstHopData fn.Option[tlv.Blob]
15✔
958
        if len(payment.FirstHopCustomRecords) > 0 {
18✔
959
                if err := payment.FirstHopCustomRecords.Validate(); err != nil {
3✔
960
                        return nil, nil, fmt.Errorf("invalid first hop custom "+
×
UNCOV
961
                                "records: %w", err)
×
UNCOV
962
                }
×
963

964
                firstHopBlob, err := payment.FirstHopCustomRecords.Serialize()
3✔
965
                if err != nil {
3✔
966
                        return nil, nil, fmt.Errorf("unable to serialize "+
×
UNCOV
967
                                "first hop custom records: %w", err)
×
UNCOV
968
                }
×
969

970
                firstHopData = fn.Some(firstHopBlob)
3✔
971
        }
972

973
        // Before starting the HTLC routing attempt, we'll create a fresh
974
        // payment session which will report our errors back to mission
975
        // control.
976
        paySession, err := r.cfg.SessionSource.NewPaymentSession(
15✔
977
                payment, firstHopData, r.cfg.TrafficShaper,
15✔
978
        )
15✔
979
        if err != nil {
15✔
UNCOV
980
                return nil, nil, err
×
UNCOV
981
        }
×
982

983
        // Record this payment hash with the ControlTower, ensuring it is not
984
        // already in-flight.
985
        //
986
        // TODO(roasbeef): store records as part of creation info?
987
        info := &channeldb.PaymentCreationInfo{
15✔
988
                PaymentIdentifier:     payment.Identifier(),
15✔
989
                Value:                 payment.Amount,
15✔
990
                CreationTime:          r.cfg.Clock.Now(),
15✔
991
                PaymentRequest:        payment.PaymentRequest,
15✔
992
                FirstHopCustomRecords: payment.FirstHopCustomRecords,
15✔
993
        }
15✔
994

15✔
995
        // Create a new ShardTracker that we'll use during the life cycle of
15✔
996
        // this payment.
15✔
997
        var shardTracker shards.ShardTracker
15✔
998
        switch {
15✔
999
        // If this is an AMP payment, we'll use the AMP shard tracker.
1000
        case payment.amp != nil:
3✔
1001
                addr := payment.PaymentAddr.UnwrapOr([32]byte{})
3✔
1002
                shardTracker = amp.NewShardTracker(
3✔
1003
                        payment.amp.RootShare, payment.amp.SetID, addr,
3✔
1004
                        payment.Amount,
3✔
1005
                )
3✔
1006

1007
        // Otherwise we'll use the simple tracker that will map each attempt to
1008
        // the same payment hash.
1009
        default:
15✔
1010
                shardTracker = shards.NewSimpleShardTracker(
15✔
1011
                        payment.Identifier(), nil,
15✔
1012
                )
15✔
1013
        }
1014

1015
        err = r.cfg.Control.InitPayment(payment.Identifier(), info)
15✔
1016
        if err != nil {
15✔
UNCOV
1017
                return nil, nil, err
×
UNCOV
1018
        }
×
1019

1020
        return paySession, shardTracker, nil
15✔
1021
}
1022

1023
// SendToRoute sends a payment using the provided route and fails the payment
1024
// when an error is returned from the attempt.
1025
func (r *ChannelRouter) SendToRoute(htlcHash lntypes.Hash, rt *route.Route,
1026
        firstHopCustomRecords lnwire.CustomRecords) (*channeldb.HTLCAttempt,
1027
        error) {
9✔
1028

9✔
1029
        return r.sendToRoute(htlcHash, rt, false, firstHopCustomRecords)
9✔
1030
}
9✔
1031

1032
// SendToRouteSkipTempErr sends a payment using the provided route and fails
1033
// the payment ONLY when a terminal error is returned from the attempt.
1034
func (r *ChannelRouter) SendToRouteSkipTempErr(htlcHash lntypes.Hash,
1035
        rt *route.Route,
1036
        firstHopCustomRecords lnwire.CustomRecords) (*channeldb.HTLCAttempt,
1037
        error) {
4✔
1038

4✔
1039
        return r.sendToRoute(htlcHash, rt, true, firstHopCustomRecords)
4✔
1040
}
4✔
1041

1042
// sendToRoute attempts to send a payment with the given hash through the
1043
// provided route. This function is blocking and will return the attempt
1044
// information as it is stored in the database. For a successful htlc, this
1045
// information will contain the preimage. If an error occurs after the attempt
1046
// was initiated, both return values will be non-nil. If skipTempErr is true,
1047
// the payment won't be failed unless a terminal error has occurred.
1048
func (r *ChannelRouter) sendToRoute(htlcHash lntypes.Hash, rt *route.Route,
1049
        skipTempErr bool,
1050
        firstHopCustomRecords lnwire.CustomRecords) (*channeldb.HTLCAttempt,
1051
        error) {
13✔
1052

13✔
1053
        // Helper function to fail a payment. It makes sure the payment is only
13✔
1054
        // failed once so that the failure reason is not overwritten.
13✔
1055
        failPayment := func(paymentIdentifier lntypes.Hash,
13✔
1056
                reason channeldb.FailureReason) error {
21✔
1057

8✔
1058
                payment, fetchErr := r.cfg.Control.FetchPayment(
8✔
1059
                        paymentIdentifier,
8✔
1060
                )
8✔
1061
                if fetchErr != nil {
8✔
UNCOV
1062
                        return fetchErr
×
UNCOV
1063
                }
×
1064

1065
                // NOTE: We cannot rely on the payment status to be failed here
1066
                // because it can still be in-flight although the payment is
1067
                // already failed.
1068
                _, failedReason := payment.TerminalInfo()
8✔
1069
                if failedReason != nil {
12✔
1070
                        return nil
4✔
1071
                }
4✔
1072

1073
                return r.cfg.Control.FailPayment(paymentIdentifier, reason)
7✔
1074
        }
1075

1076
        log.Debugf("SendToRoute for payment %v with skipTempErr=%v",
13✔
1077
                htlcHash, skipTempErr)
13✔
1078

13✔
1079
        // Calculate amount paid to receiver.
13✔
1080
        amt := rt.ReceiverAmt()
13✔
1081

13✔
1082
        // If this is meant as an MP payment shard, we set the amount for the
13✔
1083
        // creating info to the total amount of the payment.
13✔
1084
        finalHop := rt.Hops[len(rt.Hops)-1]
13✔
1085
        mpp := finalHop.MPP
13✔
1086
        if mpp != nil {
20✔
1087
                amt = mpp.TotalMsat()
7✔
1088
        }
7✔
1089

1090
        // For non-MPP, there's no such thing as temp error as there's only one
1091
        // HTLC attempt being made. When this HTLC is failed, the payment is
1092
        // failed hence cannot be retried.
1093
        if skipTempErr && mpp == nil {
14✔
1094
                return nil, ErrSkipTempErr
1✔
1095
        }
1✔
1096

1097
        // For non-AMP payments the overall payment identifier will be the same
1098
        // hash as used for this HTLC.
1099
        paymentIdentifier := htlcHash
12✔
1100

12✔
1101
        // For AMP-payments, we'll use the setID as the unique ID for the
12✔
1102
        // overall payment.
12✔
1103
        amp := finalHop.AMP
12✔
1104
        if amp != nil {
15✔
1105
                paymentIdentifier = amp.SetID()
3✔
1106
        }
3✔
1107

1108
        // Record this payment hash with the ControlTower, ensuring it is not
1109
        // already in-flight.
1110
        info := &channeldb.PaymentCreationInfo{
12✔
1111
                PaymentIdentifier:     paymentIdentifier,
12✔
1112
                Value:                 amt,
12✔
1113
                CreationTime:          r.cfg.Clock.Now(),
12✔
1114
                PaymentRequest:        nil,
12✔
1115
                FirstHopCustomRecords: firstHopCustomRecords,
12✔
1116
        }
12✔
1117

12✔
1118
        err := r.cfg.Control.InitPayment(paymentIdentifier, info)
12✔
1119
        switch {
12✔
1120
        // If this is an MPP attempt and the hash is already registered with
1121
        // the database, we can go on to launch the shard.
1122
        case mpp != nil && errors.Is(err, channeldb.ErrPaymentInFlight):
3✔
UNCOV
1123
        case mpp != nil && errors.Is(err, channeldb.ErrPaymentExists):
×
1124

1125
        // Any other error is not tolerated.
UNCOV
1126
        case err != nil:
×
UNCOV
1127
                return nil, err
×
1128
        }
1129

1130
        log.Tracef("Dispatching SendToRoute for HTLC hash %v: %v", htlcHash,
12✔
1131
                lnutils.SpewLogClosure(rt))
12✔
1132

12✔
1133
        // Since the HTLC hashes and preimages are specified manually over the
12✔
1134
        // RPC for SendToRoute requests, we don't have to worry about creating
12✔
1135
        // a ShardTracker that can generate hashes for AMP payments. Instead, we
12✔
1136
        // create a simple tracker that can just return the hash for the single
12✔
1137
        // shard we'll now launch.
12✔
1138
        shardTracker := shards.NewSimpleShardTracker(htlcHash, nil)
12✔
1139

12✔
1140
        // Create a payment lifecycle using the given route with,
12✔
1141
        // - zero fee limit as we are not requesting routes.
12✔
1142
        // - nil payment session (since we already have a route).
12✔
1143
        // - no payment timeout.
12✔
1144
        // - no current block height.
12✔
1145
        p := newPaymentLifecycle(
12✔
1146
                r, 0, paymentIdentifier, nil, shardTracker, 0,
12✔
1147
                firstHopCustomRecords,
12✔
1148
        )
12✔
1149

12✔
1150
        // Allow the traffic shaper to add custom records to the outgoing HTLC
12✔
1151
        // and also adjust the amount if needed.
12✔
1152
        err = p.amendFirstHopData(rt)
12✔
1153
        if err != nil {
12✔
UNCOV
1154
                return nil, err
×
UNCOV
1155
        }
×
1156

1157
        // We found a route to try, create a new HTLC attempt to try.
1158
        //
1159
        // NOTE: we use zero `remainingAmt` here to simulate the same effect of
1160
        // setting the lastShard to be false, which is used by previous
1161
        // implementation.
1162
        attempt, err := p.registerAttempt(rt, 0)
12✔
1163
        if err != nil {
13✔
1164
                return nil, err
1✔
1165
        }
1✔
1166

1167
        // Once the attempt is created, send it to the htlcswitch. Notice that
1168
        // the `err` returned here has already been processed by
1169
        // `handleSwitchErr`, which means if there's a terminal failure, the
1170
        // payment has been failed.
1171
        result, err := p.sendAttempt(attempt)
11✔
1172
        if err != nil {
11✔
UNCOV
1173
                return nil, err
×
UNCOV
1174
        }
×
1175

1176
        // Since for SendToRoute we won't retry in case the shard fails, we'll
1177
        // mark the payment failed with the control tower immediately if the
1178
        // skipTempErr is false.
1179
        reason := channeldb.FailureReasonError
11✔
1180

11✔
1181
        // If we failed to send the HTLC, we need to further decide if we want
11✔
1182
        // to fail the payment.
11✔
1183
        if result.err != nil {
17✔
1184
                // If skipTempErr, we'll return the attempt and the temp error.
6✔
1185
                if skipTempErr {
8✔
1186
                        return result.attempt, result.err
2✔
1187
                }
2✔
1188

1189
                err := failPayment(paymentIdentifier, reason)
4✔
1190
                if err != nil {
4✔
UNCOV
1191
                        return nil, err
×
UNCOV
1192
                }
×
1193

1194
                return result.attempt, result.err
4✔
1195
        }
1196

1197
        // The attempt was successfully sent, wait for the result to be
1198
        // available.
1199
        result, err = p.collectAndHandleResult(attempt)
8✔
1200
        if err != nil {
8✔
UNCOV
1201
                return nil, err
×
UNCOV
1202
        }
×
1203

1204
        // We got a successful result.
1205
        if result.err == nil {
12✔
1206
                return result.attempt, nil
4✔
1207
        }
4✔
1208

1209
        // An error returned from collecting the result, we'll mark the payment
1210
        // as failed if we don't skip temp error.
1211
        if !skipTempErr {
14✔
1212
                err := failPayment(paymentIdentifier, reason)
7✔
1213
                if err != nil {
7✔
UNCOV
1214
                        return nil, err
×
UNCOV
1215
                }
×
1216
        }
1217

1218
        return result.attempt, result.err
7✔
1219
}
1220

1221
// sendPayment attempts to send a payment to the passed payment hash. This
1222
// function is blocking and will return either: when the payment is successful,
1223
// or all candidates routes have been attempted and resulted in a failed
1224
// payment. If the payment succeeds, then a non-nil Route will be returned
1225
// which describes the path the successful payment traversed within the network
1226
// to reach the destination. Additionally, the payment preimage will also be
1227
// returned.
1228
//
1229
// This method relies on the ControlTower's internal payment state machine to
1230
// carry out its execution. After restarts, it is safe, and assumed, that the
1231
// router will call this method for every payment still in-flight according to
1232
// the ControlTower.
1233
func (r *ChannelRouter) sendPayment(ctx context.Context,
1234
        feeLimit lnwire.MilliSatoshi, identifier lntypes.Hash,
1235
        paymentAttemptTimeout time.Duration, paySession PaymentSession,
1236
        shardTracker shards.ShardTracker,
1237
        firstHopCustomRecords lnwire.CustomRecords) ([32]byte, *route.Route,
1238
        error) {
15✔
1239

15✔
1240
        // If the user provides a timeout, we will additionally wrap the context
15✔
1241
        // in a deadline.
15✔
1242
        cancel := func() {}
30✔
1243
        if paymentAttemptTimeout > 0 {
18✔
1244
                ctx, cancel = context.WithTimeout(ctx, paymentAttemptTimeout)
3✔
1245
        }
3✔
1246

1247
        // Since resumePayment is a blocking call, we'll cancel this
1248
        // context if the payment completes before the optional
1249
        // deadline.
1250
        defer cancel()
15✔
1251

15✔
1252
        // We'll also fetch the current block height, so we can properly
15✔
1253
        // calculate the required HTLC time locks within the route.
15✔
1254
        _, currentHeight, err := r.cfg.Chain.GetBestBlock()
15✔
1255
        if err != nil {
15✔
UNCOV
1256
                return [32]byte{}, nil, err
×
UNCOV
1257
        }
×
1258

1259
        // Validate the custom records before we attempt to send the payment.
1260
        // TODO(ziggie): Move this check before registering the payment in the
1261
        // db (InitPayment).
1262
        if err := firstHopCustomRecords.Validate(); err != nil {
15✔
UNCOV
1263
                return [32]byte{}, nil, err
×
UNCOV
1264
        }
×
1265

1266
        // Now set up a paymentLifecycle struct with these params, such that we
1267
        // can resume the payment from the current state.
1268
        p := newPaymentLifecycle(
15✔
1269
                r, feeLimit, identifier, paySession, shardTracker,
15✔
1270
                currentHeight, firstHopCustomRecords,
15✔
1271
        )
15✔
1272

15✔
1273
        return p.resumePayment(ctx)
15✔
1274
}
1275

1276
// extractChannelUpdate examines the error and extracts the channel update.
1277
func (r *ChannelRouter) extractChannelUpdate(
1278
        failure lnwire.FailureMessage) *lnwire.ChannelUpdate1 {
20✔
1279

20✔
1280
        var update *lnwire.ChannelUpdate1
20✔
1281
        switch onionErr := failure.(type) {
20✔
1282
        case *lnwire.FailExpiryTooSoon:
1✔
1283
                update = &onionErr.Update
1✔
1284
        case *lnwire.FailAmountBelowMinimum:
3✔
1285
                update = &onionErr.Update
3✔
1286
        case *lnwire.FailFeeInsufficient:
10✔
1287
                update = &onionErr.Update
10✔
UNCOV
1288
        case *lnwire.FailIncorrectCltvExpiry:
×
UNCOV
1289
                update = &onionErr.Update
×
1290
        case *lnwire.FailChannelDisabled:
3✔
1291
                update = &onionErr.Update
3✔
1292
        case *lnwire.FailTemporaryChannelFailure:
8✔
1293
                update = onionErr.Update
8✔
1294
        }
1295

1296
        return update
20✔
1297
}
1298

1299
// ErrNoChannel is returned when a route cannot be built because there are no
1300
// channels that satisfy all requirements.
1301
type ErrNoChannel struct {
1302
        position int
1303
}
1304

1305
// Error returns a human-readable string describing the error.
1306
func (e ErrNoChannel) Error() string {
1✔
1307
        return fmt.Sprintf("no matching outgoing channel available for "+
1✔
1308
                "node index %v", e.position)
1✔
1309
}
1✔
1310

1311
// BuildRoute returns a fully specified route based on a list of pubkeys. If
1312
// amount is nil, the minimum routable amount is used. To force a specific
1313
// outgoing channel, use the outgoingChan parameter.
1314
func (r *ChannelRouter) BuildRoute(amt fn.Option[lnwire.MilliSatoshi],
1315
        hops []route.Vertex, outgoingChan *uint64, finalCltvDelta int32,
1316
        payAddr fn.Option[[32]byte], firstHopBlob fn.Option[[]byte]) (
1317
        *route.Route, error) {
11✔
1318

11✔
1319
        log.Tracef("BuildRoute called: hopsCount=%v, amt=%v", len(hops), amt)
11✔
1320

11✔
1321
        var outgoingChans map[uint64]struct{}
11✔
1322
        if outgoingChan != nil {
11✔
1323
                outgoingChans = map[uint64]struct{}{
×
1324
                        *outgoingChan: {},
×
UNCOV
1325
                }
×
UNCOV
1326
        }
×
1327

1328
        // We'll attempt to obtain a set of bandwidth hints that helps us select
1329
        // the best outgoing channel to use in case no outgoing channel is set.
1330
        bandwidthHints, err := newBandwidthManager(
11✔
1331
                r.cfg.RoutingGraph, r.cfg.SelfNode, r.cfg.GetLink, firstHopBlob,
11✔
1332
                r.cfg.TrafficShaper,
11✔
1333
        )
11✔
1334
        if err != nil {
11✔
UNCOV
1335
                return nil, err
×
UNCOV
1336
        }
×
1337

1338
        sourceNode := r.cfg.SelfNode
11✔
1339

11✔
1340
        // We check that each node in the route has a connection to others that
11✔
1341
        // can forward in principle.
11✔
1342
        unifiers, err := getEdgeUnifiers(
11✔
1343
                r.cfg.SelfNode, hops, outgoingChans, r.cfg.RoutingGraph,
11✔
1344
        )
11✔
1345
        if err != nil {
12✔
1346
                return nil, err
1✔
1347
        }
1✔
1348

1349
        var (
10✔
1350
                receiverAmt lnwire.MilliSatoshi
10✔
1351
                senderAmt   lnwire.MilliSatoshi
10✔
1352
                pathEdges   []*unifiedEdge
10✔
1353
        )
10✔
1354

10✔
1355
        // We determine the edges compatible with the requested amount, as well
10✔
1356
        // as the amount to send, which can be used to determine the final
10✔
1357
        // receiver amount, if a minimal amount was requested.
10✔
1358
        pathEdges, senderAmt, err = senderAmtBackwardPass(
10✔
1359
                unifiers, amt, bandwidthHints,
10✔
1360
        )
10✔
1361
        if err != nil {
12✔
1362
                return nil, err
2✔
1363
        }
2✔
1364

1365
        // For the minimal amount search, we need to do a forward pass to find a
1366
        // larger receiver amount due to possible min HTLC bumps, otherwise we
1367
        // just use the requested amount.
1368
        receiverAmt, err = fn.ElimOption(
8✔
1369
                amt,
8✔
1370
                func() fn.Result[lnwire.MilliSatoshi] {
11✔
1371
                        return fn.NewResult(
3✔
1372
                                receiverAmtForwardPass(senderAmt, pathEdges),
3✔
1373
                        )
3✔
1374
                },
3✔
1375
                fn.Ok[lnwire.MilliSatoshi],
1376
        ).Unpack()
1377
        if err != nil {
8✔
UNCOV
1378
                return nil, err
×
UNCOV
1379
        }
×
1380

1381
        // Fetch the current block height outside the routing transaction, to
1382
        // prevent the rpc call blocking the database.
1383
        _, height, err := r.cfg.Chain.GetBestBlock()
8✔
1384
        if err != nil {
8✔
UNCOV
1385
                return nil, err
×
UNCOV
1386
        }
×
1387

1388
        // Build and return the final route.
1389
        return newRoute(
8✔
1390
                sourceNode, pathEdges, uint32(height),
8✔
1391
                finalHopParams{
8✔
1392
                        amt:         receiverAmt,
8✔
1393
                        totalAmt:    receiverAmt,
8✔
1394
                        cltvDelta:   uint16(finalCltvDelta),
8✔
1395
                        records:     nil,
8✔
1396
                        paymentAddr: payAddr,
8✔
1397
                }, nil,
8✔
1398
        )
8✔
1399
}
1400

1401
// resumePayments fetches inflight payments and resumes their payment
1402
// lifecycles.
1403
func (r *ChannelRouter) resumePayments() error {
20✔
1404
        // Get all payments that are inflight.
20✔
1405
        payments, err := r.cfg.Control.FetchInFlightPayments()
20✔
1406
        if err != nil {
20✔
UNCOV
1407
                return err
×
UNCOV
1408
        }
×
1409

1410
        // Before we restart existing payments and start accepting more
1411
        // payments to be made, we clean the network result store of the
1412
        // Switch. We do this here at startup to ensure no more payments can be
1413
        // made concurrently, so we know the toKeep map will be up-to-date
1414
        // until the cleaning has finished.
1415
        toKeep := make(map[uint64]struct{})
20✔
1416
        for _, p := range payments {
23✔
1417
                for _, a := range p.HTLCs {
6✔
1418
                        toKeep[a.AttemptID] = struct{}{}
3✔
1419

3✔
1420
                        // Try to fail the attempt if the route contains a dead
3✔
1421
                        // channel.
3✔
1422
                        r.failStaleAttempt(a, p.Info.PaymentIdentifier)
3✔
1423
                }
3✔
1424
        }
1425

1426
        log.Debugf("Cleaning network result store.")
20✔
1427
        if err := r.cfg.Payer.CleanStore(toKeep); err != nil {
20✔
UNCOV
1428
                return err
×
UNCOV
1429
        }
×
1430

1431
        // launchPayment is a helper closure that handles resuming the payment.
1432
        launchPayment := func(payment *channeldb.MPPayment) {
23✔
1433
                defer r.wg.Done()
3✔
1434

3✔
1435
                // Get the hashes used for the outstanding HTLCs.
3✔
1436
                htlcs := make(map[uint64]lntypes.Hash)
3✔
1437
                for _, a := range payment.HTLCs {
6✔
1438
                        a := a
3✔
1439

3✔
1440
                        // We check whether the individual attempts have their
3✔
1441
                        // HTLC hash set, if not we'll fall back to the overall
3✔
1442
                        // payment hash.
3✔
1443
                        hash := payment.Info.PaymentIdentifier
3✔
1444
                        if a.Hash != nil {
6✔
1445
                                hash = *a.Hash
3✔
1446
                        }
3✔
1447

1448
                        htlcs[a.AttemptID] = hash
3✔
1449
                }
1450

1451
                payHash := payment.Info.PaymentIdentifier
3✔
1452

3✔
1453
                // Since we are not supporting creating more shards after a
3✔
1454
                // restart (only receiving the result of the shards already
3✔
1455
                // outstanding), we create a simple shard tracker that will map
3✔
1456
                // the attempt IDs to hashes used for the HTLCs. This will be
3✔
1457
                // enough also for AMP payments, since we only need the hashes
3✔
1458
                // for the individual HTLCs to regenerate the circuits, and we
3✔
1459
                // don't currently persist the root share necessary to
3✔
1460
                // re-derive them.
3✔
1461
                shardTracker := shards.NewSimpleShardTracker(payHash, htlcs)
3✔
1462

3✔
1463
                // We create a dummy, empty payment session such that we won't
3✔
1464
                // make another payment attempt when the result for the
3✔
1465
                // in-flight attempt is received.
3✔
1466
                paySession := r.cfg.SessionSource.NewPaymentSessionEmpty()
3✔
1467

3✔
1468
                // We pass in a non-timeout context, to indicate we don't need
3✔
1469
                // it to timeout. It will stop immediately after the existing
3✔
1470
                // attempt has finished anyway. We also set a zero fee limit,
3✔
1471
                // as no more routes should be tried.
3✔
1472
                noTimeout := time.Duration(0)
3✔
1473
                _, _, err := r.sendPayment(
3✔
1474
                        context.Background(), 0, payHash, noTimeout, paySession,
3✔
1475
                        shardTracker, payment.Info.FirstHopCustomRecords,
3✔
1476
                )
3✔
1477
                if err != nil {
6✔
1478
                        log.Errorf("Resuming payment %v failed: %v", payHash,
3✔
1479
                                err)
3✔
1480

3✔
1481
                        return
3✔
1482
                }
3✔
1483

1484
                log.Infof("Resumed payment %v completed", payHash)
3✔
1485
        }
1486

1487
        for _, payment := range payments {
23✔
1488
                log.Infof("Resuming payment %v", payment.Info.PaymentIdentifier)
3✔
1489

3✔
1490
                r.wg.Add(1)
3✔
1491
                go launchPayment(payment)
3✔
1492
        }
3✔
1493

1494
        return nil
20✔
1495
}
1496

1497
// failStaleAttempt will fail an HTLC attempt if it's using an unknown channel
1498
// in its route. It first consults the switch to see if there's already a
1499
// network result stored for this attempt. If not, it will check whether the
1500
// first hop of this attempt is using an active channel known to us. If
1501
// inactive, this attempt will be failed.
1502
//
1503
// NOTE: there's an unknown bug that caused the network result for a particular
1504
// attempt to NOT be saved, resulting a payment being stuck forever. More info:
1505
// - https://github.com/lightningnetwork/lnd/issues/8146
1506
// - https://github.com/lightningnetwork/lnd/pull/8174
1507
func (r *ChannelRouter) failStaleAttempt(a channeldb.HTLCAttempt,
1508
        payHash lntypes.Hash) {
3✔
1509

3✔
1510
        // We can only fail inflight HTLCs so we skip the settled/failed ones.
3✔
1511
        if a.Failure != nil || a.Settle != nil {
3✔
UNCOV
1512
                return
×
UNCOV
1513
        }
×
1514

1515
        // First, check if we've already had a network result for this attempt.
1516
        // If no result is found, we'll check whether the reference link is
1517
        // still known to us.
1518
        ok, err := r.cfg.Payer.HasAttemptResult(a.AttemptID)
3✔
1519
        if err != nil {
3✔
1520
                log.Errorf("Failed to fetch network result for attempt=%v",
×
1521
                        a.AttemptID)
×
UNCOV
1522
                return
×
UNCOV
1523
        }
×
1524

1525
        // There's already a network result, no need to fail it here as the
1526
        // payment lifecycle will take care of it, so we can exit early.
1527
        if ok {
3✔
1528
                log.Debugf("Already have network result for attempt=%v",
×
1529
                        a.AttemptID)
×
UNCOV
1530
                return
×
UNCOV
1531
        }
×
1532

1533
        // We now need to decide whether this attempt should be failed here.
1534
        // For very old payments, it's possible that the network results were
1535
        // never saved, causing the payments to be stuck inflight. We now check
1536
        // whether the first hop is referencing an active channel ID and, if
1537
        // not, we will fail the attempt as it has no way to be retried again.
1538
        var shouldFail bool
3✔
1539

3✔
1540
        // Validate that the attempt has hop info. If this attempt has no hop
3✔
1541
        // info it indicates an error in our db.
3✔
1542
        if len(a.Route.Hops) == 0 {
3✔
1543
                log.Errorf("Found empty hop for attempt=%v", a.AttemptID)
×
UNCOV
1544

×
UNCOV
1545
                shouldFail = true
×
1546
        } else {
3✔
1547
                // Get the short channel ID.
3✔
1548
                chanID := a.Route.Hops[0].ChannelID
3✔
1549
                scid := lnwire.NewShortChanIDFromInt(chanID)
3✔
1550

3✔
1551
                // Check whether this link is active. If so, we won't fail the
3✔
1552
                // attempt but keep waiting for its result.
3✔
1553
                _, err := r.cfg.GetLink(scid)
3✔
1554
                if err == nil {
3✔
UNCOV
1555
                        return
×
UNCOV
1556
                }
×
1557

1558
                // We should get the link not found err. If not, we will log an
1559
                // error and skip failing this attempt since an unknown error
1560
                // occurred.
1561
                if !errors.Is(err, htlcswitch.ErrChannelLinkNotFound) {
3✔
1562
                        log.Errorf("Failed to get link for attempt=%v for "+
×
1563
                                "payment=%v: %v", a.AttemptID, payHash, err)
×
1564

×
UNCOV
1565
                        return
×
UNCOV
1566
                }
×
1567

1568
                // The channel link is not active, we now check whether this
1569
                // channel is already closed. If so, we fail the HTLC attempt
1570
                // as there's no need to wait for its network result because
1571
                // there's no link. If the channel is still pending, we'll keep
1572
                // waiting for the result as we may get a contract resolution
1573
                // for this HTLC.
1574
                if _, ok := r.cfg.ClosedSCIDs[scid]; ok {
3✔
UNCOV
1575
                        shouldFail = true
×
UNCOV
1576
                }
×
1577
        }
1578

1579
        // Exit if there's no need to fail.
1580
        if !shouldFail {
6✔
1581
                return
3✔
1582
        }
3✔
1583

1584
        log.Errorf("Failing stale attempt=%v for payment=%v", a.AttemptID,
×
1585
                payHash)
×
1586

×
1587
        // Fail the attempt in db. If there's an error, there's nothing we can
×
1588
        // do here but logging it.
×
1589
        failInfo := &channeldb.HTLCFailInfo{
×
1590
                Reason:   channeldb.HTLCFailUnknown,
×
1591
                FailTime: r.cfg.Clock.Now(),
×
1592
        }
×
1593
        _, err = r.cfg.Control.FailAttempt(payHash, a.AttemptID, failInfo)
×
1594
        if err != nil {
×
UNCOV
1595
                log.Errorf("Fail attempt=%v got error: %v", a.AttemptID, err)
×
UNCOV
1596
        }
×
1597
}
1598

1599
// getEdgeUnifiers returns a list of edge unifiers for the given route.
1600
func getEdgeUnifiers(source route.Vertex, hops []route.Vertex,
1601
        outgoingChans map[uint64]struct{},
1602
        graph Graph) ([]*edgeUnifier, error) {
11✔
1603

11✔
1604
        // Allocate a list that will contain the edge unifiers for this route.
11✔
1605
        unifiers := make([]*edgeUnifier, len(hops))
11✔
1606

11✔
1607
        // Traverse hops backwards to accumulate fees in the running amounts.
11✔
1608
        for i := len(hops) - 1; i >= 0; i-- {
27✔
1609
                toNode := hops[i]
16✔
1610

16✔
1611
                var fromNode route.Vertex
16✔
1612
                if i == 0 {
25✔
1613
                        fromNode = source
9✔
1614
                } else {
19✔
1615
                        fromNode = hops[i-1]
10✔
1616
                }
10✔
1617

1618
                // Build unified policies for this hop based on the channels
1619
                // known in the graph. Inbound fees are only active if the edge
1620
                // is not the last hop.
1621
                isExitHop := i == len(hops)-1
16✔
1622
                u := newNodeEdgeUnifier(
16✔
1623
                        source, toNode, !isExitHop, outgoingChans,
16✔
1624
                )
16✔
1625

16✔
1626
                err := u.addGraphPolicies(graph)
16✔
1627
                if err != nil {
16✔
UNCOV
1628
                        return nil, err
×
UNCOV
1629
                }
×
1630

1631
                // Exit if there are no channels.
1632
                edgeUnifier, ok := u.edgeUnifiers[fromNode]
16✔
1633
                if !ok {
17✔
1634
                        log.Errorf("Cannot find policy for node %v", fromNode)
1✔
1635
                        return nil, ErrNoChannel{position: i}
1✔
1636
                }
1✔
1637

1638
                unifiers[i] = edgeUnifier
15✔
1639
        }
1640

1641
        return unifiers, nil
10✔
1642
}
1643

1644
// senderAmtBackwardPass returns a list of unified edges for the given route and
1645
// determines the amount that should be sent to fulfill min HTLC requirements.
1646
// The minimal sender amount can be searched for by using amt=None.
1647
func senderAmtBackwardPass(unifiers []*edgeUnifier,
1648
        amt fn.Option[lnwire.MilliSatoshi],
1649
        bandwidthHints bandwidthHints) ([]*unifiedEdge, lnwire.MilliSatoshi,
1650
        error) {
14✔
1651

14✔
1652
        if len(unifiers) == 0 {
15✔
1653
                return nil, 0, fmt.Errorf("no unifiers provided")
1✔
1654
        }
1✔
1655

1656
        var unifiedEdges = make([]*unifiedEdge, len(unifiers))
13✔
1657

13✔
1658
        // We traverse the route backwards and handle the last hop separately.
13✔
1659
        edgeUnifier := unifiers[len(unifiers)-1]
13✔
1660

13✔
1661
        // incomingAmt tracks the amount that is forwarded on the edges of a
13✔
1662
        // route. The last hop only forwards the amount that the receiver should
13✔
1663
        // receive, as there are no fees paid to the last node.
13✔
1664
        // For minimum amount routes, aim to deliver at least 1 msat to
13✔
1665
        // the destination. There are nodes in the wild that have a
13✔
1666
        // min_htlc channel policy of zero, which could lead to a zero
13✔
1667
        // amount payment being made.
13✔
1668
        incomingAmt := amt.UnwrapOr(1)
13✔
1669

13✔
1670
        // If using min amt, increase the amount if needed to fulfill min HTLC
13✔
1671
        // requirements.
13✔
1672
        if amt.IsNone() {
18✔
1673
                min := edgeUnifier.minAmt()
5✔
1674
                if min > incomingAmt {
10✔
1675
                        incomingAmt = min
5✔
1676
                }
5✔
1677
        }
1678

1679
        // Get an edge for the specific amount that we want to forward.
1680
        edge := edgeUnifier.getEdge(incomingAmt, bandwidthHints, 0)
13✔
1681
        if edge == nil {
14✔
1682
                log.Errorf("Cannot find policy with amt=%v "+
1✔
1683
                        "for hop %v", incomingAmt, len(unifiers)-1)
1✔
1684

1✔
1685
                return nil, 0, ErrNoChannel{position: len(unifiers) - 1}
1✔
1686
        }
1✔
1687

1688
        unifiedEdges[len(unifiers)-1] = edge
12✔
1689

12✔
1690
        // Handle the rest of the route except the last hop.
12✔
1691
        for i := len(unifiers) - 2; i >= 0; i-- {
27✔
1692
                edgeUnifier = unifiers[i]
15✔
1693

15✔
1694
                // If using min amt, increase the amount if needed to fulfill
15✔
1695
                // min HTLC requirements.
15✔
1696
                if amt.IsNone() {
21✔
1697
                        min := edgeUnifier.minAmt()
6✔
1698
                        if min > incomingAmt {
6✔
UNCOV
1699
                                incomingAmt = min
×
UNCOV
1700
                        }
×
1701
                }
1702

1703
                // A --current hop-- B --next hop: incomingAmt-- C
1704
                // The outbound fee paid to the current end node B is based on
1705
                // the amount that the next hop forwards and B's policy for that
1706
                // hop.
1707
                outboundFee := unifiedEdges[i+1].policy.ComputeFee(
15✔
1708
                        incomingAmt,
15✔
1709
                )
15✔
1710

15✔
1711
                netAmount := incomingAmt + outboundFee
15✔
1712

15✔
1713
                // We need to select an edge that can forward the requested
15✔
1714
                // amount.
15✔
1715
                edge = edgeUnifier.getEdge(
15✔
1716
                        netAmount, bandwidthHints, outboundFee,
15✔
1717
                )
15✔
1718
                if edge == nil {
16✔
1719
                        return nil, 0, ErrNoChannel{position: i}
1✔
1720
                }
1✔
1721

1722
                // The fee paid to B depends on the current hop's inbound fee
1723
                // policy and on the outbound fee for the next hop as any
1724
                // inbound fee discount is capped by the outbound fee such that
1725
                // the total fee for B can't become negative.
1726
                inboundFee := calcCappedInboundFee(edge, netAmount, outboundFee)
14✔
1727

14✔
1728
                fee := lnwire.MilliSatoshi(int64(outboundFee) + inboundFee)
14✔
1729

14✔
1730
                log.Tracef("Select channel %v at position %v",
14✔
1731
                        edge.policy.ChannelID, i)
14✔
1732

14✔
1733
                // Finally, we update the amount that needs to flow into node B
14✔
1734
                // from A, which is the next hop's forwarding amount plus the
14✔
1735
                // fee for B: A --current hop: incomingAmt-- B --next hop-- C
14✔
1736
                incomingAmt += fee
14✔
1737

14✔
1738
                unifiedEdges[i] = edge
14✔
1739
        }
1740

1741
        return unifiedEdges, incomingAmt, nil
11✔
1742
}
1743

1744
// receiverAmtForwardPass returns the amount that a receiver will receive after
1745
// deducting all fees from the sender amount.
1746
func receiverAmtForwardPass(runningAmt lnwire.MilliSatoshi,
1747
        unifiedEdges []*unifiedEdge) (lnwire.MilliSatoshi, error) {
10✔
1748

10✔
1749
        if len(unifiedEdges) == 0 {
11✔
1750
                return 0, fmt.Errorf("no edges to forward through")
1✔
1751
        }
1✔
1752

1753
        inEdge := unifiedEdges[0]
9✔
1754
        if !inEdge.amtInRange(runningAmt) {
10✔
1755
                log.Errorf("Amount %v not in range for hop index %v",
1✔
1756
                        runningAmt, 0)
1✔
1757

1✔
1758
                return 0, ErrNoChannel{position: 0}
1✔
1759
        }
1✔
1760

1761
        // Now that we arrived at the start of the route and found out the route
1762
        // total amount, we make a forward pass. Because the amount may have
1763
        // been increased in the backward pass, fees need to be recalculated and
1764
        // amount ranges re-checked.
1765
        for i := 1; i < len(unifiedEdges); i++ {
17✔
1766
                inEdge := unifiedEdges[i-1]
9✔
1767
                outEdge := unifiedEdges[i]
9✔
1768

9✔
1769
                // Decrease the amount to send while going forward.
9✔
1770
                runningAmt = outgoingFromIncoming(runningAmt, inEdge, outEdge)
9✔
1771

9✔
1772
                if !outEdge.amtInRange(runningAmt) {
9✔
1773
                        log.Errorf("Amount %v not in range for hop index %v",
×
1774
                                runningAmt, i)
×
1775

×
UNCOV
1776
                        return 0, ErrNoChannel{position: i}
×
UNCOV
1777
                }
×
1778
        }
1779

1780
        return runningAmt, nil
8✔
1781
}
1782

1783
// incomingFromOutgoing computes the incoming amount based on the outgoing
1784
// amount by adding fees to the outgoing amount, replicating the path finding
1785
// and routing process, see also CheckHtlcForward.
1786
func incomingFromOutgoing(outgoingAmt lnwire.MilliSatoshi,
1787
        incoming, outgoing *unifiedEdge) lnwire.MilliSatoshi {
31✔
1788

31✔
1789
        outgoingFee := outgoing.policy.ComputeFee(outgoingAmt)
31✔
1790

31✔
1791
        // Net amount is the amount the inbound fees are calculated with.
31✔
1792
        netAmount := outgoingAmt + outgoingFee
31✔
1793

31✔
1794
        inboundFee := incoming.inboundFees.CalcFee(netAmount)
31✔
1795

31✔
1796
        // The inbound fee is not allowed to reduce the incoming amount below
31✔
1797
        // the outgoing amount.
31✔
1798
        if int64(outgoingFee)+inboundFee < 0 {
40✔
1799
                return outgoingAmt
9✔
1800
        }
9✔
1801

1802
        return netAmount + lnwire.MilliSatoshi(inboundFee)
22✔
1803
}
1804

1805
// outgoingFromIncoming computes the outgoing amount based on the incoming
1806
// amount by subtracting fees from the incoming amount. Note that this is not
1807
// exactly the inverse of incomingFromOutgoing, because of some rounding.
1808
func outgoingFromIncoming(incomingAmt lnwire.MilliSatoshi,
1809
        incoming, outgoing *unifiedEdge) lnwire.MilliSatoshi {
40✔
1810

40✔
1811
        // Convert all quantities to big.Int to be able to hande negative
40✔
1812
        // values. The formulas to compute the outgoing amount involve terms
40✔
1813
        // with PPM*PPM*A, which can easily overflow an int64.
40✔
1814
        A := big.NewInt(int64(incomingAmt))
40✔
1815
        Ro := big.NewInt(int64(outgoing.policy.FeeProportionalMillionths))
40✔
1816
        Bo := big.NewInt(int64(outgoing.policy.FeeBaseMSat))
40✔
1817
        Ri := big.NewInt(int64(incoming.inboundFees.Rate))
40✔
1818
        Bi := big.NewInt(int64(incoming.inboundFees.Base))
40✔
1819
        PPM := big.NewInt(1_000_000)
40✔
1820

40✔
1821
        // The following discussion was contributed by user feelancer21, see
40✔
1822
        //nolint:ll
40✔
1823
        // https://github.com/feelancer21/lnd/commit/f6f05fa930985aac0d27c3f6681aada1b599162a.
40✔
1824

40✔
1825
        // The incoming amount Ai based on the outgoing amount Ao is computed by
40✔
1826
        // Ai = max(Ai(Ao), Ao), which caps the incoming amount such that the
40✔
1827
        // total node fee (Ai - Ao) is non-negative. This is commonly enforced
40✔
1828
        // by routing nodes.
40✔
1829

40✔
1830
        // The function Ai(Ao) is given by:
40✔
1831
        // Ai(Ao) = (Ao + Bo + Ro/PPM) + (Bi + (Ao + Ro/PPM + Bo)*Ri/PPM), where
40✔
1832
        // the first term is the net amount (the outgoing amount plus the
40✔
1833
        // outbound fee), and the second is the inbound fee computed based on
40✔
1834
        // the net amount.
40✔
1835

40✔
1836
        // Ai(Ao) can potentially become more negative in absolute value than
40✔
1837
        // Ao, which is why the above mentioned capping is needed. We can
40✔
1838
        // abbreviate Ai(Ao) with Ai(Ao) = m*Ao + n, where m and n are:
40✔
1839
        // m := (1 + Ro/PPM) * (1 + Ri/PPM)
40✔
1840
        // n := Bi + Bo*(1 + Ri/PPM)
40✔
1841

40✔
1842
        // If we know that m > 0, this is equivalent of Ri/PPM > -1, because Ri
40✔
1843
        // is the only factor that can become negative. A value or Ri/PPM = -1,
40✔
1844
        // means that the routing node is willing to give up on 100% of the
40✔
1845
        // net amount (based on the fee rate), which is likely to not happen in
40✔
1846
        // practice. This condition will be important for a later trick.
40✔
1847

40✔
1848
        // If we want to compute the incoming amount based on the outgoing
40✔
1849
        // amount, which is the reverse problem, we need to solve Ai =
40✔
1850
        // max(Ai(Ao), Ao) for Ao(Ai). Given an incoming amount A,
40✔
1851
        // we look for an Ao such that A = max(Ai(Ao), Ao).
40✔
1852

40✔
1853
        // The max function separates this into two cases. The case to take is
40✔
1854
        // not clear yet, because we don't know Ao, but later we see a trick
40✔
1855
        // how to determine which case is the one to take.
40✔
1856

40✔
1857
        // first case: Ai(Ao) <= Ao:
40✔
1858
        // Therefore, A = max(Ai(Ao), Ao) = Ao, we find Ao = A.
40✔
1859
        // This also leads to Ai(A) <= A by substitution into the condition.
40✔
1860

40✔
1861
        // second case: Ai(Ao) > Ao:
40✔
1862
        // Therefore, A = max(Ai(Ao), Ao) = Ai(Ao) = m*Ao + n. Solving for Ao
40✔
1863
        // gives Ao = (A - n)/m.
40✔
1864
        //
40✔
1865
        // We know
40✔
1866
        // Ai(Ao) > Ao  <=>  A = Ai(Ao) > Ao = (A - n)/m,
40✔
1867
        // so A > (A - n)/m.
40✔
1868
        //
40✔
1869
        // **Assuming m > 0**, by multiplying with m, we can transform this to
40✔
1870
        // A * m + n > A.
40✔
1871
        //
40✔
1872
        // We know Ai(A) = A*m + n, therefore Ai(A) > A.
40✔
1873
        //
40✔
1874
        // This means that if we apply the incoming amount calculation to the
40✔
1875
        // **incoming** amount, and this condition holds, then we know that we
40✔
1876
        // deal with the second case, being able to compute the outgoing amount
40✔
1877
        // based off the formula Ao = (A - n)/m, otherwise we will just return
40✔
1878
        // the incoming amount.
40✔
1879

40✔
1880
        // In case the inbound fee rate is less than -1 (-100%), we fail to
40✔
1881
        // compute the outbound amount and return the incoming amount. This also
40✔
1882
        // protects against zero division later.
40✔
1883

40✔
1884
        // We compute m in terms of big.Int to be safe from overflows and to be
40✔
1885
        // consistent with later calculations.
40✔
1886
        // m := (PPM*PPM + Ri*PPM + Ro*PPM + Ro*Ri)/(PPM*PPM)
40✔
1887

40✔
1888
        // Compute terms in (PPM*PPM + Ri*PPM + Ro*PPM + Ro*Ri).
40✔
1889
        m1 := new(big.Int).Mul(PPM, PPM)
40✔
1890
        m2 := new(big.Int).Mul(Ri, PPM)
40✔
1891
        m3 := new(big.Int).Mul(Ro, PPM)
40✔
1892
        m4 := new(big.Int).Mul(Ro, Ri)
40✔
1893

40✔
1894
        // Add up terms m1..m4.
40✔
1895
        m := big.NewInt(0)
40✔
1896
        m.Add(m, m1)
40✔
1897
        m.Add(m, m2)
40✔
1898
        m.Add(m, m3)
40✔
1899
        m.Add(m, m4)
40✔
1900

40✔
1901
        // Since we compare to 0, we can multiply by PPM*PPM to avoid the
40✔
1902
        // division.
40✔
1903
        if m.Int64() <= 0 {
42✔
1904
                return incomingAmt
2✔
1905
        }
2✔
1906

1907
        // In order to decide if the total fee is negative, we apply the fee
1908
        // to the *incoming* amount as mentioned before.
1909

1910
        // We compute the test amount in terms of big.Int to be safe from
1911
        // overflows and to be consistent later calculations.
1912
        // testAmtF := A*m + n =
1913
        // = A + Bo + Bi + (PPM*(A*Ri + A*Ro + Ro*Ri) + A*Ri*Ro)/(PPM*PPM)
1914

1915
        // Compute terms in (A*Ri + A*Ro + Ro*Ri).
1916
        t1 := new(big.Int).Mul(A, Ri)
38✔
1917
        t2 := new(big.Int).Mul(A, Ro)
38✔
1918
        t3 := new(big.Int).Mul(Ro, Ri)
38✔
1919

38✔
1920
        // Sum up terms t1-t3.
38✔
1921
        t4 := big.NewInt(0)
38✔
1922
        t4.Add(t4, t1)
38✔
1923
        t4.Add(t4, t2)
38✔
1924
        t4.Add(t4, t3)
38✔
1925

38✔
1926
        // Compute PPM*(A*Ri + A*Ro + Ro*Ri).
38✔
1927
        t6 := new(big.Int).Mul(PPM, t4)
38✔
1928

38✔
1929
        // Compute A*Ri*Ro.
38✔
1930
        t7 := new(big.Int).Mul(A, Ri)
38✔
1931
        t7.Mul(t7, Ro)
38✔
1932

38✔
1933
        // Compute (PPM*(A*Ri + A*Ro + Ro*Ri) + A*Ri*Ro)/(PPM*PPM).
38✔
1934
        num := new(big.Int).Add(t6, t7)
38✔
1935
        denom := new(big.Int).Mul(PPM, PPM)
38✔
1936
        fraction := new(big.Int).Div(num, denom)
38✔
1937

38✔
1938
        // Sum up all terms.
38✔
1939
        testAmt := big.NewInt(0)
38✔
1940
        testAmt.Add(testAmt, A)
38✔
1941
        testAmt.Add(testAmt, Bo)
38✔
1942
        testAmt.Add(testAmt, Bi)
38✔
1943
        testAmt.Add(testAmt, fraction)
38✔
1944

38✔
1945
        // Protect against negative values for the integer cast to Msat.
38✔
1946
        if testAmt.Int64() < 0 {
42✔
1947
                return incomingAmt
4✔
1948
        }
4✔
1949

1950
        // If the second case holds, we have to compute the outgoing amount.
1951
        if lnwire.MilliSatoshi(testAmt.Int64()) > incomingAmt {
62✔
1952
                // Compute the outgoing amount by integer ceiling division. This
28✔
1953
                // precision is needed because PPM*PPM*A and other terms can
28✔
1954
                // easily overflow with int64, which happens with about
28✔
1955
                // A = 10_000 sat.
28✔
1956

28✔
1957
                // out := (A - n) / m = numerator / denominator
28✔
1958
                // numerator := PPM*(PPM*(A - Bo - Bi) - Bo*Ri)
28✔
1959
                // denominator := PPM*(PPM + Ri + Ro) + Ri*Ro
28✔
1960

28✔
1961
                var numerator big.Int
28✔
1962

28✔
1963
                // Compute (A - Bo - Bi).
28✔
1964
                temp1 := new(big.Int).Sub(A, Bo)
28✔
1965
                temp2 := new(big.Int).Sub(temp1, Bi)
28✔
1966

28✔
1967
                // Compute terms in (PPM*(A - Bo - Bi) - Bo*Ri).
28✔
1968
                temp3 := new(big.Int).Mul(PPM, temp2)
28✔
1969
                temp4 := new(big.Int).Mul(Bo, Ri)
28✔
1970

28✔
1971
                // Compute PPM*(PPM*(A - Bo - Bi) - Bo*Ri)
28✔
1972
                temp5 := new(big.Int).Sub(temp3, temp4)
28✔
1973
                numerator.Mul(PPM, temp5)
28✔
1974

28✔
1975
                var denominator big.Int
28✔
1976

28✔
1977
                // Compute (PPM + Ri + Ro).
28✔
1978
                temp1 = new(big.Int).Add(PPM, Ri)
28✔
1979
                temp2 = new(big.Int).Add(temp1, Ro)
28✔
1980

28✔
1981
                // Compute PPM*(PPM + Ri + Ro) + Ri*Ro.
28✔
1982
                temp3 = new(big.Int).Mul(PPM, temp2)
28✔
1983
                temp4 = new(big.Int).Mul(Ri, Ro)
28✔
1984
                denominator.Add(temp3, temp4)
28✔
1985

28✔
1986
                // We overestimate the outgoing amount by taking the ceiling of
28✔
1987
                // the division. This means that we may round slightly up by a
28✔
1988
                // MilliSatoshi, but this helps to ensure that we don't hit min
28✔
1989
                // HTLC constrains in the context of finding the minimum amount
28✔
1990
                // of a route.
28✔
1991
                // ceil = floor((numerator + denominator - 1) / denominator)
28✔
1992
                ceil := new(big.Int).Add(&numerator, &denominator)
28✔
1993
                ceil.Sub(ceil, big.NewInt(1))
28✔
1994
                ceil.Div(ceil, &denominator)
28✔
1995

28✔
1996
                return lnwire.MilliSatoshi(ceil.Int64())
28✔
1997
        }
28✔
1998

1999
        // Otherwise the inbound fee made up for the outbound fee, which is why
2000
        // we just return the incoming amount.
2001
        return incomingAmt
6✔
2002
}
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