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

lightningnetwork / lnd / 16291181271

15 Jul 2025 10:47AM UTC coverage: 57.167% (-10.2%) from 67.349%
16291181271

Pull #9822

github

web-flow
Merge dabf3ae6a into 302551ade
Pull Request #9822: Refactor Payments Code (Head PR for refactor to make sure the itest pass)

650 of 2407 new or added lines in 25 files covered. (27.0%)

28129 existing lines in 454 files now uncovered.

98745 of 172731 relevant lines covered (57.17%)

1.77 hits per line

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

60.32
/routing/router.go
1
package routing
2

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

14
        "github.com/btcsuite/btcd/btcec/v2"
15
        "github.com/btcsuite/btcd/btcutil"
16
        "github.com/davecgh/go-spew/spew"
17
        "github.com/lightningnetwork/lnd/amp"
18
        "github.com/lightningnetwork/lnd/clock"
19
        "github.com/lightningnetwork/lnd/fn/v2"
20
        "github.com/lightningnetwork/lnd/graph/db/models"
21
        "github.com/lightningnetwork/lnd/htlcswitch"
22
        "github.com/lightningnetwork/lnd/lntypes"
23
        "github.com/lightningnetwork/lnd/lnutils"
24
        "github.com/lightningnetwork/lnd/lnwallet"
25
        "github.com/lightningnetwork/lnd/lnwire"
26
        pymtpkgDB "github.com/lightningnetwork/lnd/payments/db"
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
                *pymtpkgDB.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
        //
280
        // TODO(ziggie): Needs to be renamed to NextAttemptID.
281
        NextPaymentID func() (uint64, error)
282

283
        // PathFindingConfig defines global path finding parameters.
284
        PathFindingConfig PathFindingConfig
285

286
        // Clock is mockable time provider.
287
        Clock clock.Clock
288

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

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

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

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

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

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

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

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

334
        quit chan struct{}
335
        wg   sync.WaitGroup
336
}
337

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

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

358
        log.Info("Channel Router starting")
3✔
359

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

366
        return nil
3✔
367
}
368

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

377
        log.Info("Channel Router shutting down...")
3✔
378
        defer log.Debug("Channel Router shutdown complete")
3✔
379

3✔
380
        close(r.quit)
3✔
381
        r.wg.Wait()
3✔
382

3✔
383
        return nil
3✔
384
}
385

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

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

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

402
        // TimePreference expresses the caller's time preference for
403
        // pathfinding.
404
        TimePreference float64
405

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

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

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

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

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

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

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

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

3✔
451
        if blindedPathSet != nil {
6✔
452
                if blindedPathSet.IsIntroNode(source) {
3✔
UNCOV
453
                        return nil, ErrSelfIntro
×
UNCOV
454
                }
×
455

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

462
                if finalExpiry != 0 {
3✔
UNCOV
463
                        return nil, ErrExpiryAndBlinded
×
UNCOV
464
                }
×
465

466
                requestExpiry = blindedPathSet.FinalCLTVDelta()
3✔
467

3✔
468
                requestHints, err = blindedPathSet.ToRouteHints()
3✔
469
                if err != nil {
3✔
470
                        return nil, err
×
471
                }
×
472
        }
473

474
        requestTarget, err := getTargetNode(target, blindedPathSet)
3✔
475
        if err != nil {
3✔
UNCOV
476
                return nil, err
×
UNCOV
477
        }
×
478

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

492
func getTargetNode(target *route.Vertex,
493
        blindedPathSet *BlindedPaymentPathSet) (route.Vertex, error) {
3✔
494

3✔
495
        var (
3✔
496
                blinded   = blindedPathSet != nil
3✔
497
                targetSet = target != nil
3✔
498
        )
3✔
499

3✔
500
        switch {
3✔
UNCOV
501
        case blinded && targetSet:
×
UNCOV
502
                return route.Vertex{}, ErrTargetAndBlinded
×
503

504
        case blinded:
3✔
505
                return route.NewVertex(blindedPathSet.TargetPubKey()), nil
3✔
506

507
        case targetSet:
3✔
508
                return *target, nil
3✔
509

510
        default:
×
511
                return route.Vertex{}, ErrNoTarget
×
512
        }
513
}
514

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

3✔
521
        log.Debugf("Searching for path to %v, sending %v", req.Target,
3✔
522
                req.Amount)
3✔
523

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

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

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

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

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

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

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

3✔
582
        return route, probability, nil
3✔
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
        // IncomingChainedChannels holds the chained channels list (specified
617
        // via channel id) starting from a channel which points to the receiver
618
        // node.
619
        IncomingChainedChannels []uint64
620
}
621

622
// FindBlindedPaths finds a selection of paths to the destination node that can
623
// be used in blinded payment paths.
624
func (r *ChannelRouter) FindBlindedPaths(destination route.Vertex,
625
        amt lnwire.MilliSatoshi, probabilitySrc probabilitySource,
626
        restrictions *BlindedPathRestrictions) ([]*route.Route, error) {
3✔
627

3✔
628
        // First, find a set of candidate paths given the destination node and
3✔
629
        // path length restrictions.
3✔
630
        incomingChainedChannels := restrictions.IncomingChainedChannels
3✔
631
        minDistanceFromIntroNode := restrictions.MinDistanceFromIntroNode
3✔
632
        paths, err := findBlindedPaths(
3✔
633
                r.cfg.RoutingGraph, destination, &blindedPathRestrictions{
3✔
634
                        minNumHops:              minDistanceFromIntroNode,
3✔
635
                        maxNumHops:              restrictions.NumHops,
3✔
636
                        nodeOmissionSet:         restrictions.NodeOmissionSet,
3✔
637
                        incomingChainedChannels: incomingChainedChannels,
3✔
638
                },
3✔
639
        )
3✔
640
        if err != nil {
6✔
641
                return nil, err
3✔
642
        }
3✔
643

644
        // routeWithProbability groups a route with the probability of a
645
        // payment of the given amount succeeding on that path.
646
        type routeWithProbability struct {
3✔
647
                route       *route.Route
3✔
648
                probability float64
3✔
649
        }
3✔
650

3✔
651
        // Iterate over all the candidate paths and determine the success
3✔
652
        // probability of each path given the data we have about forwards
3✔
653
        // between any two nodes on a path.
3✔
654
        routes := make([]*routeWithProbability, 0, len(paths))
3✔
655
        for _, path := range paths {
6✔
656
                if len(path) < 1 {
3✔
657
                        return nil, fmt.Errorf("a blinded path must have at " +
×
658
                                "least one hop")
×
659
                }
×
660

661
                var (
3✔
662
                        introNode = path[0].vertex
3✔
663
                        prevNode  = introNode
3✔
664
                        hops      = make(
3✔
665
                                []*route.Hop, 0, len(path)-1,
3✔
666
                        )
3✔
667
                        totalRouteProbability = float64(1)
3✔
668
                )
3✔
669

3✔
670
                // For each set of hops on the path, get the success probability
3✔
671
                // of a forward between those two vertices and use that to
3✔
672
                // update the overall route probability.
3✔
673
                for j := 1; j < len(path); j++ {
6✔
674
                        probability := probabilitySrc(
3✔
675
                                prevNode, path[j].vertex, amt,
3✔
676
                                path[j-1].edgeCapacity,
3✔
677
                        )
3✔
678

3✔
679
                        totalRouteProbability *= probability
3✔
680

3✔
681
                        hops = append(hops, &route.Hop{
3✔
682
                                PubKeyBytes: path[j].vertex,
3✔
683
                                ChannelID:   path[j-1].channelID,
3✔
684
                        })
3✔
685

3✔
686
                        prevNode = path[j].vertex
3✔
687
                }
3✔
688

689
                routeWithProbability := &routeWithProbability{
3✔
690
                        route: &route.Route{
3✔
691
                                SourcePubKey: introNode,
3✔
692
                                Hops:         hops,
3✔
693
                        },
3✔
694
                        probability: totalRouteProbability,
3✔
695
                }
3✔
696

3✔
697
                // Don't bother adding a route if its success probability less
3✔
698
                // minimum that can be assigned to any single pair.
3✔
699
                if totalRouteProbability <= DefaultMinRouteProbability {
3✔
UNCOV
700
                        log.Debugf("Not using route (%v) as a blinded "+
×
UNCOV
701
                                "path since it resulted in an low "+
×
UNCOV
702
                                "probability path(%.3f)",
×
UNCOV
703
                                route.ChanIDString(routeWithProbability.route),
×
UNCOV
704
                                routeWithProbability.probability)
×
UNCOV
705

×
UNCOV
706
                        continue
×
707
                }
708

709
                routes = append(routes, routeWithProbability)
3✔
710
        }
711

712
        // Sort the routes based on probability.
713
        sort.Slice(routes, func(i, j int) bool {
6✔
714
                return routes[i].probability > routes[j].probability
3✔
715
        })
3✔
716

717
        // Now just choose the best paths up until the maximum number of allowed
718
        // paths.
719
        bestRoutes := make([]*route.Route, 0, restrictions.MaxNumPaths)
3✔
720
        for _, route := range routes {
6✔
721
                if len(bestRoutes) >= int(restrictions.MaxNumPaths) {
3✔
UNCOV
722
                        break
×
723
                }
724

725
                bestRoutes = append(bestRoutes, route.route)
3✔
726
        }
727

728
        return bestRoutes, nil
3✔
729
}
730

