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

lightningnetwork / lnd / 17830307614

18 Sep 2025 01:29PM UTC coverage: 54.617% (-12.0%) from 66.637%
17830307614

Pull #10200

github

web-flow
Merge 181a0a7bc into b34fc964b
Pull Request #10200: github: change to form-based issue template

109249 of 200028 relevant lines covered (54.62%)

21896.43 hits per line

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

47.0
/lnrpc/routerrpc/router_backend.go
1
package routerrpc
2

3
import (
4
        "context"
5
        "crypto/rand"
6
        "encoding/hex"
7
        "errors"
8
        "fmt"
9
        math "math"
10
        "time"
11

12
        "github.com/btcsuite/btcd/btcec/v2"
13
        "github.com/btcsuite/btcd/btcutil"
14
        "github.com/btcsuite/btcd/chaincfg"
15
        "github.com/btcsuite/btcd/wire"
16
        sphinx "github.com/lightningnetwork/lightning-onion"
17
        "github.com/lightningnetwork/lnd/clock"
18
        "github.com/lightningnetwork/lnd/feature"
19
        "github.com/lightningnetwork/lnd/fn/v2"
20
        "github.com/lightningnetwork/lnd/htlcswitch"
21
        "github.com/lightningnetwork/lnd/lnrpc"
22
        "github.com/lightningnetwork/lnd/lntypes"
23
        "github.com/lightningnetwork/lnd/lnwire"
24
        paymentsdb "github.com/lightningnetwork/lnd/payments/db"
25
        "github.com/lightningnetwork/lnd/record"
26
        "github.com/lightningnetwork/lnd/routing"
27
        "github.com/lightningnetwork/lnd/routing/route"
28
        "github.com/lightningnetwork/lnd/subscribe"
29
        "github.com/lightningnetwork/lnd/zpay32"
30
        "google.golang.org/protobuf/proto"
31
)
32

33
const (
34
        // DefaultMaxParts is the default number of splits we'll possibly use
35
        // for MPP when the user is attempting to send a payment.
36
        //
37
        // TODO(roasbeef): make this value dynamic based on expected number of
38
        // attempts for given amount.
39
        DefaultMaxParts = 16
40

41
        // MaxPartsUpperLimit defines the maximum allowable number of splits
42
        // for MPP/AMP when the user is attempting to send a payment.
43
        MaxPartsUpperLimit = 1000
44
)
45

46
// RouterBackend contains the backend implementation of the router rpc sub
47
// server calls.
48
type RouterBackend struct {
49
        // SelfNode is the vertex of the node sending the payment.
50
        SelfNode route.Vertex
51

52
        // FetchChannelCapacity is a closure that we'll use the fetch the total
53
        // capacity of a channel to populate in responses.
54
        FetchChannelCapacity func(chanID uint64) (btcutil.Amount, error)
55

56
        // FetchAmountPairCapacity determines the maximal channel capacity
57
        // between two nodes given a certain amount.
58
        FetchAmountPairCapacity func(nodeFrom, nodeTo route.Vertex,
59
                amount lnwire.MilliSatoshi) (btcutil.Amount, error)
60

61
        // FetchChannelEndpoints returns the pubkeys of both endpoints of the
62
        // given channel id.
63
        FetchChannelEndpoints func(chanID uint64) (route.Vertex,
64
                route.Vertex, error)
65

66
        // FindRoute is a closure that abstracts away how we locate/query for
67
        // routes.
68
        FindRoute func(*routing.RouteRequest) (*route.Route, float64, error)
69

70
        MissionControl MissionControl
71

72
        // ActiveNetParams are the network parameters of the primary network
73
        // that the route is operating on. This is necessary so we can ensure
74
        // that we receive payment requests that send to destinations on our
75
        // network.
76
        ActiveNetParams *chaincfg.Params
77

78
        // Tower is the ControlTower instance that is used to track pending
79
        // payments.
80
        Tower routing.ControlTower
81

82
        // MaxTotalTimelock is the maximum total time lock a route is allowed to
83
        // have.
84
        MaxTotalTimelock uint32
85

86
        // DefaultFinalCltvDelta is the default value used as final cltv delta
87
        // when an RPC caller doesn't specify a value.
88
        DefaultFinalCltvDelta uint16
89

90
        // SubscribeHtlcEvents returns a subscription client for the node's
91
        // htlc events.
92
        SubscribeHtlcEvents func() (*subscribe.Client, error)
93

94
        // InterceptableForwarder exposes the ability to intercept forward events
95
        // by letting the router register a ForwardInterceptor.
96
        InterceptableForwarder htlcswitch.InterceptableHtlcForwarder
97

98
        // SetChannelEnabled exposes the ability to manually enable a channel.
99
        SetChannelEnabled func(wire.OutPoint) error
100

101
        // SetChannelDisabled exposes the ability to manually disable a channel
102
        SetChannelDisabled func(wire.OutPoint) error
103

104
        // SetChannelAuto exposes the ability to restore automatic channel state
105
        // management after manually setting channel status.
106
        SetChannelAuto func(wire.OutPoint) error
107

108
        // UseStatusInitiated is a boolean that indicates whether the router
109
        // should use the new status code `Payment_INITIATED`.
110
        //
111
        // TODO(yy): remove this config after the new status code is fully
112
        // deployed to the network(v0.20.0).
113
        UseStatusInitiated bool
114

115
        // ParseCustomChannelData is a function that can be used to parse custom
116
        // channel data from the first hop of a route.
117
        ParseCustomChannelData func(message proto.Message) error
118

119
        // ShouldSetExpEndorsement returns a boolean indicating whether the
120
        // experimental endorsement bit should be set.
121
        ShouldSetExpEndorsement func() bool
122

123
        // Clock is the clock used to validate payment requests expiry.
124
        // It is useful for testing.
125
        Clock clock.Clock
126
}
127

128
// MissionControl defines the mission control dependencies of routerrpc.
129
type MissionControl interface {
130
        // GetProbability is expected to return the success probability of a
131
        // payment from fromNode to toNode.
132
        GetProbability(fromNode, toNode route.Vertex,
133
                amt lnwire.MilliSatoshi, capacity btcutil.Amount) float64
134

135
        // ResetHistory resets the history of MissionControl returning it to a
136
        // state as if no payment attempts have been made.
137
        ResetHistory() error
138

139
        // GetHistorySnapshot takes a snapshot from the current mission control
140
        // state and actual probability estimates.
141
        GetHistorySnapshot() *routing.MissionControlSnapshot
142

143
        // ImportHistory imports the mission control snapshot to our internal
144
        // state. This import will only be applied in-memory, and will not be
145
        // persisted across restarts.
146
        ImportHistory(snapshot *routing.MissionControlSnapshot, force bool) error
147

148
        // GetPairHistorySnapshot returns the stored history for a given node
149
        // pair.
150
        GetPairHistorySnapshot(fromNode,
151
                toNode route.Vertex) routing.TimedPairResult
152

153
        // GetConfig gets mission control's current config.
154
        GetConfig() *routing.MissionControlConfig
155

156
        // SetConfig sets mission control's config to the values provided, if
157
        // they are valid.
158
        SetConfig(cfg *routing.MissionControlConfig) error
159
}
160

161
// QueryRoutes attempts to query the daemons' Channel Router for a possible
162
// route to a target destination capable of carrying a specific amount of
163
// satoshis within the route's flow. The returned route contains the full
164
// details required to craft and send an HTLC, also including the necessary
165
// information that should be present within the Sphinx packet encapsulated
166
// within the HTLC.
167
//
168
// TODO(roasbeef): should return a slice of routes in reality * create separate
169
// PR to send based on well formatted route
170
func (r *RouterBackend) QueryRoutes(ctx context.Context,
171
        in *lnrpc.QueryRoutesRequest) (*lnrpc.QueryRoutesResponse, error) {
6✔
172

6✔
173
        routeReq, err := r.parseQueryRoutesRequest(in)
6✔
174
        if err != nil {
8✔
175
                return nil, err
2✔
176
        }
2✔
177

178
        // Query the channel router for a possible path to the destination that
179
        // can carry `in.Amt` satoshis _including_ the total fee required on
180
        // the route
181
        route, successProb, err := r.FindRoute(routeReq)
4✔
182
        if err != nil {
4✔
183
                return nil, err
×
184
        }
×
185

186
        // For each valid route, we'll convert the result into the format
187
        // required by the RPC system.
188
        rpcRoute, err := r.MarshallRoute(route)
4✔
189
        if err != nil {
4✔
190
                return nil, err
×
191
        }
×
192

193
        routeResp := &lnrpc.QueryRoutesResponse{
4✔
194
                Routes:      []*lnrpc.Route{rpcRoute},
4✔
195
                SuccessProb: successProb,
4✔
196
        }
4✔
197

4✔
198
        return routeResp, nil
4✔
199
}
200

201
func parsePubKey(key string) (route.Vertex, error) {
6✔
202
        pubKeyBytes, err := hex.DecodeString(key)
6✔
203
        if err != nil {
6✔
204
                return route.Vertex{}, err
×
205
        }
×
206

207
        return route.NewVertexFromBytes(pubKeyBytes)
6✔
208
}
209

210
func (r *RouterBackend) parseIgnored(in *lnrpc.QueryRoutesRequest) (
211
        map[route.Vertex]struct{}, map[routing.DirectedNodePair]struct{},
212
        error) {
5✔
213

5✔
214
        ignoredNodes := make(map[route.Vertex]struct{})
5✔
215
        for _, ignorePubKey := range in.IgnoredNodes {
10✔
216
                ignoreVertex, err := route.NewVertexFromBytes(ignorePubKey)
5✔
217
                if err != nil {
5✔
218
                        return nil, nil, err
×
219
                }
×
220
                ignoredNodes[ignoreVertex] = struct{}{}
5✔
221
        }
222

223
        ignoredPairs := make(map[routing.DirectedNodePair]struct{})
5✔
224

5✔
225
        // Convert deprecated ignoredEdges to pairs.
5✔
226
        for _, ignoredEdge := range in.IgnoredEdges {
10✔
227
                pair, err := r.rpcEdgeToPair(ignoredEdge)
5✔
228
                if err != nil {
5✔
229
                        log.Warnf("Ignore channel %v skipped: %v",
×
230
                                ignoredEdge.ChannelId, err)
×
231

×
232
                        continue
×
233
                }
234
                ignoredPairs[pair] = struct{}{}
5✔
235
        }
236

237
        // Add ignored pairs to set.
238
        for _, ignorePair := range in.IgnoredPairs {
10✔
239
                from, err := route.NewVertexFromBytes(ignorePair.From)
5✔
240
                if err != nil {
5✔
241
                        return nil, nil, err
×
242
                }
×
243

244
                to, err := route.NewVertexFromBytes(ignorePair.To)
5✔
245
                if err != nil {
5✔
246
                        return nil, nil, err
×
247
                }
×
248

249
                pair := routing.NewDirectedNodePair(from, to)
5✔
250
                ignoredPairs[pair] = struct{}{}
5✔
251
        }
252

253
        return ignoredNodes, ignoredPairs, nil
5✔
254
}
255

