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

lightningnetwork / lnd / 14601852330

22 Apr 2025 06:21PM UTC coverage: 68.962% (+10.4%) from 58.602%
14601852330

Pull #9752

github

web-flow
Merge bb59d5222 into 987302923
Pull Request #9752: routerrpc: reject payment to invoice that don't have payment secret or blinded paths

1 of 4 new or added lines in 1 file covered. (25.0%)

197 existing lines in 17 files now uncovered.

133751 of 193949 relevant lines covered (68.96%)

22152.3 hits per line

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

77.45
/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/channeldb"
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
        "github.com/lightningnetwork/lnd/record"
25
        "github.com/lightningnetwork/lnd/routing"
26
        "github.com/lightningnetwork/lnd/routing/route"
27
        "github.com/lightningnetwork/lnd/subscribe"
28
        "github.com/lightningnetwork/lnd/zpay32"
29
        "google.golang.org/protobuf/proto"
30
)
31

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

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

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

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

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

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

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

69
        MissionControl MissionControl
70

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

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

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

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

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

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

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

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

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

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

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

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

123
// MissionControl defines the mission control dependencies of routerrpc.
124
type MissionControl interface {
125
        // GetProbability is expected to return the success probability of a
126
        // payment from fromNode to toNode.
127
        GetProbability(fromNode, toNode route.Vertex,
128
                amt lnwire.MilliSatoshi, capacity btcutil.Amount) float64
129

130
        // ResetHistory resets the history of MissionControl returning it to a
131
        // state as if no payment attempts have been made.
132
        ResetHistory() error
133

134
        // GetHistorySnapshot takes a snapshot from the current mission control
135
        // state and actual probability estimates.
136
        GetHistorySnapshot() *routing.MissionControlSnapshot
137

138
        // ImportHistory imports the mission control snapshot to our internal
139
        // state. This import will only be applied in-memory, and will not be
140
        // persisted across restarts.
141
        ImportHistory(snapshot *routing.MissionControlSnapshot, force bool) error
142

143
        // GetPairHistorySnapshot returns the stored history for a given node
144
        // pair.
145
        GetPairHistorySnapshot(fromNode,
146
                toNode route.Vertex) routing.TimedPairResult
147

148
        // GetConfig gets mission control's current config.
149
        GetConfig() *routing.MissionControlConfig
150

151
        // SetConfig sets mission control's config to the values provided, if
152
        // they are valid.
153
        SetConfig(cfg *routing.MissionControlConfig) error
154
}
155

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

6✔
168
        routeReq, err := r.parseQueryRoutesRequest(in)
6✔
169
        if err != nil {
7✔
170
                return nil, err
1✔
171
        }
1✔
172

173
        // Query the channel router for a possible path to the destination that
174
        // can carry `in.Amt` satoshis _including_ the total fee required on
175
        // the route
176
        route, successProb, err := r.FindRoute(routeReq)
5✔
177
        if err != nil {
5✔
178
                return nil, err
×
179
        }
×
180

181
        // For each valid route, we'll convert the result into the format
182
        // required by the RPC system.
183
        rpcRoute, err := r.MarshallRoute(route)
5✔
184
        if err != nil {
5✔
185
                return nil, err
×
186
        }
×
187

188
        routeResp := &lnrpc.QueryRoutesResponse{
5✔
189
                Routes:      []*lnrpc.Route{rpcRoute},
5✔
190
                SuccessProb: successProb,
5✔
191
        }
5✔
192

5✔
193
        return routeResp, nil
5✔
194
}
195

196
func parsePubKey(key string) (route.Vertex, error) {
6✔
197
        pubKeyBytes, err := hex.DecodeString(key)
6✔
198
        if err != nil {
6✔
199
                return route.Vertex{}, err
×
200
        }
×
201

202
        return route.NewVertexFromBytes(pubKeyBytes)
6✔
203
}
204

205
func (r *RouterBackend) parseIgnored(in *lnrpc.QueryRoutesRequest) (
206
        map[route.Vertex]struct{}, map[routing.DirectedNodePair]struct{},
207
        error) {
5✔
208

5✔
209
        ignoredNodes := make(map[route.Vertex]struct{})
5✔
210
        for _, ignorePubKey := range in.IgnoredNodes {
8✔
211
                ignoreVertex, err := route.NewVertexFromBytes(ignorePubKey)
3✔
212
                if err != nil {
3✔
213
                        return nil, nil, err
×
214
                }
×
215
                ignoredNodes[ignoreVertex] = struct{}{}
3✔
216
        }
217

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

5✔
220
        // Convert deprecated ignoredEdges to pairs.
5✔
221
        for _, ignoredEdge := range in.IgnoredEdges {
8✔
222
                pair, err := r.rpcEdgeToPair(ignoredEdge)
3✔
223
                if err != nil {
3✔
224
                        log.Warnf("Ignore channel %v skipped: %v",
×
225
                                ignoredEdge.ChannelId, err)
×
226

×
227
                        continue
×
228
                }
229
                ignoredPairs[pair] = struct{}{}
3✔
230
        }
231

232
        // Add ignored pairs to set.
233
        for _, ignorePair := range in.IgnoredPairs {
8✔
234
                from, err := route.NewVertexFromBytes(ignorePair.From)
3✔
235
                if err != nil {
3✔
236
                        return nil, nil, err
×
237
                }
×
238

239
                to, err := route.NewVertexFromBytes(ignorePair.To)
3✔
240
                if err != nil {
3✔
241
                        return nil, nil, err
×
242
                }
×
243

244
                pair := routing.NewDirectedNodePair(from, to)
3✔
245
                ignoredPairs[pair] = struct{}{}
3✔
246
        }
247

248
        return ignoredNodes, ignoredPairs, nil
5✔
249
}
250

251
func (r *RouterBackend) parseQueryRoutesRequest(in *lnrpc.QueryRoutesRequest) (
252
        *routing.RouteRequest, error) {
6✔
253

6✔
254
        // Parse the hex-encoded source public key into a full public key that
6✔
255
        // we can properly manipulate.
6✔
256

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

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

277
        // Unmarshall restrictions from request.
278
        feeLimit := lnrpc.CalculateFeeLimit(in.FeeLimit, amt)
6✔
279

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

287
        cltvLimit, err := ValidateCLTVLimit(in.CltvLimit, maxTotalTimelock)
6✔
288
        if err != nil {
6✔
289
                return nil, err
×
290
        }
×
291

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

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

6✔
306
                // destinationFeatures is the set of features for the
6✔
307
                // destination node.
6✔
308
                destinationFeatures *lnwire.FeatureVector
6✔
309
        )
6✔
310

6✔
311
        // Validate that the fields provided in the request are sane depending
6✔
312
        // on whether it is using a blinded path or not.
6✔
313
        if len(in.BlindedPaymentPaths) > 0 {
8✔
314
                blindedPathSet, err = parseBlindedPaymentPaths(in)
2✔
315
                if err != nil {
2✔
316
                        return nil, err
×
317
                }
×
318

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

6✔
332
                // Convert route hints to an edge map.
6✔
333
                routeHints, err := unmarshallRouteHints(in.RouteHints)
6✔
334
                if err != nil {
6✔
335
                        return nil, err
×
336
                }
×
337

338
                routeHintEdges, err = routing.RouteHintsToEdges(
6✔
339
                        routeHints, *targetPubKey,
6✔
340
                )
6✔
341
                if err != nil {
6✔
342
                        return nil, err
×
343
                }
×
344

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

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

362
                // Parse destination feature bits.
363
                destinationFeatures, err = UnmarshalFeatures(in.DestFeatures)
5✔
364
                if err != nil {
5✔
365
                        return nil, err
×
366
                }
×
367
        }
368

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

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

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

14✔
385
                        if _, ok := ignoredNodes[fromNode]; ok {
17✔
386
                                return 0
3✔
387
                        }
3✔
388

389
                        pair := routing.DirectedNodePair{
11✔
390
                                From: fromNode,
11✔
391
                                To:   toNode,
11✔
392
                        }
11✔
393
                        if _, ok := ignoredPairs[pair]; ok {
17✔
394
                                return 0
6✔
395
                        }
6✔
396

397
                        if !in.UseMissionControl {
9✔
398
                                return 1
4✔
399
                        }
4✔
400

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

411
        // Pass along an outgoing channel restriction if specified.
412
        if in.OutgoingChanId != 0 {
8✔
413
                restrictions.OutgoingChannelIDs = []uint64{in.OutgoingChanId}
3✔
414
        }
3✔
415

416
        // Pass along a last hop restriction if specified.
417
        if len(in.LastHopPubkey) > 0 {
8✔
418
                lastHop, err := route.NewVertexFromBytes(
3✔
419
                        in.LastHopPubkey,
3✔
420
                )
3✔
421
                if err != nil {
3✔
422
                        return nil, err
×
423
                }
×
424
                restrictions.LastHop = &lastHop
3✔
425
        }
426

427
        // If we have any TLV records destined for the final hop, then we'll
428
        // attempt to decode them now into a form that the router can more
429
        // easily manipulate.
430
        customRecords := record.CustomSet(in.DestCustomRecords)
5✔
431
        if err := customRecords.Validate(); err != nil {
5✔
432
                return nil, err
×
433
        }
×
434