731
// generateNewSessionKey generates a new ephemeral private key to be used for a
732
// payment attempt.
733
func generateNewSessionKey() (*btcec.PrivateKey, error) {
3✔
734
        // Generate a new random session key to ensure that we don't trigger
3✔
735
        // any replay.
3✔
736
        //
3✔
737
        // TODO(roasbeef): add more sources of randomness?
3✔
738
        return btcec.NewPrivateKey()
3✔
739
}
3✔
740

741
// LightningPayment describes a payment to be sent through the network to the
742
// final destination.
743
type LightningPayment struct {
744
        // Target is the node in which the payment should be routed towards.
745
        Target route.Vertex
746

747
        // Amount is the value of the payment to send through the network in
748
        // milli-satoshis.
749
        Amount lnwire.MilliSatoshi
750

751
        // FeeLimit is the maximum fee in millisatoshis that the payment should
752
        // accept when sending it through the network. The payment will fail
753
        // if there isn't a route with lower fees than this limit.
754
        FeeLimit lnwire.MilliSatoshi
755

756
        // CltvLimit is the maximum time lock that is allowed for attempts to
757
        // complete this payment.
758
        CltvLimit uint32
759

760
        // paymentHash is the r-hash value to use within the HTLC extended to
761
        // the first hop. This won't be set for AMP payments.
762
        paymentHash *lntypes.Hash
763

764
        // amp is an optional field that is set if and only if this is am AMP
765
        // payment.
766
        amp *AMPOptions
767

768
        // FinalCLTVDelta is the CTLV expiry delta to use for the _final_ hop
769
        // in the route. This means that the final hop will have a CLTV delta
770
        // of at least: currentHeight + FinalCLTVDelta.
771
        FinalCLTVDelta uint16
772

773
        // PayAttemptTimeout is a timeout value that we'll use to determine
774
        // when we should should abandon the payment attempt after consecutive
775
        // payment failure. This prevents us from attempting to send a payment
776
        // indefinitely. A zero value means the payment will never time out.
777
        //
778
        // TODO(halseth): make wallclock time to allow resume after startup.
779
        PayAttemptTimeout time.Duration
780

781
        // RouteHints represents the different routing hints that can be used to
782
        // assist a payment in reaching its destination successfully. These
783
        // hints will act as intermediate hops along the route.
784
        //
785
        // NOTE: This is optional unless required by the payment. When providing
786
        // multiple routes, ensure the hop hints within each route are chained
787
        // together and sorted in forward order in order to reach the
788
        // destination successfully. This is mutually exclusive to the
789
        // BlindedPayment field.
790
        RouteHints [][]zpay32.HopHint
791

792
        // BlindedPathSet holds the information about a set of blinded paths to
793
        // the payment recipient. This is mutually exclusive to the RouteHints
794
        // field.
795
        BlindedPathSet *BlindedPaymentPathSet
796

797
        // OutgoingChannelIDs is the list of channels that are allowed for the
798
        // first hop. If nil, any channel may be used.
799
        OutgoingChannelIDs []uint64
800

801
        // LastHop is the pubkey of the last node before the final destination
802
        // is reached. If nil, any node may be used.
803
        LastHop *route.Vertex
804

805
        // DestFeatures specifies the set of features we assume the final node
806
        // has for pathfinding. Typically, these will be taken directly from an
807
        // invoice, but they can also be manually supplied or assumed by the
808
        // sender. If a nil feature vector is provided, the router will try to
809
        // fall back to the graph in order to load a feature vector for a node
810
        // in the public graph.
811
        DestFeatures *lnwire.FeatureVector
812

813
        // PaymentAddr is the payment address specified by the receiver. This
814
        // field should be a random 32-byte nonce presented in the receiver's
815
        // invoice to prevent probing of the destination.
816
        PaymentAddr fn.Option[[32]byte]
817

818
        // PaymentRequest is an optional payment request that this payment is
819
        // attempting to complete.
820
        PaymentRequest []byte
821

822
        // DestCustomRecords are TLV records that are to be sent to the final
823
        // hop in the new onion payload format. If the destination does not
824
        // understand this new onion payload format, then the payment will
825
        // fail.
826
        DestCustomRecords record.CustomSet
827

828
        // FirstHopCustomRecords are the TLV records that are to be sent to the
829
        // first hop of this payment. These records will be transmitted via the
830
        // wire message and therefore do not affect the onion payload size.
831
        FirstHopCustomRecords lnwire.CustomRecords
832

833
        // MaxParts is the maximum number of partial payments that may be used
834
        // to complete the full amount.
835
        MaxParts uint32
836

837
        // MaxShardAmt is the largest shard that we'll attempt to split using.
838
        // If this field is set, and we need to split, rather than attempting
839
        // half of the original payment amount, we'll use this value if half
840
        // the payment amount is greater than it.
841
        //
842
        // NOTE: This field is _optional_.
843
        MaxShardAmt *lnwire.MilliSatoshi
844

845
        // TimePref is the time preference for this payment. Set to -1 to
846
        // optimize for fees only, to 1 to optimize for reliability only or a
847
        // value in between for a mix.
848
        TimePref float64
849

850
        // Metadata is additional data that is sent along with the payment to
851
        // the payee.
852
        Metadata []byte
853
}
854

855
// AMPOptions houses information that must be known in order to send an AMP
856
// payment.
857
type AMPOptions struct {
858
        SetID     [32]byte
859
        RootShare [32]byte
860
}
861

862
// SetPaymentHash sets the given hash as the payment's overall hash. This
863
// should only be used for non-AMP payments.
864
func (l *LightningPayment) SetPaymentHash(hash lntypes.Hash) error {
3✔
865
        if l.amp != nil {
3✔
866
                return fmt.Errorf("cannot set payment hash for AMP payment")
×
867
        }
×
868

869
        l.paymentHash = &hash
3✔
870
        return nil
3✔
871
}
872

873
// SetAMP sets the given AMP options for the payment.
874
func (l *LightningPayment) SetAMP(amp *AMPOptions) error {
3✔
875
        if l.paymentHash != nil {
3✔
876
                return fmt.Errorf("cannot set amp options for payment " +
×
877
                        "with payment hash")
×
878
        }
×
879

880
        l.amp = amp
3✔
881
        return nil
3✔
882
}
883

884
// Identifier returns a 32-byte slice that uniquely identifies this single
885
// payment. For non-AMP payments this will be the payment hash, for AMP
886
// payments this will be the used SetID.
887
func (l *LightningPayment) Identifier() [32]byte {
3✔
888
        if l.amp != nil {
6✔
889
                return l.amp.SetID
3✔
890
        }
3✔
891

892
        return *l.paymentHash
3✔
893
}
894

895
// SendPayment attempts to send a payment as described within the passed
896
// LightningPayment. This function is blocking and will return either: when the
897
// payment is successful, or all candidates routes have been attempted and
898
// resulted in a failed payment. If the payment succeeds, then a non-nil Route
899
// will be returned which describes the path the successful payment traversed
900
// within the network to reach the destination. Additionally, the payment
901
// preimage will also be returned.
902
func (r *ChannelRouter) SendPayment(payment *LightningPayment) ([32]byte,
UNCOV
903
        *route.Route, error) {
×
UNCOV
904

×
UNCOV
905
        paySession, shardTracker, err := r.PreparePayment(payment)
×
UNCOV
906
        if err != nil {
×
907
                return [32]byte{}, nil, err
×
908
        }
×
909

UNCOV
910
        log.Tracef("Dispatching SendPayment for lightning payment: %v",
×
UNCOV
911
                spewPayment(payment))
×
UNCOV
912

×
UNCOV
913
        return r.sendPayment(
×
UNCOV
914
                context.Background(), payment.FeeLimit, payment.Identifier(),
×
UNCOV
915
                payment.PayAttemptTimeout, paySession, shardTracker,
×
UNCOV
916
                payment.FirstHopCustomRecords,
×
UNCOV
917
        )
×
918
}
919

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

3✔
925
        // Since this is the first time this payment is being made, we pass nil
3✔
926
        // for the existing attempt.
3✔
927
        r.wg.Add(1)
3✔
928
        go func() {
6✔
929
                defer r.wg.Done()
3✔
930

3✔
931
                log.Tracef("Dispatching SendPayment for lightning payment: %v",
3✔
932
                        spewPayment(payment))
3✔
933

3✔
934
                _, _, err := r.sendPayment(
3✔
935
                        ctx, payment.FeeLimit, payment.Identifier(),
3✔
936
                        payment.PayAttemptTimeout, ps, st,
3✔
937
                        payment.FirstHopCustomRecords,
3✔
938
                )
3✔
939
                if err != nil {
6✔
940
                        log.Errorf("Payment %x failed: %v",
3✔
941
                                payment.Identifier(), err)
3✔
942
                }
3✔
943
        }()
944
}
945