256
func (r *RouterBackend) parseQueryRoutesRequest(in *lnrpc.QueryRoutesRequest) (
257
        *routing.RouteRequest, error) {
6✔
258

6✔
259
        // Parse the hex-encoded source public key into a full public key that
6✔
260
        // we can properly manipulate.
6✔
261

6✔
262
        var sourcePubKey route.Vertex
6✔
263
        if in.SourcePubKey != "" {
6✔
264
                var err error
×
265
                sourcePubKey, err = parsePubKey(in.SourcePubKey)
×
266
                if err != nil {
×
267
                        return nil, err
×
268
                }
×
269
        } else {
6✔
270
                // If no source is specified, use self.
6✔
271
                sourcePubKey = r.SelfNode
6✔
272
        }
6✔
273

274
        // Currently, within the bootstrap phase of the network, we limit the
275
        // largest payment size allotted to (2^32) - 1 mSAT or 4.29 million
276
        // satoshis.
277
        amt, err := lnrpc.UnmarshallAmt(in.Amt, in.AmtMsat)
6✔
278
        if err != nil {
6✔
279
                return nil, err
×
280
        }
×
281

282
        // Unmarshall restrictions from request.
283
        feeLimit := lnrpc.CalculateFeeLimit(in.FeeLimit, amt)
6✔
284

6✔
285
        // Since QueryRoutes allows having a different source other than
6✔
286
        // ourselves, we'll only apply our max time lock if we are the source.
6✔
287
        maxTotalTimelock := r.MaxTotalTimelock
6✔
288
        if sourcePubKey != r.SelfNode {
6✔
289
                maxTotalTimelock = math.MaxUint32
×
290
        }
×
291

292
        cltvLimit, err := ValidateCLTVLimit(in.CltvLimit, maxTotalTimelock)
6✔
293
        if err != nil {
6✔
294
                return nil, err
×
295
        }
×
296

297
        // If we have a blinded path set, we'll get a few of our fields from
298
        // inside of the path rather than the request's fields.
299
        var (
6✔
300
                targetPubKey   *route.Vertex
6✔
301
                routeHintEdges map[route.Vertex][]routing.AdditionalEdge
6✔
302
                blindedPathSet *routing.BlindedPaymentPathSet
6✔
303

6✔
304
                // finalCLTVDelta varies depending on whether we're sending to
6✔
305
                // a blinded route or an unblinded node. For blinded paths,
6✔
306
                // our final cltv is already baked into the path so we restrict
6✔
307
                // this value to zero on the API. Bolt11 invoices have a
6✔
308
                // default, so we'll fill that in for the non-blinded case.
6✔
309
                finalCLTVDelta uint16
6✔
310

6✔
311
                // destinationFeatures is the set of features for the
6✔
312
                // destination node.
6✔
313
                destinationFeatures *lnwire.FeatureVector
6✔
314
        )
6✔
315

6✔
316
        // Validate that the fields provided in the request are sane depending
6✔
317
        // on whether it is using a blinded path or not.
6✔
318
        if len(in.BlindedPaymentPaths) > 0 {
6✔
319
                blindedPathSet, err = parseBlindedPaymentPaths(in)
×
320
                if err != nil {
×
321
                        return nil, err
×
322
                }
×
323

324
                pathFeatures := blindedPathSet.Features()
×
325
                if pathFeatures != nil {
×
326
                        destinationFeatures = pathFeatures.Clone()
×
327
                }
×
328
        } else {
6✔
329
                // If we do not have a blinded path, a target pubkey must be
6✔
330
                // set.
6✔
331
                pk, err := parsePubKey(in.PubKey)
6✔
332
                if err != nil {
6✔
333
                        return nil, err
×
334
                }
×
335
                targetPubKey = &pk
6✔
336

6✔
337
                // Convert route hints to an edge map.
6✔
338
                routeHints, err := unmarshallRouteHints(in.RouteHints)
6✔
339
                if err != nil {
6✔
340
                        return nil, err
×
341
                }
×
342

343
                routeHintEdges, err = routing.RouteHintsToEdges(
6✔
344
                        routeHints, *targetPubKey,
6✔
345
                )
6✔
346
                if err != nil {
6✔
347
                        return nil, err
×
348
                }
×
349

350
                // Set a non-zero final CLTV delta for payments that are not
351
                // to blinded paths, as bolt11 has a default final cltv delta
352
                // value that is used in the absence of a value.
353
                finalCLTVDelta = r.DefaultFinalCltvDelta
6✔
354
                if in.FinalCltvDelta != 0 {
12✔
355
                        finalCLTVDelta = uint16(in.FinalCltvDelta)
6✔
356
                }
6✔
357

358
                // Do bounds checking without block padding so we don't give
359
                // routes that will leave the router in a zombie payment state.
360
                err = routing.ValidateCLTVLimit(
6✔
361
                        cltvLimit, finalCLTVDelta, false,
6✔
362
                )
6✔
363
                if err != nil {
7✔
364
                        return nil, err
1✔
365
                }
1✔
366

367
                // Parse destination feature bits.
368
                destinationFeatures = UnmarshalFeatures(in.DestFeatures)
5✔
369
        }
370

371
        // We need to subtract the final delta before passing it into path
372
        // finding. The optimal path is independent of the final cltv delta and
373
        // the path finding algorithm is unaware of this value.
374
        cltvLimit -= uint32(finalCLTVDelta)
5✔
375

5✔
376
        ignoredNodes, ignoredPairs, err := r.parseIgnored(in)
5✔
377
        if err != nil {
5✔
378
                return nil, err
×
379
        }
×
380

381
        restrictions := &routing.RestrictParams{
5✔
382
                FeeLimit: feeLimit,
5✔
383
                ProbabilitySource: func(fromNode, toNode route.Vertex,
5✔
384
                        amt lnwire.MilliSatoshi,
5✔
385
                        capacity btcutil.Amount) float64 {
21✔
386

16✔
387
                        if _, ok := ignoredNodes[fromNode]; ok {
20✔
388
                                return 0
4✔
389
                        }
4✔
390

391
                        pair := routing.DirectedNodePair{
12✔
392
                                From: fromNode,
12✔
393
                                To:   toNode,
12✔
394
                        }
12✔
395
                        if _, ok := ignoredPairs[pair]; ok {
20✔
396
                                return 0
8✔
397
                        }
8✔
398

399
                        if !in.UseMissionControl {
7✔
400
                                return 1
3✔
401
                        }
3✔
402

403
                        return r.MissionControl.GetProbability(
1✔
404
                                fromNode, toNode, amt, capacity,
1✔
405
                        )
1✔
406
                },
407
                DestCustomRecords:     record.CustomSet(in.DestCustomRecords),
408
                CltvLimit:             cltvLimit,
409
                DestFeatures:          destinationFeatures,
410
                BlindedPaymentPathSet: blindedPathSet,
411
        }
412

413
        // We set the outgoing channel restrictions if the user provides a
414
        // list of channel ids. We also handle the case where the user
415
        // provides the deprecated `OutgoingChanId` field.
416
        switch {
5✔
417
        case len(in.OutgoingChanIds) > 0 && in.OutgoingChanId != 0:
1✔
418
                return nil, errors.New("outgoing_chan_id and " +
1✔
419
                        "outgoing_chan_ids cannot both be set")
1✔
420

421
        case len(in.OutgoingChanIds) > 0:
1✔
422
                restrictions.OutgoingChannelIDs = in.OutgoingChanIds
1✔
423

424
        case in.OutgoingChanId != 0:
3✔
425
                restrictions.OutgoingChannelIDs = []uint64{in.OutgoingChanId}
3✔
426
        }
427

428
        // Pass along a last hop restriction if specified.
429
        if len(in.LastHopPubkey) > 0 {
8✔
430
                lastHop, err := route.NewVertexFromBytes(
4✔
431
                        in.LastHopPubkey,
4✔
432
                )
4✔
433
                if err != nil {
4✔
434
                        return nil, err
×
435
                }
×
436
                restrictions.LastHop = &lastHop
4✔
437
        }
438

439
        // If we have any TLV records destined for the final hop, then we'll
440
        // attempt to decode them now into a form that the router can more
441
        // easily manipulate.
442
        customRecords := record.CustomSet(in.DestCustomRecords)
4✔
443
        if err := customRecords.Validate(); err != nil {
4✔
444
                return nil, err
×
445
        }
×
446

447
        return routing.NewRouteRequest(
4✔
448
                sourcePubKey, targetPubKey, amt, in.TimePref, restrictions,
4✔
449
                customRecords, routeHintEdges, blindedPathSet,
4✔
450
                finalCLTVDelta,
4✔
451
        )
4✔
452
}
453

454
func parseBlindedPaymentPaths(in *lnrpc.QueryRoutesRequest) (
455
        *routing.BlindedPaymentPathSet, error) {
×
456

×
457
        if len(in.PubKey) != 0 {
×
458
                return nil, fmt.Errorf("target pubkey: %x should not be set "+
×
459
                        "when blinded path is provided", in.PubKey)
×
460
        }
×
461

462
        if len(in.RouteHints) > 0 {
×
463
                return nil, errors.New("route hints and blinded path can't " +
×
464
                        "both be set")
×
465
        }
×
466

467
        if in.FinalCltvDelta != 0 {
×
468
                return nil, errors.New("final cltv delta should be " +
×
469
                        "zero for blinded paths")
×
470
        }
×
471

472
        // For blinded paths, we get one set of features for the relaying
473
        // intermediate nodes and the final destination. We don't allow the
474
        // destination feature bit field for regular payments to be set, as
475
        // this could lead to ambiguity.
476
        if len(in.DestFeatures) > 0 {
×
477
                return nil, errors.New("destination features should " +
×
478
                        "be populated in blinded path")
×
479
        }
×
480

481
        paths := make([]*routing.BlindedPayment, len(in.BlindedPaymentPaths))
×
482
        for i, paymentPath := range in.BlindedPaymentPaths {
×
483
                blindedPmt, err := unmarshalBlindedPayment(paymentPath)
×
484
                if err != nil {
×
485
                        return nil, fmt.Errorf("parse blinded payment: %w", err)
×
486
                }
×
487

488
                if err := blindedPmt.Validate(); err != nil {
×
489
                        return nil, fmt.Errorf("invalid blinded path: %w", err)
×
490
                }
×
491

492
                paths[i] = blindedPmt
×
493
        }
494

495
        return routing.NewBlindedPaymentPathSet(paths)
×
496
}
497