435
        return routing.NewRouteRequest(
5✔
436
                sourcePubKey, targetPubKey, amt, in.TimePref, restrictions,
5✔
437
                customRecords, routeHintEdges, blindedPathSet,
5✔
438
                finalCLTVDelta,
5✔
439
        )
5✔
440
}
441

442
func parseBlindedPaymentPaths(in *lnrpc.QueryRoutesRequest) (
443
        *routing.BlindedPaymentPathSet, error) {
2✔
444

2✔
445
        if len(in.PubKey) != 0 {
2✔
446
                return nil, fmt.Errorf("target pubkey: %x should not be set "+
×
447
                        "when blinded path is provided", in.PubKey)
×
448
        }
×
449

450
        if len(in.RouteHints) > 0 {
2✔
451
                return nil, errors.New("route hints and blinded path can't " +
×
452
                        "both be set")
×
453
        }
×
454

455
        if in.FinalCltvDelta != 0 {
2✔
456
                return nil, errors.New("final cltv delta should be " +
×
457
                        "zero for blinded paths")
×
458
        }
×
459

460
        // For blinded paths, we get one set of features for the relaying
461
        // intermediate nodes and the final destination. We don't allow the
462
        // destination feature bit field for regular payments to be set, as
463
        // this could lead to ambiguity.
464
        if len(in.DestFeatures) > 0 {
2✔
465
                return nil, errors.New("destination features should " +
×
466
                        "be populated in blinded path")
×
467
        }
×
468

469
        paths := make([]*routing.BlindedPayment, len(in.BlindedPaymentPaths))
2✔
470
        for i, paymentPath := range in.BlindedPaymentPaths {
4✔
471
                blindedPmt, err := unmarshalBlindedPayment(paymentPath)
2✔
472
                if err != nil {
2✔
473
                        return nil, fmt.Errorf("parse blinded payment: %w", err)
×
474
                }
×
475

476
                if err := blindedPmt.Validate(); err != nil {
2✔
477
                        return nil, fmt.Errorf("invalid blinded path: %w", err)
×
478
                }
×
479

480
                paths[i] = blindedPmt
2✔
481
        }
482

483
        return routing.NewBlindedPaymentPathSet(paths)
2✔
484
}
485

486
func unmarshalBlindedPayment(rpcPayment *lnrpc.BlindedPaymentPath) (
487
        *routing.BlindedPayment, error) {
2✔
488

2✔
489
        if rpcPayment == nil {
2✔
490
                return nil, errors.New("nil blinded payment")
×
491
        }
×
492

493
        path, err := unmarshalBlindedPaymentPaths(rpcPayment.BlindedPath)
2✔
494
        if err != nil {
2✔
495
                return nil, err
×
496
        }
×
497

498
        features, err := UnmarshalFeatures(rpcPayment.Features)
2✔
499
        if err != nil {
2✔
500
                return nil, err
×
501
        }
×
502

503
        return &routing.BlindedPayment{
2✔
504
                BlindedPath:         path,
2✔
505
                CltvExpiryDelta:     uint16(rpcPayment.TotalCltvDelta),
2✔
506
                BaseFee:             uint32(rpcPayment.BaseFeeMsat),
2✔
507
                ProportionalFeeRate: rpcPayment.ProportionalFeeRate,
2✔
508
                HtlcMinimum:         rpcPayment.HtlcMinMsat,
2✔
509
                HtlcMaximum:         rpcPayment.HtlcMaxMsat,
2✔
510
                Features:            features,
2✔
511
        }, nil
2✔
512
}
513

514
func unmarshalBlindedPaymentPaths(rpcPath *lnrpc.BlindedPath) (
515
        *sphinx.BlindedPath, error) {
2✔
516

2✔
517
        if rpcPath == nil {
2✔
518
                return nil, errors.New("blinded path required when blinded " +
×
519
                        "route is provided")
×
520
        }
×
521

522
        introduction, err := btcec.ParsePubKey(rpcPath.IntroductionNode)
2✔
523
        if err != nil {
2✔
524
                return nil, err
×
525
        }
×
526

527
        blinding, err := btcec.ParsePubKey(rpcPath.BlindingPoint)
2✔
528
        if err != nil {
2✔
529
                return nil, err
×
530
        }
×
531

532
        if len(rpcPath.BlindedHops) < 1 {
2✔
533
                return nil, errors.New("at least 1 blinded hops required")
×
534
        }
×
535

536
        path := &sphinx.BlindedPath{
2✔
537
                IntroductionPoint: introduction,
2✔
538
                BlindingPoint:     blinding,
2✔
539
                BlindedHops: make(
2✔
540
                        []*sphinx.BlindedHopInfo, len(rpcPath.BlindedHops),
2✔
541
                ),
2✔
542
        }
2✔
543

2✔
544
        for i, hop := range rpcPath.BlindedHops {
4✔
545
                path.BlindedHops[i], err = unmarshalBlindedHop(hop)
2✔
546
                if err != nil {
2✔
547
                        return nil, err
×
548
                }
×
549
        }
550

551
        return path, nil
2✔
552
}
553

554
func unmarshalBlindedHop(rpcHop *lnrpc.BlindedHop) (*sphinx.BlindedHopInfo,
555
        error) {
2✔
556

2✔
557
        pubkey, err := btcec.ParsePubKey(rpcHop.BlindedNode)
2✔
558
        if err != nil {
2✔
559
                return nil, err
×
560
        }
×
561

562
        if len(rpcHop.EncryptedData) == 0 {
2✔
563
                return nil, errors.New("empty encrypted data not allowed")
×
564
        }
×
565

566
        return &sphinx.BlindedHopInfo{
2✔
567
                BlindedNodePub: pubkey,
2✔
568
                CipherText:     rpcHop.EncryptedData,
2✔
569
        }, nil
2✔
570
}
571

572
// rpcEdgeToPair looks up the provided channel and returns the channel endpoints
573
// as a directed pair.
574
func (r *RouterBackend) rpcEdgeToPair(e *lnrpc.EdgeLocator) (
575
        routing.DirectedNodePair, error) {
3✔
576

3✔
577
        a, b, err := r.FetchChannelEndpoints(e.ChannelId)
3✔
578
        if err != nil {
3✔
579
                return routing.DirectedNodePair{}, err
×
580
        }
×
581

582
        var pair routing.DirectedNodePair
3✔
583
        if e.DirectionReverse {
6✔
584
                pair.From, pair.To = b, a
3✔
585
        } else {
3✔
586
                pair.From, pair.To = a, b
×
587
        }
×
588

589
        return pair, nil
3✔
590
}
591

592
// MarshallRoute marshalls an internal route to an rpc route struct.
593
func (r *RouterBackend) MarshallRoute(route *route.Route) (*lnrpc.Route, error) {
5✔
594
        resp := &lnrpc.Route{
5✔
595
                TotalTimeLock:      route.TotalTimeLock,
5✔
596
                TotalFees:          int64(route.TotalFees().ToSatoshis()),
5✔
597
                TotalFeesMsat:      int64(route.TotalFees()),
5✔
598
                TotalAmt:           int64(route.TotalAmount.ToSatoshis()),
5✔
599
                TotalAmtMsat:       int64(route.TotalAmount),
5✔
600
                Hops:               make([]*lnrpc.Hop, len(route.Hops)),
5✔
601
                FirstHopAmountMsat: int64(route.FirstHopAmount.Val.Int()),
5✔
602
        }
5✔
603

5✔
604
        // Encode the route's custom channel data (if available).
5✔
605
        if len(route.FirstHopWireCustomRecords) > 0 {
7✔
606
                customData, err := route.FirstHopWireCustomRecords.Serialize()
2✔
607
                if err != nil {
2✔
608
                        return nil, err
×
609
                }
×
610

611
                resp.CustomChannelData = customData
2✔
612

2✔
613
                // Allow the aux data parser to parse the custom records into
2✔
614
                // a human-readable JSON (if available).
2✔
615
                if r.ParseCustomChannelData != nil {
4✔
616
                        err := r.ParseCustomChannelData(resp)
2✔
617
                        if err != nil {
2✔
618
                                return nil, err
×
619
                        }
×
620
                }
621
        }
622

623
        incomingAmt := route.TotalAmount
5✔
624
        for i, hop := range route.Hops {
10✔
625
                fee := route.HopFee(i)
5✔
626

5✔
627
                // Channel capacity is not a defining property of a route. For
5✔
628
                // backwards RPC compatibility, we retrieve it here from the
5✔
629
                // graph.
5✔
630
                chanCapacity, err := r.FetchChannelCapacity(hop.ChannelID)
5✔
631
                if err != nil {
7✔
632
                        // If capacity cannot be retrieved, this may be a
2✔
633
                        // not-yet-received or private channel. Then report
2✔
634
                        // amount that is sent through the channel as capacity.
2✔
635
                        chanCapacity = incomingAmt.ToSatoshis()
2✔
636
                }
2✔
637

638
                // Extract the MPP fields if present on this hop.
639
                var mpp *lnrpc.MPPRecord
5✔
640
                if hop.MPP != nil {
7✔
641
                        addr := hop.MPP.PaymentAddr()
2✔
642

2✔
643
                        mpp = &lnrpc.MPPRecord{
2✔
644
                                PaymentAddr:  addr[:],
2✔
645
                                TotalAmtMsat: int64(hop.MPP.TotalMsat()),
2✔
646
                        }
2✔
647
                }
2✔
648

649
                var amp *lnrpc.AMPRecord
5✔
650
                if hop.AMP != nil {
7✔
651
                        rootShare := hop.AMP.RootShare()
2✔
652
                        setID := hop.AMP.SetID()
2✔
653

2✔
654
                        amp = &lnrpc.AMPRecord{
2✔
655
                                RootShare:  rootShare[:],
2✔
656
                                SetId:      setID[:],
2✔
657
                                ChildIndex: hop.AMP.ChildIndex(),
2✔
658
                        }
2✔
659
                }
2✔
660

661
                resp.Hops[i] = &lnrpc.Hop{
5✔
662
                        ChanId:           hop.ChannelID,
5✔
663
                        ChanCapacity:     int64(chanCapacity),
5✔
664
                        AmtToForward:     int64(hop.AmtToForward.ToSatoshis()),
5✔
665
                        AmtToForwardMsat: int64(hop.AmtToForward),
5✔
666
                        Fee:              int64(fee.ToSatoshis()),
5✔
667
                        FeeMsat:          int64(fee),
5✔
668
                        Expiry:           uint32(hop.OutgoingTimeLock),
5✔
669
                        PubKey: hex.EncodeToString(
5✔
670
                                hop.PubKeyBytes[:],
5✔
671
                        ),
5✔
672
                        CustomRecords: hop.CustomRecords,
5✔
673
                        TlvPayload:    !hop.LegacyPayload,
5✔
674
                        MppRecord:     mpp,
5✔
675
                        AmpRecord:     amp,
5✔
676
                        Metadata:      hop.Metadata,
5✔
677
                        EncryptedData: hop.EncryptedData,
5✔
678
                        TotalAmtMsat:  uint64(hop.TotalAmtMsat),
5✔
679
                }
5✔
680

5✔
681
                if hop.BlindingPoint != nil {
7✔
682
                        blinding := hop.BlindingPoint.SerializeCompressed()
2✔
683
                        resp.Hops[i].BlindingPoint = blinding
2✔
684
                }
2✔
685
                incomingAmt = hop.AmtToForward
5✔
686
        }
687

688
        return resp, nil
5✔
689
}
690