946
// spewPayment returns a log closures that provides a spewed string
947
// representation of the passed payment.
948
func spewPayment(payment *LightningPayment) lnutils.LogClosure {
3✔
949
        return lnutils.NewLogClosure(func() string {
3✔
950
                // Make a copy of the payment with a nilled Curve
×
951
                // before spewing.
×
952
                var routeHints [][]zpay32.HopHint
×
953
                for _, routeHint := range payment.RouteHints {
×
954
                        var hopHints []zpay32.HopHint
×
955
                        for _, hopHint := range routeHint {
×
956
                                h := hopHint.Copy()
×
957
                                hopHints = append(hopHints, h)
×
958
                        }
×
959
                        routeHints = append(routeHints, hopHints)
×
960
                }
961
                p := *payment
×
962
                p.RouteHints = routeHints
×
963
                return spew.Sdump(p)
×
964
        })
965
}
966

967
// PreparePayment creates the payment session and registers the payment with the
968
// control tower.
969
func (r *ChannelRouter) PreparePayment(payment *LightningPayment) (
970
        PaymentSession, shards.ShardTracker, error) {
3✔
971

3✔
972
        // Assemble any custom data we want to send to the first hop only.
3✔
973
        var firstHopData fn.Option[tlv.Blob]
3✔
974
        if len(payment.FirstHopCustomRecords) > 0 {
6✔
975
                if err := payment.FirstHopCustomRecords.Validate(); err != nil {
3✔
976
                        return nil, nil, fmt.Errorf("invalid first hop custom "+
×
977
                                "records: %w", err)
×
978
                }
×
979

980
                firstHopBlob, err := payment.FirstHopCustomRecords.Serialize()
3✔
981
                if err != nil {
3✔
982
                        return nil, nil, fmt.Errorf("unable to serialize "+
×
983
                                "first hop custom records: %w", err)
×
984
                }
×
985

986
                firstHopData = fn.Some(firstHopBlob)
3✔
987
        }
988

989
        // Before starting the HTLC routing attempt, we'll create a fresh
990
        // payment session which will report our errors back to mission
991
        // control.
992
        paySession, err := r.cfg.SessionSource.NewPaymentSession(
3✔
993
                payment, firstHopData, r.cfg.TrafficShaper,
3✔
994
        )
3✔
995
        if err != nil {
3✔
996
                return nil, nil, err
×
997
        }
×
998

999
        // Record this payment hash with the ControlTower, ensuring it is not
1000
        // already in-flight.
1001
        //
1002
        // TODO(roasbeef): store records as part of creation info?
1003
        info := &pymtpkgDB.PaymentCreationInfo{
3✔
1004
                PaymentIdentifier:     payment.Identifier(),
3✔
1005
                Value:                 payment.Amount,
3✔
1006
                CreationTime:          r.cfg.Clock.Now(),
3✔
1007
                PaymentRequest:        payment.PaymentRequest,
3✔
1008
                FirstHopCustomRecords: payment.FirstHopCustomRecords,
3✔
1009
        }
3✔
1010

3✔
1011
        // Create a new ShardTracker that we'll use during the life cycle of
3✔
1012
        // this payment.
3✔
1013
        var shardTracker shards.ShardTracker
3✔
1014
        switch {
3✔
1015
        // If this is an AMP payment, we'll use the AMP shard tracker.
1016
        case payment.amp != nil:
3✔
1017
                addr := payment.PaymentAddr.UnwrapOr([32]byte{})
3✔
1018
                shardTracker = amp.NewShardTracker(
3✔
1019
                        payment.amp.RootShare, payment.amp.SetID, addr,
3✔
1020
                        payment.Amount,
3✔
1021
                )
3✔
1022

1023
        // Otherwise we'll use the simple tracker that will map each attempt to
1024
        // the same payment hash.
1025
        default:
3✔
1026
                shardTracker = shards.NewSimpleShardTracker(
3✔
1027
                        payment.Identifier(), nil,
3✔
1028
                )
3✔
1029
        }
1030

1031
        err = r.cfg.Control.InitPayment(payment.Identifier(), info)
3✔
1032
        if err != nil {
3✔
1033
                return nil, nil, err
×
1034
        }
×
1035

1036
        return paySession, shardTracker, nil
3✔
1037
}
1038

1039
// SendToRoute sends a payment using the provided route and fails the payment
1040
// when an error is returned from the attempt.
1041
func (r *ChannelRouter) SendToRoute(htlcHash lntypes.Hash, rt *route.Route,
1042
        firstHopCustomRecords lnwire.CustomRecords) (*pymtpkgDB.HTLCAttempt,
1043
        error) {
3✔
1044

3✔
1045
        return r.sendToRoute(htlcHash, rt, false, firstHopCustomRecords)
3✔
1046
}
3✔
1047

1048
// SendToRouteSkipTempErr sends a payment using the provided route and fails
1049
// the payment ONLY when a terminal error is returned from the attempt.
1050
func (r *ChannelRouter) SendToRouteSkipTempErr(htlcHash lntypes.Hash,
1051
        rt *route.Route,
1052
        firstHopCustomRecords lnwire.CustomRecords) (*pymtpkgDB.HTLCAttempt,
UNCOV
1053
        error) {
×
UNCOV
1054

×
UNCOV
1055
        return r.sendToRoute(htlcHash, rt, true, firstHopCustomRecords)
×
UNCOV
1056
}
×
1057

1058
// sendToRoute attempts to send a payment with the given hash through the
1059
// provided route. This function is blocking and will return the attempt
1060
// information as it is stored in the database. For a successful htlc, this
1061
// information will contain the preimage. If an error occurs after the attempt
1062
// was initiated, both return values will be non-nil. If skipTempErr is true,
1063
// the payment won't be failed unless a terminal error has occurred.
1064
func (r *ChannelRouter) sendToRoute(htlcHash lntypes.Hash, rt *route.Route,
1065
        skipTempErr bool,
1066
        firstHopCustomRecords lnwire.CustomRecords) (*pymtpkgDB.HTLCAttempt,
1067
        error) {
3✔
1068

3✔
1069
        // Helper function to fail a payment. It makes sure the payment is only
3✔
1070
        // failed once so that the failure reason is not overwritten.
3✔
1071
        failPayment := func(paymentIdentifier lntypes.Hash,
3✔
1072
                reason pymtpkgDB.FailureReason) error {
6✔
1073

3✔
1074
                payment, fetchErr := r.cfg.Control.FetchPayment(
3✔
1075
                        paymentIdentifier,
3✔
1076
                )
3✔
1077
                if fetchErr != nil {
3✔
1078
                        return fetchErr
×
1079
                }
×
1080

1081
                // NOTE: We cannot rely on the payment status to be failed here
1082
                // because it can still be in-flight although the payment is
1083
                // already failed.
1084
                _, failedReason := payment.TerminalInfo()
3✔
1085
                if failedReason != nil {
6✔
1086
                        return nil
3✔
1087
                }
3✔
1088

1089
                return r.cfg.Control.FailPayment(paymentIdentifier, reason)
3✔
1090
        }
1091

1092
        log.Debugf("SendToRoute for payment %v with skipTempErr=%v",
3✔
1093
                htlcHash, skipTempErr)
3✔
1094

3✔
1095
        // Calculate amount paid to receiver.
3✔
1096
        amt := rt.ReceiverAmt()
3✔
1097

3✔
1098
        // If this is meant as an MP payment shard, we set the amount for the
3✔
1099
        // creating info to the total amount of the payment.
3✔
1100
        finalHop := rt.Hops[len(rt.Hops)-1]
3✔
1101
        mpp := finalHop.MPP
3✔
1102
        if mpp != nil {
6✔
1103
                amt = mpp.TotalMsat()
3✔
1104
        }
3✔
1105

1106
        // For non-MPP, there's no such thing as temp error as there's only one
1107
        // HTLC attempt being made. When this HTLC is failed, the payment is
1108
        // failed hence cannot be retried.
1109
        if skipTempErr && mpp == nil {
3✔
UNCOV
1110
                return nil, ErrSkipTempErr
×
UNCOV
1111
        }
×
1112

1113
        // For non-AMP payments the overall payment identifier will be the same
1114
        // hash as used for this HTLC.
1115
        paymentIdentifier := htlcHash
3✔
1116

3✔
1117
        // For AMP-payments, we'll use the setID as the unique ID for the
3✔
1118
        // overall payment.
3✔
1119
        amp := finalHop.AMP
3✔
1120
        if amp != nil {
6✔
1121
                paymentIdentifier = amp.SetID()
3✔
1122
        }
3✔
1123

1124
        // Record this payment hash with the ControlTower, ensuring it is not
1125
        // already in-flight.
1126
        info := &pymtpkgDB.PaymentCreationInfo{
3✔
1127
                PaymentIdentifier:     paymentIdentifier,
3✔
1128
                Value:                 amt,
3✔
1129
                CreationTime:          r.cfg.Clock.Now(),
3✔
1130
                PaymentRequest:        nil,
3✔
1131
                FirstHopCustomRecords: firstHopCustomRecords,
3✔
1132
        }
3✔
1133

3✔
1134
        err := r.cfg.Control.InitPayment(paymentIdentifier, info)
3✔
1135
        switch {
3✔
1136
        // If this is an MPP attempt and the hash is already registered with
1137
        // the database, we can go on to launch the shard.
1138
        case mpp != nil && errors.Is(err, pymtpkgDB.ErrPaymentInFlight):
3✔
NEW
1139
        case mpp != nil && errors.Is(err, pymtpkgDB.ErrPaymentExists):
×
1140

1141
        // Any other error is not tolerated.
1142
        case err != nil:
×
1143
                return nil, err
×
1144
        }
1145

1146
        log.Tracef("Dispatching SendToRoute for HTLC hash %v: %v", htlcHash,
3✔
1147
                lnutils.SpewLogClosure(rt))
3✔
1148

3✔
1149
        // Since the HTLC hashes and preimages are specified manually over the
3✔
1150
        // RPC for SendToRoute requests, we don't have to worry about creating
3✔
1151
        // a ShardTracker that can generate hashes for AMP payments. Instead, we
3✔
1152
        // create a simple tracker that can just return the hash for the single
3✔
1153
        // shard we'll now launch.
3✔
1154
        shardTracker := shards.NewSimpleShardTracker(htlcHash, nil)
3✔
1155

3✔
1156
        // Create a payment lifecycle using the given route with,
3✔
1157
        // - zero fee limit as we are not requesting routes.
3✔
1158
        // - nil payment session (since we already have a route).
3✔
1159
        // - no payment timeout.
3✔
1160
        // - no current block height.
3✔
1161
        p := newPaymentLifecycle(
3✔
1162
                r, 0, paymentIdentifier, nil, shardTracker, 0,
3✔
1163
                firstHopCustomRecords,
3✔
1164
        )
3✔
1165

3✔
1166
        // Allow the traffic shaper to add custom records to the outgoing HTLC
3✔
1167
        // and also adjust the amount if needed.
3✔
1168
        err = p.amendFirstHopData(rt)
3✔
1169
        if err != nil {
3✔
1170
                return nil, err
×
1171
        }
×
1172

1173
        // We found a route to try, create a new HTLC attempt to try.
1174
        //
1175
        // NOTE: we use zero `remainingAmt` here to simulate the same effect of
1176
        // setting the lastShard to be false, which is used by previous
1177
        // implementation.
1178
        attempt, err := p.registerAttempt(rt, 0)
3✔
1179
        if err != nil {
3✔
UNCOV
1180
                return nil, err
×
UNCOV
1181
        }
×
1182

1183
        // Once the attempt is created, send it to the htlcswitch. Notice that
1184
        // the `err` returned here has already been processed by
1185
        // `handleSwitchErr`, which means if there's a terminal failure, the
1186
        // payment has been failed.
1187
        result, err := p.sendAttempt(attempt)
3✔
1188
        if err != nil {
3✔
1189
                return nil, err
×
1190
        }
×
1191

1192
        // Since for SendToRoute we won't retry in case the shard fails, we'll
1193
        // mark the payment failed with the control tower immediately if the
1194
        // skipTempErr is false.
1195
        reason := pymtpkgDB.FailureReasonError
3✔
1196

3✔
1197
        // If we failed to send the HTLC, we need to further decide if we want
3✔
1198
        // to fail the payment.
3✔
1199
        if result.err != nil {
6✔
1200
                // If skipTempErr, we'll return the attempt and the temp error.
3✔
1201
                if skipTempErr {
3✔
UNCOV
1202
                        return result.attempt, result.err
×
UNCOV
1203
                }
×
1204

1205
                err := failPayment(paymentIdentifier, reason)
3✔
1206
                if err != nil {
3✔
1207
                        return nil, err
×
1208
                }
×
1209

1210
                return result.attempt, result.err
3✔
1211
        }
1212

1213
        // The attempt was successfully sent, wait for the result to be
1214
        // available.
1215
        result, err = p.collectAndHandleResult(attempt)
3✔
1216
        if err != nil {
3✔
1217
                return nil, err
×
1218
        }
×
1219

1220
        // We got a successful result.
1221
        if result.err == nil {
6✔
1222
                return result.attempt, nil
3✔
1223
        }
3✔
1224

1225
        // An error returned from collecting the result, we'll mark the payment
1226
        // as failed if we don't skip temp error.
1227
        if !skipTempErr {
6✔
1228
                err := failPayment(paymentIdentifier, reason)
3✔
1229
                if err != nil {
3✔
1230
                        return nil, err
×
1231
                }
×
1232
        }
1233

1234
        return result.attempt, result.err
3✔
1235
}
1236