498
func unmarshalBlindedPayment(rpcPayment *lnrpc.BlindedPaymentPath) (
499
        *routing.BlindedPayment, error) {
×
500

×
501
        if rpcPayment == nil {
×
502
                return nil, errors.New("nil blinded payment")
×
503
        }
×
504

505
        path, err := unmarshalBlindedPaymentPaths(rpcPayment.BlindedPath)
×
506
        if err != nil {
×
507
                return nil, err
×
508
        }
×
509

510
        features := UnmarshalFeatures(rpcPayment.Features)
×
511

×
512
        return &routing.BlindedPayment{
×
513
                BlindedPath:         path,
×
514
                CltvExpiryDelta:     uint16(rpcPayment.TotalCltvDelta),
×
515
                BaseFee:             uint32(rpcPayment.BaseFeeMsat),
×
516
                ProportionalFeeRate: rpcPayment.ProportionalFeeRate,
×
517
                HtlcMinimum:         rpcPayment.HtlcMinMsat,
×
518
                HtlcMaximum:         rpcPayment.HtlcMaxMsat,
×
519
                Features:            features,
×
520
        }, nil
×
521
}
522

523
func unmarshalBlindedPaymentPaths(rpcPath *lnrpc.BlindedPath) (
524
        *sphinx.BlindedPath, error) {
×
525

×
526
        if rpcPath == nil {
×
527
                return nil, errors.New("blinded path required when blinded " +
×
528
                        "route is provided")
×
529
        }
×
530

531
        introduction, err := btcec.ParsePubKey(rpcPath.IntroductionNode)
×
532
        if err != nil {
×
533
                return nil, err
×
534
        }
×
535

536
        blinding, err := btcec.ParsePubKey(rpcPath.BlindingPoint)
×
537
        if err != nil {
×
538
                return nil, err
×
539
        }
×
540

541
        if len(rpcPath.BlindedHops) < 1 {
×
542
                return nil, errors.New("at least 1 blinded hops required")
×
543
        }
×
544

545
        path := &sphinx.BlindedPath{
×
546
                IntroductionPoint: introduction,
×
547
                BlindingPoint:     blinding,
×
548
                BlindedHops: make(
×
549
                        []*sphinx.BlindedHopInfo, len(rpcPath.BlindedHops),
×
550
                ),
×
551
        }
×
552

×
553
        for i, hop := range rpcPath.BlindedHops {
×
554
                path.BlindedHops[i], err = unmarshalBlindedHop(hop)
×
555
                if err != nil {
×
556
                        return nil, err
×
557
                }
×
558
        }
559

560
        return path, nil
×
561
}
562

563
func unmarshalBlindedHop(rpcHop *lnrpc.BlindedHop) (*sphinx.BlindedHopInfo,
564
        error) {
×
565

×
566
        pubkey, err := btcec.ParsePubKey(rpcHop.BlindedNode)
×
567
        if err != nil {
×
568
                return nil, err
×
569
        }
×
570

571
        if len(rpcHop.EncryptedData) == 0 {
×
572
                return nil, errors.New("empty encrypted data not allowed")
×
573
        }
×
574

575
        return &sphinx.BlindedHopInfo{
×
576
                BlindedNodePub: pubkey,
×
577
                CipherText:     rpcHop.EncryptedData,
×
578
        }, nil
×
579
}
580

581
// rpcEdgeToPair looks up the provided channel and returns the channel endpoints
582
// as a directed pair.
583
func (r *RouterBackend) rpcEdgeToPair(e *lnrpc.EdgeLocator) (
584
        routing.DirectedNodePair, error) {
5✔
585

5✔
586
        a, b, err := r.FetchChannelEndpoints(e.ChannelId)
5✔
587
        if err != nil {
5✔
588
                return routing.DirectedNodePair{}, err
×
589
        }
×
590

591
        var pair routing.DirectedNodePair
5✔
592
        if e.DirectionReverse {
10✔
593
                pair.From, pair.To = b, a
5✔
594
        } else {
5✔
595
                pair.From, pair.To = a, b
×
596
        }
×
597

598
        return pair, nil
5✔
599
}
600

601
// MarshallRoute marshalls an internal route to an rpc route struct.
602
func (r *RouterBackend) MarshallRoute(route *route.Route) (*lnrpc.Route, error) {
4✔
603
        resp := &lnrpc.Route{
4✔
604
                TotalTimeLock:      route.TotalTimeLock,
4✔
605
                TotalFees:          int64(route.TotalFees().ToSatoshis()),
4✔
606
                TotalFeesMsat:      int64(route.TotalFees()),
4✔
607
                TotalAmt:           int64(route.TotalAmount.ToSatoshis()),
4✔
608
                TotalAmtMsat:       int64(route.TotalAmount),
4✔
609
                Hops:               make([]*lnrpc.Hop, len(route.Hops)),
4✔
610
                FirstHopAmountMsat: int64(route.FirstHopAmount.Val.Int()),
4✔
611
        }
4✔
612

4✔
613
        // Encode the route's custom channel data (if available).
4✔
614
        if len(route.FirstHopWireCustomRecords) > 0 {
4✔
615
                customData, err := route.FirstHopWireCustomRecords.Serialize()
×
616
                if err != nil {
×
617
                        return nil, err
×
618
                }
×
619

620
                resp.CustomChannelData = customData
×
621

×
622
                // Allow the aux data parser to parse the custom records into
×
623
                // a human-readable JSON (if available).
×
624
                if r.ParseCustomChannelData != nil {
×
625
                        err := r.ParseCustomChannelData(resp)
×
626
                        if err != nil {
×
627
                                return nil, err
×
628
                        }
×
629
                }
630
        }
631

632
        incomingAmt := route.TotalAmount
4✔
633
        for i, hop := range route.Hops {
8✔
634
                fee := route.HopFee(i)
4✔
635

4✔
636
                // Channel capacity is not a defining property of a route. For
4✔
637
                // backwards RPC compatibility, we retrieve it here from the
4✔
638
                // graph.
4✔
639
                chanCapacity, err := r.FetchChannelCapacity(hop.ChannelID)
4✔
640
                if err != nil {
4✔
641
                        // If capacity cannot be retrieved, this may be a
×
642
                        // not-yet-received or private channel. Then report
×
643
                        // amount that is sent through the channel as capacity.
×
644
                        chanCapacity = incomingAmt.ToSatoshis()
×
645
                }
×
646

647
                // Extract the MPP fields if present on this hop.
648
                var mpp *lnrpc.MPPRecord
4✔
649
                if hop.MPP != nil {
4✔
650
                        addr := hop.MPP.PaymentAddr()
×
651

×
652
                        mpp = &lnrpc.MPPRecord{
×
653
                                PaymentAddr:  addr[:],
×
654
                                TotalAmtMsat: int64(hop.MPP.TotalMsat()),
×
655
                        }
×
656
                }
×
657

658
                var amp *lnrpc.AMPRecord
4✔
659
                if hop.AMP != nil {
4✔
660
                        rootShare := hop.AMP.RootShare()
×
661
                        setID := hop.AMP.SetID()
×
662

×
663
                        amp = &lnrpc.AMPRecord{
×
664
                                RootShare:  rootShare[:],
×
665
                                SetId:      setID[:],
×
666
                                ChildIndex: hop.AMP.ChildIndex(),
×
667
                        }
×
668
                }
×
669

670
                resp.Hops[i] = &lnrpc.Hop{
4✔
671
                        ChanId:           hop.ChannelID,
4✔
672
                        ChanCapacity:     int64(chanCapacity),
4✔
673
                        AmtToForward:     int64(hop.AmtToForward.ToSatoshis()),
4✔
674
                        AmtToForwardMsat: int64(hop.AmtToForward),
4✔
675
                        Fee:              int64(fee.ToSatoshis()),
4✔
676
                        FeeMsat:          int64(fee),
4✔
677
                        Expiry:           uint32(hop.OutgoingTimeLock),
4✔
678
                        PubKey: hex.EncodeToString(
4✔
679
                                hop.PubKeyBytes[:],
4✔
680
                        ),
4✔
681
                        CustomRecords: hop.CustomRecords,
4✔
682
                        TlvPayload:    !hop.LegacyPayload,
4✔
683
                        MppRecord:     mpp,
4✔
684
                        AmpRecord:     amp,
4✔
685
                        Metadata:      hop.Metadata,
4✔
686
                        EncryptedData: hop.EncryptedData,
4✔
687
                        TotalAmtMsat:  uint64(hop.TotalAmtMsat),
4✔
688
                }
4✔
689

4✔
690
                if hop.BlindingPoint != nil {
4✔
691
                        blinding := hop.BlindingPoint.SerializeCompressed()
×
692
                        resp.Hops[i].BlindingPoint = blinding
×
693
                }
×
694
                incomingAmt = hop.AmtToForward
4✔
695
        }
696

697
        return resp, nil
4✔
698
}
699

700
// UnmarshallHopWithPubkey unmarshalls an rpc hop for which the pubkey has
701
// already been extracted.
702
func UnmarshallHopWithPubkey(rpcHop *lnrpc.Hop, pubkey route.Vertex) (*route.Hop,
703
        error) {
×
704

×
705
        customRecords := record.CustomSet(rpcHop.CustomRecords)
×
706
        if err := customRecords.Validate(); err != nil {
×
707
                return nil, err
×
708
        }
×
709

710
        mpp, err := UnmarshalMPP(rpcHop.MppRecord)
×
711
        if err != nil {
×
712
                return nil, err
×
713
        }
×
714

715
        amp, err := UnmarshalAMP(rpcHop.AmpRecord)
×
716
        if err != nil {
×
717
                return nil, err
×
718
        }
×
719

720
        hop := &route.Hop{
×
721
                OutgoingTimeLock: rpcHop.Expiry,
×
722
                AmtToForward:     lnwire.MilliSatoshi(rpcHop.AmtToForwardMsat),
×
723
                PubKeyBytes:      pubkey,
×
724
                ChannelID:        rpcHop.ChanId,
×
725
                CustomRecords:    customRecords,
×
726
                LegacyPayload:    false,
×
727
                MPP:              mpp,
×
728
                AMP:              amp,
×
729
                EncryptedData:    rpcHop.EncryptedData,
×
730
                TotalAmtMsat:     lnwire.MilliSatoshi(rpcHop.TotalAmtMsat),
×
731
        }
×
732

×
733
        haveBlindingPoint := len(rpcHop.BlindingPoint) != 0
×
734
        if haveBlindingPoint {
×
735
                hop.BlindingPoint, err = btcec.ParsePubKey(
×
736
                        rpcHop.BlindingPoint,
×
737
                )
×
738
                if err != nil {
×
739
                        return nil, fmt.Errorf("blinding point: %w", err)
×
740
                }
×
741
        }
742

743
        if haveBlindingPoint && len(rpcHop.EncryptedData) == 0 {
×
744
                return nil, errors.New("encrypted data should be present if " +
×
745
                        "blinding point is provided")
×
746
        }
×
747

748
        return hop, nil
×
749
}
750