691
// UnmarshallHopWithPubkey unmarshalls an rpc hop for which the pubkey has
692
// already been extracted.
693
func UnmarshallHopWithPubkey(rpcHop *lnrpc.Hop, pubkey route.Vertex) (*route.Hop,
694
        error) {
2✔
695

2✔
696
        customRecords := record.CustomSet(rpcHop.CustomRecords)
2✔
697
        if err := customRecords.Validate(); err != nil {
2✔
698
                return nil, err
×
699
        }
×
700

701
        mpp, err := UnmarshalMPP(rpcHop.MppRecord)
2✔
702
        if err != nil {
2✔
703
                return nil, err
×
704
        }
×
705

706
        amp, err := UnmarshalAMP(rpcHop.AmpRecord)
2✔
707
        if err != nil {
2✔
708
                return nil, err
×
709
        }
×
710

711
        hop := &route.Hop{
2✔
712
                OutgoingTimeLock: rpcHop.Expiry,
2✔
713
                AmtToForward:     lnwire.MilliSatoshi(rpcHop.AmtToForwardMsat),
2✔
714
                PubKeyBytes:      pubkey,
2✔
715
                ChannelID:        rpcHop.ChanId,
2✔
716
                CustomRecords:    customRecords,
2✔
717
                LegacyPayload:    false,
2✔
718
                MPP:              mpp,
2✔
719
                AMP:              amp,
2✔
720
                EncryptedData:    rpcHop.EncryptedData,
2✔
721
                TotalAmtMsat:     lnwire.MilliSatoshi(rpcHop.TotalAmtMsat),
2✔
722
        }
2✔
723

2✔
724
        haveBlindingPoint := len(rpcHop.BlindingPoint) != 0
2✔
725
        if haveBlindingPoint {
4✔
726
                hop.BlindingPoint, err = btcec.ParsePubKey(
2✔
727
                        rpcHop.BlindingPoint,
2✔
728
                )
2✔
729
                if err != nil {
2✔
730
                        return nil, fmt.Errorf("blinding point: %w", err)
×
731
                }
×
732
        }
733

734
        if haveBlindingPoint && len(rpcHop.EncryptedData) == 0 {
2✔
735
                return nil, errors.New("encrypted data should be present if " +
×
736
                        "blinding point is provided")
×
737
        }
×
738

739
        return hop, nil
2✔
740
}
741

742
// UnmarshallHop unmarshalls an rpc hop that may or may not contain a node
743
// pubkey.
744
func (r *RouterBackend) UnmarshallHop(rpcHop *lnrpc.Hop,
745
        prevNodePubKey [33]byte) (*route.Hop, error) {
2✔
746

2✔
747
        var pubKeyBytes [33]byte
2✔
748
        if rpcHop.PubKey != "" {
4✔
749
                // Unmarshall the provided hop pubkey.
2✔
750
                pubKey, err := hex.DecodeString(rpcHop.PubKey)
2✔
751
                if err != nil {
2✔
752
                        return nil, fmt.Errorf("cannot decode pubkey %s",
×
753
                                rpcHop.PubKey)
×
754
                }
×
755
                copy(pubKeyBytes[:], pubKey)
2✔
756
        } else {
×
757
                // If no pub key is given of the hop, the local channel graph
×
758
                // needs to be queried to complete the information necessary for
×
759
                // routing. Discard edge policies, because they may be nil.
×
760
                node1, node2, err := r.FetchChannelEndpoints(rpcHop.ChanId)
×
761
                if err != nil {
×
762
                        return nil, err
×
763
                }
×
764

765
                switch {
×
766
                case prevNodePubKey == node1:
×
767
                        pubKeyBytes = node2
×
768
                case prevNodePubKey == node2:
×
769
                        pubKeyBytes = node1
×
770
                default:
×
771
                        return nil, fmt.Errorf("channel edge does not match " +
×
772
                                "expected node")
×
773
                }
774
        }
775

776
        return UnmarshallHopWithPubkey(rpcHop, pubKeyBytes)
2✔
777
}
778

779
// UnmarshallRoute unmarshalls an rpc route. For hops that don't specify a
780
// pubkey, the channel graph is queried.
781
func (r *RouterBackend) UnmarshallRoute(rpcroute *lnrpc.Route) (
782
        *route.Route, error) {
2✔
783

2✔
784
        prevNodePubKey := r.SelfNode
2✔
785

2✔
786
        hops := make([]*route.Hop, len(rpcroute.Hops))
2✔
787
        for i, hop := range rpcroute.Hops {
4✔
788
                routeHop, err := r.UnmarshallHop(hop, prevNodePubKey)
2✔
789
                if err != nil {
2✔
790
                        return nil, err
×
791
                }
×
792

793
                hops[i] = routeHop
2✔
794

2✔
795
                prevNodePubKey = routeHop.PubKeyBytes
2✔
796
        }
797

798
        route, err := route.NewRouteFromHops(
2✔
799
                lnwire.MilliSatoshi(rpcroute.TotalAmtMsat),
2✔
800
                rpcroute.TotalTimeLock,
2✔
801
                r.SelfNode,
2✔
802
                hops,
2✔
803
        )
2✔
804
        if err != nil {
2✔
805
                return nil, err
×
806
        }
×
807

808
        return route, nil
2✔
809
}
810