1237
// sendPayment attempts to send a payment to the passed payment hash. This
1238
// function is blocking and will return either: when the payment is successful,
1239
// or all candidates routes have been attempted and resulted in a failed
1240
// payment. If the payment succeeds, then a non-nil Route will be returned
1241
// which describes the path the successful payment traversed within the network
1242
// to reach the destination. Additionally, the payment preimage will also be
1243
// returned.
1244
//
1245
// This method relies on the ControlTower's internal payment state machine to
1246
// carry out its execution. After restarts, it is safe, and assumed, that the
1247
// router will call this method for every payment still in-flight according to
1248
// the ControlTower.
1249
func (r *ChannelRouter) sendPayment(ctx context.Context,
1250
        feeLimit lnwire.MilliSatoshi, identifier lntypes.Hash,
1251
        paymentAttemptTimeout time.Duration, paySession PaymentSession,
1252
        shardTracker shards.ShardTracker,
1253
        firstHopCustomRecords lnwire.CustomRecords) ([32]byte, *route.Route,
1254
        error) {
3✔
1255

3✔
1256
        // If the user provides a timeout, we will additionally wrap the context
3✔
1257
        // in a deadline.
3✔
1258
        cancel := func() {}
6✔
1259
        if paymentAttemptTimeout > 0 {
6✔
1260
                ctx, cancel = context.WithTimeout(ctx, paymentAttemptTimeout)
3✔
1261
        }
3✔
1262

1263
        // Since resumePayment is a blocking call, we'll cancel this
1264
        // context if the payment completes before the optional
1265
        // deadline.
1266
        defer cancel()
3✔
1267

3✔
1268
        // We'll also fetch the current block height, so we can properly
3✔
1269
        // calculate the required HTLC time locks within the route.
3✔
1270
        _, currentHeight, err := r.cfg.Chain.GetBestBlock()
3✔
1271
        if err != nil {
3✔
1272
                return [32]byte{}, nil, err
×
1273
        }
×
1274

1275
        // Validate the custom records before we attempt to send the payment.
1276
        // TODO(ziggie): Move this check before registering the payment in the
1277
        // db (InitPayment).
1278
        if err := firstHopCustomRecords.Validate(); err != nil {
3✔
1279
                return [32]byte{}, nil, err
×
1280
        }
×
1281

1282
        // Now set up a paymentLifecycle struct with these params, such that we
1283
        // can resume the payment from the current state.
1284
        p := newPaymentLifecycle(
3✔
1285
                r, feeLimit, identifier, paySession, shardTracker,
3✔
1286
                currentHeight, firstHopCustomRecords,
3✔
1287
        )
3✔
1288

3✔
1289
        return p.resumePayment(ctx)
3✔
1290
}
1291

1292
// extractChannelUpdate examines the error and extracts the channel update.
1293
func (r *ChannelRouter) extractChannelUpdate(
1294
        failure lnwire.FailureMessage) *lnwire.ChannelUpdate1 {
3✔
1295

3✔
1296
        var update *lnwire.ChannelUpdate1
3✔
1297
        switch onionErr := failure.(type) {
3✔
UNCOV
1298
        case *lnwire.FailExpiryTooSoon:
×
UNCOV
1299
                update = &onionErr.Update
×
1300
        case *lnwire.FailAmountBelowMinimum:
3✔
1301
                update = &onionErr.Update
3✔
1302
        case *lnwire.FailFeeInsufficient:
3✔
1303
                update = &onionErr.Update
3✔
1304
        case *lnwire.FailIncorrectCltvExpiry:
×
1305
                update = &onionErr.Update
×
1306
        case *lnwire.FailChannelDisabled:
3✔
1307
                update = &onionErr.Update
3✔
1308
        case *lnwire.FailTemporaryChannelFailure:
3✔
1309
                update = onionErr.Update
3✔
1310
        }
1311

1312
        return update
3✔
1313
}
1314

1315
// ErrNoChannel is returned when a route cannot be built because there are no
1316
// channels that satisfy all requirements.
1317
type ErrNoChannel struct {
1318
        position int
1319
}
1320

1321
// Error returns a human-readable string describing the error.
UNCOV
1322
func (e ErrNoChannel) Error() string {
×
UNCOV
1323
        return fmt.Sprintf("no matching outgoing channel available for "+
×
UNCOV
1324
                "node index %v", e.position)
×
UNCOV
1325
}
×
1326