751
// UnmarshallHop unmarshalls an rpc hop that may or may not contain a node
752
// pubkey.
753
func (r *RouterBackend) UnmarshallHop(rpcHop *lnrpc.Hop,
754
        prevNodePubKey [33]byte) (*route.Hop, error) {
×
755

×
756
        var pubKeyBytes [33]byte
×
757
        if rpcHop.PubKey != "" {
×
758
                // Unmarshall the provided hop pubkey.
×
759
                pubKey, err := hex.DecodeString(rpcHop.PubKey)
×
760
                if err != nil {
×
761
                        return nil, fmt.Errorf("cannot decode pubkey %s",
×
762
                                rpcHop.PubKey)
×
763
                }
×
764
                copy(pubKeyBytes[:], pubKey)
×
765
        } else {
×
766
                // If no pub key is given of the hop, the local channel graph
×
767
                // needs to be queried to complete the information necessary for
×
768
                // routing. Discard edge policies, because they may be nil.
×
769
                node1, node2, err := r.FetchChannelEndpoints(rpcHop.ChanId)
×
770
                if err != nil {
×
771
                        return nil, err
×
772
                }
×
773

774
                switch {
×
775
                case prevNodePubKey == node1:
×
776
                        pubKeyBytes = node2
×
777
                case prevNodePubKey == node2:
×
778
                        pubKeyBytes = node1
×
779
                default:
×
780
                        return nil, fmt.Errorf("channel edge does not match " +
×
781
                                "expected node")
×
782
                }
783
        }
784

785
        return UnmarshallHopWithPubkey(rpcHop, pubKeyBytes)
×
786
}
787

788
// UnmarshallRoute unmarshalls an rpc route. For hops that don't specify a
789
// pubkey, the channel graph is queried.
790
func (r *RouterBackend) UnmarshallRoute(rpcroute *lnrpc.Route) (
791
        *route.Route, error) {
×
792

×
793
        prevNodePubKey := r.SelfNode
×
794

×
795
        hops := make([]*route.Hop, len(rpcroute.Hops))
×
796
        for i, hop := range rpcroute.Hops {
×
797
                routeHop, err := r.UnmarshallHop(hop, prevNodePubKey)
×
798
                if err != nil {
×
799
                        return nil, err
×
800
                }
×
801

802
                hops[i] = routeHop
×
803

×
804
                prevNodePubKey = routeHop.PubKeyBytes
×
805
        }
806

807
        route, err := route.NewRouteFromHops(
×
808
                lnwire.MilliSatoshi(rpcroute.TotalAmtMsat),
×
809
                rpcroute.TotalTimeLock,
×
810
                r.SelfNode,
×
811
                hops,
×
812
        )
×
813
        if err != nil {
×
814
                return nil, err
×
815
        }
×
816

817
        return route, nil
×
818
}
819