811
// extractIntentFromSendRequest attempts to parse the SendRequest details
812
// required to dispatch a client from the information presented by an RPC
813
// client.
814
func (r *RouterBackend) extractIntentFromSendRequest(
815
        rpcPayReq *SendPaymentRequest) (*routing.LightningPayment, error) {
25✔
816

25✔
817
        payIntent := &routing.LightningPayment{}
25✔
818

25✔
819
        // Pass along time preference.
25✔
820
        if rpcPayReq.TimePref < -1 || rpcPayReq.TimePref > 1 {
26✔
821
                return nil, errors.New("time preference out of range")
1✔
822
        }
1✔
823
        payIntent.TimePref = rpcPayReq.TimePref
24✔
824

24✔
825
        // Pass along restrictions on the outgoing channels that may be used.
24✔
826
        payIntent.OutgoingChannelIDs = rpcPayReq.OutgoingChanIds
24✔
827

24✔
828
        // Add the deprecated single outgoing channel restriction if present.
24✔
829
        if rpcPayReq.OutgoingChanId != 0 {
25✔
830
                if payIntent.OutgoingChannelIDs != nil {
2✔
831
                        return nil, errors.New("outgoing_chan_id and " +
1✔
832
                                "outgoing_chan_ids are mutually exclusive")
1✔
833
                }
1✔
834

835
                payIntent.OutgoingChannelIDs = append(
×
836
                        payIntent.OutgoingChannelIDs, rpcPayReq.OutgoingChanId,
×
837
                )
×
838
        }
839

840
        // Pass along a last hop restriction if specified.
841
        if len(rpcPayReq.LastHopPubkey) > 0 {
24✔
842
                lastHop, err := route.NewVertexFromBytes(
1✔
843
                        rpcPayReq.LastHopPubkey,
1✔
844
                )
1✔
845
                if err != nil {
2✔
846
                        return nil, err
1✔
847
                }
1✔
848
                payIntent.LastHop = &lastHop
×
849
        }
850

851
        // Take the CLTV limit from the request if set, otherwise use the max.
852
        cltvLimit, err := ValidateCLTVLimit(
22✔
853
                uint32(rpcPayReq.CltvLimit), r.MaxTotalTimelock,
22✔
854
        )
22✔
855
        if err != nil {
23✔
856
                return nil, err
1✔
857
        }
1✔
858
        payIntent.CltvLimit = cltvLimit
21✔
859

21✔
860
        // Attempt to parse the max parts value set by the user, if this value
21✔
861
        // isn't set, then we'll use the current default value for this
21✔
862
        // setting.
21✔
863
        maxParts := rpcPayReq.MaxParts
21✔
864
        if maxParts == 0 {
39✔
865
                maxParts = DefaultMaxParts
18✔
866
        }
18✔
867
        payIntent.MaxParts = maxParts
21✔
868

21✔
869
        // If this payment had a max shard amount specified, then we'll apply
21✔
870
        // that now, which'll force us to always make payment splits smaller
21✔
871
        // than this.
21✔
872
        if rpcPayReq.MaxShardSizeMsat > 0 {
27✔
873
                shardAmtMsat := lnwire.MilliSatoshi(rpcPayReq.MaxShardSizeMsat)
6✔
874
                payIntent.MaxShardAmt = &shardAmtMsat
6✔
875

6✔
876
                // If the requested max_parts exceeds the allowed limit, then we
6✔
877
                // cannot send the payment amount.
6✔
878
                if payIntent.MaxParts > MaxPartsUpperLimit {
7✔
879
                        return nil, fmt.Errorf("requested max_parts (%v) "+
1✔
880
                                "exceeds the allowed upper limit of %v; cannot"+
1✔
881
                                " send payment amount with max_shard_size_msat"+
1✔
882
                                "=%v", payIntent.MaxParts, MaxPartsUpperLimit,
1✔
883
                                *payIntent.MaxShardAmt)
1✔
884
                }
1✔
885
        }
886

887
        // Take fee limit from request.
888
        payIntent.FeeLimit, err = lnrpc.UnmarshallAmt(
20✔
889
                rpcPayReq.FeeLimitSat, rpcPayReq.FeeLimitMsat,
20✔
890
        )
20✔
891
        if err != nil {
22✔
892
                return nil, err
2✔
893
        }
2✔
894

895
        customRecords := record.CustomSet(rpcPayReq.DestCustomRecords)
18✔
896
        if err := customRecords.Validate(); err != nil {
19✔
897
                return nil, err
1✔
898
        }
1✔
899
        payIntent.DestCustomRecords = customRecords
17✔
900

17✔
901
        // Keysend payments do not support MPP payments.
17✔
902
        //
17✔
903
        // NOTE: There is no need to validate the `MaxParts` value here because
17✔
904
        // it is set to 1 somewhere else in case it's a keysend payment.
17✔
905
        if customRecords.IsKeysend() {
20✔
906
                if payIntent.MaxShardAmt != nil {
6✔
907
                        return nil, errors.New("keysend payments cannot " +
3✔
908
                                "specify a max shard amount - MPP not " +
3✔
909
                                "supported with keysend payments")
3✔
910
                }
3✔
911
        }
912

913
        firstHopRecords := lnwire.CustomRecords(rpcPayReq.FirstHopCustomRecords)
16✔
914
        if err := firstHopRecords.Validate(); err != nil {
17✔
915
                return nil, err
1✔
916
        }
1✔
917
        payIntent.FirstHopCustomRecords = firstHopRecords
15✔
918

15✔
919
        // If the experimental endorsement signal is not already set, propagate
15✔
920
        // a zero value field if configured to set this signal.
15✔
921
        if r.ShouldSetExpEndorsement() {
18✔
922
                if payIntent.FirstHopCustomRecords == nil {
6✔
923
                        payIntent.FirstHopCustomRecords = make(
3✔
924
                                map[uint64][]byte,
3✔
925
                        )
3✔
926
                }
3✔
927

928
                t := uint64(lnwire.ExperimentalEndorsementType)
3✔
929
                if _, set := payIntent.FirstHopCustomRecords[t]; !set {
6✔
930
                        payIntent.FirstHopCustomRecords[t] = []byte{
3✔
931
                                lnwire.ExperimentalUnendorsed,
3✔
932
                        }
3✔
933
                }
3✔
934
        }
935

936
        payIntent.PayAttemptTimeout = time.Second *
15✔
937
                time.Duration(rpcPayReq.TimeoutSeconds)
15✔
938

15✔
939
        // Route hints.
15✔
940
        routeHints, err := unmarshallRouteHints(
15✔
941
                rpcPayReq.RouteHints,
15✔
942
        )
15✔
943
        if err != nil {
15✔
944
                return nil, err
×
945
        }
×
946
        payIntent.RouteHints = routeHints
15✔
947

15✔
948
        // Unmarshall either sat or msat amount from request.
15✔
949
        reqAmt, err := lnrpc.UnmarshallAmt(
15✔
950
                rpcPayReq.Amt, rpcPayReq.AmtMsat,
15✔
951
        )
15✔
952
        if err != nil {
16✔
953
                return nil, err
1✔
954
        }
1✔
955

956
        // If the payment request field isn't blank, then the details of the
957
        // invoice are encoded entirely within the encoded payReq.  So we'll
958
        // attempt to decode it, populating the payment accordingly.
959
        if rpcPayReq.PaymentRequest != "" {
21✔
960
                switch {
7✔
961

962
                case len(rpcPayReq.Dest) > 0:
1✔
963
                        return nil, errors.New("dest and payment_request " +
1✔
964
                                "cannot appear together")
1✔
965

966
                case len(rpcPayReq.PaymentHash) > 0:
1✔
967
                        return nil, errors.New("payment_hash and payment_request " +
1✔
968
                                "cannot appear together")
1✔
969

970
                case rpcPayReq.FinalCltvDelta != 0:
1✔
971
                        return nil, errors.New("final_cltv_delta and payment_request " +
1✔
972
                                "cannot appear together")
1✔
973
                }
974

975
                payReq, err := zpay32.Decode(
4✔
976
                        rpcPayReq.PaymentRequest, r.ActiveNetParams,
4✔
977
                )
4✔
978
                if err != nil {
5✔
979
                        return nil, err
1✔
980
                }
1✔
981

982
                // Next, we'll ensure that this payreq hasn't already expired.
983
                err = ValidatePayReqExpiry(payReq)
3✔
984
                if err != nil {
4✔
985
                        return nil, err
1✔
986
                }
1✔
987

988
                // An invoice must include either a payment address or
989
                // blinded paths.
990
                if payReq.PaymentAddr.IsNone() && len(payReq.BlindedPaymentPaths) == 0 {
2✔
NEW
991
                        return nil, errors.New("payment request must contain " +
×
NEW
992
                                "either a payment address or blinded paths")
×
NEW
993
                }
×
994

995
                // If the amount was not included in the invoice, then we let
996
                // the payer specify the amount of satoshis they wish to send.
997
                // We override the amount to pay with the amount provided from
998
                // the payment request.
999
                if payReq.MilliSat == nil {
2✔
1000
                        if reqAmt == 0 {
×
1001
                                return nil, errors.New("amount must be " +
×
1002
                                        "specified when paying a zero amount " +
×
1003
                                        "invoice")
×
1004
                        }
×
1005

1006
                        payIntent.Amount = reqAmt
×
1007
                } else {
2✔
1008
                        if reqAmt != 0 {
2✔
1009
                                return nil, errors.New("amount must not be " +
×
1010
                                        "specified when paying a non-zero " +
×
1011
                                        " amount invoice")
×
1012
                        }
×
1013

1014
                        payIntent.Amount = *payReq.MilliSat
2✔
1015
                }
1016

1017
                if !payReq.Features.HasFeature(lnwire.MPPOptional) &&
2✔
1018
                        !payReq.Features.HasFeature(lnwire.AMPOptional) {
2✔
1019

×
1020
                        payIntent.MaxParts = 1
×
1021
                }
×
1022

1023
                payAddr := payReq.PaymentAddr
2✔
1024
                if payReq.Features.HasFeature(lnwire.AMPOptional) {
4✔
1025
                        // The opt-in AMP flag is required to pay an AMP
2✔
1026
                        // invoice.
2✔
1027
                        if !rpcPayReq.Amp {
2✔
1028
                                return nil, fmt.Errorf("the AMP flag (--amp " +
×
1029
                                        "or SendPaymentRequest.Amp) must be " +
×
1030
                                        "set to pay an AMP invoice")
×
1031
                        }
×
1032

1033
                        // Generate random SetID and root share.
1034
                        var setID [32]byte
2✔
1035
                        _, err = rand.Read(setID[:])
2✔
1036
                        if err != nil {
2✔
1037
                                return nil, err
×
1038
                        }
×
1039

1040
                        var rootShare [32]byte
2✔
1041
                        _, err = rand.Read(rootShare[:])
2✔
1042
                        if err != nil {
2✔
1043
                                return nil, err
×
1044
                        }
×
1045
                        err := payIntent.SetAMP(&routing.AMPOptions{
2✔
1046
                                SetID:     setID,
2✔
1047
                                RootShare: rootShare,
2✔
1048
                        })
2✔
1049
                        if err != nil {
2✔
1050
                                return nil, err
×
1051
                        }
×
1052

1053
                        // For AMP invoices, we'll allow users to override the
1054
                        // included payment addr to allow the invoice to be
1055
                        // pseudo-reusable, e.g. the invoice parameters are
1056
                        // reused (amt, cltv, hop hints, etc) even though the
1057
                        // payments will share different payment hashes.
1058
                        //
1059
                        // NOTE: This will only work when the peer has
1060
                        // spontaneous AMP payments enabled.
1061
                        if len(rpcPayReq.PaymentAddr) > 0 {
4✔
1062
                                var addr [32]byte
2✔
1063
                                copy(addr[:], rpcPayReq.PaymentAddr)
2✔
1064
                                payAddr = fn.Some(addr)
2✔
1065
                        }
2✔
1066
                } else {
2✔
1067
                        err = payIntent.SetPaymentHash(*payReq.PaymentHash)
2✔
1068
                        if err != nil {
2✔
1069
                                return nil, err
×
1070
                        }
×
1071
                }
1072

1073
                destKey := payReq.Destination.SerializeCompressed()
2✔
1074
                copy(payIntent.Target[:], destKey)
2✔
1075

2✔
1076
                payIntent.FinalCLTVDelta = uint16(payReq.MinFinalCLTVExpiry())
2✔
1077
                payIntent.RouteHints = append(
2✔
1078
                        payIntent.RouteHints, payReq.RouteHints...,
2✔
1079
                )
2✔
1080
                payIntent.DestFeatures = payReq.Features
2✔
1081
                payIntent.PaymentAddr = payAddr
2✔
1082
                payIntent.PaymentRequest = []byte(rpcPayReq.PaymentRequest)
2✔
1083
                payIntent.Metadata = payReq.Metadata
2✔
1084

2✔
1085
                if len(payReq.BlindedPaymentPaths) > 0 {
4✔
1086
                        pathSet, err := BuildBlindedPathSet(
2✔
1087
                                payReq.BlindedPaymentPaths,
2✔
1088
                        )
2✔
1089
                        if err != nil {
2✔
1090
                                return nil, err
×
1091
                        }
×
1092
                        payIntent.BlindedPathSet = pathSet
2✔
1093

2✔
1094
                        // Replace the target node with the target public key
2✔
1095
                        // of the blinded path set.
2✔
1096
                        copy(
2✔
1097
                                payIntent.Target[:],
2✔
1098
                                pathSet.TargetPubKey().SerializeCompressed(),
2✔
1099
                        )
2✔
1100

2✔
1101
                        pathFeatures := pathSet.Features()
2✔
1102
                        if !pathFeatures.IsEmpty() {
2✔
1103
                                payIntent.DestFeatures = pathFeatures.Clone()
×
1104
                        }
×
1105
                }
1106
        } else {
9✔
1107
                // Otherwise, If the payment request field was not specified
9✔
1108
                // (and a custom route wasn't specified), construct the payment
9✔
1109
                // from the other fields.
9✔
1110

9✔
1111
                // Payment destination.
9✔
1112
                target, err := route.NewVertexFromBytes(rpcPayReq.Dest)
9✔
1113
                if err != nil {
10✔
1114
                        return nil, err
1✔
1115
                }
1✔
1116
                payIntent.Target = target
8✔
1117

8✔
1118
                // Final payment CLTV delta.
8✔
1119
                if rpcPayReq.FinalCltvDelta != 0 {
11✔
1120
                        payIntent.FinalCLTVDelta =
3✔
1121
                                uint16(rpcPayReq.FinalCltvDelta)
3✔
1122
                } else {
10✔
1123
                        payIntent.FinalCLTVDelta = r.DefaultFinalCltvDelta
7✔
1124
                }
7✔
1125

1126
                // Amount.
1127
                if reqAmt == 0 {
9✔
1128
                        return nil, errors.New("amount must be specified")
1✔
1129
                }
1✔
1130

1131
                payIntent.Amount = reqAmt
7✔
1132

7✔
1133
                // Parse destination feature bits.
7✔
1134
                features, err := UnmarshalFeatures(rpcPayReq.DestFeatures)
7✔
1135
                if err != nil {
7✔
1136
                        return nil, err
×
1137
                }
×
1138

1139
                // Validate the features if any was specified.
1140
                if features != nil {
10✔
1141
                        err = feature.ValidateDeps(features)
3✔
1142
                        if err != nil {
3✔
1143
                                return nil, err
×
1144
                        }
×
1145
                }
1146

1147
                // If this is an AMP payment, we must generate the initial
1148
                // randomness.
1149
                if rpcPayReq.Amp {
10✔
1150
                        // If no destination features were specified, we set
3✔
1151
                        // those necessary for AMP payments.
3✔
1152
                        if features == nil {
5✔
1153
                                ampFeatures := []lnrpc.FeatureBit{
2✔
1154
                                        lnrpc.FeatureBit_TLV_ONION_OPT,
2✔
1155
                                        lnrpc.FeatureBit_PAYMENT_ADDR_OPT,
2✔
1156
                                        lnrpc.FeatureBit_AMP_OPT,
2✔
1157
                                }
2✔
1158

2✔
1159
                                features, err = UnmarshalFeatures(ampFeatures)
2✔
1160
                                if err != nil {
2✔
1161
                                        return nil, err
×
1162
                                }
×
1163
                        }
1164

1165
                        // First make sure the destination supports AMP.
1166
                        if !features.HasFeature(lnwire.AMPOptional) {
4✔
1167
                                return nil, fmt.Errorf("destination doesn't " +
1✔
1168
                                        "support AMP payments")
1✔
1169
                        }
1✔
1170

1171
                        // If no payment address is set, generate a random one.
1172
                        var payAddr [32]byte
2✔
1173
                        if len(rpcPayReq.PaymentAddr) == 0 {
4✔
1174
                                _, err = rand.Read(payAddr[:])
2✔
1175
                                if err != nil {
2✔
1176
                                        return nil, err
×
1177
                                }
×
1178
                        } else {
×
1179
                                copy(payAddr[:], rpcPayReq.PaymentAddr)
×
1180
                        }
×
1181
                        payIntent.PaymentAddr = fn.Some(payAddr)
2✔
1182

2✔
1183
                        // Generate random SetID and root share.
2✔
1184
                        var setID [32]byte
2✔
1185
                        _, err = rand.Read(setID[:])
2✔
1186
                        if err != nil {
2✔
1187
                                return nil, err
×
1188
                        }
×
1189

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

1209
                        err = payIntent.SetPaymentHash(paymentHash)
5✔
1210
                        if err != nil {
5✔
1211
                                return nil, err
×
1212
                        }
×
1213

1214
                        // If the payment addresses is specified, then we'll
1215
                        // also populate that now as well.
1216
                        if len(rpcPayReq.PaymentAddr) != 0 {
5✔
1217
                                var payAddr [32]byte
×
1218
                                copy(payAddr[:], rpcPayReq.PaymentAddr)
×
1219

×
1220
                                payIntent.PaymentAddr = fn.Some(payAddr)
×
1221
                        }
×
1222
                }
1223

1224
                payIntent.DestFeatures = features
5✔
1225
        }
1226

1227
        // Validate that the MPP parameters are compatible with the
1228
        // payment amount. In other words, the parameters are invalid if
1229
        // they do not permit sending the full payment amount.
1230
        if payIntent.MaxShardAmt != nil {
7✔
1231
                maxPossibleAmount := (*payIntent.MaxShardAmt) *
2✔
1232
                        lnwire.MilliSatoshi(payIntent.MaxParts)
2✔
1233

2✔
1234
                if payIntent.Amount > maxPossibleAmount {
3✔
1235
                        return nil, fmt.Errorf("payment amount %v exceeds "+
1✔
1236
                                "maximum possible amount %v with max_parts=%v "+
1✔
1237
                                "and max_shard_size_msat=%v", payIntent.Amount,
1✔
1238
                                maxPossibleAmount, payIntent.MaxParts,
1✔
1239
                                *payIntent.MaxShardAmt,
1✔
1240
                        )
1✔
1241
                }
1✔
1242
        }
1243

1244
        // Do bounds checking with the block padding so the router isn't
1245
        // left with a zombie payment in case the user messes up.
1246
        err = routing.ValidateCLTVLimit(
4✔
1247
                payIntent.CltvLimit, payIntent.FinalCLTVDelta, true,
4✔
1248
        )
4✔
1249
        if err != nil {
4✔
1250
                return nil, err
×
1251
        }
×
1252

1253
        // Check for disallowed payments to self.
1254
        if !rpcPayReq.AllowSelfPayment && payIntent.Target == r.SelfNode {
5✔
1255
                return nil, errors.New("self-payments not allowed")
1✔
1256
        }
1✔
1257

1258
        return payIntent, nil
3✔
1259
}
1260