1327
// BuildRoute returns a fully specified route based on a list of pubkeys. If
1328
// amount is nil, the minimum routable amount is used. To force a specific
1329
// outgoing channel, use the outgoingChan parameter.
1330
func (r *ChannelRouter) BuildRoute(amt fn.Option[lnwire.MilliSatoshi],
1331
        hops []route.Vertex, outgoingChan *uint64, finalCltvDelta int32,
1332
        payAddr fn.Option[[32]byte], firstHopBlob fn.Option[[]byte]) (
1333
        *route.Route, error) {
3✔
1334

3✔
1335
        log.Tracef("BuildRoute called: hopsCount=%v, amt=%v", len(hops), amt)
3✔
1336

3✔
1337
        var outgoingChans map[uint64]struct{}
3✔
1338
        if outgoingChan != nil {
3✔
1339
                outgoingChans = map[uint64]struct{}{
×
1340
                        *outgoingChan: {},
×
1341
                }
×
1342
        }
×
1343

1344
        // We'll attempt to obtain a set of bandwidth hints that helps us select
1345
        // the best outgoing channel to use in case no outgoing channel is set.
1346
        bandwidthHints, err := newBandwidthManager(
3✔
1347
                r.cfg.RoutingGraph, r.cfg.SelfNode, r.cfg.GetLink, firstHopBlob,
3✔
1348
                r.cfg.TrafficShaper,
3✔
1349
        )
3✔
1350
        if err != nil {
3✔
1351
                return nil, err
×
1352
        }
×
1353

1354
        sourceNode := r.cfg.SelfNode
3✔
1355

3✔
1356
        // We check that each node in the route has a connection to others that
3✔
1357
        // can forward in principle.
3✔
1358
        unifiers, err := getEdgeUnifiers(
3✔
1359
                r.cfg.SelfNode, hops, outgoingChans, r.cfg.RoutingGraph,
3✔
1360
        )
3✔
1361
        if err != nil {
3✔
UNCOV
1362
                return nil, err
×
UNCOV
1363
        }
×
1364

1365
        var (
3✔
1366
                receiverAmt lnwire.MilliSatoshi
3✔
1367
                senderAmt   lnwire.MilliSatoshi
3✔
1368
                pathEdges   []*unifiedEdge
3✔
1369
        )
3✔
1370

3✔
1371
        // We determine the edges compatible with the requested amount, as well
3✔
1372
        // as the amount to send, which can be used to determine the final
3✔
1373
        // receiver amount, if a minimal amount was requested.
3✔
1374
        pathEdges, senderAmt, err = senderAmtBackwardPass(
3✔
1375
                unifiers, amt, bandwidthHints,
3✔
1376
        )
3✔
1377
        if err != nil {
3✔
UNCOV
1378
                return nil, err
×
UNCOV
1379
        }
×
1380

1381
        // For the minimal amount search, we need to do a forward pass to find a
1382
        // larger receiver amount due to possible min HTLC bumps, otherwise we
1383
        // just use the requested amount.
1384
        receiverAmt, err = fn.ElimOption(
3✔
1385
                amt,
3✔
1386
                func() fn.Result[lnwire.MilliSatoshi] {
3✔
UNCOV
1387
                        return fn.NewResult(
×
UNCOV
1388
                                receiverAmtForwardPass(senderAmt, pathEdges),
×
UNCOV
1389
                        )
×
UNCOV
1390
                },
×
1391
                fn.Ok[lnwire.MilliSatoshi],
1392
        ).Unpack()
1393
        if err != nil {
3✔
1394
                return nil, err
×
1395
        }
×
1396

1397
        // Fetch the current block height outside the routing transaction, to
1398
        // prevent the rpc call blocking the database.
1399
        _, height, err := r.cfg.Chain.GetBestBlock()
3✔
1400
        if err != nil {
3✔
1401
                return nil, err
×
1402
        }
×
1403

1404
        // Build and return the final route.
1405
        return newRoute(
3✔
1406
                sourceNode, pathEdges, uint32(height),
3✔
1407
                finalHopParams{
3✔
1408
                        amt:         receiverAmt,
3✔
1409
                        totalAmt:    receiverAmt,
3✔
1410
                        cltvDelta:   uint16(finalCltvDelta),
3✔
1411
                        records:     nil,
3✔
1412
                        paymentAddr: payAddr,
3✔
1413
                }, nil,
3✔
1414
        )
3✔
1415
}
1416

1417
// resumePayments fetches inflight payments and resumes their payment
1418
// lifecycles.
1419
func (r *ChannelRouter) resumePayments() error {
3✔
1420
        // Get all payments that are inflight.
3✔
1421
        log.Debugf("Scanning for inflight payments")
3✔
1422
        payments, err := r.cfg.Control.FetchInFlightPayments()
3✔
1423
        if err != nil {
3✔
1424
                return err
×
1425
        }
×
1426

1427
        log.Debugf("Scanning finished, found %d inflight payments",
3✔
1428
                len(payments))
3✔
1429

3✔
1430
        // Before we restart existing payments and start accepting more
3✔
1431
        // payments to be made, we clean the network result store of the
3✔
1432
        // Switch. We do this here at startup to ensure no more payments can be
3✔
1433
        // made concurrently, so we know the toKeep map will be up-to-date
3✔
1434
        // until the cleaning has finished.
3✔
1435
        toKeep := make(map[uint64]struct{})
3✔
1436
        for _, p := range payments {
6✔
1437
                for _, a := range p.HTLCs {
6✔
1438
                        toKeep[a.AttemptID] = struct{}{}
3✔
1439

3✔
1440
                        // Try to fail the attempt if the route contains a dead
3✔
1441
                        // channel.
3✔
1442
                        r.failStaleAttempt(a, p.Info.PaymentIdentifier)
3✔
1443
                }
3✔
1444
        }
1445

1446
        log.Debugf("Cleaning network result store.")
3✔
1447
        if err := r.cfg.Payer.CleanStore(toKeep); err != nil {
3✔
1448
                return err
×
1449
        }
×
1450

1451
        // launchPayment is a helper closure that handles resuming the payment.
1452
        launchPayment := func(payment *pymtpkgDB.MPPayment) {
6✔
1453
                defer r.wg.Done()
3✔
1454

3✔
1455
                // Get the hashes used for the outstanding HTLCs.
3✔
1456
                htlcs := make(map[uint64]lntypes.Hash)
3✔
1457
                for _, a := range payment.HTLCs {
6✔
1458
                        a := a
3✔
1459

3✔
1460
                        // We check whether the individual attempts have their
3✔
1461
                        // HTLC hash set, if not we'll fall back to the overall
3✔
1462
                        // payment hash.
3✔
1463
                        hash := payment.Info.PaymentIdentifier
3✔
1464
                        if a.Hash != nil {
6✔
1465
                                hash = *a.Hash
3✔
1466
                        }
3✔
1467

1468
                        htlcs[a.AttemptID] = hash
3✔
1469
                }
1470

1471
                payHash := payment.Info.PaymentIdentifier
3✔
1472

3✔
1473
                // Since we are not supporting creating more shards after a
3✔
1474
                // restart (only receiving the result of the shards already
3✔
1475
                // outstanding), we create a simple shard tracker that will map
3✔
1476
                // the attempt IDs to hashes used for the HTLCs. This will be
3✔
1477
                // enough also for AMP payments, since we only need the hashes
3✔
1478
                // for the individual HTLCs to regenerate the circuits, and we
3✔
1479
                // don't currently persist the root share necessary to
3✔
1480
                // re-derive them.
3✔
1481
                shardTracker := shards.NewSimpleShardTracker(payHash, htlcs)
3✔
1482

3✔
1483
                // We create a dummy, empty payment session such that we won't
3✔
1484
                // make another payment attempt when the result for the
3✔
1485
                // in-flight attempt is received.
3✔
1486
                paySession := r.cfg.SessionSource.NewPaymentSessionEmpty()
3✔
1487

3✔
1488
                // We pass in a non-timeout context, to indicate we don't need
3✔
1489
                // it to timeout. It will stop immediately after the existing
3✔
1490
                // attempt has finished anyway. We also set a zero fee limit,
3✔
1491
                // as no more routes should be tried.
3✔
1492
                noTimeout := time.Duration(0)
3✔
1493
                _, _, err := r.sendPayment(
3✔
1494
                        context.Background(), 0, payHash, noTimeout, paySession,
3✔
1495
                        shardTracker, payment.Info.FirstHopCustomRecords,
3✔
1496
                )
3✔
1497
                if err != nil {
6✔
1498
                        log.Errorf("Resuming payment %v failed: %v", payHash,
3✔
1499
                                err)
3✔
1500

3✔
1501
                        return
3✔
1502
                }
3✔
1503

1504
                log.Infof("Resumed payment %v completed", payHash)
3✔
1505
        }
1506

1507
        for _, payment := range payments {
6✔
1508
                log.Infof("Resuming payment %v", payment.Info.PaymentIdentifier)
3✔
1509

3✔
1510
                r.wg.Add(1)
3✔
1511
                go launchPayment(payment)
3✔
1512
        }
3✔
1513

1514
        return nil
3✔
1515
}
1516

