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

lightningnetwork / lnd / 13963228263

20 Mar 2025 06:23AM UTC coverage: 58.609% (-0.6%) from 59.168%
13963228263

Pull #9603

github

web-flow
Merge ae6dfb46c into ea050d06f
Pull Request #9603: routerrpc+itest: add validation to MPP params

19 of 21 new or added lines in 1 file covered. (90.48%)

998 existing lines in 23 files now uncovered.

95951 of 163714 relevant lines covered (58.61%)

1.23 hits per line

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

69.19
/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 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) {
2✔
167

2✔
168
        routeReq, err := r.parseQueryRoutesRequest(in)
2✔
169
        if err != nil {
2✔
170
                return nil, err
×
171
        }
×
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)
2✔
177
        if err != nil {
2✔
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)
2✔
184
        if err != nil {
2✔
185
                return nil, err
×
186
        }
×
187

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2✔
257
        var sourcePubKey route.Vertex
2✔
258
        if in.SourcePubKey != "" {
2✔
259
                var err error
×
260
                sourcePubKey, err = parsePubKey(in.SourcePubKey)
×
261
                if err != nil {
×
262
                        return nil, err
×
263
                }
×
264
        } else {
2✔
265
                // If no source is specified, use self.
2✔
266
                sourcePubKey = r.SelfNode
2✔
267
        }
2✔
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)
2✔
273
        if err != nil {
2✔
274
                return nil, err
×
275
        }
×
276

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

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

287
        cltvLimit, err := ValidateCLTVLimit(in.CltvLimit, maxTotalTimelock)