820
// extractIntentFromSendRequest attempts to parse the SendRequest details
821
// required to dispatch a client from the information presented by an RPC
822
// client.
823
func (r *RouterBackend) extractIntentFromSendRequest(
824
        rpcPayReq *SendPaymentRequest) (*routing.LightningPayment, error) {
25✔
825

25✔
826
        payIntent := &routing.LightningPayment{}
25✔
827

25✔
828
        // Pass along time preference.
25✔
829
        if rpcPayReq.TimePref < -1 || rpcPayReq.TimePref > 1 {
26✔
830
                return nil, errors.New("time preference out of range")
1✔
831
        }
1✔
832
        payIntent.TimePref = rpcPayReq.TimePref
24✔
833

24✔
834
        // Pass along restrictions on the outgoing channels that may be used.
24✔
835
        payIntent.OutgoingChannelIDs = rpcPayReq.OutgoingChanIds
24✔
836

24✔
837
        // Add the deprecated single outgoing channel restriction if present.
24✔
838
        if rpcPayReq.OutgoingChanId != 0 {
25✔
839
                if payIntent.OutgoingChannelIDs != nil {
2✔
840
                        return nil, errors.New("outgoing_chan_id and " +
1✔
841
                                "outgoing_chan_ids are mutually exclusive")
1✔
842
                }
1✔
843

844
                payIntent.OutgoingChannelIDs = append(
×
845
                        payIntent.OutgoingChannelIDs, rpcPayReq.OutgoingChanId,
×
846
                )
×
847
        }
848

849
        // Pass along a last hop restriction if specified.
850
        if len(rpcPayReq.LastHopPubkey) > 0 {
24✔
851
                lastHop, err := route.NewVertexFromBytes(
1✔
852
                        rpcPayReq.LastHopPubkey,
1✔
853
                )
1✔
854
                if err != nil {
2✔
855
                        return nil, err
1✔
856
                }
1✔
857
                payIntent.LastHop = &lastHop
×
858
        }
859

860
        // Take the CLTV limit from the request if set, otherwise use the max.
861
        cltvLimit, err := ValidateCLTVLimit(
22✔
862
                uint32(rpcPayReq.CltvLimit), r.MaxTotalTimelock,
22✔
863
        )
22✔
864
        if err != nil {
23✔
865
                return nil, err
1✔
866
        }
1✔
867
        payIntent.CltvLimit = cltvLimit
21✔
868

21✔
869
        // Attempt to parse the max parts value set by the user, if this value
21✔
870
        // isn't set, then we'll use the current default value for this
21✔
871
        // setting.
21✔
872
        maxParts := rpcPayReq.MaxParts
21✔
873
        if maxParts == 0 {
38✔
874
                maxParts = DefaultMaxParts
17✔
875
        }
17✔
876
        payIntent.MaxParts = maxParts
21✔
877

21✔
878
        // If this payment had a max shard amount specified, then we'll apply
21✔
879
        // that now, which'll force us to always make payment splits smaller
21✔
880
        // than this.
21✔
881
        if rpcPayReq.MaxShardSizeMsat > 0 {
26✔
882
                shardAmtMsat := lnwire.MilliSatoshi(rpcPayReq.MaxShardSizeMsat)
5✔
883
                payIntent.MaxShardAmt = &shardAmtMsat
5✔
884

5✔
885
                // If the requested max_parts exceeds the allowed limit, then we
5✔
886
                // cannot send the payment amount.
5✔
887
                if payIntent.MaxParts > MaxPartsUpperLimit {
6✔
888
                        return nil, fmt.Errorf("requested max_parts (%v) "+
1✔
889
                                "exceeds the allowed upper limit of %v; cannot"+
1✔
890
                                " send payment amount with max_shard_size_msat"+
1✔
891
                                "=%v", payIntent.MaxParts, MaxPartsUpperLimit,
1✔
892
                                *payIntent.MaxShardAmt)
1✔
893
                }
1✔
894
        }
895

896
        // Take fee limit from request.
897
        payIntent.FeeLimit, err = lnrpc.UnmarshallAmt(
20✔
898
                rpcPayReq.FeeLimitSat, rpcPayReq.FeeLimitMsat,
20✔
899
        )
20✔
900
        if err != nil {
22✔
901
                return nil, err
2✔
902
        }
2✔
903

904
        customRecords := record.CustomSet(rpcPayReq.DestCustomRecords)
18✔
905
        if err := customRecords.Validate(); err != nil {
19✔
906
                return nil, err
1✔
907
        }
1✔
908
        payIntent.DestCustomRecords = customRecords
17✔
909

17✔
910
        // Keysend payments do not support MPP payments.
17✔
911
        //
17✔
912
        // NOTE: There is no need to validate the `MaxParts` value here because
17✔
913
        // it is set to 1 somewhere else in case it's a keysend payment.
17✔
914
        if customRecords.IsKeysend() {
18✔
915
                if payIntent.MaxShardAmt != nil {
2✔
916
                        return nil, errors.New("keysend payments cannot " +
1✔
917
                                "specify a max shard amount - MPP not " +
1✔
918
                                "supported with keysend payments")
1✔
919
                }
1✔
920
        }
921

922
        firstHopRecords := lnwire.CustomRecords(rpcPayReq.FirstHopCustomRecords)
16✔
923
        if err := firstHopRecords.Validate(); err != nil {
17✔
924
                return nil, err
1✔
925
        }
1✔
926
        payIntent.FirstHopCustomRecords = firstHopRecords
15✔
927

15✔
928
        // If the experimental endorsement signal is not already set, propagate
15✔
929
        // a zero value field if configured to set this signal.
15✔
930
        if r.ShouldSetExpEndorsement() {
16✔
931
                if payIntent.FirstHopCustomRecords == nil {
2✔
932
                        payIntent.FirstHopCustomRecords = make(
1✔
933
                                map[uint64][]byte,
1✔
934
                        )
1✔
935
                }
1✔
936

937
                t := uint64(lnwire.ExperimentalEndorsementType)
1✔
938
                if _, set := payIntent.FirstHopCustomRecords[t]; !set {
2✔
939
                        payIntent.FirstHopCustomRecords[t] = []byte{
1✔
940
                                lnwire.ExperimentalUnendorsed,
1✔
941
                        }
1✔
942
                }
1✔
943
        }
944

945
        payIntent.PayAttemptTimeout = time.Second *
15✔
946
                time.Duration(rpcPayReq.TimeoutSeconds)
15✔
947

15✔
948
        // Route hints.
15✔
949
        routeHints, err := unmarshallRouteHints(
15✔
950
                rpcPayReq.RouteHints,
15✔
951
        )
15✔
952
        if err != nil {
15✔
953
                return nil, err
×
954
        }
×
955
        payIntent.RouteHints = routeHints
15✔
956

15✔
957
        // Unmarshall either sat or msat amount from request.
15✔
958
        reqAmt, err := lnrpc.UnmarshallAmt(
15✔
959
                rpcPayReq.Amt, rpcPayReq.AmtMsat,
15✔
960
        )
15✔
961
        if err != nil {
16✔
962
                return nil, err
1✔
963
        }
1✔
964

965
        // If the payment request field isn't blank, then the details of the
966
        // invoice are encoded entirely within the encoded payReq.  So we'll
967
        // attempt to decode it, populating the payment accordingly.
968
        if rpcPayReq.PaymentRequest != "" {
20✔
969
                switch {
6✔
970

971
                case len(rpcPayReq.Dest) > 0:
1✔
972
                        return nil, errors.New("dest and payment_request " +
1✔
973
                                "cannot appear together")
1✔
974

975
                case len(rpcPayReq.PaymentHash) > 0:
1✔
976
                        return nil, errors.New("payment_hash and payment_request " +
1✔
977
                                "cannot appear together")
1✔
978

979
                case rpcPayReq.FinalCltvDelta != 0:
1✔
980
                        return nil, errors.New("final_cltv_delta and payment_request " +
1✔
981
                                "cannot appear together")
1✔
982
                }
983

984
                payReq, err := zpay32.Decode(
3✔
985
                        rpcPayReq.PaymentRequest, r.ActiveNetParams,
3✔
986
                )
3✔
987
                if err != nil {
4✔
988
                        return nil, err
1✔
989
                }
1✔
990

991
                // Next, we'll ensure that this payreq hasn't already expired.
992
                err = ValidatePayReqExpiry(r.Clock, payReq)
2✔
993
                if err != nil {
3✔
994
                        return nil, err
1✔
995
                }
1✔
996

997
                // An invoice must include either a payment address or
998
                // blinded paths.
999
                if payReq.PaymentAddr.IsNone() &&
1✔
1000
                        len(payReq.BlindedPaymentPaths) == 0 {
2✔
1001

1✔
1002
                        return nil, errors.New("payment request must contain " +
1✔
1003
                                "either a payment address or blinded paths")
1✔
1004
                }
1✔
1005

1006
                // If the amount was not included in the invoice, then we let
1007
                // the payer specify the amount of satoshis they wish to send.
1008
                // We override the amount to pay with the amount provided from
1009
                // the payment request.
1010
                if payReq.MilliSat == nil {
×
1011
                        if reqAmt == 0 {
×
1012
                                return nil, errors.New("amount must be " +
×
1013
                                        "specified when paying a zero amount " +
×
1014
                                        "invoice")
×
1015
                        }
×
1016

1017
                        payIntent.Amount = reqAmt
×
1018
                } else {
×
1019
                        if reqAmt != 0 {
×
1020
                                return nil, errors.New("amount must not be " +
×
1021
                                        "specified when paying a non-zero " +
×
1022
                                        "amount invoice")
×
1023
                        }
×
1024

1025
                        payIntent.Amount = *payReq.MilliSat
×
1026
                }
1027

1028
                if !payReq.Features.HasFeature(lnwire.MPPOptional) &&
×
1029
                        !payReq.Features.HasFeature(lnwire.AMPOptional) {
×
1030

×
1031
                        payIntent.MaxParts = 1
×
1032
                }
×
1033

1034
                payAddr := payReq.PaymentAddr
×
1035
                if payReq.Features.HasFeature(lnwire.AMPOptional) {
×
1036
                        // The opt-in AMP flag is required to pay an AMP
×
1037
                        // invoice.
×
1038
                        if !rpcPayReq.Amp {
×
1039
                                return nil, fmt.Errorf("the AMP flag (--amp " +
×
1040
                                        "or SendPaymentRequest.Amp) must be " +
×
1041
                                        "set to pay an AMP invoice")
×
1042
                        }
×
1043

1044
                        // Generate random SetID and root share.
1045
                        var setID [32]byte
×
1046
                        _, err = rand.Read(setID[:])
×
1047
                        if err != nil {
×
1048
                                return nil, err
×
1049
                        }
×
1050

1051
                        var rootShare [32]byte
×
1052
                        _, err = rand.Read(rootShare[:])
×
1053
                        if err != nil {
×
1054
                                return nil, err
×
1055
                        }
×
1056
                        err := payIntent.SetAMP(&routing.AMPOptions{
×
1057
                                SetID:     setID,
×
1058
                                RootShare: rootShare,
×
1059
                        })
×
1060
                        if err != nil {
×
1061
                                return nil, err
×
1062
                        }
×
1063

1064
                        // For AMP invoices, we'll allow users to override the
1065
                        // included payment addr to allow the invoice to be
1066
                        // pseudo-reusable, e.g. the invoice parameters are
1067
                        // reused (amt, cltv, hop hints, etc) even though the
1068
                        // payments will share different payment hashes.
1069
                        //
1070
                        // NOTE: This will only work when the peer has
1071
                        // spontaneous AMP payments enabled.
1072
                        if len(rpcPayReq.PaymentAddr) > 0 {
×
1073
                                var addr [32]byte
×
1074
                                copy(addr[:], rpcPayReq.PaymentAddr)
×
1075
                                payAddr = fn.Some(addr)
×
1076
                        }
×
1077
                } else {
×
1078
                        err = payIntent.SetPaymentHash(*payReq.PaymentHash)
×
1079
                        if err != nil {
×
1080
                                return nil, err
×
1081
                        }
×
1082
                }
1083

1084
                destKey := payReq.Destination.SerializeCompressed()
×
1085
                copy(payIntent.Target[:], destKey)
×
1086

×
1087
                payIntent.FinalCLTVDelta = uint16(payReq.MinFinalCLTVExpiry())
×
1088
                payIntent.RouteHints = append(
×
1089
                        payIntent.RouteHints, payReq.RouteHints...,
×
1090
                )
×
1091
                payIntent.DestFeatures = payReq.Features
×
1092
                payIntent.PaymentAddr = payAddr
×
1093
                payIntent.PaymentRequest = []byte(rpcPayReq.PaymentRequest)
×
1094
                payIntent.Metadata = payReq.Metadata
×
1095

×
1096
                if len(payReq.BlindedPaymentPaths) > 0 {
×
1097
                        pathSet, err := BuildBlindedPathSet(
×
1098
                                payReq.BlindedPaymentPaths,
×
1099
                        )
×
1100
                        if err != nil {
×
1101
                                return nil, err
×
1102
                        }
×
1103
                        payIntent.BlindedPathSet = pathSet
×
1104

×
1105
                        // Replace the target node with the target public key
×
1106
                        // of the blinded path set.
×
1107
                        copy(
×
1108
                                payIntent.Target[:],
×
1109
                                pathSet.TargetPubKey().SerializeCompressed(),
×
1110
                        )
×
1111

×
1112
                        pathFeatures := pathSet.Features()
×
1113
                        if !pathFeatures.IsEmpty() {
×
1114
                                payIntent.DestFeatures = pathFeatures.Clone()
×
1115
                        }
×
1116
                }
1117
        } else {
8✔
1118
                // Otherwise, If the payment request field was not specified
8✔
1119
                // (and a custom route wasn't specified), construct the payment
8✔
1120
                // from the other fields.
8✔
1121

8✔
1122
                // Payment destination.
8✔
1123
                target, err := route.NewVertexFromBytes(rpcPayReq.Dest)
8✔
1124
                if err != nil {
9✔
1125
                        return nil, err
1✔
1126
                }
1✔
1127
                payIntent.Target = target
7✔
1128

7✔
1129
                // Final payment CLTV delta.
7✔
1130
                if rpcPayReq.FinalCltvDelta != 0 {
8✔
1131
                        payIntent.FinalCLTVDelta =
1✔
1132
                                uint16(rpcPayReq.FinalCltvDelta)
1✔
1133
                } else {
7✔
1134
                        payIntent.FinalCLTVDelta = r.DefaultFinalCltvDelta
6✔
1135
                }
6✔
1136

1137
                // Amount.
1138
                if reqAmt == 0 {
8✔
1139
                        return nil, errors.New("amount must be specified")
1✔
1140
                }
1✔
1141

1142
                payIntent.Amount = reqAmt
6✔
1143

6✔
1144
                // Parse destination feature bits.
6✔
1145
                features := UnmarshalFeatures(rpcPayReq.DestFeatures)
6✔
1146

6✔
1147
                // Validate the features if any was specified.
6✔
1148
                if features != nil {
8✔
1149
                        err = feature.ValidateDeps(features)
2✔
1150
                        if err != nil {
2✔
1151
                                return nil, err
×
1152
                        }
×
1153
                }
1154

1155
                // If this is an AMP payment, we must generate the initial
1156
                // randomness.
1157
                if rpcPayReq.Amp {
7✔
1158
                        // If no destination features were specified, we set
1✔
1159
                        // those necessary for AMP payments.
1✔
1160
                        if features == nil {
1✔
1161
                                ampFeatures := []lnrpc.FeatureBit{
×
1162
                                        lnrpc.FeatureBit_TLV_ONION_OPT,
×
1163
                                        lnrpc.FeatureBit_PAYMENT_ADDR_OPT,
×
1164
                                        lnrpc.FeatureBit_AMP_OPT,
×
1165
                                }
×
1166

×
1167
                                features = UnmarshalFeatures(ampFeatures)
×
1168
                        }
×
1169

1170
                        // First make sure the destination supports AMP.
1171
                        if !features.HasFeature(lnwire.AMPOptional) {
2✔
1172
                                return nil, fmt.Errorf("destination doesn't " +
1✔
1173
                                        "support AMP payments")
1✔
1174
                        }
1✔
1175

1176
                        // If no payment address is set, generate a random one.
1177
                        var payAddr [32]byte
×
1178
                        if len(rpcPayReq.PaymentAddr) == 0 {
×
1179
                                _, err = rand.Read(payAddr[:])
×
1180
                                if err != nil {
×
1181
                                        return nil, err
×
1182
                                }
×
1183
                        } else {
×
1184
                                copy(payAddr[:], rpcPayReq.PaymentAddr)
×
1185
                        }
×
1186
                        payIntent.PaymentAddr = fn.Some(payAddr)
×
1187

×
1188
                        // Generate random SetID and root share.
×
1189
                        var setID [32]byte
×
1190
                        _, err = rand.Read(setID[:])
×
1191
                        if err != nil {
×
1192
                                return nil, err
×
1193
                        }
×
1194

1195
                        var rootShare [32]byte
×
1196
                        _, err = rand.Read(rootShare[:])
×
1197
                        if err != nil {
×
1198
                                return nil, err
×
1199
                        }
×
1200
                        err := payIntent.SetAMP(&routing.AMPOptions{
×
1201
                                SetID:     setID,
×
1202
                                RootShare: rootShare,
×
1203
                        })
×
1204
                        if err != nil {
×
1205
                                return nil, err
×
1206
                        }
×
1207
                } else {
5✔
1208
                        // Payment hash.
5✔
1209
                        paymentHash, err := lntypes.MakeHash(rpcPayReq.PaymentHash)
5✔
1210
                        if err != nil {
6✔
1211
                                return nil, err
1✔
1212
                        }
1✔
1213

1214
                        err = payIntent.SetPaymentHash(paymentHash)
4✔
1215
                        if err != nil {
4✔
1216
                                return nil, err
×
1217
                        }
×
1218

1219
                        // If the payment addresses is specified, then we'll
1220
                        // also populate that now as well.
1221
                        if len(rpcPayReq.PaymentAddr) != 0 {
4✔
1222
                                var payAddr [32]byte
×
1223
                                copy(payAddr[:], rpcPayReq.PaymentAddr)
×
1224

×
1225
                                payIntent.PaymentAddr = fn.Some(payAddr)
×
1226
                        }
×
1227
                }
1228

1229
                payIntent.DestFeatures = features
4✔
1230
        }
1231

1232
        // Validate that the MPP parameters are compatible with the
1233
        // payment amount. In other words, the parameters are invalid if
1234
        // they do not permit sending the full payment amount.
1235
        if payIntent.MaxShardAmt != nil {
7✔
1236
                maxPossibleAmount := (*payIntent.MaxShardAmt) *
3✔
1237
                        lnwire.MilliSatoshi(payIntent.MaxParts)
3✔
1238

3✔
1239
                if payIntent.Amount > maxPossibleAmount {
4✔
1240
                        return nil, fmt.Errorf("payment amount %v exceeds "+
1✔
1241
                                "maximum possible amount %v with max_parts=%v "+
1✔
1242
                                "and max_shard_size_msat=%v", payIntent.Amount,
1✔
1243
                                maxPossibleAmount, payIntent.MaxParts,
1✔
1244
                                *payIntent.MaxShardAmt,
1✔
1245
                        )
1✔
1246
                }
1✔
1247
        }
1248

1249
        // Do bounds checking with the block padding so the router isn't
1250
        // left with a zombie payment in case the user messes up.
1251
        err = routing.ValidateCLTVLimit(
3✔
1252
                payIntent.CltvLimit, payIntent.FinalCLTVDelta, true,
3✔
1253
        )
3✔
1254
        if err != nil {
3✔
1255
                return nil, err
×
1256
        }
×
1257

1258
        // Check for disallowed payments to self.
1259
        if !rpcPayReq.AllowSelfPayment && payIntent.Target == r.SelfNode {
4✔
1260
                return nil, errors.New("self-payments not allowed")
1✔
1261
        }
1✔
1262

1263
        return payIntent, nil
2✔
1264
}
1265