1517
// failStaleAttempt will fail an HTLC attempt if it's using an unknown channel
1518
// in its route. It first consults the switch to see if there's already a
1519
// network result stored for this attempt. If not, it will check whether the
1520
// first hop of this attempt is using an active channel known to us. If
1521
// inactive, this attempt will be failed.
1522
//
1523
// NOTE: there's an unknown bug that caused the network result for a particular
1524
// attempt to NOT be saved, resulting a payment being stuck forever. More info:
1525
// - https://github.com/lightningnetwork/lnd/issues/8146
1526
// - https://github.com/lightningnetwork/lnd/pull/8174
1527
func (r *ChannelRouter) failStaleAttempt(a pymtpkgDB.HTLCAttempt,
1528
        payHash lntypes.Hash) {
3✔
1529

3✔
1530
        // We can only fail inflight HTLCs so we skip the settled/failed ones.
3✔
1531
        if a.Failure != nil || a.Settle != nil {
3✔
1532
                return
×
1533
        }
×
1534

1535
        // First, check if we've already had a network result for this attempt.
1536
        // If no result is found, we'll check whether the reference link is
1537
        // still known to us.
1538
        ok, err := r.cfg.Payer.HasAttemptResult(a.AttemptID)
3✔
1539
        if err != nil {
3✔
1540
                log.Errorf("Failed to fetch network result for attempt=%v",
×
1541
                        a.AttemptID)
×
1542
                return
×
1543
        }
×
1544

1545
        // There's already a network result, no need to fail it here as the
1546
        // payment lifecycle will take care of it, so we can exit early.
1547
        if ok {
3✔
1548
                log.Debugf("Already have network result for attempt=%v",
×
1549
                        a.AttemptID)
×
1550
                return
×
1551
        }
×
1552

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

3✔
1560
        // Validate that the attempt has hop info. If this attempt has no hop
3✔
1561
        // info it indicates an error in our db.
3✔
1562
        if len(a.Route.Hops) == 0 {
3✔
1563
                log.Errorf("Found empty hop for attempt=%v", a.AttemptID)
×
1564

×
1565
                shouldFail = true
×
1566
        } else {
3✔
1567
                // Get the short channel ID.
3✔
1568
                chanID := a.Route.Hops[0].ChannelID
3✔
1569
                scid := lnwire.NewShortChanIDFromInt(chanID)
3✔
1570

3✔
1571
                // Check whether this link is active. If so, we won't fail the
3✔
1572
                // attempt but keep waiting for its result.
3✔
1573
                _, err := r.cfg.GetLink(scid)
3✔
1574
                if err == nil {
3✔
1575
                        return
×
1576
                }
×
1577

1578
                // We should get the link not found err. If not, we will log an
1579
                // error and skip failing this attempt since an unknown error
1580
                // occurred.
1581
                if !errors.Is(err, htlcswitch.ErrChannelLinkNotFound) {
3✔
1582
                        log.Errorf("Failed to get link for attempt=%v for "+
×
1583
                                "payment=%v: %v", a.AttemptID, payHash, err)
×
1584

×
1585
                        return
×
1586
                }
×
1587

1588
                // The channel link is not active, we now check whether this
1589
                // channel is already closed. If so, we fail the HTLC attempt
1590
                // as there's no need to wait for its network result because
1591
                // there's no link. If the channel is still pending, we'll keep
1592
                // waiting for the result as we may get a contract resolution
1593
                // for this HTLC.
1594
                if _, ok := r.cfg.ClosedSCIDs[scid]; ok {
3✔
1595
                        shouldFail = true
×
1596
                }
×
1597
        }
1598

1599
        // Exit if there's no need to fail.
1600
        if !shouldFail {
6✔
1601
                return
3✔
1602
        }
3✔
1603

1604
        log.Errorf("Failing stale attempt=%v for payment=%v", a.AttemptID,
×
1605
                payHash)
×
1606

×
1607
        // Fail the attempt in db. If there's an error, there's nothing we can
×
1608
        // do here but logging it.
×
NEW
1609
        failInfo := &pymtpkgDB.HTLCFailInfo{
×
NEW
1610
                Reason:   pymtpkgDB.HTLCFailUnknown,
×
1611
                FailTime: r.cfg.Clock.Now(),
×
1612
        }
×
1613
        _, err = r.cfg.Control.FailAttempt(payHash, a.AttemptID, failInfo)
×
1614
        if err != nil {
×
1615
                log.Errorf("Fail attempt=%v got error: %v", a.AttemptID, err)
×
1616
        }
×
1617
}
1618

1619
// getEdgeUnifiers returns a list of edge unifiers for the given route.
1620
func getEdgeUnifiers(source route.Vertex, hops []route.Vertex,
1621
        outgoingChans map[uint64]struct{},
1622
        graph Graph) ([]*edgeUnifier, error) {
3✔
1623

3✔
1624
        // Allocate a list that will contain the edge unifiers for this route.
3✔
1625
        unifiers := make([]*edgeUnifier, len(hops))
3✔
1626

3✔
1627
        // Traverse hops backwards to accumulate fees in the running amounts.
3✔
1628
        for i := len(hops) - 1; i >= 0; i-- {
6✔
1629
                toNode := hops[i]
3✔
1630

3✔
1631
                var fromNode route.Vertex
3✔
1632
                if i == 0 {
6✔
1633
                        fromNode = source
3✔
1634
                } else {
6✔
1635
                        fromNode = hops[i-1]
3✔
1636
                }
3✔
1637

1638
                // Build unified policies for this hop based on the channels
1639
                // known in the graph. Inbound fees are only active if the edge
1640
                // is not the last hop.
1641
                isExitHop := i == len(hops)-1
3✔
1642
                u := newNodeEdgeUnifier(
3✔
1643
                        source, toNode, !isExitHop, outgoingChans,
3✔
1644
                )
3✔
1645

3✔
1646
                err := u.addGraphPolicies(graph)
3✔
1647
                if err != nil {
3✔
1648
                        return nil, err
×
1649
                }
×
1650

1651
                // Exit if there are no channels.
1652
                edgeUnifier, ok := u.edgeUnifiers[fromNode]
3✔
1653
                if !ok {
3✔
UNCOV
1654
                        log.Errorf("Cannot find policy for node %v", fromNode)
×
UNCOV
1655
                        return nil, ErrNoChannel{position: i}
×
UNCOV
1656
                }
×
1657

1658
                unifiers[i] = edgeUnifier
3✔
1659
        }
1660

1661
        return unifiers, nil
3✔
1662
}
1663

1664
// senderAmtBackwardPass returns a list of unified edges for the given route and
1665
// determines the amount that should be sent to fulfill min HTLC requirements.
1666
// The minimal sender amount can be searched for by using amt=None.
1667
func senderAmtBackwardPass(unifiers []*edgeUnifier,
1668
        amt fn.Option[lnwire.MilliSatoshi],
1669
        bandwidthHints bandwidthHints) ([]*unifiedEdge, lnwire.MilliSatoshi,
1670
        error) {
3✔
1671

3✔
1672
        if len(unifiers) == 0 {
3✔
UNCOV
1673
                return nil, 0, fmt.Errorf("no unifiers provided")
×
UNCOV
1674
        }
×
1675

1676
        var unifiedEdges = make([]*unifiedEdge, len(unifiers))
3✔
1677

3✔
1678
        // We traverse the route backwards and handle the last hop separately.
3✔
1679
        edgeUnifier := unifiers[len(unifiers)-1]
3✔
1680

3✔
1681
        // incomingAmt tracks the amount that is forwarded on the edges of a
3✔
1682
        // route. The last hop only forwards the amount that the receiver should
3✔
1683
        // receive, as there are no fees paid to the last node.
3✔
1684
        // For minimum amount routes, aim to deliver at least 1 msat to
3✔
1685
        // the destination. There are nodes in the wild that have a
3✔
1686
        // min_htlc channel policy of zero, which could lead to a zero
3✔
1687
        // amount payment being made.
3✔
1688
        incomingAmt := amt.UnwrapOr(1)
3✔
1689

3✔
1690
        // If using min amt, increase the amount if needed to fulfill min HTLC
3✔
1691
        // requirements.
3✔
1692
        if amt.IsNone() {
3✔
UNCOV
1693
                min := edgeUnifier.minAmt()
×
UNCOV
1694
                if min > incomingAmt {
×
UNCOV
1695
                        incomingAmt = min
×
UNCOV
1696
                }
×
1697
        }
1698

1699
        // Get an edge for the specific amount that we want to forward.
1700
        edge := edgeUnifier.getEdge(incomingAmt, bandwidthHints, 0)
3✔
1701
        if edge == nil {
3✔
UNCOV
1702
                log.Errorf("Cannot find policy with amt=%v "+
×
UNCOV
1703
                        "for hop %v", incomingAmt, len(unifiers)-1)
×
UNCOV
1704

×
UNCOV
1705
                return nil, 0, ErrNoChannel{position: len(unifiers) - 1}
×
UNCOV
1706
        }
×
1707

1708
        unifiedEdges[len(unifiers)-1] = edge
3✔
1709

3✔
1710
        // Handle the rest of the route except the last hop.
3✔
1711
        for i := len(unifiers) - 2; i >= 0; i-- {
6✔
1712
                edgeUnifier = unifiers[i]
3✔
1713

3✔
1714
                // If using min amt, increase the amount if needed to fulfill
3✔
1715
                // min HTLC requirements.
3✔
1716
                if amt.IsNone() {
3✔
UNCOV
1717
                        min := edgeUnifier.minAmt()
×
UNCOV
1718
                        if min > incomingAmt {
×
1719
                                incomingAmt = min
×
1720
                        }
×
1721
                }
1722

1723
                // A --current hop-- B --next hop: incomingAmt-- C
1724
                // The outbound fee paid to the current end node B is based on
1725
                // the amount that the next hop forwards and B's policy for that
1726
                // hop.
1727
                outboundFee := unifiedEdges[i+1].policy.ComputeFee(
3✔
1728
                        incomingAmt,
3✔
1729
                )
3✔
1730

3✔
1731
                netAmount := incomingAmt + outboundFee
3✔
1732

3✔
1733
                // We need to select an edge that can forward the requested
3✔
1734
                // amount.
3✔
1735
                edge = edgeUnifier.getEdge(
3✔
1736
                        netAmount, bandwidthHints, outboundFee,
3✔
1737
                )
3✔
1738
                if edge == nil {
3✔
UNCOV
1739
                        return nil, 0, ErrNoChannel{position: i}
×
UNCOV
1740
                }
×
1741

1742
                // The fee paid to B depends on the current hop's inbound fee
1743
                // policy and on the outbound fee for the next hop as any
1744
                // inbound fee discount is capped by the outbound fee such that
1745
                // the total fee for B can't become negative.
1746
                inboundFee := calcCappedInboundFee(edge, netAmount, outboundFee)
3✔
1747

3✔
1748
                fee := lnwire.MilliSatoshi(int64(outboundFee) + inboundFee)
3✔
1749

3✔
1750
                log.Tracef("Select channel %v at position %v",
3✔
1751
                        edge.policy.ChannelID, i)
3✔
1752

3✔
1753
                // Finally, we update the amount that needs to flow into node B
3✔
1754
                // from A, which is the next hop's forwarding amount plus the
3✔
1755
                // fee for B: A --current hop: incomingAmt-- B --next hop-- C
3✔
1756
                incomingAmt += fee
3✔
1757

3✔
1758
                unifiedEdges[i] = edge
3✔
1759
        }
1760

1761
        return unifiedEdges, incomingAmt, nil
3✔
1762
}
1763