1261
// BuildBlindedPathSet marshals a set of zpay32.BlindedPaymentPath and uses
1262
// the result to build a new routing.BlindedPaymentPathSet.
1263
func BuildBlindedPathSet(paths []*zpay32.BlindedPaymentPath) (
1264
        *routing.BlindedPaymentPathSet, error) {
2✔
1265

2✔
1266
        marshalledPaths := make([]*routing.BlindedPayment, len(paths))
2✔
1267
        for i, path := range paths {
4✔
1268
                paymentPath := marshalBlindedPayment(path)
2✔
1269

2✔
1270
                err := paymentPath.Validate()
2✔
1271
                if err != nil {
2✔
1272
                        return nil, err
×
1273
                }
×
1274

1275
                marshalledPaths[i] = paymentPath
2✔
1276
        }
1277

1278
        return routing.NewBlindedPaymentPathSet(marshalledPaths)
2✔
1279
}
1280

1281
// marshalBlindedPayment marshals a zpay32.BLindedPaymentPath into a
1282
// routing.BlindedPayment.
1283
func marshalBlindedPayment(
1284
        path *zpay32.BlindedPaymentPath) *routing.BlindedPayment {
2✔
1285

2✔
1286
        return &routing.BlindedPayment{
2✔
1287
                BlindedPath: &sphinx.BlindedPath{
2✔
1288
                        IntroductionPoint: path.Hops[0].BlindedNodePub,
2✔
1289
                        BlindingPoint:     path.FirstEphemeralBlindingPoint,
2✔
1290
                        BlindedHops:       path.Hops,
2✔
1291
                },
2✔
1292
                BaseFee:             path.FeeBaseMsat,
2✔
1293
                ProportionalFeeRate: path.FeeRate,
2✔
1294
                CltvExpiryDelta:     path.CltvExpiryDelta,
2✔
1295
                HtlcMinimum:         path.HTLCMinMsat,
2✔
1296
                HtlcMaximum:         path.HTLCMaxMsat,
2✔
1297
                Features:            path.Features,
2✔
1298
        }
2✔
1299
}
2✔
1300