1266
// BuildBlindedPathSet marshals a set of zpay32.BlindedPaymentPath and uses
1267
// the result to build a new routing.BlindedPaymentPathSet.
1268
func BuildBlindedPathSet(paths []*zpay32.BlindedPaymentPath) (
1269
        *routing.BlindedPaymentPathSet, error) {
×
1270

×
1271
        marshalledPaths := make([]*routing.BlindedPayment, len(paths))
×
1272
        for i, path := range paths {
×
1273
                paymentPath := marshalBlindedPayment(path)
×
1274

×
1275
                err := paymentPath.Validate()
×
1276
                if err != nil {
×
1277
                        return nil, err
×
1278
                }
×
1279

1280
                marshalledPaths[i] = paymentPath
×
1281
        }
1282

1283
        return routing.NewBlindedPaymentPathSet(marshalledPaths)
×
1284
}
1285

1286
// marshalBlindedPayment marshals a zpay32.BLindedPaymentPath into a
1287
// routing.BlindedPayment.
1288
func marshalBlindedPayment(
1289
        path *zpay32.BlindedPaymentPath) *routing.BlindedPayment {
×
1290

×
1291
        return &routing.BlindedPayment{
×
1292
                BlindedPath: &sphinx.BlindedPath{
×
1293
                        IntroductionPoint: path.Hops[0].BlindedNodePub,
×
1294
                        BlindingPoint:     path.FirstEphemeralBlindingPoint,
×
1295
                        BlindedHops:       path.Hops,
×
1296
                },
×
1297
                BaseFee:             path.FeeBaseMsat,
×
1298
                ProportionalFeeRate: path.FeeRate,
×
1299
                CltvExpiryDelta:     path.CltvExpiryDelta,
×
1300
                HtlcMinimum:         path.HTLCMinMsat,
×
1301
                HtlcMaximum:         path.HTLCMaxMsat,
×
1302
                Features:            path.Features,
×
1303
        }
×
1304
}
×
1305

1306
// unmarshallRouteHints unmarshalls a list of route hints.
1307
func unmarshallRouteHints(rpcRouteHints []*lnrpc.RouteHint) (
1308
        [][]zpay32.HopHint, error) {
21✔
1309

21✔
1310
        routeHints := make([][]zpay32.HopHint, 0, len(rpcRouteHints))
21✔
1311
        for _, rpcRouteHint := range rpcRouteHints {
27✔
1312
                routeHint := make(
6✔
1313
                        []zpay32.HopHint, 0, len(rpcRouteHint.HopHints),
6✔
1314
                )
6✔
1315
                for _, rpcHint := range rpcRouteHint.HopHints {
12✔
1316
                        hint, err := unmarshallHopHint(rpcHint)
6✔
1317
                        if err != nil {
6✔
1318
                                return nil, err
×
1319
                        }
×
1320

1321
                        routeHint = append(routeHint, hint)
6✔
1322
                }
1323
                routeHints = append(routeHints, routeHint)
6✔
1324
        }
1325

1326
        return routeHints, nil
21✔
1327
}
1328

1329
// unmarshallHopHint unmarshalls a single hop hint.
1330
func unmarshallHopHint(rpcHint *lnrpc.HopHint) (zpay32.HopHint, error) {
6✔
1331
        pubBytes, err := hex.DecodeString(rpcHint.NodeId)
6✔
1332
        if err != nil {
6✔
1333
                return zpay32.HopHint{}, err
×
1334
        }
×
1335

1336
        pubkey, err := btcec.ParsePubKey(pubBytes)
6✔
1337
        if err != nil {
6✔
1338
                return zpay32.HopHint{}, err
×
1339
        }
×
1340

1341
        return zpay32.HopHint{
6✔
1342
                NodeID:                    pubkey,
6✔
1343
                ChannelID:                 rpcHint.ChanId,
6✔
1344
                FeeBaseMSat:               rpcHint.FeeBaseMsat,
6✔
1345
                FeeProportionalMillionths: rpcHint.FeeProportionalMillionths,
6✔
1346
                CLTVExpiryDelta:           uint16(rpcHint.CltvExpiryDelta),
6✔
1347
        }, nil
6✔
1348
}
1349

1350
// MarshalFeatures converts a feature vector into a list of uint32's.
1351
func MarshalFeatures(feats *lnwire.FeatureVector) []lnrpc.FeatureBit {
×
1352
        var featureBits []lnrpc.FeatureBit
×
1353
        for feature := range feats.Features() {
×
1354
                featureBits = append(featureBits, lnrpc.FeatureBit(feature))
×
1355
        }
×
1356

1357
        return featureBits
×
1358
}
1359

1360
// UnmarshalFeatures converts a list of uint32's into a valid feature vector.
1361
// This method checks that feature bit pairs aren't assigned together, and
1362
// validates transitive dependencies.
1363
func UnmarshalFeatures(rpcFeatures []lnrpc.FeatureBit) *lnwire.FeatureVector {
11✔
1364
        // If no destination features are specified we'll return nil to signal
11✔
1365
        // that the router should try to use the graph as a fallback.
11✔
1366
        if rpcFeatures == nil {
15✔
1367
                return nil
4✔
1368
        }
4✔
1369

1370
        raw := lnwire.NewRawFeatureVector()
7✔
1371
        for _, bit := range rpcFeatures {
14✔
1372
                // Even though the spec says that the writer of a feature vector
7✔
1373
                // should never set both the required and optional bits of a
7✔
1374
                // feature, it also says that if we receive a vector with both
7✔
1375
                // bits set, then we should just treat the feature as required.
7✔
1376
                // Therefore, we don't use SafeSet here when parsing a peer's
7✔
1377
                // feature bits and just set the feature no matter what so that
7✔
1378
                // if both are set then IsRequired returns true.
7✔
1379
                raw.Set(lnwire.FeatureBit(bit))
7✔
1380
        }
7✔
1381

1382
        return lnwire.NewFeatureVector(raw, lnwire.Features)
7✔
1383
}
1384

1385
// ValidatePayReqExpiry checks if the passed payment request has expired. In
1386
// the case it has expired, an error will be returned.
1387
func ValidatePayReqExpiry(clock clock.Clock, payReq *zpay32.Invoice) error {
2✔
1388
        expiry := payReq.Expiry()
2✔
1389
        validUntil := payReq.Timestamp.Add(expiry)
2✔
1390
        if clock.Now().After(validUntil) {
3✔
1391
                return fmt.Errorf("invoice expired. Valid until %v", validUntil)
1✔
1392
        }
1✔
1393

1394
        return nil
1✔
1395
}
1396

1397
// ValidateCLTVLimit returns a valid CLTV limit given a value and a maximum. If
1398
// the value exceeds the maximum, then an error is returned. If the value is 0,
1399
// then the maximum is used.
1400
func ValidateCLTVLimit(val, max uint32) (uint32, error) {
28✔
1401
        switch {
28✔
1402
        case val == 0:
27✔
1403
                return max, nil
27✔
1404
        case val > max:
1✔
1405
                return 0, fmt.Errorf("total time lock of %v exceeds max "+
1✔
1406
                        "allowed %v", val, max)
1✔
1407
        default:
×
1408
                return val, nil
×
1409
        }
1410
}
1411

1412
// UnmarshalMPP accepts the mpp_total_amt_msat and mpp_payment_addr fields from
1413
// an RPC request and converts into an record.MPP object. An error is returned
1414
// if the payment address is not 0 or 32 bytes. If the total amount and payment
1415
// address are zero-value, the return value will be nil signaling there is no
1416
// MPP record to attach to this hop. Otherwise, a non-nil reocrd will be
1417
// contained combining the provided values.
1418
func UnmarshalMPP(reqMPP *lnrpc.MPPRecord) (*record.MPP, error) {
6✔
1419
        // If no MPP record was submitted, assume the user wants to send a
6✔
1420
        // regular payment.
6✔
1421
        if reqMPP == nil {
7✔
1422
                return nil, nil
1✔
1423
        }
1✔
1424

1425
        reqTotal := reqMPP.TotalAmtMsat
5✔
1426
        reqAddr := reqMPP.PaymentAddr
5✔
1427

5✔
1428
        switch {
5✔
1429
        // No MPP fields were provided.
1430
        case reqTotal == 0 && len(reqAddr) == 0:
1✔
1431
                return nil, fmt.Errorf("missing total_msat and payment_addr")
1✔
1432

1433
        // Total is present, but payment address is missing.
1434
        case reqTotal > 0 && len(reqAddr) == 0:
1✔
1435
                return nil, fmt.Errorf("missing payment_addr")
1✔
1436

1437
        // Payment address is present, but total is missing.
1438
        case reqTotal == 0 && len(reqAddr) > 0:
1✔
1439
                return nil, fmt.Errorf("missing total_msat")
1✔
1440
        }
1441

1442
        addr, err := lntypes.MakeHash(reqAddr)
2✔
1443
        if err != nil {
3✔
1444
                return nil, fmt.Errorf("unable to parse "+
1✔
1445
                        "payment_addr: %v", err)
1✔
1446
        }
1✔
1447

1448
        total := lnwire.MilliSatoshi(reqTotal)
1✔
1449

1✔
1450
        return record.NewMPP(total, addr), nil
1✔
1451
}
1452