2✔
288
        if err != nil {
2✔
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 (
2✔
295
                targetPubKey   *route.Vertex
2✔
296
                routeHintEdges map[route.Vertex][]routing.AdditionalEdge
2✔
297
                blindedPathSet *routing.BlindedPaymentPathSet
2✔
298

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

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

2✔
311
        // Validate that the fields provided in the request are sane depending
2✔
312
        // on whether it is using a blinded path or not.
2✔
313
        if len(in.BlindedPaymentPaths) > 0 {
4✔
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 {
2✔
324
                // If we do not have a blinded path, a target pubkey must be
2✔
325
                // set.
2✔
326
                pk, err := parsePubKey(in.PubKey)
2✔
327
                if err != nil {
2✔
328
                        return nil, err
×
329
                }
×
330
                targetPubKey = &pk
2✔
331

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

338
                routeHintEdges, err = routing.RouteHintsToEdges(
2✔
339
                        routeHints, *targetPubKey,
2✔
340
                )
2✔
341
                if err != nil {
2✔
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
2✔
349
                if in.FinalCltvDelta != 0 {
4✔
350
                        finalCLTVDelta = uint16(in.FinalCltvDelta)
2✔
351
                }
2✔
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(
2✔
356
                        cltvLimit, finalCLTVDelta, false,
2✔
357
                )
2✔
358
                if err != nil {
2✔
359
                        return nil, err
×
360
                }
×
361

362
                // Parse destination feature bits.
363
                destinationFeatures, err = UnmarshalFeatures(in.DestFeatures)
2✔
364
                if err != nil {
2✔
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)
2✔
373

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

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

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

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

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

401
                        return r.MissionControl.GetProbability(
×
402
                                fromNode, toNode, amt, capacity,
×
403
                        )
×
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 {
2✔
413
                restrictions.OutgoingChannelIDs = []uint64{in.OutgoingChanId}
×
414
        }
×
415

416
        // Pass along a last hop restriction if specified.
417
        if len(in.LastHopPubkey) > 0 {
2✔
418
                lastHop, err := route.NewVertexFromBytes(
×
419
                        in.LastHopPubkey,
×
420
                )
×
421
                if err != nil {
×
422
                        return nil, err
×
423
                }
×
424
                restrictions.LastHop = &lastHop
×
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)
2✔
431
        if err := customRecords.Validate(); err != nil {
2✔
432
                return nil, err
×
433
        }
×
434

435
        return routing.NewRouteRequest(
2✔
436
                sourcePubKey, targetPubKey, amt, in.TimePref, restrictions,
2✔
437
                customRecords, routeHintEdges, blindedPathSet,
2✔
438
                finalCLTVDelta,
2✔
439
        )
2✔
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) {
×
576

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

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

589
        return pair, nil
×
590
}
591

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

2✔
604
        // Encode the route's custom channel data (if available).
2✔
605
        if len(route.FirstHopWireCustomRecords) > 0 {
4✔
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
2✔
624
        for i, hop := range route.Hops {
4✔
625
                fee := route.HopFee(i)
2✔
626

2✔
627
                // Channel capacity is not a defining property of a route. For
2✔
628
                // backwards RPC compatibility, we retrieve it here from the
2✔
629
                // graph.
2✔
630
                chanCapacity, err := r.FetchChannelCapacity(hop.ChannelID)
2✔
631
                if err != nil {
4✔
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
2✔
640
                if hop.MPP != nil {
4✔
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
2✔
650
                if hop.AMP != nil {
4✔
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{
2✔
662
                        ChanId:           hop.ChannelID,
2✔
663
                        ChanCapacity:     int64(chanCapacity),
2✔
664
                        AmtToForward:     int64(hop.AmtToForward.ToSatoshis()),
2✔
665
                        AmtToForwardMsat: int64(hop.AmtToForward),
2✔
666
                        Fee:              int64(fee.ToSatoshis()),
2✔
667
                        FeeMsat:          int64(fee),
2✔
668
                        Expiry:           uint32(hop.OutgoingTimeLock),
2✔
669
                        PubKey: hex.EncodeToString(
2✔
670
                                hop.PubKeyBytes[:],
2✔
671
                        ),
2✔
672
                        CustomRecords: hop.CustomRecords,
2✔
673
                        TlvPayload:    !hop.LegacyPayload,
2✔
674
                        MppRecord:     mpp,
2✔
675
                        AmpRecord:     amp,
2✔
676
                        Metadata:      hop.Metadata,
2✔
677
                        EncryptedData: hop.EncryptedData,
2✔
678
                        TotalAmtMsat:  uint64(hop.TotalAmtMsat),
2✔
679
                }
2✔
680

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

688
        return resp, nil
2✔
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) {
2✔
816

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

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

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

2✔
828
        // Add the deprecated single outgoing channel restriction if present.
2✔
829
        if rpcPayReq.OutgoingChanId != 0 {
2✔
830
                if payIntent.OutgoingChannelIDs != nil {
×
831
                        return nil, errors.New("outgoing_chan_id and " +
×
832
                                "outgoing_chan_ids are mutually exclusive")
×
833
                }
×
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 {
2✔
842
                lastHop, err := route.NewVertexFromBytes(
×
843
                        rpcPayReq.LastHopPubkey,
×
844
                )
×
845
                if err != nil {
×
846
                        return nil, err
×
847
                }
×
848
                payIntent.LastHop = &lastHop
×
849
        }
850

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

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

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

877
        // Take fee limit from request.
878
        payIntent.FeeLimit, err = lnrpc.UnmarshallAmt(
2✔
879
                rpcPayReq.FeeLimitSat, rpcPayReq.FeeLimitMsat,
2✔
880
        )
2✔
881
        if err != nil {
2✔
NEW
882
                return nil, err
×
NEW
883
        }
×
884

885
        customRecords := record.CustomSet(rpcPayReq.DestCustomRecords)
2✔
886
        if err := customRecords.Validate(); err != nil {
2✔
887
                return nil, err
×
888
        }
×
889
        payIntent.DestCustomRecords = customRecords
2✔
890

2✔
891
        firstHopRecords := lnwire.CustomRecords(rpcPayReq.FirstHopCustomRecords)
2✔
892
        if err := firstHopRecords.Validate(); err != nil {
2✔
893
                return nil, err
×
894
        }
×
895
        payIntent.FirstHopCustomRecords = firstHopRecords
2✔
896

2✔
897
        // If the experimental endorsement signal is not already set, propagate
2✔
898
        // a zero value field if configured to set this signal.
2✔
899
        if r.ShouldSetExpEndorsement() {
4✔
900
                if payIntent.FirstHopCustomRecords == nil {
4✔
901
                        payIntent.FirstHopCustomRecords = make(
2✔
902
                                map[uint64][]byte,
2✔
903
                        )
2✔
904
                }
2✔
905

906
                t := uint64(lnwire.ExperimentalEndorsementType)
2✔
907
                if _, set := payIntent.FirstHopCustomRecords[t]; !set {
4✔
908
                        payIntent.FirstHopCustomRecords[t] = []byte{
2✔
909
                                lnwire.ExperimentalUnendorsed,
2✔
910
                        }
2✔
911
                }
2✔
912
        }
913

914
        payIntent.PayAttemptTimeout = time.Second *
2✔
915
                time.Duration(rpcPayReq.TimeoutSeconds)
2✔
916

2✔
917
        // Route hints.
2✔
918
        routeHints, err := unmarshallRouteHints(
2✔
919
                rpcPayReq.RouteHints,
2✔
920
        )
2✔
921
        if err != nil {
2✔
922
                return nil, err
×
923
        }
×
924
        payIntent.RouteHints = routeHints
2✔
925

2✔
926
        // Unmarshall either sat or msat amount from request.
2✔
927
        reqAmt, err := lnrpc.UnmarshallAmt(
2✔
928
                rpcPayReq.Amt, rpcPayReq.AmtMsat,
2✔
929
        )
2✔
930
        if err != nil {
2✔
931
                return nil, err
×
932
        }
×
933

934
        // If the payment request field isn't blank, then the details of the
935
        // invoice are encoded entirely within the encoded payReq.  So we'll
936
        // attempt to decode it, populating the payment accordingly.
937
        if rpcPayReq.PaymentRequest != "" {
4✔
938
                switch {
2✔
939

940
                case len(rpcPayReq.Dest) > 0:
×
941
                        return nil, errors.New("dest and payment_request " +
×
942
                                "cannot appear together")
×
943

944
                case len(rpcPayReq.PaymentHash) > 0:
×
945
                        return nil, errors.New("payment_hash and payment_request " +
×
946
                                "cannot appear together")
×
947

948
                case rpcPayReq.FinalCltvDelta != 0:
×
949
                        return nil, errors.New("final_cltv_delta and payment_request " +
×
950
                                "cannot appear together")
×
951
                }
952

953
                payReq, err := zpay32.Decode(
2✔
954
                        rpcPayReq.PaymentRequest, r.ActiveNetParams,
2✔
955
                )
2✔
956
                if err != nil {
2✔
957
                        return nil, err
×
958
                }
×
959

960
                // Next, we'll ensure that this payreq hasn't already expired.
961
                err = ValidatePayReqExpiry(payReq)
2✔
962
                if err != nil {
2✔
963
                        return nil, err
×
964
                }
×
965

966
                // If the amount was not included in the invoice, then we let
967
                // the payer specify the amount of satoshis they wish to send.
968
                // We override the amount to pay with the amount provided from
969
                // the payment request.
970
                if payReq.MilliSat == nil {
2✔
971
                        if reqAmt == 0 {
×
972
                                return nil, errors.New("amount must be " +
×
973
                                        "specified when paying a zero amount " +
×
974
                                        "invoice")
×
975
                        }
×
976

977
                        payIntent.Amount = reqAmt
×
978
                } else {
2✔
979
                        if reqAmt != 0 {
2✔
980
                                return nil, errors.New("amount must not be " +
×
981
                                        "specified when paying a non-zero " +
×
982
                                        " amount invoice")
×
983
                        }
×
984

985
                        payIntent.Amount = *payReq.MilliSat
2✔
986
                }
987

988
                if !payReq.Features.HasFeature(lnwire.MPPOptional) &&
2✔
989
                        !payReq.Features.HasFeature(lnwire.AMPOptional) {
2✔
990

×
991
                        payIntent.MaxParts = 1
×
992
                }
×
993

994
                payAddr := payReq.PaymentAddr
2✔
995
                if payReq.Features.HasFeature(lnwire.AMPOptional) {
4✔
996
                        // The opt-in AMP flag is required to pay an AMP
2✔
997
                        // invoice.
2✔
998
                        if !rpcPayReq.Amp {
2✔
999
                                return nil, fmt.Errorf("the AMP flag (--amp " +
×
1000
                                        "or SendPaymentRequest.Amp) must be " +
×
1001
                                        "set to pay an AMP invoice")
×
1002
                        }
×
1003

1004
                        // Generate random SetID and root share.
1005
                        var setID [32]byte
2✔
1006
                        _, err = rand.Read(setID[:])
2✔
1007
                        if err != nil {
2✔
1008
                                return nil, err
×
1009
                        }
×
1010

1011
                        var rootShare [32]byte
2✔
1012
                        _, err = rand.Read(rootShare[:])
2✔
1013
                        if err != nil {
2✔
1014
                                return nil, err
×
1015
                        }
×
1016
                        err := payIntent.SetAMP(&routing.AMPOptions{
2✔
1017
                                SetID:     setID,
2✔
1018
                                RootShare: rootShare,
2✔
1019
                        })
2✔
1020
                        if err != nil {
2✔
1021
                                return nil, err
×
1022
                        }
×
1023

1024
                        // For AMP invoices, we'll allow users to override the
1025
                        // included payment addr to allow the invoice to be
1026
                        // pseudo-reusable, e.g. the invoice parameters are
1027
                        // reused (amt, cltv, hop hints, etc) even though the
1028
                        // payments will share different payment hashes.
1029
                        //
1030
                        // NOTE: This will only work when the peer has
1031
                        // spontaneous AMP payments enabled.
1032
                        if len(rpcPayReq.PaymentAddr) > 0 {
4✔
1033
                                var addr [32]byte
2✔
1034
                                copy(addr[:], rpcPayReq.PaymentAddr)
2✔
1035
                                payAddr = fn.Some(addr)
2✔
1036
                        }
2✔
1037
                } else {
2✔
1038
                        err = payIntent.SetPaymentHash(*payReq.PaymentHash)
2✔
1039
                        if err != nil {
2✔
1040
                                return nil, err
×
1041
                        }
×
1042
                }
1043

1044
                destKey := payReq.Destination.SerializeCompressed()
2✔
1045
                copy(payIntent.Target[:], destKey)
2✔
1046

2✔
1047
                payIntent.FinalCLTVDelta = uint16(payReq.MinFinalCLTVExpiry())
2✔
1048
                payIntent.RouteHints = append(
2✔
1049
                        payIntent.RouteHints, payReq.RouteHints...,
2✔
1050
                )
2✔
1051
                payIntent.DestFeatures = payReq.Features
2✔
1052
                payIntent.PaymentAddr = payAddr
2✔
1053
                payIntent.PaymentRequest = []byte(rpcPayReq.PaymentRequest)
2✔
1054
                payIntent.Metadata = payReq.Metadata
2✔
1055

2✔
1056
                if len(payReq.BlindedPaymentPaths) > 0 {
4✔
1057
                        pathSet, err := BuildBlindedPathSet(
2✔
1058
                                payReq.BlindedPaymentPaths,
2✔
1059
                        )
2✔
1060
                        if err != nil {
2✔
1061
                                return nil, err
×
1062
                        }
×
1063
                        payIntent.BlindedPathSet = pathSet
2✔
1064

2✔
1065
                        // Replace the target node with the target public key
2✔
1066
                        // of the blinded path set.
2✔
1067
                        copy(
2✔
1068
                                payIntent.Target[:],
2✔
1069
                                pathSet.TargetPubKey().SerializeCompressed(),
2✔
1070
                        )
2✔
1071

2✔
1072
                        pathFeatures := pathSet.Features()
2✔
1073
                        if !pathFeatures.IsEmpty() {
2✔
1074
                                payIntent.DestFeatures = pathFeatures.Clone()
×
1075
                        }
×
1076
                }
1077
        } else {
2✔
1078
                // Otherwise, If the payment request field was not specified
2✔
1079
                // (and a custom route wasn't specified), construct the payment
2✔
1080
                // from the other fields.
2✔
1081

2✔
1082
                // Payment destination.
2✔
1083
                target, err := route.NewVertexFromBytes(rpcPayReq.Dest)
2✔
1084
                if err != nil {
2✔
1085
                        return nil, err
×
1086
                }
×
1087
                payIntent.Target = target
2✔
1088

2✔
1089
                // Final payment CLTV delta.
2✔
1090
                if rpcPayReq.FinalCltvDelta != 0 {
4✔
1091
                        payIntent.FinalCLTVDelta =
2✔
1092
                                uint16(rpcPayReq.FinalCltvDelta)
2✔
1093
                } else {
4✔
1094
                        payIntent.FinalCLTVDelta = r.DefaultFinalCltvDelta
2✔
1095
                }
2✔
1096

1097
                // Amount.
1098
                if reqAmt == 0 {
2✔
1099
                        return nil, errors.New("amount must be specified")
×
1100
                }
×
1101

1102
                payIntent.Amount = reqAmt
2✔
1103

2✔
1104
                // Parse destination feature bits.
2✔
1105
                features, err := UnmarshalFeatures(rpcPayReq.DestFeatures)
2✔
1106
                if err != nil {
2✔
1107
                        return nil, err
×
1108
                }
×
1109

1110
                // Validate the features if any was specified.
1111
                if features != nil {
4✔
1112
                        err = feature.ValidateDeps(features)
2✔
1113
                        if err != nil {
2✔
1114
                                return nil, err
×
1115
                        }
×
1116
                }
1117

1118
                // If this is an AMP payment, we must generate the initial
1119
                // randomness.
1120
                if rpcPayReq.Amp {
4✔
1121
                        // If no destination features were specified, we set
2✔
1122
                        // those necessary for AMP payments.
2✔
1123
                        if features == nil {
4✔
1124
                                ampFeatures := []lnrpc.FeatureBit{
2✔
1125
                                        lnrpc.FeatureBit_TLV_ONION_OPT,
2✔
1126
                                        lnrpc.FeatureBit_PAYMENT_ADDR_OPT,
2✔
1127
                                        lnrpc.FeatureBit_AMP_OPT,
2✔
1128
                                }
2✔
1129

2✔
1130
                                features, err = UnmarshalFeatures(ampFeatures)
2✔
1131
                                if err != nil {
2✔
1132
                                        return nil, err
×
1133
                                }
×
1134
                        }
1135

1136
                        // First make sure the destination supports AMP.
1137
                        if !features.HasFeature(lnwire.AMPOptional) {
2✔
1138
                                return nil, fmt.Errorf("destination doesn't " +
×
1139
                                        "support AMP payments")
×
1140
                        }
×
1141

1142
                        // If no payment address is set, generate a random one.
1143
                        var payAddr [32]byte
2✔
1144
                        if len(rpcPayReq.PaymentAddr) == 0 {
4✔
1145
                                _, err = rand.Read(payAddr[:])
2✔
1146
                                if err != nil {
2✔
1147
                                        return nil, err
×
1148
                                }
×
1149
                        } else {
×
1150
                                copy(payAddr[:], rpcPayReq.PaymentAddr)
×
1151
                        }
×
1152
                        payIntent.PaymentAddr = fn.Some(payAddr)
2✔
1153

2✔
1154
                        // Generate random SetID and root share.
2✔
1155
                        var setID [32]byte
2✔
1156
                        _, err = rand.Read(setID[:])
2✔
1157
                        if err != nil {
2✔
1158
                                return nil, err
×
1159
                        }
×
1160

1161
                        var rootShare [32]byte
2✔
1162
                        _, err = rand.Read(rootShare[:])
2✔
1163
                        if err != nil {
2✔
1164
                                return nil, err
×
1165
                        }
×
1166
                        err := payIntent.SetAMP(&routing.AMPOptions{
2✔
1167
                                SetID:     setID,
2✔
1168
                                RootShare: rootShare,
2✔
1169
                        })
2✔
1170
                        if err != nil {
2✔
1171
                                return nil, err
×
1172
                        }
×
1173
                } else {
2✔
1174
                        // Payment hash.
2✔
1175
                        paymentHash, err := lntypes.MakeHash(rpcPayReq.PaymentHash)
2✔
1176
                        if err != nil {
2✔
1177
                                return nil, err
×
1178
                        }
×
1179

1180
                        err = payIntent.SetPaymentHash(paymentHash)
2✔
1181
                        if err != nil {
2✔
1182
                                return nil, err
×
1183
                        }
×
1184

1185
                        // If the payment addresses is specified, then we'll
1186
                        // also populate that now as well.
1187
                        if len(rpcPayReq.PaymentAddr) != 0 {
2✔
1188
                                var payAddr [32]byte
×
1189
                                copy(payAddr[:], rpcPayReq.PaymentAddr)
×
1190

×
1191
                                payIntent.PaymentAddr = fn.Some(payAddr)
×
1192
                        }
×
1193
                }
1194

1195
                payIntent.DestFeatures = features
2✔
1196
        }
1197

1198
        // Validate that the MPP parameters are compatible with the
1199
        // payment amount. In other words, the parameters are invalid if
1200
        // they do not permit sending the full payment amount.
1201
        if rpcPayReq.MaxShardSizeMsat > 0 {
4✔
1202
                if payIntent.MaxParts > MaxPartsUpperLimit {
4✔
1203
                        return nil, fmt.Errorf("requested max_parts (%v) "+
2✔
1204
                                "exceeds the allowed upper limit of %v; cannot"+
2✔
1205
                                " send payment amount %v with "+
2✔
1206
                                "max_shard_size_msat=%v.", payIntent.MaxParts,
2✔
1207
                                MaxPartsUpperLimit, payIntent.Amount,
2✔
1208
                                *payIntent.MaxShardAmt)
2✔
1209
                }
2✔
1210

1211
                maxPossibleAmount := (*payIntent.MaxShardAmt) *
2✔
1212
                        lnwire.MilliSatoshi(payIntent.MaxParts)
2✔
1213
                if payIntent.Amount > maxPossibleAmount {
4✔
1214
                        minRequiredParts := uint32((payIntent.Amount +
2✔
1215
                                *payIntent.MaxShardAmt - 1) /
2✔
1216
                                *payIntent.MaxShardAmt)
2✔
1217

2✔
1218
                        if minRequiredParts > MaxPartsUpperLimit {
4✔
1219
                                return nil, fmt.Errorf("required minimum "+
2✔
1220
                                        "max_parts exceeds allowed limit (%v);"+
2✔
1221
                                        " cannot send payment of %v with "+
2✔
1222
                                        "max_parts=%v and max_shard_size_msat="+
2✔
1223
                                        "%v", MaxPartsUpperLimit,
2✔
1224
                                        payIntent.Amount, payIntent.MaxParts,
2✔
1225
                                        *payIntent.MaxShardAmt)
2✔
1226
                        }
2✔
1227

1228
                        return nil, fmt.Errorf("payment amount %v exceeds "+
2✔
1229
                                "maximum allowed amount %v with max_parts=%v "+
2✔
1230
                                "and max_shard_size_msat=%v; consider setting "+
2✔
1231
                                "max_parts to at least %v", payIntent.Amount,
2✔
1232
                                maxPossibleAmount, payIntent.MaxParts,
2✔
1233
                                *payIntent.MaxShardAmt, minRequiredParts,
2✔
1234
                        )
2✔
1235
                }
1236
        }
1237

1238
        // Do bounds checking with the block padding so the router isn't
1239
        // left with a zombie payment in case the user messes up.
1240
        err = routing.ValidateCLTVLimit(
2✔
1241
                payIntent.CltvLimit, payIntent.FinalCLTVDelta, true,
2✔
1242
        )
2✔
1243
        if err != nil {
2✔
1244
                return nil, err
×
1245
        }
×
1246

1247
        // Check for disallowed payments to self.
1248
        if !rpcPayReq.AllowSelfPayment && payIntent.Target == r.SelfNode {
2✔
1249
                return nil, errors.New("self-payments not allowed")
×
1250
        }
×
1251

1252
        return payIntent, nil
2✔
1253
}
1254

1255
// BuildBlindedPathSet marshals a set of zpay32.BlindedPaymentPath and uses
1256
// the result to build a new routing.BlindedPaymentPathSet.
1257
func BuildBlindedPathSet(paths []*zpay32.BlindedPaymentPath) (
1258
        *routing.BlindedPaymentPathSet, error) {
2✔
1259

2✔
1260
        marshalledPaths := make([]*routing.BlindedPayment, len(paths))
2✔
1261
        for i, path := range paths {
4✔
1262
                paymentPath := marshalBlindedPayment(path)
2✔
1263

2✔
1264
                err := paymentPath.Validate()
2✔
1265
                if err != nil {
2✔
1266
                        return nil, err
×
1267
                }
×
1268

1269
                marshalledPaths[i] = paymentPath
2✔
1270
        }
1271

1272
        return routing.NewBlindedPaymentPathSet(marshalledPaths)
2✔
1273
}
1274

1275
// marshalBlindedPayment marshals a zpay32.BLindedPaymentPath into a
1276
// routing.BlindedPayment.
1277
func marshalBlindedPayment(
1278
        path *zpay32.BlindedPaymentPath) *routing.BlindedPayment {
2✔
1279

2✔
1280
        return &routing.BlindedPayment{
2✔
1281
                BlindedPath: &sphinx.BlindedPath{
2✔
1282
                        IntroductionPoint: path.Hops[0].BlindedNodePub,
2✔
1283
                        BlindingPoint:     path.FirstEphemeralBlindingPoint,
2✔
1284
                        BlindedHops:       path.Hops,
2✔
1285
                },
2✔
1286
                BaseFee:             path.FeeBaseMsat,
2✔
1287
                ProportionalFeeRate: path.FeeRate,
2✔
1288
                CltvExpiryDelta:     path.CltvExpiryDelta,
2✔
1289
                HtlcMinimum:         path.HTLCMinMsat,
2✔
1290
                HtlcMaximum:         path.HTLCMaxMsat,
2✔
1291
                Features:            path.Features,
2✔
1292
        }
2✔
1293
}
2✔
1294

1295
// unmarshallRouteHints unmarshalls a list of route hints.
1296
func unmarshallRouteHints(rpcRouteHints []*lnrpc.RouteHint) (
1297
        [][]zpay32.HopHint, error) {
2✔
1298

2✔
1299
        routeHints := make([][]zpay32.HopHint, 0, len(rpcRouteHints))
2✔
1300
        for _, rpcRouteHint := range rpcRouteHints {
4✔
1301
                routeHint := make(
2✔
1302
                        []zpay32.HopHint, 0, len(rpcRouteHint.HopHints),
2✔
1303
                )
2✔
1304
                for _, rpcHint := range rpcRouteHint.HopHints {
4✔
1305
                        hint, err := unmarshallHopHint(rpcHint)
2✔
1306
                        if err != nil {
2✔
1307
                                return nil, err
×
1308
                        }
×
1309

1310
                        routeHint = append(routeHint, hint)
2✔
1311
                }
1312
                routeHints = append(routeHints, routeHint)
2✔
1313
        }
1314

1315
        return routeHints, nil
2✔
1316
}
1317

1318
// unmarshallHopHint unmarshalls a single hop hint.
1319
func unmarshallHopHint(rpcHint *lnrpc.HopHint) (zpay32.HopHint, error) {
2✔
1320
        pubBytes, err := hex.DecodeString(rpcHint.NodeId)
2✔
1321
        if err != nil {
2✔
1322
                return zpay32.HopHint{}, err
×
1323
        }
×
1324

1325
        pubkey, err := btcec.ParsePubKey(pubBytes)
2✔
1326
        if err != nil {
2✔
1327
                return zpay32.HopHint{}, err
×
1328
        }
×
1329

1330
        return zpay32.HopHint{
2✔
1331
                NodeID:                    pubkey,
2✔
1332
                ChannelID:                 rpcHint.ChanId,
2✔
1333
                FeeBaseMSat:               rpcHint.FeeBaseMsat,
2✔
1334
                FeeProportionalMillionths: rpcHint.FeeProportionalMillionths,
2✔
1335
                CLTVExpiryDelta:           uint16(rpcHint.CltvExpiryDelta),
2✔
1336
        }, nil
2✔
1337
}
1338

1339
// MarshalFeatures converts a feature vector into a list of uint32's.
1340
func MarshalFeatures(feats *lnwire.FeatureVector) []lnrpc.FeatureBit {
2✔
1341
        var featureBits []lnrpc.FeatureBit
2✔
1342
        for feature := range feats.Features() {
4✔
1343
                featureBits = append(featureBits, lnrpc.FeatureBit(feature))
2✔
1344
        }
2✔
1345

1346
        return featureBits
2✔
1347
}
1348

1349
// UnmarshalFeatures converts a list of uint32's into a valid feature vector.
1350
// This method checks that feature bit pairs aren't assigned together, and
1351
// validates transitive dependencies.
1352
func UnmarshalFeatures(
1353
        rpcFeatures []lnrpc.FeatureBit) (*lnwire.FeatureVector, error) {
2✔
1354

2✔
1355
        // If no destination features are specified we'll return nil to signal
2✔
1356
        // that the router should try to use the graph as a fallback.
2✔
1357
        if rpcFeatures == nil {
4✔
1358
                return nil, nil
2✔
1359
        }
2✔
1360

1361
        raw := lnwire.NewRawFeatureVector()
2✔
1362
        for _, bit := range rpcFeatures {
4✔
1363
                err := raw.SafeSet(lnwire.FeatureBit(bit))
2✔
1364
                if err != nil {
2✔
1365
                        return nil, err
×
1366
                }
×
1367
        }
1368

1369
        return lnwire.NewFeatureVector(raw, lnwire.Features), nil
2✔
1370
}
1371

1372
// ValidatePayReqExpiry checks if the passed payment request has expired. In
1373
// the case it has expired, an error will be returned.
1374
func ValidatePayReqExpiry(payReq *zpay32.Invoice) error {
2✔
1375
        expiry := payReq.Expiry()
2✔
1376
        validUntil := payReq.Timestamp.Add(expiry)
2✔
1377
        if time.Now().After(validUntil) {
2✔
1378
                return fmt.Errorf("invoice expired. Valid until %v", validUntil)
×
1379
        }
×
1380

1381
        return nil
2✔
1382
}
1383

1384
// ValidateCLTVLimit returns a valid CLTV limit given a value and a maximum. If
1385
// the value exceeds the maximum, then an error is returned. If the value is 0,
1386
// then the maximum is used.
1387
func ValidateCLTVLimit(val, max uint32) (uint32, error) {
2✔
1388
        switch {
2✔
1389
        case val == 0:
2✔
1390
                return max, nil
2✔
1391
        case val > max:
×
1392
                return 0, fmt.Errorf("total time lock of %v exceeds max "+
×
1393
                        "allowed %v", val, max)
×
1394
        default:
×
1395
                return val, nil
×
1396
        }
1397
}
1398

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

1412
        reqTotal := reqMPP.TotalAmtMsat
2✔
1413
        reqAddr := reqMPP.PaymentAddr
2✔
1414

2✔
1415
        switch {
2✔
1416
        // No MPP fields were provided.
1417
        case reqTotal == 0 && len(reqAddr) == 0:
×
1418
                return nil, fmt.Errorf("missing total_msat and payment_addr")
×
1419

1420
        // Total is present, but payment address is missing.
1421
        case reqTotal > 0 && len(reqAddr) == 0:
×
1422
                return nil, fmt.Errorf("missing payment_addr")
×
1423

1424
        // Payment address is present, but total is missing.
1425
        case reqTotal == 0 && len(reqAddr) > 0:
×
1426
                return nil, fmt.Errorf("missing total_msat")
×
1427
        }
1428

1429
        addr, err := lntypes.MakeHash(reqAddr)
2✔
1430
        if err != nil {
2✔
1431
                return nil, fmt.Errorf("unable to parse "+
×
1432
                        "payment_addr: %v", err)
×
1433
        }
×
1434

1435
        total := lnwire.MilliSatoshi(reqTotal)
2✔
1436

2✔
1437
        return record.NewMPP(total, addr), nil
2✔
1438
}
1439

1440
func UnmarshalAMP(reqAMP *lnrpc.AMPRecord) (*record.AMP, error) {
2✔
1441
        if reqAMP == nil {
4✔
1442
                return nil, nil
2✔
1443
        }
2✔
1444

1445
        reqRootShare := reqAMP.RootShare
2✔
1446
        reqSetID := reqAMP.SetId
2✔
1447

2✔
1448
        switch {
2✔
1449
        case len(reqRootShare) != 32:
×
1450
                return nil, errors.New("AMP root_share must be 32 bytes")
×
1451

1452
        case len(reqSetID) != 32:
×
1453
                return nil, errors.New("AMP set_id must be 32 bytes")
×
1454
        }
1455

1456
        var (
2✔
1457
                rootShare [32]byte
2✔
1458
                setID     [32]byte
2✔
1459
        )
2✔
1460
        copy(rootShare[:], reqRootShare)
2✔
1461
        copy(setID[:], reqSetID)
2✔
1462

2✔
1463
        return record.NewAMP(rootShare, setID, reqAMP.ChildIndex), nil
2✔
1464
}
1465

1466
// MarshalHTLCAttempt constructs an RPC HTLCAttempt from the db representation.
1467
func (r *RouterBackend) MarshalHTLCAttempt(
1468
        htlc channeldb.HTLCAttempt) (*lnrpc.HTLCAttempt, error) {
2✔
1469

2✔
1470
        route, err := r.MarshallRoute(&htlc.Route)
2✔
1471
        if err != nil {
2✔
1472
                return nil, err
×
1473
        }
×
1474

1475
        rpcAttempt := &lnrpc.HTLCAttempt{
2✔
1476
                AttemptId:     htlc.AttemptID,
2✔
1477
                AttemptTimeNs: MarshalTimeNano(htlc.AttemptTime),
2✔
1478
                Route:         route,
2✔
1479
        }
2✔
1480

2✔
1481
        switch {
2✔
1482
        case htlc.Settle != nil:
2✔
1483
                rpcAttempt.Status = lnrpc.HTLCAttempt_SUCCEEDED
2✔
1484
                rpcAttempt.ResolveTimeNs = MarshalTimeNano(
2✔
1485
                        htlc.Settle.SettleTime,
2✔
1486
                )
2✔
1487
                rpcAttempt.Preimage = htlc.Settle.Preimage[:]
2✔
1488

1489
        case htlc.Failure != nil:
2✔
1490
                rpcAttempt.Status = lnrpc.HTLCAttempt_FAILED
2✔
1491
                rpcAttempt.ResolveTimeNs = MarshalTimeNano(
2✔
1492
                        htlc.Failure.FailTime,
2✔
1493
                )
2✔
1494

2✔
1495
                var err error
2✔
1496
                rpcAttempt.Failure, err = marshallHtlcFailure(htlc.Failure)
2✔
1497
                if err != nil {
2✔
1498
                        return nil, err
×
1499
                }
×
1500
        default:
2✔
1501
                rpcAttempt.Status = lnrpc.HTLCAttempt_IN_FLIGHT
2✔
1502
        }
1503

1504
        return rpcAttempt, nil
2✔
1505
}
1506

1507
// marshallHtlcFailure marshalls htlc fail info from the database to its rpc
1508
// representation.
1509
func marshallHtlcFailure(failure *channeldb.HTLCFailInfo) (*lnrpc.Failure,
1510
        error) {
2✔
1511

2✔
1512
        rpcFailure := &lnrpc.Failure{
2✔
1513
                FailureSourceIndex: failure.FailureSourceIndex,
2✔
1514
        }
2✔
1515

2✔
1516
        switch failure.Reason {
2✔
1517
        case channeldb.HTLCFailUnknown:
×
1518
                rpcFailure.Code = lnrpc.Failure_UNKNOWN_FAILURE
×
1519

1520
        case channeldb.HTLCFailUnreadable:
×
1521
                rpcFailure.Code = lnrpc.Failure_UNREADABLE_FAILURE
×
1522

1523
        case channeldb.HTLCFailInternal:
×
1524
                rpcFailure.Code = lnrpc.Failure_INTERNAL_FAILURE
×
1525

1526
        case channeldb.HTLCFailMessage:
2✔
1527
                err := marshallWireError(failure.Message, rpcFailure)
2✔
1528
                if err != nil {
2✔
1529
                        return nil, err
×
1530
                }
×
1531

1532
        default:
×
1533
                return nil, errors.New("unknown htlc failure reason")
×
1534
        }
1535

1536
        return rpcFailure, nil
2✔
1537
}
1538

1539
// MarshalTimeNano converts a time.Time into its nanosecond representation. If
1540
// the time is zero, this method simply returns 0, since calling UnixNano() on a
1541
// zero-valued time is undefined.
1542
func MarshalTimeNano(t time.Time) int64 {
2✔
1543
        if t.IsZero() {
2✔
1544
                return 0
×
1545
        }
×
1546
        return t.UnixNano()
2✔
1547
}
1548

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

2✔
1558
        if sendError == htlcswitch.ErrUnreadableFailureMessage {
2✔
1559
                response.Code = lnrpc.Failure_UNREADABLE_FAILURE
×
1560
                return response, nil
×
1561
        }
×
1562

1563
        rtErr, ok := sendError.(htlcswitch.ClearTextError)
2✔
1564
        if !ok {
2✔
1565
                return nil, sendError
×
1566
        }
×
1567

1568
        err := marshallWireError(rtErr.WireMessage(), response)
2✔
1569
        if err != nil {
2✔
1570
                return nil, err
×
1571
        }
×
1572

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

1584
        return response, nil
2✔
1585
}
1586

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

2✔
1596
        switch onionErr := msg.(type) {
2✔
1597
        case *lnwire.FailIncorrectDetails:
2✔
1598
                response.Code = lnrpc.Failure_INCORRECT_OR_UNKNOWN_PAYMENT_DETAILS
2✔
1599
                response.Height = onionErr.Height()
2✔
1600

1601
        case *lnwire.FailIncorrectPaymentAmount:
×
1602
                response.Code = lnrpc.Failure_INCORRECT_PAYMENT_AMOUNT
×
1603

1604
        case *lnwire.FailFinalIncorrectCltvExpiry:
×
1605
                response.Code = lnrpc.Failure_FINAL_INCORRECT_CLTV_EXPIRY
×
1606
                response.CltvExpiry = onionErr.CltvExpiry
×
1607

1608
        case *lnwire.FailFinalIncorrectHtlcAmount:
×
1609
                response.Code = lnrpc.Failure_FINAL_INCORRECT_HTLC_AMOUNT
×
1610
                response.HtlcMsat = uint64(onionErr.IncomingHTLCAmount)
×
1611

1612
        case *lnwire.FailFinalExpiryTooSoon:
×
1613
                response.Code = lnrpc.Failure_FINAL_EXPIRY_TOO_SOON
×
1614

1615
        case *lnwire.FailInvalidRealm:
×
1616
                response.Code = lnrpc.Failure_INVALID_REALM
×
1617

1618
        case *lnwire.FailExpiryTooSoon:
×
1619
                response.Code = lnrpc.Failure_EXPIRY_TOO_SOON
×
1620
                response.ChannelUpdate = marshallChannelUpdate(&onionErr.Update)
×
1621

1622
        case *lnwire.FailExpiryTooFar:
×
1623
                response.Code = lnrpc.Failure_EXPIRY_TOO_FAR
×
1624

1625
        case *lnwire.FailInvalidOnionVersion:
2✔
1626
                response.Code = lnrpc.Failure_INVALID_ONION_VERSION
2✔
1627
                response.OnionSha_256 = onionErr.OnionSHA256[:]
2✔
1628

1629
        case *lnwire.FailInvalidOnionHmac:
×
1630
                response.Code = lnrpc.Failure_INVALID_ONION_HMAC
×
1631
                response.OnionSha_256 = onionErr.OnionSHA256[:]
×
1632

1633
        case *lnwire.FailInvalidOnionKey:
×
1634
                response.Code = lnrpc.Failure_INVALID_ONION_KEY
×
1635
                response.OnionSha_256 = onionErr.OnionSHA256[:]
×
1636

1637
        case *lnwire.FailAmountBelowMinimum:
×
1638
                response.Code = lnrpc.Failure_AMOUNT_BELOW_MINIMUM
×
1639
                response.ChannelUpdate = marshallChannelUpdate(&onionErr.Update)
×
1640
                response.HtlcMsat = uint64(onionErr.HtlcMsat)
×
1641

1642
        case *lnwire.FailFeeInsufficient:
2✔
1643
                response.Code = lnrpc.Failure_FEE_INSUFFICIENT
2✔
1644
                response.ChannelUpdate = marshallChannelUpdate(&onionErr.Update)
2✔
1645
                response.HtlcMsat = uint64(onionErr.HtlcMsat)
2✔
1646

1647
        case *lnwire.FailIncorrectCltvExpiry:
×
1648
                response.Code = lnrpc.Failure_INCORRECT_CLTV_EXPIRY
×
1649
                response.ChannelUpdate = marshallChannelUpdate(&onionErr.Update)
×
1650
                response.CltvExpiry = onionErr.CltvExpiry
×
1651

1652
        case *lnwire.FailChannelDisabled:
2✔
1653
                response.Code = lnrpc.Failure_CHANNEL_DISABLED
2✔
1654
                response.ChannelUpdate = marshallChannelUpdate(&onionErr.Update)
2✔
1655
                response.Flags = uint32(onionErr.Flags)
2✔
1656

1657
        case *lnwire.FailTemporaryChannelFailure:
2✔
1658
                response.Code = lnrpc.Failure_TEMPORARY_CHANNEL_FAILURE
2✔
1659
                response.ChannelUpdate = marshallChannelUpdate(onionErr.Update)
2✔
1660

1661
        case *lnwire.FailRequiredNodeFeatureMissing:
×
1662
                response.Code = lnrpc.Failure_REQUIRED_NODE_FEATURE_MISSING
×
1663

1664
        case *lnwire.FailRequiredChannelFeatureMissing:
×
1665
                response.Code = lnrpc.Failure_REQUIRED_CHANNEL_FEATURE_MISSING
×
1666

1667
        case *lnwire.FailUnknownNextPeer:
2✔
1668
                response.Code = lnrpc.Failure_UNKNOWN_NEXT_PEER
2✔
1669

1670
        case *lnwire.FailTemporaryNodeFailure:
×
1671
                response.Code = lnrpc.Failure_TEMPORARY_NODE_FAILURE
×
1672

1673
        case *lnwire.FailPermanentNodeFailure:
×
1674
                response.Code = lnrpc.Failure_PERMANENT_NODE_FAILURE
×
1675

1676
        case *lnwire.FailPermanentChannelFailure:
2✔
1677
                response.Code = lnrpc.Failure_PERMANENT_CHANNEL_FAILURE
2✔
1678

1679
        case *lnwire.FailMPPTimeout:
×
1680
                response.Code = lnrpc.Failure_MPP_TIMEOUT
×
1681

1682
        case *lnwire.InvalidOnionPayload:
2✔
1683
                response.Code = lnrpc.Failure_INVALID_ONION_PAYLOAD
2✔
1684

1685
        case *lnwire.FailInvalidBlinding:
2✔
1686
                response.Code = lnrpc.Failure_INVALID_ONION_BLINDING
2✔
1687
                response.OnionSha_256 = onionErr.OnionSHA256[:]
2✔
1688

1689
        case nil:
×
1690
                response.Code = lnrpc.Failure_UNKNOWN_FAILURE
×
1691

1692
        default:
×
1693
                return fmt.Errorf("cannot marshall failure %T", onionErr)
×
1694
        }
1695

1696
        return nil
2✔
1697
}
1698

1699
// marshallChannelUpdate marshalls a channel update as received over the wire to
1700
// the router rpc format.
1701
func marshallChannelUpdate(update *lnwire.ChannelUpdate1) *lnrpc.ChannelUpdate {
2✔
1702
        if update == nil {
2✔
1703
                return nil
×
1704
        }
×
1705

1706
        return &lnrpc.ChannelUpdate{
2✔
1707
                Signature:       update.Signature.RawBytes(),
2✔
1708
                ChainHash:       update.ChainHash[:],
2✔
1709
                ChanId:          update.ShortChannelID.ToUint64(),
2✔
1710
                Timestamp:       update.Timestamp,
2✔
1711
                MessageFlags:    uint32(update.MessageFlags),
2✔
1712
                ChannelFlags:    uint32(update.ChannelFlags),
2✔
1713
                TimeLockDelta:   uint32(update.TimeLockDelta),
2✔
1714
                HtlcMinimumMsat: uint64(update.HtlcMinimumMsat),
2✔
1715
                BaseFee:         update.BaseFee,
2✔
1716
                FeeRate:         update.FeeRate,
2✔
1717
                HtlcMaximumMsat: uint64(update.HtlcMaximumMsat),
2✔
1718
                ExtraOpaqueData: update.ExtraOpaqueData,
2✔
1719
        }
2✔
1720
}
1721

1722
// MarshallPayment marshall a payment to its rpc representation.
1723
func (r *RouterBackend) MarshallPayment(payment *channeldb.MPPayment) (
1724
        *lnrpc.Payment, error) {
2✔
1725

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

1740
        msatValue := int64(payment.Info.Value)
2✔
1741
        satValue := int64(payment.Info.Value.ToSatoshis())
2✔
1742

2✔
1743
        status, err := convertPaymentStatus(
2✔
1744
                payment.Status, r.UseStatusInitiated,
2✔
1745
        )
2✔
1746
        if err != nil {
2✔
1747
                return nil, err
×
1748
        }
×
1749

1750
        htlcs := make([]*lnrpc.HTLCAttempt, 0, len(payment.HTLCs))
2✔
1751
        for _, dbHTLC := range payment.HTLCs {
4✔
1752
                htlc, err := r.MarshalHTLCAttempt(dbHTLC)
2✔
1753
                if err != nil {
2✔
1754
                        return nil, err
×
1755
                }
×
1756

1757
                htlcs = append(htlcs, htlc)
2✔
1758
        }
1759

1760
        paymentID := payment.Info.PaymentIdentifier
2✔
1761
        creationTimeNS := MarshalTimeNano(payment.Info.CreationTime)
2✔
1762

2✔
1763
        failureReason, err := marshallPaymentFailureReason(
2✔
1764
                payment.FailureReason,
2✔
1765
        )
2✔
1766
        if err != nil {
2✔
1767
                return nil, err
×
1768
        }
×
1769

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

1791
// convertPaymentStatus converts a channeldb.PaymentStatus to the type expected
1792
// by the RPC.
1793
func convertPaymentStatus(dbStatus channeldb.PaymentStatus, useInit bool) (
1794
        lnrpc.Payment_PaymentStatus, error) {
2✔
1795

2✔
1796
        switch dbStatus {
2✔
1797
        case channeldb.StatusInitiated:
2✔
1798
                // If the client understands the new status, return it.
2✔
1799
                if useInit {
4✔
1800
                        return lnrpc.Payment_INITIATED, nil
2✔
1801
                }
2✔
1802

1803
                // Otherwise remain the old behavior.
1804
                return lnrpc.Payment_IN_FLIGHT, nil
2✔
1805

1806
        case channeldb.StatusInFlight:
2✔
1807
                return lnrpc.Payment_IN_FLIGHT, nil
2✔
1808

1809
        case channeldb.StatusSucceeded:
2✔
1810
                return lnrpc.Payment_SUCCEEDED, nil
2✔
1811

1812
        case channeldb.StatusFailed:
2✔
1813
                return lnrpc.Payment_FAILED, nil
2✔
1814

1815
        default:
×
1816
                return 0, fmt.Errorf("unhandled payment status %v", dbStatus)
×
1817
        }
1818
}
1819

1820
// marshallPaymentFailureReason marshalls the failure reason to the corresponding rpc
1821
// type.
1822
func marshallPaymentFailureReason(reason *channeldb.FailureReason) (
1823
        lnrpc.PaymentFailureReason, error) {
2✔
1824

2✔
1825
        if reason == nil {
4✔
1826
                return lnrpc.PaymentFailureReason_FAILURE_REASON_NONE, nil
2✔
1827
        }
2✔
1828

1829
        switch *reason {
2✔
1830
        case channeldb.FailureReasonTimeout:
×
1831
                return lnrpc.PaymentFailureReason_FAILURE_REASON_TIMEOUT, nil
×
1832

1833
        case channeldb.FailureReasonNoRoute:
2✔
1834
                return lnrpc.PaymentFailureReason_FAILURE_REASON_NO_ROUTE, nil
2✔
1835

1836
        case channeldb.FailureReasonError:
2✔
1837
                return lnrpc.PaymentFailureReason_FAILURE_REASON_ERROR, nil
2✔
1838

1839
        case channeldb.FailureReasonPaymentDetails:
2✔
1840
                return lnrpc.PaymentFailureReason_FAILURE_REASON_INCORRECT_PAYMENT_DETAILS, nil
2✔
1841

1842
        case channeldb.FailureReasonInsufficientBalance:
2✔
1843
                return lnrpc.PaymentFailureReason_FAILURE_REASON_INSUFFICIENT_BALANCE, nil
2✔
1844

1845
        case channeldb.FailureReasonCanceled:
2✔
1846
                return lnrpc.PaymentFailureReason_FAILURE_REASON_CANCELED, nil
2✔
1847
        }
1848

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