1301
// unmarshallRouteHints unmarshalls a list of route hints.
1302
func unmarshallRouteHints(rpcRouteHints []*lnrpc.RouteHint) (
1303
        [][]zpay32.HopHint, error) {
19✔
1304

19✔
1305
        routeHints := make([][]zpay32.HopHint, 0, len(rpcRouteHints))
19✔
1306
        for _, rpcRouteHint := range rpcRouteHints {
25✔
1307
                routeHint := make(
6✔
1308
                        []zpay32.HopHint, 0, len(rpcRouteHint.HopHints),
6✔
1309
                )
6✔
1310
                for _, rpcHint := range rpcRouteHint.HopHints {
12✔
1311
                        hint, err := unmarshallHopHint(rpcHint)
6✔
1312
                        if err != nil {
6✔
1313
                                return nil, err
×
1314
                        }
×
1315

1316
                        routeHint = append(routeHint, hint)
6✔
1317
                }
1318
                routeHints = append(routeHints, routeHint)
6✔
1319
        }
1320

1321
        return routeHints, nil
19✔
1322
}
1323

1324
// unmarshallHopHint unmarshalls a single hop hint.
1325
func unmarshallHopHint(rpcHint *lnrpc.HopHint) (zpay32.HopHint, error) {
6✔
1326
        pubBytes, err := hex.DecodeString(rpcHint.NodeId)
6✔
1327
        if err != nil {
6✔
1328
                return zpay32.HopHint{}, err
×
1329
        }
×
1330

1331
        pubkey, err := btcec.ParsePubKey(pubBytes)
6✔
1332
        if err != nil {
6✔
1333
                return zpay32.HopHint{}, err
×
1334
        }
×
1335

1336
        return zpay32.HopHint{
6✔
1337
                NodeID:                    pubkey,
6✔
1338
                ChannelID:                 rpcHint.ChanId,
6✔
1339
                FeeBaseMSat:               rpcHint.FeeBaseMsat,
6✔
1340
                FeeProportionalMillionths: rpcHint.FeeProportionalMillionths,
6✔
1341
                CLTVExpiryDelta:           uint16(rpcHint.CltvExpiryDelta),
6✔
1342
        }, nil
6✔
1343
}
1344

1345
// MarshalFeatures converts a feature vector into a list of uint32's.
1346
func MarshalFeatures(feats *lnwire.FeatureVector) []lnrpc.FeatureBit {
2✔
1347
        var featureBits []lnrpc.FeatureBit
2✔
1348
        for feature := range feats.Features() {
4✔
1349
                featureBits = append(featureBits, lnrpc.FeatureBit(feature))
2✔
1350
        }
2✔
1351

1352
        return featureBits
2✔
1353
}
1354

1355
// UnmarshalFeatures converts a list of uint32's into a valid feature vector.
1356
// This method checks that feature bit pairs aren't assigned together, and
1357
// validates transitive dependencies.
1358
func UnmarshalFeatures(
1359
        rpcFeatures []lnrpc.FeatureBit) (*lnwire.FeatureVector, error) {
10✔
1360

10✔
1361
        // If no destination features are specified we'll return nil to signal
10✔
1362
        // that the router should try to use the graph as a fallback.
10✔
1363
        if rpcFeatures == nil {
16✔
1364
                return nil, nil
6✔
1365
        }
6✔
1366

1367
        raw := lnwire.NewRawFeatureVector()
6✔
1368
        for _, bit := range rpcFeatures {
11✔
1369
                err := raw.SafeSet(lnwire.FeatureBit(bit))
5✔
1370
                if err != nil {
5✔
1371
                        return nil, err
×
1372
                }
×
1373
        }
1374

1375
        return lnwire.NewFeatureVector(raw, lnwire.Features), nil
6✔
1376
}
1377

1378
// ValidatePayReqExpiry checks if the passed payment request has expired. In
1379
// the case it has expired, an error will be returned.
1380
func ValidatePayReqExpiry(payReq *zpay32.Invoice) error {
3✔
1381
        expiry := payReq.Expiry()
3✔
1382
        validUntil := payReq.Timestamp.Add(expiry)
3✔
1383
        if time.Now().After(validUntil) {
4✔
1384
                return fmt.Errorf("invoice expired. Valid until %v", validUntil)
1✔
1385
        }
1✔
1386

1387
        return nil
2✔
1388
}
1389

1390
// ValidateCLTVLimit returns a valid CLTV limit given a value and a maximum. If
1391
// the value exceeds the maximum, then an error is returned. If the value is 0,
1392
// then the maximum is used.
1393
func ValidateCLTVLimit(val, max uint32) (uint32, error) {
26✔
1394
        switch {
26✔
1395
        case val == 0:
25✔
1396
                return max, nil
25✔
1397
        case val > max:
1✔
1398
                return 0, fmt.Errorf("total time lock of %v exceeds max "+
1✔
1399
                        "allowed %v", val, max)
1✔
1400
        default:
×
1401
                return val, nil
×
1402
        }
1403
}
1404

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

1418
        reqTotal := reqMPP.TotalAmtMsat
7✔
1419
        reqAddr := reqMPP.PaymentAddr
7✔
1420

7✔
1421
        switch {
7✔
1422
        // No MPP fields were provided.
1423
        case reqTotal == 0 && len(reqAddr) == 0:
1✔
1424
                return nil, fmt.Errorf("missing total_msat and payment_addr")
1✔
1425

1426
        // Total is present, but payment address is missing.
1427
        case reqTotal > 0 && len(reqAddr) == 0:
1✔
1428
                return nil, fmt.Errorf("missing payment_addr")
1✔
1429

1430
        // Payment address is present, but total is missing.
1431
        case reqTotal == 0 && len(reqAddr) > 0:
1✔
1432
                return nil, fmt.Errorf("missing total_msat")
1✔
1433
        }
1434

1435
        addr, err := lntypes.MakeHash(reqAddr)
4✔
1436
        if err != nil {
5✔
1437
                return nil, fmt.Errorf("unable to parse "+
1✔
1438
                        "payment_addr: %v", err)
1✔
1439
        }
1✔
1440

1441
        total := lnwire.MilliSatoshi(reqTotal)
3✔
1442

3✔
1443
        return record.NewMPP(total, addr), nil
3✔
1444
}
1445

1446
func UnmarshalAMP(reqAMP *lnrpc.AMPRecord) (*record.AMP, error) {
7✔
1447
        if reqAMP == nil {
10✔
1448
                return nil, nil
3✔
1449
        }
3✔
1450

1451
        reqRootShare := reqAMP.RootShare
6✔
1452
        reqSetID := reqAMP.SetId
6✔
1453

6✔
1454
        switch {
6✔
1455
        case len(reqRootShare) != 32:
2✔
1456
                return nil, errors.New("AMP root_share must be 32 bytes")
2✔
1457

1458
        case len(reqSetID) != 32:
1✔
1459
                return nil, errors.New("AMP set_id must be 32 bytes")
1✔
1460
        }
1461

1462
        var (
3✔
1463
                rootShare [32]byte
3✔
1464
                setID     [32]byte
3✔
1465
        )
3✔
1466
        copy(rootShare[:], reqRootShare)
3✔
1467
        copy(setID[:], reqSetID)
3✔
1468

3✔
1469
        return record.NewAMP(rootShare, setID, reqAMP.ChildIndex), nil
3✔
1470
}
1471