1453
func UnmarshalAMP(reqAMP *lnrpc.AMPRecord) (*record.AMP, error) {
5✔
1454
        if reqAMP == nil {
6✔
1455
                return nil, nil
1✔
1456
        }
1✔
1457

1458
        reqRootShare := reqAMP.RootShare
4✔
1459
        reqSetID := reqAMP.SetId
4✔
1460

4✔
1461
        switch {
4✔
1462
        case len(reqRootShare) != 32:
2✔
1463
                return nil, errors.New("AMP root_share must be 32 bytes")
2✔
1464

1465
        case len(reqSetID) != 32:
1✔
1466
                return nil, errors.New("AMP set_id must be 32 bytes")
1✔
1467
        }
1468

1469
        var (
1✔
1470
                rootShare [32]byte
1✔
1471
                setID     [32]byte
1✔
1472
        )
1✔
1473
        copy(rootShare[:], reqRootShare)
1✔
1474
        copy(setID[:], reqSetID)
1✔
1475

1✔
1476
        return record.NewAMP(rootShare, setID, reqAMP.ChildIndex), nil
1✔
1477
}
1478

1479
// MarshalHTLCAttempt constructs an RPC HTLCAttempt from the db representation.
1480
func (r *RouterBackend) MarshalHTLCAttempt(
1481
        htlc paymentsdb.HTLCAttempt) (*lnrpc.HTLCAttempt, error) {
×
1482

×
1483
        route, err := r.MarshallRoute(&htlc.Route)
×
1484
        if err != nil {
×
1485
                return nil, err
×
1486
        }
×
1487

1488
        rpcAttempt := &lnrpc.HTLCAttempt{
×
1489
                AttemptId:     htlc.AttemptID,
×
1490
                AttemptTimeNs: MarshalTimeNano(htlc.AttemptTime),
×
1491
                Route:         route,
×
1492
        }
×
1493

×
1494
        switch {
×
1495
        case htlc.Settle != nil:
×
1496
                rpcAttempt.Status = lnrpc.HTLCAttempt_SUCCEEDED
×
1497
                rpcAttempt.ResolveTimeNs = MarshalTimeNano(
×
1498
                        htlc.Settle.SettleTime,
×
1499
                )
×
1500
                rpcAttempt.Preimage = htlc.Settle.Preimage[:]
×
1501

1502
        case htlc.Failure != nil:
×
1503
                rpcAttempt.Status = lnrpc.HTLCAttempt_FAILED
×
1504
                rpcAttempt.ResolveTimeNs = MarshalTimeNano(
×
1505
                        htlc.Failure.FailTime,
×
1506
                )
×
1507

×
1508
                var err error
×
1509
                rpcAttempt.Failure, err = marshallHtlcFailure(htlc.Failure)
×
1510
                if err != nil {
×
1511
                        return nil, err
×
1512
                }
×
1513
        default:
×
1514
                rpcAttempt.Status = lnrpc.HTLCAttempt_IN_FLIGHT
×
1515
        }
1516

1517
        return rpcAttempt, nil
×
1518
}
1519

1520
// marshallHtlcFailure marshalls htlc fail info from the database to its rpc
1521
// representation.
1522
func marshallHtlcFailure(failure *paymentsdb.HTLCFailInfo) (*lnrpc.Failure,
1523
        error) {
×
1524

×
1525
        rpcFailure := &lnrpc.Failure{
×
1526
                FailureSourceIndex: failure.FailureSourceIndex,
×
1527
        }
×
1528

×
1529
        switch failure.Reason {
×
1530
        case paymentsdb.HTLCFailUnknown:
×
1531
                rpcFailure.Code = lnrpc.Failure_UNKNOWN_FAILURE
×
1532

1533
        case paymentsdb.HTLCFailUnreadable:
×
1534
                rpcFailure.Code = lnrpc.Failure_UNREADABLE_FAILURE
×
1535

1536
        case paymentsdb.HTLCFailInternal:
×
1537
                rpcFailure.Code = lnrpc.Failure_INTERNAL_FAILURE
×
1538

1539
        case paymentsdb.HTLCFailMessage:
×
1540
                err := marshallWireError(failure.Message, rpcFailure)
×
1541
                if err != nil {
×
1542
                        return nil, err
×
1543
                }
×
1544

1545
        default:
×
1546
                return nil, errors.New("unknown htlc failure reason")
×
1547
        }
1548

1549
        return rpcFailure, nil
×
1550
}
1551

1552
// MarshalTimeNano converts a time.Time into its nanosecond representation. If
1553
// the time is zero, this method simply returns 0, since calling UnixNano() on a
1554
// zero-valued time is undefined.
1555
func MarshalTimeNano(t time.Time) int64 {
3✔
1556
        if t.IsZero() {
6✔
1557
                return 0
3✔
1558
        }
3✔
1559
        return t.UnixNano()
×
1560
}
1561

1562
// marshallError marshall an error as received from the switch to rpc structs
1563
// suitable for returning to the caller of an rpc method.
1564
//
1565
// Because of difficulties with using protobuf oneof constructs in some
1566
// languages, the decision was made here to use a single message format for all
1567
// failure messages with some fields left empty depending on the failure type.
1568
func marshallError(sendError error) (*lnrpc.Failure, error) {
×
1569
        response := &lnrpc.Failure{}
×
1570

×
1571
        if sendError == htlcswitch.ErrUnreadableFailureMessage {
×
1572
                response.Code = lnrpc.Failure_UNREADABLE_FAILURE
×
1573
                return response, nil
×
1574
        }
×
1575

1576
        rtErr, ok := sendError.(htlcswitch.ClearTextError)
×
1577
        if !ok {
×
1578
                return nil, sendError
×
1579
        }
×
1580

1581
        err := marshallWireError(rtErr.WireMessage(), response)
×
1582
        if err != nil {
×
1583
                return nil, err
×
1584
        }
×
1585

1586
        // If the ClearTextError received is a ForwardingError, the error
1587
        // originated from a node along the route, not locally on our outgoing
1588
        // link. We set failureSourceIdx to the index of the node where the
1589
        // failure occurred. If the error is not a ForwardingError, the failure
1590
        // occurred at our node, so we leave the index as 0 to indicate that
1591
        // we failed locally.
1592
        fErr, ok := rtErr.(*htlcswitch.ForwardingError)
×
1593
        if ok {
×
1594
                response.FailureSourceIndex = uint32(fErr.FailureSourceIdx)
×
1595
        }
×
1596

1597
        return response, nil
×
1598
}
1599

1600
// marshallError marshall an error as received from the switch to rpc structs
1601
// suitable for returning to the caller of an rpc method.
1602
//
1603
// Because of difficulties with using protobuf oneof constructs in some
1604
// languages, the decision was made here to use a single message format for all
1605
// failure messages with some fields left empty depending on the failure type.
1606
func marshallWireError(msg lnwire.FailureMessage,
1607
        response *lnrpc.Failure) error {
×
1608

×
1609
        switch onionErr := msg.(type) {
×
1610
        case *lnwire.FailIncorrectDetails:
×
1611
                response.Code = lnrpc.Failure_INCORRECT_OR_UNKNOWN_PAYMENT_DETAILS
×
1612
                response.Height = onionErr.Height()
×
1613

1614
        case *lnwire.FailIncorrectPaymentAmount:
×
1615
                response.Code = lnrpc.Failure_INCORRECT_PAYMENT_AMOUNT
×
1616

1617
        case *lnwire.FailFinalIncorrectCltvExpiry:
×
1618
                response.Code = lnrpc.Failure_FINAL_INCORRECT_CLTV_EXPIRY
×
1619
                response.CltvExpiry = onionErr.CltvExpiry
×
1620

1621
        case *lnwire.FailFinalIncorrectHtlcAmount:
×
1622
                response.Code = lnrpc.Failure_FINAL_INCORRECT_HTLC_AMOUNT
×
1623
                response.HtlcMsat = uint64(onionErr.IncomingHTLCAmount)
×
1624

1625
        case *lnwire.FailFinalExpiryTooSoon:
×
1626
                response.Code = lnrpc.Failure_FINAL_EXPIRY_TOO_SOON
×
1627

1628
        case *lnwire.FailInvalidRealm:
×
1629
                response.Code = lnrpc.Failure_INVALID_REALM
×
1630

1631
        case *lnwire.FailExpiryTooSoon:
×
1632
                response.Code = lnrpc.Failure_EXPIRY_TOO_SOON
×
1633
                response.ChannelUpdate = marshallChannelUpdate(&onionErr.Update)
×
1634

1635
        case *lnwire.FailExpiryTooFar:
×
1636
                response.Code = lnrpc.Failure_EXPIRY_TOO_FAR
×
1637

1638
        case *lnwire.FailInvalidOnionVersion:
×
1639
                response.Code = lnrpc.Failure_INVALID_ONION_VERSION
×
1640
                response.OnionSha_256 = onionErr.OnionSHA256[:]
×
1641

1642
        case *lnwire.FailInvalidOnionHmac:
×
1643
                response.Code = lnrpc.Failure_INVALID_ONION_HMAC
×
1644
                response.OnionSha_256 = onionErr.OnionSHA256[:]
×
1645

1646
        case *lnwire.FailInvalidOnionKey:
×
1647
                response.Code = lnrpc.Failure_INVALID_ONION_KEY
×
1648
                response.OnionSha_256 = onionErr.OnionSHA256[:]
×
1649

1650
        case *lnwire.FailAmountBelowMinimum:
×
1651
                response.Code = lnrpc.Failure_AMOUNT_BELOW_MINIMUM
×
1652
                response.ChannelUpdate = marshallChannelUpdate(&onionErr.Update)
×
1653
                response.HtlcMsat = uint64(onionErr.HtlcMsat)
×
1654

1655
        case *lnwire.FailFeeInsufficient:
×
1656
                response.Code = lnrpc.Failure_FEE_INSUFFICIENT
×
1657
                response.ChannelUpdate = marshallChannelUpdate(&onionErr.Update)
×
1658
                response.HtlcMsat = uint64(onionErr.HtlcMsat)
×
1659

1660
        case *lnwire.FailIncorrectCltvExpiry:
×
1661
                response.Code = lnrpc.Failure_INCORRECT_CLTV_EXPIRY
×
1662
                response.ChannelUpdate = marshallChannelUpdate(&onionErr.Update)
×
1663
                response.CltvExpiry = onionErr.CltvExpiry
×
1664

1665
        case *lnwire.FailChannelDisabled:
×
1666
                response.Code = lnrpc.Failure_CHANNEL_DISABLED
×
1667
                response.ChannelUpdate = marshallChannelUpdate(&onionErr.Update)
×
1668
                response.Flags = uint32(onionErr.Flags)
×
1669

1670
        case *lnwire.FailTemporaryChannelFailure:
×
1671
                response.Code = lnrpc.Failure_TEMPORARY_CHANNEL_FAILURE
×
1672
                response.ChannelUpdate = marshallChannelUpdate(onionErr.Update)
×
1673

1674
        case *lnwire.FailRequiredNodeFeatureMissing:
×
1675
                response.Code = lnrpc.Failure_REQUIRED_NODE_FEATURE_MISSING
×
1676

1677
        case *lnwire.FailRequiredChannelFeatureMissing:
×
1678
                response.Code = lnrpc.Failure_REQUIRED_CHANNEL_FEATURE_MISSING
×
1679

1680
        case *lnwire.FailUnknownNextPeer:
×
1681
                response.Code = lnrpc.Failure_UNKNOWN_NEXT_PEER
×
1682

1683
        case *lnwire.FailTemporaryNodeFailure:
×
1684
                response.Code = lnrpc.Failure_TEMPORARY_NODE_FAILURE
×
1685

1686
        case *lnwire.FailPermanentNodeFailure:
×
1687
                response.Code = lnrpc.Failure_PERMANENT_NODE_FAILURE
×
1688

1689
        case *lnwire.FailPermanentChannelFailure:
×
1690
                response.Code = lnrpc.Failure_PERMANENT_CHANNEL_FAILURE
×
1691

1692
        case *lnwire.FailMPPTimeout:
×
1693
                response.Code = lnrpc.Failure_MPP_TIMEOUT
×
1694

1695
        case *lnwire.InvalidOnionPayload:
×
1696
                response.Code = lnrpc.Failure_INVALID_ONION_PAYLOAD
×
1697

1698
        case *lnwire.FailInvalidBlinding:
×
1699
                response.Code = lnrpc.Failure_INVALID_ONION_BLINDING
×
1700
                response.OnionSha_256 = onionErr.OnionSHA256[:]
×
1701

1702
        case nil:
×
1703
                response.Code = lnrpc.Failure_UNKNOWN_FAILURE
×
1704

1705
        default:
×
1706
                return fmt.Errorf("cannot marshall failure %T", onionErr)
×
1707
        }
1708

1709
        return nil
×
1710
}
1711