1764
// receiverAmtForwardPass returns the amount that a receiver will receive after
1765
// deducting all fees from the sender amount.
1766
func receiverAmtForwardPass(runningAmt lnwire.MilliSatoshi,
UNCOV
1767
        unifiedEdges []*unifiedEdge) (lnwire.MilliSatoshi, error) {
×
UNCOV
1768

×
UNCOV
1769
        if len(unifiedEdges) == 0 {
×
UNCOV
1770
                return 0, fmt.Errorf("no edges to forward through")
×
UNCOV
1771
        }
×
1772

UNCOV
1773
        inEdge := unifiedEdges[0]
×
UNCOV
1774
        if !inEdge.amtInRange(runningAmt) {
×
UNCOV
1775
                log.Errorf("Amount %v not in range for hop index %v",
×
UNCOV
1776
                        runningAmt, 0)
×
UNCOV
1777

×
UNCOV
1778
                return 0, ErrNoChannel{position: 0}
×
UNCOV
1779
        }
×
1780

1781
        // Now that we arrived at the start of the route and found out the route
1782
        // total amount, we make a forward pass. Because the amount may have
1783
        // been increased in the backward pass, fees need to be recalculated and
1784
        // amount ranges re-checked.
UNCOV
1785
        for i := 1; i < len(unifiedEdges); i++ {
×
UNCOV
1786
                inEdge := unifiedEdges[i-1]
×
UNCOV
1787
                outEdge := unifiedEdges[i]
×
UNCOV
1788

×
UNCOV
1789
                // Decrease the amount to send while going forward.
×
UNCOV
1790
                runningAmt = outgoingFromIncoming(runningAmt, inEdge, outEdge)
×
UNCOV
1791

×
UNCOV
1792
                if !outEdge.amtInRange(runningAmt) {
×
1793
                        log.Errorf("Amount %v not in range for hop index %v",
×
1794
                                runningAmt, i)
×
1795

×
1796
                        return 0, ErrNoChannel{position: i}
×
1797
                }
×
1798
        }
1799

UNCOV
1800
        return runningAmt, nil
×
1801
}
1802

1803
// incomingFromOutgoing computes the incoming amount based on the outgoing
1804
// amount by adding fees to the outgoing amount, replicating the path finding
1805
// and routing process, see also CheckHtlcForward.
1806
func incomingFromOutgoing(outgoingAmt lnwire.MilliSatoshi,
UNCOV
1807
        incoming, outgoing *unifiedEdge) lnwire.MilliSatoshi {
×
UNCOV
1808

×
UNCOV
1809
        outgoingFee := outgoing.policy.ComputeFee(outgoingAmt)
×
UNCOV
1810

×
UNCOV
1811
        // Net amount is the amount the inbound fees are calculated with.
×
UNCOV
1812
        netAmount := outgoingAmt + outgoingFee
×
UNCOV
1813

×
UNCOV
1814
        inboundFee := incoming.inboundFees.CalcFee(netAmount)
×
UNCOV
1815

×
UNCOV
1816
        // The inbound fee is not allowed to reduce the incoming amount below
×
UNCOV
1817
        // the outgoing amount.
×
UNCOV
1818
        if int64(outgoingFee)+inboundFee < 0 {
×
UNCOV
1819
                return outgoingAmt
×
UNCOV
1820
        }
×
1821

UNCOV
1822
        return netAmount + lnwire.MilliSatoshi(inboundFee)
×
1823
}
1824