1472
// MarshalHTLCAttempt constructs an RPC HTLCAttempt from the db representation.
1473
func (r *RouterBackend) MarshalHTLCAttempt(
1474
        htlc channeldb.HTLCAttempt) (*lnrpc.HTLCAttempt, error) {
2✔
1475

2✔
1476
        route, err := r.MarshallRoute(&htlc.Route)
2✔
1477
        if err != nil {
2✔
1478
                return nil, err
×
1479
        }
×
1480

1481
        rpcAttempt := &lnrpc.HTLCAttempt{
2✔
1482
                AttemptId:     htlc.AttemptID,
2✔
1483
                AttemptTimeNs: MarshalTimeNano(htlc.AttemptTime),
2✔
1484
                Route:         route,
2✔
1485
        }
2✔
1486

2✔
1487
        switch {
2✔
1488
        case htlc.Settle != nil:
2✔
1489
                rpcAttempt.Status = lnrpc.HTLCAttempt_SUCCEEDED
2✔
1490
                rpcAttempt.ResolveTimeNs = MarshalTimeNano(
2✔
1491
                        htlc.Settle.SettleTime,
2✔
1492
                )
2✔
1493
                rpcAttempt.Preimage = htlc.Settle.Preimage[:]
2✔
1494

1495
        case htlc.Failure != nil:
2✔
1496
                rpcAttempt.Status = lnrpc.HTLCAttempt_FAILED
2✔
1497
                rpcAttempt.ResolveTimeNs = MarshalTimeNano(
2✔
1498
                        htlc.Failure.FailTime,
2✔
1499
                )
2✔
1500

2✔
1501
                var err error
2✔
1502
                rpcAttempt.Failure, err = marshallHtlcFailure(htlc.Failure)
2✔
1503
                if err != nil {
2✔
1504
                        return nil, err
×
1505
                }
×
1506
        default:
2✔
1507
                rpcAttempt.Status = lnrpc.HTLCAttempt_IN_FLIGHT
2✔
1508
        }
1509

1510
        return rpcAttempt, nil
2✔
1511
}
1512

1513
// marshallHtlcFailure marshalls htlc fail info from the database to its rpc
1514
// representation.
1515
func marshallHtlcFailure(failure *channeldb.HTLCFailInfo) (*lnrpc.Failure,
1516
        error) {
2✔
1517

2✔
1518
        rpcFailure := &lnrpc.Failure{
2✔
1519
                FailureSourceIndex: failure.FailureSourceIndex,
2✔
1520
        }
2✔
1521

2✔
1522
        switch failure.Reason {
2✔
1523
        case channeldb.HTLCFailUnknown:
×
1524
                rpcFailure.Code = lnrpc.Failure_UNKNOWN_FAILURE
×
1525

1526
        case channeldb.HTLCFailUnreadable:
×
1527
                rpcFailure.Code = lnrpc.Failure_UNREADABLE_FAILURE
×
1528

1529
        case channeldb.HTLCFailInternal:
×
1530
                rpcFailure.Code = lnrpc.Failure_INTERNAL_FAILURE
×
1531

1532
        case channeldb.HTLCFailMessage:
2✔
1533
                err := marshallWireError(failure.Message, rpcFailure)
2✔
1534
                if err != nil {
2✔
1535
                        return nil, err
×
1536
                }
×
1537

1538
        default:
×
1539
                return nil, errors.New("unknown htlc failure reason")
×
1540
        }
1541

1542
        return rpcFailure, nil
2✔
1543
}
1544

1545
// MarshalTimeNano converts a time.Time into its nanosecond representation. If
1546
// the time is zero, this method simply returns 0, since calling UnixNano() on a
1547
// zero-valued time is undefined.
1548
func MarshalTimeNano(t time.Time) int64 {
5✔
1549
        if t.IsZero() {
8✔
1550
                return 0
3✔
1551
        }
3✔
1552
        return t.UnixNano()
2✔
1553
}
1554

1555
// marshallError marshall an error as received from the switch to rpc structs
1556
// suitable for returning to the caller of an rpc method.
1557
//
1558
// Because of difficulties with using protobuf oneof constructs in some
1559
// languages, the decision was made here to use a single message format for all
1560
// failure messages with some fields left empty depending on the failure type.
1561
func marshallError(sendError error) (*lnrpc.Failure, error) {
2✔
1562
        response := &lnrpc.Failure{}
2✔
1563

2✔
1564
        if sendError == htlcswitch.ErrUnreadableFailureMessage {
2✔
1565
                response.Code = lnrpc.Failure_UNREADABLE_FAILURE
×
1566
                return response, nil
×
1567
        }
×
1568

1569
        rtErr, ok := sendError.(htlcswitch.ClearTextError)
2✔
1570
        if !ok {
2✔
1571
                return nil, sendError
×
1572
        }
×
1573

1574
        err := marshallWireError(rtErr.WireMessage(), response)
2✔
1575
        if err != nil {
2✔
1576
                return nil, err
×
1577
        }
×
1578

1579
        // If the ClearTextError received is a ForwardingError, the error
1580
        // originated from a node along the route, not locally on our outgoing
1581
        // link. We set failureSourceIdx to the index of the node where the
1582
        // failure occurred. If the error is not a ForwardingError, the failure
1583
        // occurred at our node, so we leave the index as 0 to indicate that
1584
        // we failed locally.
1585
        fErr, ok := rtErr.(*htlcswitch.ForwardingError)
2✔
1586
        if ok {
2✔
1587
                response.FailureSourceIndex = uint32(fErr.FailureSourceIdx)
×
1588
        }
×
1589

1590
        return response, nil
2✔
1591
}
1592

1593
// marshallError marshall an error as received from the switch to rpc structs
1594
// suitable for returning to the caller of an rpc method.
1595
//
1596
// Because of difficulties with using protobuf oneof constructs in some
1597
// languages, the decision was made here to use a single message format for all
1598
// failure messages with some fields left empty depending on the failure type.
1599
func marshallWireError(msg lnwire.FailureMessage,
1600
        response *lnrpc.Failure) error {
2✔
1601

2✔
1602
        switch onionErr := msg.(type) {
2✔
1603
        case *lnwire.FailIncorrectDetails:
2✔
1604
                response.Code = lnrpc.Failure_INCORRECT_OR_UNKNOWN_PAYMENT_DETAILS
2✔
1605
                response.Height = onionErr.Height()
2✔
1606

1607
        case *lnwire.FailIncorrectPaymentAmount:
×
1608
                response.Code = lnrpc.Failure_INCORRECT_PAYMENT_AMOUNT
×
1609

1610
        case *lnwire.FailFinalIncorrectCltvExpiry:
×
1611
                response.Code = lnrpc.Failure_FINAL_INCORRECT_CLTV_EXPIRY
×
1612
                response.CltvExpiry = onionErr.CltvExpiry
×
1613

1614
        case *lnwire.FailFinalIncorrectHtlcAmount:
×
1615
                response.Code = lnrpc.Failure_FINAL_INCORRECT_HTLC_AMOUNT
×
1616
                response.HtlcMsat = uint64(onionErr.IncomingHTLCAmount)
×
1617

1618
        case *lnwire.FailFinalExpiryTooSoon:
×
1619
                response.Code = lnrpc.Failure_FINAL_EXPIRY_TOO_SOON
×
1620

1621
        case *lnwire.FailInvalidRealm:
×
1622
                response.Code = lnrpc.Failure_INVALID_REALM
×
1623

1624
        case *lnwire.FailExpiryTooSoon:
×
1625
                response.Code = lnrpc.Failure_EXPIRY_TOO_SOON
×
1626
                response.ChannelUpdate = marshallChannelUpdate(&onionErr.Update)
×
1627

1628
        case *lnwire.FailExpiryTooFar:
×
1629
                response.Code = lnrpc.Failure_EXPIRY_TOO_FAR
×
1630

1631
        case *lnwire.FailInvalidOnionVersion:
2✔
1632
                response.Code = lnrpc.Failure_INVALID_ONION_VERSION
2✔
1633
                response.OnionSha_256 = onionErr.OnionSHA256[:]
2✔
1634

1635
        case *lnwire.FailInvalidOnionHmac:
×
1636
                response.Code = lnrpc.Failure_INVALID_ONION_HMAC
×
1637
                response.OnionSha_256 = onionErr.OnionSHA256[:]
×
1638

1639
        case *lnwire.FailInvalidOnionKey:
×
1640
                response.Code = lnrpc.Failure_INVALID_ONION_KEY
×
1641
                response.OnionSha_256 = onionErr.OnionSHA256[:]
×
1642

1643
        case *lnwire.FailAmountBelowMinimum:
×
1644
                response.Code = lnrpc.Failure_AMOUNT_BELOW_MINIMUM
×
1645
                response.ChannelUpdate = marshallChannelUpdate(&onionErr.Update)
×
1646
                response.HtlcMsat = uint64(onionErr.HtlcMsat)
×
1647

1648
        case *lnwire.FailFeeInsufficient:
2✔
1649
                response.Code = lnrpc.Failure_FEE_INSUFFICIENT
2✔
1650
                response.ChannelUpdate = marshallChannelUpdate(&onionErr.Update)
2✔
1651
                response.HtlcMsat = uint64(onionErr.HtlcMsat)
2✔
1652

1653
        case *lnwire.FailIncorrectCltvExpiry:
×
1654
                response.Code = lnrpc.Failure_INCORRECT_CLTV_EXPIRY
×
1655
                response.ChannelUpdate = marshallChannelUpdate(&onionErr.Update)
×
1656
                response.CltvExpiry = onionErr.CltvExpiry
×
1657

1658
        case *lnwire.FailChannelDisabled:
2✔
1659
                response.Code = lnrpc.Failure_CHANNEL_DISABLED
2✔
1660
                response.ChannelUpdate = marshallChannelUpdate(&onionErr.Update)
2✔
1661
                response.Flags = uint32(onionErr.Flags)
2✔
1662

1663
        case *lnwire.FailTemporaryChannelFailure:
2✔
1664
                response.Code = lnrpc.Failure_TEMPORARY_CHANNEL_FAILURE
2✔
1665
                response.ChannelUpdate = marshallChannelUpdate(onionErr.Update)
2✔
1666

1667
        case *lnwire.FailRequiredNodeFeatureMissing:
×
1668
                response.Code = lnrpc.Failure_REQUIRED_NODE_FEATURE_MISSING
×
1669

1670
        case *lnwire.FailRequiredChannelFeatureMissing:
×
1671
                response.Code = lnrpc.Failure_REQUIRED_CHANNEL_FEATURE_MISSING
×
1672

1673
        case *lnwire.FailUnknownNextPeer:
2✔
1674
                response.Code = lnrpc.Failure_UNKNOWN_NEXT_PEER
2✔
1675

1676
        case *lnwire.FailTemporaryNodeFailure:
×
1677
                response.Code = lnrpc.Failure_TEMPORARY_NODE_FAILURE
×
1678

1679
        case *lnwire.FailPermanentNodeFailure:
×
1680
                response.Code = lnrpc.Failure_PERMANENT_NODE_FAILURE
×
1681

1682
        case *lnwire.FailPermanentChannelFailure:
2✔
1683
                response.Code = lnrpc.Failure_PERMANENT_CHANNEL_FAILURE
2✔
1684

1685
        case *lnwire.FailMPPTimeout:
×
1686
                response.Code = lnrpc.Failure_MPP_TIMEOUT
×
1687

1688
        case *lnwire.InvalidOnionPayload:
2✔
1689
                response.Code = lnrpc.Failure_INVALID_ONION_PAYLOAD
2✔
1690

1691
        case *lnwire.FailInvalidBlinding:
2✔
1692
                response.Code = lnrpc.Failure_INVALID_ONION_BLINDING
2✔
1693
                response.OnionSha_256 = onionErr.OnionSHA256[:]
2✔
1694

1695
        case nil:
×
1696
                response.Code = lnrpc.Failure_UNKNOWN_FAILURE
×
1697

1698
        default:
×
1699
                return fmt.Errorf("cannot marshall failure %T", onionErr)
×
1700
        }
1701

1702
        return nil
2✔
1703
}
1704