1712
// marshallChannelUpdate marshalls a channel update as received over the wire to
1713
// the router rpc format.
1714
func marshallChannelUpdate(update *lnwire.ChannelUpdate1) *lnrpc.ChannelUpdate {
×
1715
        if update == nil {
×
1716
                return nil
×
1717
        }
×
1718

1719
        return &lnrpc.ChannelUpdate{
×
1720
                Signature:       update.Signature.RawBytes(),
×
1721
                ChainHash:       update.ChainHash[:],
×
1722
                ChanId:          update.ShortChannelID.ToUint64(),
×
1723
                Timestamp:       update.Timestamp,
×
1724
                MessageFlags:    uint32(update.MessageFlags),
×
1725
                ChannelFlags:    uint32(update.ChannelFlags),
×
1726
                TimeLockDelta:   uint32(update.TimeLockDelta),
×
1727
                HtlcMinimumMsat: uint64(update.HtlcMinimumMsat),
×
1728
                BaseFee:         update.BaseFee,
×
1729
                FeeRate:         update.FeeRate,
×
1730
                HtlcMaximumMsat: uint64(update.HtlcMaximumMsat),
×
1731
                ExtraOpaqueData: update.ExtraOpaqueData,
×
1732
        }
×
1733
}
1734

1735
// MarshallPayment marshall a payment to its rpc representation.
1736
func (r *RouterBackend) MarshallPayment(payment *paymentsdb.MPPayment) (
1737
        *lnrpc.Payment, error) {
3✔
1738

3✔
1739
        // Fetch the payment's preimage and the total paid in fees.
3✔
1740
        var (
3✔
1741
                fee      lnwire.MilliSatoshi
3✔
1742
                preimage lntypes.Preimage
3✔
1743
        )
3✔
1744
        for _, htlc := range payment.HTLCs {
3✔
1745
                // If any of the htlcs have settled, extract a valid
×
1746
                // preimage.
×
1747
                if htlc.Settle != nil {
×
1748
                        preimage = htlc.Settle.Preimage
×
1749
                        fee += htlc.Route.TotalFees()
×
1750
                }
×
1751
        }
1752

1753
        msatValue := int64(payment.Info.Value)
3✔
1754
        satValue := int64(payment.Info.Value.ToSatoshis())
3✔
1755

3✔
1756
        status, err := convertPaymentStatus(
3✔
1757
                payment.Status, r.UseStatusInitiated,
3✔
1758
        )
3✔
1759
        if err != nil {
3✔
1760
                return nil, err
×
1761
        }
×
1762

1763
        htlcs := make([]*lnrpc.HTLCAttempt, 0, len(payment.HTLCs))
3✔
1764
        for _, dbHTLC := range payment.HTLCs {
3✔
1765
                htlc, err := r.MarshalHTLCAttempt(dbHTLC)
×
1766
                if err != nil {
×
1767
                        return nil, err
×
1768
                }
×
1769

1770
                htlcs = append(htlcs, htlc)
×
1771
        }
1772

1773
        paymentID := payment.Info.PaymentIdentifier
3✔
1774
        creationTimeNS := MarshalTimeNano(payment.Info.CreationTime)
3✔
1775

3✔
1776
        failureReason, err := marshallPaymentFailureReason(
3✔
1777
                payment.FailureReason,
3✔
1778
        )
3✔
1779
        if err != nil {
3✔
1780
                return nil, err
×
1781
        }
×
1782

1783
        return &lnrpc.Payment{
3✔
1784
                // TODO: set this to setID for AMP-payments?
3✔
1785
                PaymentHash:           hex.EncodeToString(paymentID[:]),
3✔
1786
                Value:                 satValue,
3✔
1787
                ValueMsat:             msatValue,
3✔
1788
                ValueSat:              satValue,
3✔
1789
                CreationDate:          payment.Info.CreationTime.Unix(),
3✔
1790
                CreationTimeNs:        creationTimeNS,
3✔
1791
                Fee:                   int64(fee.ToSatoshis()),
3✔
1792
                FeeSat:                int64(fee.ToSatoshis()),
3✔
1793
                FeeMsat:               int64(fee),
3✔
1794
                PaymentPreimage:       hex.EncodeToString(preimage[:]),
3✔
1795
                PaymentRequest:        string(payment.Info.PaymentRequest),
3✔
1796
                Status:                status,
3✔
1797
                Htlcs:                 htlcs,
3✔
1798
                PaymentIndex:          payment.SequenceNum,
3✔
1799
                FailureReason:         failureReason,
3✔
1800
                FirstHopCustomRecords: payment.Info.FirstHopCustomRecords,
3✔
1801
        }, nil
3✔
1802
}
1803

1804
// convertPaymentStatus converts a channeldb.PaymentStatus to the type expected
1805
// by the RPC.
1806
func convertPaymentStatus(dbStatus paymentsdb.PaymentStatus, useInit bool) (
1807
        lnrpc.Payment_PaymentStatus, error) {
3✔
1808

3✔
1809
        switch dbStatus {
3✔
1810
        case paymentsdb.StatusInitiated:
×
1811
                // If the client understands the new status, return it.
×
1812
                if useInit {
×
1813
                        return lnrpc.Payment_INITIATED, nil
×
1814
                }
×
1815

1816
                // Otherwise remain the old behavior.
1817
                return lnrpc.Payment_IN_FLIGHT, nil
×
1818

1819
        case paymentsdb.StatusInFlight:
1✔
1820
                return lnrpc.Payment_IN_FLIGHT, nil
1✔
1821

1822
        case paymentsdb.StatusSucceeded:
2✔
1823
                return lnrpc.Payment_SUCCEEDED, nil
2✔
1824

1825
        case paymentsdb.StatusFailed:
×
1826
                return lnrpc.Payment_FAILED, nil
×
1827

1828
        default:
×
1829
                return 0, fmt.Errorf("unhandled payment status %v", dbStatus)
×
1830
        }
1831
}
1832

1833
// marshallPaymentFailureReason marshalls the failure reason to the corresponding rpc
1834
// type.
1835
func marshallPaymentFailureReason(reason *paymentsdb.FailureReason) (
1836
        lnrpc.PaymentFailureReason, error) {
3✔
1837

3✔
1838
        if reason == nil {
6✔
1839
                return lnrpc.PaymentFailureReason_FAILURE_REASON_NONE, nil
3✔
1840
        }
3✔
1841

1842
        switch *reason {
×
1843
        case paymentsdb.FailureReasonTimeout:
×
1844
                return lnrpc.PaymentFailureReason_FAILURE_REASON_TIMEOUT, nil
×
1845

1846
        case paymentsdb.FailureReasonNoRoute:
×
1847
                return lnrpc.PaymentFailureReason_FAILURE_REASON_NO_ROUTE, nil
×
1848

1849
        case paymentsdb.FailureReasonError:
×
1850
                return lnrpc.PaymentFailureReason_FAILURE_REASON_ERROR, nil
×
1851

1852
        case paymentsdb.FailureReasonPaymentDetails:
×
1853
                return lnrpc.PaymentFailureReason_FAILURE_REASON_INCORRECT_PAYMENT_DETAILS, nil
×
1854

1855
        case paymentsdb.FailureReasonInsufficientBalance:
×
1856
                return lnrpc.PaymentFailureReason_FAILURE_REASON_INSUFFICIENT_BALANCE, nil
×
1857

1858
        case paymentsdb.FailureReasonCanceled:
×
1859
                return lnrpc.PaymentFailureReason_FAILURE_REASON_CANCELED, nil
×
1860
        }
1861

1862
        return 0, errors.New("unknown failure reason")
×
1863
}
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