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

lightningnetwork / lnd / 13963480979

20 Mar 2025 06:43AM UTC coverage: 59.157% (-0.01%) from 59.168%
13963480979

Pull #9603

github

web-flow
Merge 791dd9799 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%)

57 existing lines in 13 files now uncovered.

96849 of 163714 relevant lines covered (59.16%)

1.84 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) {
3✔
167

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

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

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

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

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

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

3✔
209
        ignoredNodes := make(map[route.Vertex]struct{})
3✔
210
        for _, ignorePubKey := range in.IgnoredNodes {
3✔
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{})
3✔
219

3✔
220
        // Convert deprecated ignoredEdges to pairs.
3✔
221
        for _, ignoredEdge := range in.IgnoredEdges {
3✔
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 {
3✔
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
3✔
249
}
250

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

397
                        if !in.UseMissionControl {
6✔
398
                                return 1
3✔
399
                        }
3✔
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 {
3✔
413
                restrictions.OutgoingChannelIDs = []uint64{in.OutgoingChanId}
×
414
        }
×
415

416
        // Pass along a last hop restriction if specified.
417
        if len(in.LastHopPubkey) > 0 {
3✔
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)
3✔
431
        if err := customRecords.Validate(); err != nil {
3✔
432
                return nil, err
×
433
        }
×
434

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

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

3✔
445
        if len(in.PubKey) != 0 {
3✔
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 {
3✔
451
                return nil, errors.New("route hints and blinded path can't " +
×
452
                        "both be set")
×
453
        }
×
454

455
        if in.FinalCltvDelta != 0 {
3✔
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 {
3✔
465
                return nil, errors.New("destination features should " +
×
466
                        "be populated in blinded path")
×
467
        }
×
468

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

551
        return path, nil
3✔
552
}
553

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

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

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

566
        return &sphinx.BlindedHopInfo{
3✔
567
                BlindedNodePub: pubkey,
3✔
568
                CipherText:     rpcHop.EncryptedData,
3✔
569
        }, nil
3✔
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) {
3✔
594
        resp := &lnrpc.Route{
3✔
595
                TotalTimeLock:      route.TotalTimeLock,
3✔
596
                TotalFees:          int64(route.TotalFees().ToSatoshis()),
3✔
597
                TotalFeesMsat:      int64(route.TotalFees()),
3✔
598
                TotalAmt:           int64(route.TotalAmount.ToSatoshis()),
3✔
599
                TotalAmtMsat:       int64(route.TotalAmount),
3✔
600
                Hops:               make([]*lnrpc.Hop, len(route.Hops)),
3✔
601
                FirstHopAmountMsat: int64(route.FirstHopAmount.Val.Int()),
3✔
602
        }
3✔
603

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

611
                resp.CustomChannelData = customData
3✔
612

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

739
        return hop, nil
3✔
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) {
3✔
746

3✔
747
        var pubKeyBytes [33]byte
3✔
748
        if rpcHop.PubKey != "" {
6✔
749
                // Unmarshall the provided hop pubkey.
3✔
750
                pubKey, err := hex.DecodeString(rpcHop.PubKey)
3✔
751
                if err != nil {
3✔
752
                        return nil, fmt.Errorf("cannot decode pubkey %s",
×
753
                                rpcHop.PubKey)
×
754
                }
×
755
                copy(pubKeyBytes[:], pubKey)
3✔
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)
3✔
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) {
3✔
783

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

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

793
                hops[i] = routeHop
3✔
794

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

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

808
        return route, nil
3✔
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) {
3✔
816

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

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

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

3✔
828
        // Add the deprecated single outgoing channel restriction if present.
3✔
829
        if rpcPayReq.OutgoingChanId != 0 {
3✔
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 {
3✔
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(
3✔
853
                uint32(rpcPayReq.CltvLimit), r.MaxTotalTimelock,
3✔
854
        )
3✔
855
        if err != nil {
3✔
856
                return nil, err
×
857
        }
×
858
        payIntent.CltvLimit = cltvLimit
3✔
859

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

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

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

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

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

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

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

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

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

3✔
926
        // Unmarshall either sat or msat amount from request.
3✔
927
        reqAmt, err := lnrpc.UnmarshallAmt(
3✔
928
                rpcPayReq.Amt, rpcPayReq.AmtMsat,
3✔
929
        )
3✔
930
        if err != nil {
3✔
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 != "" {
6✔
938
                switch {
3✔
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(
3✔
954
                        rpcPayReq.PaymentRequest, r.ActiveNetParams,
3✔
955
                )
3✔
956
                if err != nil {
3✔
957
                        return nil, err
×
958
                }
×
959

960
                // Next, we'll ensure that this payreq hasn't already expired.
961
                err = ValidatePayReqExpiry(payReq)
3✔
962
                if err != nil {
3✔
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 {
3✔
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 {
3✔
979
                        if reqAmt != 0 {
3✔
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
3✔
986
                }
987

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

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

994
                payAddr := payReq.PaymentAddr
3✔
995
                if payReq.Features.HasFeature(lnwire.AMPOptional) {
6✔
996
                        // The opt-in AMP flag is required to pay an AMP
3✔
997
                        // invoice.
3✔
998
                        if !rpcPayReq.Amp {
3✔
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
3✔
1006
                        _, err = rand.Read(setID[:])
3✔
1007
                        if err != nil {
3✔
1008
                                return nil, err
×
1009
                        }
×
1010

1011
                        var rootShare [32]byte
3✔
1012
                        _, err = rand.Read(rootShare[:])
3✔
1013
                        if err != nil {
3✔
1014
                                return nil, err
×
1015
                        }
×
1016
                        err := payIntent.SetAMP(&routing.AMPOptions{
3✔
1017
                                SetID:     setID,
3✔
1018
                                RootShare: rootShare,
3✔
1019
                        })
3✔
1020
                        if err != nil {
3✔
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 {
6✔
1033
                                var addr [32]byte
3✔
1034
                                copy(addr[:], rpcPayReq.PaymentAddr)
3✔
1035
                                payAddr = fn.Some(addr)
3✔
1036
                        }
3✔
1037
                } else {
3✔
1038
                        err = payIntent.SetPaymentHash(*payReq.PaymentHash)
3✔
1039
                        if err != nil {
3✔
1040
                                return nil, err
×
1041
                        }
×
1042
                }
1043

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

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

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

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

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

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

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

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

1102
                payIntent.Amount = reqAmt
3✔
1103

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

1110
                // Validate the features if any was specified.
1111
                if features != nil {
6✔
1112
                        err = feature.ValidateDeps(features)
3✔
1113
                        if err != nil {
3✔
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 {
6✔
1121
                        // If no destination features were specified, we set
3✔
1122
                        // those necessary for AMP payments.
3✔
1123
                        if features == nil {
6✔
1124
                                ampFeatures := []lnrpc.FeatureBit{
3✔
1125
                                        lnrpc.FeatureBit_TLV_ONION_OPT,
3✔
1126
                                        lnrpc.FeatureBit_PAYMENT_ADDR_OPT,
3✔
1127
                                        lnrpc.FeatureBit_AMP_OPT,
3✔
1128
                                }
3✔
1129

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

1136
                        // First make sure the destination supports AMP.
1137
                        if !features.HasFeature(lnwire.AMPOptional) {
3✔
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
3✔
1144
                        if len(rpcPayReq.PaymentAddr) == 0 {
6✔
1145
                                _, err = rand.Read(payAddr[:])
3✔
1146
                                if err != nil {
3✔
1147
                                        return nil, err
×
1148
                                }
×
1149
                        } else {
×
1150
                                copy(payAddr[:], rpcPayReq.PaymentAddr)
×
1151
                        }
×
1152
                        payIntent.PaymentAddr = fn.Some(payAddr)
3✔
1153

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

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

1180
                        err = payIntent.SetPaymentHash(paymentHash)
3✔
1181
                        if err != nil {
3✔
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 {
3✔
1188
                                var payAddr [32]byte
×
1189
                                copy(payAddr[:], rpcPayReq.PaymentAddr)
×
1190

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

1195
                payIntent.DestFeatures = features
3✔
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 {
6✔
1202
                if payIntent.MaxParts > MaxPartsUpperLimit {
6✔
1203
                        return nil, fmt.Errorf("requested max_parts (%v) "+
3✔
1204
                                "exceeds the allowed upper limit of %v; cannot"+
3✔
1205
                                " send payment amount %v with "+
3✔
1206
                                "max_shard_size_msat=%v", payIntent.MaxParts,
3✔
1207
                                MaxPartsUpperLimit, payIntent.Amount,
3✔
1208
                                *payIntent.MaxShardAmt)
3✔
1209
                }
3✔
1210

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

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

1228
                        return nil, fmt.Errorf("payment amount %v exceeds "+
3✔
1229
                                "maximum allowed amount %v with max_parts=%v "+
3✔
1230
                                "and max_shard_size_msat=%v; consider setting "+
3✔
1231
                                "max_parts to at least %v", payIntent.Amount,
3✔
1232
                                maxPossibleAmount, payIntent.MaxParts,
3✔
1233
                                *payIntent.MaxShardAmt, minRequiredParts,
3✔
1234
                        )
3✔
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(
3✔
1241
                payIntent.CltvLimit, payIntent.FinalCLTVDelta, true,
3✔
1242
        )
3✔
1243
        if err != nil {
3✔
1244
                return nil, err
×
1245
        }
×
1246

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

1252
        return payIntent, nil
3✔
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) {
3✔
1259

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

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

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

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

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

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

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

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

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

1315
        return routeHints, nil
3✔
1316
}
1317

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

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

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

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

1346
        return featureBits
3✔
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) {
3✔
1354

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

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

1369
        return lnwire.NewFeatureVector(raw, lnwire.Features), nil
3✔
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 {
3✔
1375
        expiry := payReq.Expiry()
3✔
1376
        validUntil := payReq.Timestamp.Add(expiry)
3✔
1377
        if time.Now().After(validUntil) {
3✔
1378
                return fmt.Errorf("invoice expired. Valid until %v", validUntil)
×
1379
        }
×
1380

1381
        return nil
3✔
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) {
3✔
1388
        switch {
3✔
1389
        case val == 0:
3✔
1390
                return max, nil
3✔
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) {
3✔
1406
        // If no MPP record was submitted, assume the user wants to send a
3✔
1407
        // regular payment.
3✔
1408
        if reqMPP == nil {
6✔
1409
                return nil, nil
3✔
1410
        }
3✔
1411

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

3✔
1415
        switch {
3✔
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)
3✔
1430
        if err != nil {
3✔
1431
                return nil, fmt.Errorf("unable to parse "+
×
1432
                        "payment_addr: %v", err)
×
1433
        }
×
1434

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

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

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

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

3✔
1448
        switch {
3✔
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 (
3✔
1457
                rootShare [32]byte
3✔
1458
                setID     [32]byte
3✔
1459
        )
3✔
1460
        copy(rootShare[:], reqRootShare)
3✔
1461
        copy(setID[:], reqSetID)
3✔
1462

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

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

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

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

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

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

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

1504
        return rpcAttempt, nil
3✔
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) {
3✔
1511

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

3✔
1516
        switch failure.Reason {
3✔
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:
3✔
1527
                err := marshallWireError(failure.Message, rpcFailure)
3✔
1528
                if err != nil {
3✔
1529
                        return nil, err
×
1530
                }
×
1531

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

1536
        return rpcFailure, nil
3✔
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 {
3✔
1543
        if t.IsZero() {
3✔
1544
                return 0
×
1545
        }
×
1546
        return t.UnixNano()
3✔
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) {
3✔
1556
        response := &lnrpc.Failure{}
3✔
1557

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

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

1568
        err := marshallWireError(rtErr.WireMessage(), response)
3✔
1569
        if err != nil {
3✔
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)
3✔
1580
        if ok {
3✔
1581
                response.FailureSourceIndex = uint32(fErr.FailureSourceIdx)
×
1582
        }
×
1583

1584
        return response, nil
3✔
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 {
3✔
1595

3✔
1596
        switch onionErr := msg.(type) {
3✔
1597
        case *lnwire.FailIncorrectDetails:
3✔
1598
                response.Code = lnrpc.Failure_INCORRECT_OR_UNKNOWN_PAYMENT_DETAILS
3✔
1599
                response.Height = onionErr.Height()
3✔
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:
3✔
1626
                response.Code = lnrpc.Failure_INVALID_ONION_VERSION
3✔
1627
                response.OnionSha_256 = onionErr.OnionSHA256[:]
3✔
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:
3✔
1643
                response.Code = lnrpc.Failure_FEE_INSUFFICIENT
3✔
1644
                response.ChannelUpdate = marshallChannelUpdate(&onionErr.Update)
3✔
1645
                response.HtlcMsat = uint64(onionErr.HtlcMsat)
3✔
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:
3✔
1653
                response.Code = lnrpc.Failure_CHANNEL_DISABLED
3✔
1654
                response.ChannelUpdate = marshallChannelUpdate(&onionErr.Update)
3✔
1655
                response.Flags = uint32(onionErr.Flags)
3✔
1656

1657
        case *lnwire.FailTemporaryChannelFailure:
3✔
1658
                response.Code = lnrpc.Failure_TEMPORARY_CHANNEL_FAILURE
3✔
1659
                response.ChannelUpdate = marshallChannelUpdate(onionErr.Update)
3✔
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:
3✔
1668
                response.Code = lnrpc.Failure_UNKNOWN_NEXT_PEER
3✔
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:
3✔
1677
                response.Code = lnrpc.Failure_PERMANENT_CHANNEL_FAILURE
3✔
1678

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

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

1685
        case *lnwire.FailInvalidBlinding:
3✔
1686
                response.Code = lnrpc.Failure_INVALID_ONION_BLINDING
3✔
1687
                response.OnionSha_256 = onionErr.OnionSHA256[:]
3✔
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
3✔
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 {
3✔
1702
        if update == nil {
3✔
1703
                return nil
×
1704
        }
×
1705

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1812
        case channeldb.StatusFailed:
3✔
1813
                return lnrpc.Payment_FAILED, nil
3✔
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) {
3✔
1824

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

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

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

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

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

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

1845
        case channeldb.FailureReasonCanceled:
3✔
1846
                return lnrpc.PaymentFailureReason_FAILURE_REASON_CANCELED, nil
3✔
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