1825
// outgoingFromIncoming computes the outgoing amount based on the incoming
1826
// amount by subtracting fees from the incoming amount. Note that this is not
1827
// exactly the inverse of incomingFromOutgoing, because of some rounding.
1828
func outgoingFromIncoming(incomingAmt lnwire.MilliSatoshi,
UNCOV
1829
        incoming, outgoing *unifiedEdge) lnwire.MilliSatoshi {
×
UNCOV
1830

×
UNCOV
1831
        // Convert all quantities to big.Int to be able to hande negative
×
UNCOV
1832
        // values. The formulas to compute the outgoing amount involve terms
×
UNCOV
1833
        // with PPM*PPM*A, which can easily overflow an int64.
×
UNCOV
1834
        A := big.NewInt(int64(incomingAmt))
×
UNCOV
1835
        Ro := big.NewInt(int64(outgoing.policy.FeeProportionalMillionths))
×
UNCOV
1836
        Bo := big.NewInt(int64(outgoing.policy.FeeBaseMSat))
×
UNCOV
1837
        Ri := big.NewInt(int64(incoming.inboundFees.Rate))
×
UNCOV
1838
        Bi := big.NewInt(int64(incoming.inboundFees.Base))
×
UNCOV
1839
        PPM := big.NewInt(1_000_000)
×
UNCOV
1840

×
UNCOV
1841
        // The following discussion was contributed by user feelancer21, see
×
UNCOV
1842
        //nolint:ll
×
UNCOV
1843
        // https://github.com/feelancer21/lnd/commit/f6f05fa930985aac0d27c3f6681aada1b599162a.
×
UNCOV
1844

×
UNCOV
1845
        // The incoming amount Ai based on the outgoing amount Ao is computed by
×
UNCOV
1846
        // Ai = max(Ai(Ao), Ao), which caps the incoming amount such that the
×
UNCOV
1847
        // total node fee (Ai - Ao) is non-negative. This is commonly enforced
×
UNCOV
1848
        // by routing nodes.
×
UNCOV
1849

×
UNCOV
1850
        // The function Ai(Ao) is given by:
×
UNCOV
1851
        // Ai(Ao) = (Ao + Bo + Ro/PPM) + (Bi + (Ao + Ro/PPM + Bo)*Ri/PPM), where
×
UNCOV
1852
        // the first term is the net amount (the outgoing amount plus the
×
UNCOV
1853
        // outbound fee), and the second is the inbound fee computed based on
×
UNCOV
1854
        // the net amount.
×
UNCOV
1855

×
UNCOV
1856
        // Ai(Ao) can potentially become more negative in absolute value than
×
UNCOV
1857
        // Ao, which is why the above mentioned capping is needed. We can
×
UNCOV
1858
        // abbreviate Ai(Ao) with Ai(Ao) = m*Ao + n, where m and n are:
×
UNCOV
1859
        // m := (1 + Ro/PPM) * (1 + Ri/PPM)
×
UNCOV
1860
        // n := Bi + Bo*(1 + Ri/PPM)
×
UNCOV
1861

×
UNCOV
1862
        // If we know that m > 0, this is equivalent of Ri/PPM > -1, because Ri
×
UNCOV
1863
        // is the only factor that can become negative. A value or Ri/PPM = -1,
×
UNCOV
1864
        // means that the routing node is willing to give up on 100% of the
×
UNCOV
1865
        // net amount (based on the fee rate), which is likely to not happen in
×
UNCOV
1866
        // practice. This condition will be important for a later trick.
×
UNCOV
1867

×
UNCOV
1868
        // If we want to compute the incoming amount based on the outgoing
×
UNCOV
1869
        // amount, which is the reverse problem, we need to solve Ai =
×
UNCOV
1870
        // max(Ai(Ao), Ao) for Ao(Ai). Given an incoming amount A,
×
UNCOV
1871
        // we look for an Ao such that A = max(Ai(Ao), Ao).
×
UNCOV
1872

×
UNCOV
1873
        // The max function separates this into two cases. The case to take is
×
UNCOV
1874
        // not clear yet, because we don't know Ao, but later we see a trick
×
UNCOV
1875
        // how to determine which case is the one to take.
×
UNCOV
1876

×
UNCOV
1877
        // first case: Ai(Ao) <= Ao:
×
UNCOV
1878
        // Therefore, A = max(Ai(Ao), Ao) = Ao, we find Ao = A.
×
UNCOV
1879
        // This also leads to Ai(A) <= A by substitution into the condition.
×
UNCOV
1880

×
UNCOV
1881
        // second case: Ai(Ao) > Ao:
×
UNCOV
1882
        // Therefore, A = max(Ai(Ao), Ao) = Ai(Ao) = m*Ao + n. Solving for Ao
×
UNCOV
1883
        // gives Ao = (A - n)/m.
×
UNCOV
1884
        //
×
UNCOV
1885
        // We know
×
UNCOV
1886
        // Ai(Ao) > Ao  <=>  A = Ai(Ao) > Ao = (A - n)/m,
×
UNCOV
1887
        // so A > (A - n)/m.
×
UNCOV
1888
        //
×
UNCOV
1889
        // **Assuming m > 0**, by multiplying with m, we can transform this to
×
UNCOV
1890
        // A * m + n > A.
×
UNCOV
1891
        //
×
UNCOV
1892
        // We know Ai(A) = A*m + n, therefore Ai(A) > A.
×
UNCOV
1893
        //
×
UNCOV
1894
        // This means that if we apply the incoming amount calculation to the
×
UNCOV
1895
        // **incoming** amount, and this condition holds, then we know that we
×
UNCOV
1896
        // deal with the second case, being able to compute the outgoing amount
×
UNCOV
1897
        // based off the formula Ao = (A - n)/m, otherwise we will just return
×
UNCOV
1898
        // the incoming amount.
×
UNCOV
1899

×
UNCOV
1900
        // In case the inbound fee rate is less than -1 (-100%), we fail to
×
UNCOV
1901
        // compute the outbound amount and return the incoming amount. This also
×
UNCOV
1902
        // protects against zero division later.
×
UNCOV
1903

×
UNCOV
1904
        // We compute m in terms of big.Int to be safe from overflows and to be
×
UNCOV
1905
        // consistent with later calculations.
×
UNCOV
1906
        // m := (PPM*PPM + Ri*PPM + Ro*PPM + Ro*Ri)/(PPM*PPM)
×
UNCOV
1907

×
UNCOV
1908
        // Compute terms in (PPM*PPM + Ri*PPM + Ro*PPM + Ro*Ri).
×
UNCOV
1909
        m1 := new(big.Int).Mul(PPM, PPM)
×
UNCOV
1910
        m2 := new(big.Int).Mul(Ri, PPM)
×
UNCOV
1911
        m3 := new(big.Int).Mul(Ro, PPM)
×
UNCOV
1912
        m4 := new(big.Int).Mul(Ro, Ri)
×
UNCOV
1913

×
UNCOV
1914
        // Add up terms m1..m4.
×
UNCOV
1915
        m := big.NewInt(0)
×
UNCOV
1916
        m.Add(m, m1)
×
UNCOV
1917
        m.Add(m, m2)
×
UNCOV
1918
        m.Add(m, m3)
×
UNCOV
1919
        m.Add(m, m4)
×
UNCOV
1920

×
UNCOV
1921
        // Since we compare to 0, we can multiply by PPM*PPM to avoid the
×
UNCOV
1922
        // division.
×
UNCOV
1923
        if m.Int64() <= 0 {
×
UNCOV
1924
                return incomingAmt
×
UNCOV
1925
        }
×
1926

1927
        // In order to decide if the total fee is negative, we apply the fee
1928
        // to the *incoming* amount as mentioned before.
1929

1930
        // We compute the test amount in terms of big.Int to be safe from
1931
        // overflows and to be consistent later calculations.
1932
        // testAmtF := A*m + n =
1933
        // = A + Bo + Bi + (PPM*(A*Ri + A*Ro + Ro*Ri) + A*Ri*Ro)/(PPM*PPM)
1934

1935
        // Compute terms in (A*Ri + A*Ro + Ro*Ri).
UNCOV
1936
        t1 := new(big.Int).Mul(A, Ri)
×
UNCOV
1937
        t2 := new(big.Int).Mul(A, Ro)
×
UNCOV
1938
        t3 := new(big.Int).Mul(Ro, Ri)
×
UNCOV
1939

×
UNCOV
1940
        // Sum up terms t1-t3.
×
UNCOV
1941
        t4 := big.NewInt(0)
×
UNCOV
1942
        t4.Add(t4, t1)
×
UNCOV
1943
        t4.Add(t4, t2)
×
UNCOV
1944
        t4.Add(t4, t3)
×
UNCOV
1945

×
UNCOV
1946
        // Compute PPM*(A*Ri + A*Ro + Ro*Ri).
×
UNCOV
1947
        t6 := new(big.Int).Mul(PPM, t4)
×
UNCOV
1948

×
UNCOV
1949
        // Compute A*Ri*Ro.
×
UNCOV
1950
        t7 := new(big.Int).Mul(A, Ri)
×
UNCOV
1951
        t7.Mul(t7, Ro)
×
UNCOV
1952

×
UNCOV
1953
        // Compute (PPM*(A*Ri + A*Ro + Ro*Ri) + A*Ri*Ro)/(PPM*PPM).
×
UNCOV
1954
        num := new(big.Int).Add(t6, t7)
×
UNCOV
1955
        denom := new(big.Int).Mul(PPM, PPM)
×
UNCOV
1956
        fraction := new(big.Int).Div(num, denom)
×
UNCOV
1957

×
UNCOV
1958
        // Sum up all terms.
×
UNCOV
1959
        testAmt := big.NewInt(0)
×
UNCOV
1960
        testAmt.Add(testAmt, A)
×
UNCOV
1961
        testAmt.Add(testAmt, Bo)
×
UNCOV
1962
        testAmt.Add(testAmt, Bi)
×
UNCOV
1963
        testAmt.Add(testAmt, fraction)
×
UNCOV
1964

×
UNCOV
1965
        // Protect against negative values for the integer cast to Msat.
×
UNCOV
1966
        if testAmt.Int64() < 0 {
×
UNCOV
1967
                return incomingAmt
×
UNCOV
1968
        }
×
1969

1970
        // If the second case holds, we have to compute the outgoing amount.
UNCOV
1971
        if lnwire.MilliSatoshi(testAmt.Int64()) > incomingAmt {
×
UNCOV
1972
                // Compute the outgoing amount by integer ceiling division. This
×
UNCOV
1973
                // precision is needed because PPM*PPM*A and other terms can
×
UNCOV
1974
                // easily overflow with int64, which happens with about
×
UNCOV
1975
                // A = 10_000 sat.
×
UNCOV
1976

×
UNCOV
1977
                // out := (A - n) / m = numerator / denominator
×
UNCOV
1978
                // numerator := PPM*(PPM*(A - Bo - Bi) - Bo*Ri)
×
UNCOV
1979
                // denominator := PPM*(PPM + Ri + Ro) + Ri*Ro
×
UNCOV
1980

×
UNCOV
1981
                var numerator big.Int
×
UNCOV
1982

×
UNCOV
1983
                // Compute (A - Bo - Bi).
×
UNCOV
1984
                temp1 := new(big.Int).Sub(A, Bo)
×
UNCOV
1985
                temp2 := new(big.Int).Sub(temp1, Bi)
×
UNCOV
1986

×
UNCOV
1987
                // Compute terms in (PPM*(A - Bo - Bi) - Bo*Ri).
×
UNCOV
1988
                temp3 := new(big.Int).Mul(PPM, temp2)
×
UNCOV
1989
                temp4 := new(big.Int).Mul(Bo, Ri)
×
UNCOV
1990

×
UNCOV
1991
                // Compute PPM*(PPM*(A - Bo - Bi) - Bo*Ri)
×
UNCOV
1992
                temp5 := new(big.Int).Sub(temp3, temp4)
×
UNCOV
1993
                numerator.Mul(PPM, temp5)
×
UNCOV
1994

×
UNCOV
1995
                var denominator big.Int
×
UNCOV
1996

×
UNCOV
1997
                // Compute (PPM + Ri + Ro).
×
UNCOV
1998
                temp1 = new(big.Int).Add(PPM, Ri)
×
UNCOV
1999
                temp2 = new(big.Int).Add(temp1, Ro)
×
UNCOV
2000

×
UNCOV
2001
                // Compute PPM*(PPM + Ri + Ro) + Ri*Ro.
×
UNCOV
2002
                temp3 = new(big.Int).Mul(PPM, temp2)
×
UNCOV
2003
                temp4 = new(big.Int).Mul(Ri, Ro)
×
UNCOV
2004
                denominator.Add(temp3, temp4)
×
UNCOV
2005

×
UNCOV
2006
                // We overestimate the outgoing amount by taking the ceiling of
×
UNCOV
2007
                // the division. This means that we may round slightly up by a
×
UNCOV
2008
                // MilliSatoshi, but this helps to ensure that we don't hit min
×
UNCOV
2009
                // HTLC constrains in the context of finding the minimum amount
×
UNCOV
2010
                // of a route.
×
UNCOV
2011
                // ceil = floor((numerator + denominator - 1) / denominator)
×
UNCOV
2012
                ceil := new(big.Int).Add(&numerator, &denominator)
×
UNCOV
2013
                ceil.Sub(ceil, big.NewInt(1))
×
UNCOV
2014
                ceil.Div(ceil, &denominator)
×
UNCOV
2015

×
UNCOV
2016
                return lnwire.MilliSatoshi(ceil.Int64())
×
UNCOV
2017
        }
×
2018

2019
        // Otherwise the inbound fee made up for the outbound fee, which is why
2020
        // we just return the incoming amount.
UNCOV
2021
        return incomingAmt
×
2022
}
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