1705
// marshallChannelUpdate marshalls a channel update as received over the wire to
1706
// the router rpc format.
1707
func marshallChannelUpdate(update *lnwire.ChannelUpdate1) *lnrpc.ChannelUpdate {
2✔
1708
        if update == nil {
2✔
1709
                return nil
×
1710
        }
×
1711

1712
        return &lnrpc.ChannelUpdate{
2✔
1713
                Signature:       update.Signature.RawBytes(),
2✔
1714
                ChainHash:       update.ChainHash[:],
2✔
1715
                ChanId:          update.ShortChannelID.ToUint64(),
2✔
1716
                Timestamp:       update.Timestamp,
2✔
1717
                MessageFlags:    uint32(update.MessageFlags),
2✔
1718
                ChannelFlags:    uint32(update.ChannelFlags),
2✔
1719
                TimeLockDelta:   uint32(update.TimeLockDelta),
2✔
1720
                HtlcMinimumMsat: uint64(update.HtlcMinimumMsat),
2✔
1721
                BaseFee:         update.BaseFee,
2✔
1722
                FeeRate:         update.FeeRate,
2✔
1723
                HtlcMaximumMsat: uint64(update.HtlcMaximumMsat),
2✔
1724
                ExtraOpaqueData: update.ExtraOpaqueData,
2✔
1725
        }
2✔
1726
}
1727

1728
// MarshallPayment marshall a payment to its rpc representation.
1729
func (r *RouterBackend) MarshallPayment(payment *channeldb.MPPayment) (
1730
        *lnrpc.Payment, error) {
5✔
1731

5✔
1732
        // Fetch the payment's preimage and the total paid in fees.
5✔
1733
        var (
5✔
1734
                fee      lnwire.MilliSatoshi
5✔
1735
                preimage lntypes.Preimage
5✔
1736
        )
5✔
1737
        for _, htlc := range payment.HTLCs {
7✔
1738
                // If any of the htlcs have settled, extract a valid
2✔
1739
                // preimage.
2✔
1740
                if htlc.Settle != nil {
4✔
1741
                        preimage = htlc.Settle.Preimage
2✔
1742
                        fee += htlc.Route.TotalFees()
2✔
1743
                }
2✔
1744
        }
1745

1746
        msatValue := int64(payment.Info.Value)
5✔
1747
        satValue := int64(payment.Info.Value.ToSatoshis())
5✔
1748

5✔
1749
        status, err := convertPaymentStatus(
5✔
1750
                payment.Status, r.UseStatusInitiated,
5✔
1751
        )
5✔
1752
        if err != nil {
5✔
1753
                return nil, err
×
1754
        }
×
1755

1756
        htlcs := make([]*lnrpc.HTLCAttempt, 0, len(payment.HTLCs))
5✔
1757
        for _, dbHTLC := range payment.HTLCs {
7✔
1758
                htlc, err := r.MarshalHTLCAttempt(dbHTLC)
2✔
1759
                if err != nil {
2✔
1760
                        return nil, err
×
1761
                }
×
1762

1763
                htlcs = append(htlcs, htlc)
2✔
1764
        }
1765

1766
        paymentID := payment.Info.PaymentIdentifier
5✔
1767
        creationTimeNS := MarshalTimeNano(payment.Info.CreationTime)
5✔
1768

5✔
1769
        failureReason, err := marshallPaymentFailureReason(
5✔
1770
                payment.FailureReason,
5✔
1771
        )
5✔
1772
        if err != nil {
5✔
1773
                return nil, err
×
1774
        }
×
1775

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

1797
// convertPaymentStatus converts a channeldb.PaymentStatus to the type expected
1798
// by the RPC.
1799
func convertPaymentStatus(dbStatus channeldb.PaymentStatus, useInit bool) (
1800
        lnrpc.Payment_PaymentStatus, error) {
5✔
1801

5✔
1802
        switch dbStatus {
5✔
1803
        case channeldb.StatusInitiated:
2✔
1804
                // If the client understands the new status, return it.
2✔
1805
                if useInit {
4✔
1806
                        return lnrpc.Payment_INITIATED, nil
2✔
1807
                }
2✔
1808

1809
                // Otherwise remain the old behavior.
1810
                return lnrpc.Payment_IN_FLIGHT, nil
2✔
1811

1812
        case channeldb.StatusInFlight:
3✔
1813
                return lnrpc.Payment_IN_FLIGHT, nil
3✔
1814

1815
        case channeldb.StatusSucceeded:
4✔
1816
                return lnrpc.Payment_SUCCEEDED, nil
4✔
1817

1818
        case channeldb.StatusFailed:
2✔
1819
                return lnrpc.Payment_FAILED, nil
2✔
1820

1821
        default:
×
1822
                return 0, fmt.Errorf("unhandled payment status %v", dbStatus)
×
1823
        }
1824
}
1825

1826
// marshallPaymentFailureReason marshalls the failure reason to the corresponding rpc
1827
// type.
1828
func marshallPaymentFailureReason(reason *channeldb.FailureReason) (
1829
        lnrpc.PaymentFailureReason, error) {
5✔
1830

5✔
1831
        if reason == nil {
10✔
1832
                return lnrpc.PaymentFailureReason_FAILURE_REASON_NONE, nil
5✔
1833
        }
5✔
1834

1835
        switch *reason {
2✔
1836
        case channeldb.FailureReasonTimeout:
×
1837
                return lnrpc.PaymentFailureReason_FAILURE_REASON_TIMEOUT, nil
×
1838

1839
        case channeldb.FailureReasonNoRoute:
2✔
1840
                return lnrpc.PaymentFailureReason_FAILURE_REASON_NO_ROUTE, nil
2✔
1841

1842
        case channeldb.FailureReasonError:
2✔
1843
                return lnrpc.PaymentFailureReason_FAILURE_REASON_ERROR, nil
2✔
1844

1845
        case channeldb.FailureReasonPaymentDetails:
2✔
1846
                return lnrpc.PaymentFailureReason_FAILURE_REASON_INCORRECT_PAYMENT_DETAILS, nil
2✔
1847

1848
        case channeldb.FailureReasonInsufficientBalance:
2✔
1849
                return lnrpc.PaymentFailureReason_FAILURE_REASON_INSUFFICIENT_BALANCE, nil
2✔
1850

1851
        case channeldb.FailureReasonCanceled:
2✔
1852
                return lnrpc.PaymentFailureReason_FAILURE_REASON_CANCELED, nil
2✔
1853
        }
1854

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