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

lightningnetwork / lnd / 14076767081

26 Mar 2025 06:16AM UTC coverage: 58.581% (-10.5%) from 69.049%
14076767081

Pull #9643

github

web-flow
Merge 1e0ddf3a1 into 0a2b33abe
Pull Request #9643: lnd: make sure startup flow is not aborted

3 of 21 new or added lines in 1 file covered. (14.29%)

28092 existing lines in 448 files now uncovered.

96997 of 165578 relevant lines covered (58.58%)

1.82 hits per line

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

68.63
/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

41
// RouterBackend contains the backend implementation of the router rpc sub
42
// server calls.
43
type RouterBackend struct {
44
        // SelfNode is the vertex of the node sending the payment.
45
        SelfNode route.Vertex
46

47
        // FetchChannelCapacity is a closure that we'll use the fetch the total
48
        // capacity of a channel to populate in responses.
49
        FetchChannelCapacity func(chanID uint64) (btcutil.Amount, error)
50

51
        // FetchAmountPairCapacity determines the maximal channel capacity
52
        // between two nodes given a certain amount.
53
        FetchAmountPairCapacity func(nodeFrom, nodeTo route.Vertex,
54
                amount lnwire.MilliSatoshi) (btcutil.Amount, error)
55

56
        // FetchChannelEndpoints returns the pubkeys of both endpoints of the
57
        // given channel id.
58
        FetchChannelEndpoints func(chanID uint64) (route.Vertex,
59
                route.Vertex, error)
60

61
        // FindRoute is a closure that abstracts away how we locate/query for
62
        // routes.
63
        FindRoute func(*routing.RouteRequest) (*route.Route, float64, error)
64

65
        MissionControl MissionControl
66

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

73
        // Tower is the ControlTower instance that is used to track pending
74
        // payments.
75
        Tower routing.ControlTower
76

77
        // MaxTotalTimelock is the maximum total time lock a route is allowed to
78
        // have.
79
        MaxTotalTimelock uint32
80

81
        // DefaultFinalCltvDelta is the default value used as final cltv delta
82
        // when an RPC caller doesn't specify a value.
83
        DefaultFinalCltvDelta uint16
84

85
        // SubscribeHtlcEvents returns a subscription client for the node's
86
        // htlc events.
87
        SubscribeHtlcEvents func() (*subscribe.Client, error)
88

89
        // InterceptableForwarder exposes the ability to intercept forward events
90
        // by letting the router register a ForwardInterceptor.
91
        InterceptableForwarder htlcswitch.InterceptableHtlcForwarder
92

93
        // SetChannelEnabled exposes the ability to manually enable a channel.
94
        SetChannelEnabled func(wire.OutPoint) error
95

96
        // SetChannelDisabled exposes the ability to manually disable a channel
97
        SetChannelDisabled func(wire.OutPoint) error
98

99
        // SetChannelAuto exposes the ability to restore automatic channel state
100
        // management after manually setting channel status.
101
        SetChannelAuto func(wire.OutPoint) error
102

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

110
        // ParseCustomChannelData is a function that can be used to parse custom
111
        // channel data from the first hop of a route.
112
        ParseCustomChannelData func(message proto.Message) error
113

114
        // ShouldSetExpEndorsement returns a boolean indicating whether the
115
        // experimental endorsement bit should be set.
116
        ShouldSetExpEndorsement func() bool
117
}
118

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

126
        // ResetHistory resets the history of MissionControl returning it to a
127
        // state as if no payment attempts have been made.
128
        ResetHistory() error
129

130
        // GetHistorySnapshot takes a snapshot from the current mission control
131
        // state and actual probability estimates.
132
        GetHistorySnapshot() *routing.MissionControlSnapshot
133

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

139
        // GetPairHistorySnapshot returns the stored history for a given node
140
        // pair.
141
        GetPairHistorySnapshot(fromNode,
142
                toNode route.Vertex) routing.TimedPairResult
143

144
        // GetConfig gets mission control's current config.
145
        GetConfig() *routing.MissionControlConfig
146

147
        // SetConfig sets mission control's config to the values provided, if
148
        // they are valid.
149
        SetConfig(cfg *routing.MissionControlConfig) error
150
}
151

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

3✔
164
        routeReq, err := r.parseQueryRoutesRequest(in)
3✔
165
        if err != nil {
3✔
UNCOV
166
                return nil, err
×
UNCOV
167
        }
×
168

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

177
        // For each valid route, we'll convert the result into the format
178
        // required by the RPC system.
179
        rpcRoute, err := r.MarshallRoute(route)
3✔
180
        if err != nil {
3✔
181
                return nil, err
×
182
        }
×
183

184
        routeResp := &lnrpc.QueryRoutesResponse{
3✔
185
                Routes:      []*lnrpc.Route{rpcRoute},
3✔
186
                SuccessProb: successProb,
3✔
187
        }
3✔
188

3✔
189
        return routeResp, nil
3✔
190
}
191

192
func parsePubKey(key string) (route.Vertex, error) {
3✔
193
        pubKeyBytes, err := hex.DecodeString(key)
3✔
194
        if err != nil {
3✔
195
                return route.Vertex{}, err
×
196
        }
×
197

198
        return route.NewVertexFromBytes(pubKeyBytes)
3✔
199
}
200

201
func (r *RouterBackend) parseIgnored(in *lnrpc.QueryRoutesRequest) (
202
        map[route.Vertex]struct{}, map[routing.DirectedNodePair]struct{},
203
        error) {
3✔
204

3✔
205
        ignoredNodes := make(map[route.Vertex]struct{})
3✔
206
        for _, ignorePubKey := range in.IgnoredNodes {
3✔
UNCOV
207
                ignoreVertex, err := route.NewVertexFromBytes(ignorePubKey)
×
UNCOV
208
                if err != nil {
×
209
                        return nil, nil, err
×
210
                }
×
UNCOV
211
                ignoredNodes[ignoreVertex] = struct{}{}
×
212
        }
213

214
        ignoredPairs := make(map[routing.DirectedNodePair]struct{})
3✔
215

3✔
216
        // Convert deprecated ignoredEdges to pairs.
3✔
217
        for _, ignoredEdge := range in.IgnoredEdges {
3✔
UNCOV
218
                pair, err := r.rpcEdgeToPair(ignoredEdge)
×
UNCOV
219
                if err != nil {
×
220
                        log.Warnf("Ignore channel %v skipped: %v",
×
221
                                ignoredEdge.ChannelId, err)
×
222

×
223
                        continue
×
224
                }
UNCOV
225
                ignoredPairs[pair] = struct{}{}
×
226
        }
227

228
        // Add ignored pairs to set.
229
        for _, ignorePair := range in.IgnoredPairs {
3✔
UNCOV
230
                from, err := route.NewVertexFromBytes(ignorePair.From)
×
UNCOV
231
                if err != nil {
×
232
                        return nil, nil, err
×
233
                }
×
234

UNCOV
235
                to, err := route.NewVertexFromBytes(ignorePair.To)
×
UNCOV
236
                if err != nil {
×
237
                        return nil, nil, err
×
238
                }
×
239

UNCOV
240
                pair := routing.NewDirectedNodePair(from, to)
×
UNCOV
241
                ignoredPairs[pair] = struct{}{}
×
242
        }
243

244
        return ignoredNodes, ignoredPairs, nil
3✔
245
}
246

247
func (r *RouterBackend) parseQueryRoutesRequest(in *lnrpc.QueryRoutesRequest) (
248
        *routing.RouteRequest, error) {
3✔
249

3✔
250
        // Parse the hex-encoded source public key into a full public key that
3✔
251
        // we can properly manipulate.
3✔
252

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

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

273
        // Unmarshall restrictions from request.
274
        feeLimit := lnrpc.CalculateFeeLimit(in.FeeLimit, amt)
3✔
275

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

283
        cltvLimit, err := ValidateCLTVLimit(in.CltvLimit, maxTotalTimelock)
3✔
284
        if err != nil {
3✔
285
                return nil, err
×
286
        }
×
287

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

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

3✔
302
                // destinationFeatures is the set of features for the
3✔
303
                // destination node.
3✔
304
                destinationFeatures *lnwire.FeatureVector
3✔
305
        )
3✔
306

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

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

3✔
328
                // Convert route hints to an edge map.
3✔
329
                routeHints, err := unmarshallRouteHints(in.RouteHints)
3✔
330
                if err != nil {
3✔
331
                        return nil, err
×
332
                }
×
333

334
                routeHintEdges, err = routing.RouteHintsToEdges(
3✔
335
                        routeHints, *targetPubKey,
3✔
336
                )
3✔
337
                if err != nil {
3✔
338
                        return nil, err
×
339
                }
×
340

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

349
                // Do bounds checking without block padding so we don't give
350
                // routes that will leave the router in a zombie payment state.
351
                err = routing.ValidateCLTVLimit(
3✔
352
                        cltvLimit, finalCLTVDelta, false,
3✔
353
                )
3✔
354
                if err != nil {
3✔
UNCOV
355
                        return nil, err
×
UNCOV
356
                }
×
357

358
                // Parse destination feature bits.
359
                destinationFeatures, err = UnmarshalFeatures(in.DestFeatures)
3✔
360
                if err != nil {
3✔
361
                        return nil, err
×
362
                }
×
363
        }
364

365
        // We need to subtract the final delta before passing it into path
366
        // finding. The optimal path is independent of the final cltv delta and
367
        // the path finding algorithm is unaware of this value.
368
        cltvLimit -= uint32(finalCLTVDelta)
3✔
369

3✔
370
        ignoredNodes, ignoredPairs, err := r.parseIgnored(in)
3✔
371
        if err != nil {
3✔
372
                return nil, err
×
373
        }
×
374

375
        restrictions := &routing.RestrictParams{
3✔
376
                FeeLimit: feeLimit,
3✔
377
                ProbabilitySource: func(fromNode, toNode route.Vertex,
3✔
378
                        amt lnwire.MilliSatoshi,
3✔
379
                        capacity btcutil.Amount) float64 {
6✔
380

3✔
381
                        if _, ok := ignoredNodes[fromNode]; ok {
3✔
UNCOV
382
                                return 0
×
UNCOV
383
                        }
×
384

385
                        pair := routing.DirectedNodePair{
3✔
386
                                From: fromNode,
3✔
387
                                To:   toNode,
3✔
388
                        }
3✔
389
                        if _, ok := ignoredPairs[pair]; ok {
3✔
UNCOV
390
                                return 0
×
UNCOV
391
                        }
×
392

393
                        if !in.UseMissionControl {
6✔
394
                                return 1
3✔
395
                        }
3✔
396

UNCOV
397
                        return r.MissionControl.GetProbability(
×
UNCOV
398
                                fromNode, toNode, amt, capacity,
×
UNCOV
399
                        )
×
400
                },
401
                DestCustomRecords:     record.CustomSet(in.DestCustomRecords),
402
                CltvLimit:             cltvLimit,
403
                DestFeatures:          destinationFeatures,
404
                BlindedPaymentPathSet: blindedPathSet,
405
        }
406

407
        // Pass along an outgoing channel restriction if specified.
408
        if in.OutgoingChanId != 0 {
3✔
UNCOV
409
                restrictions.OutgoingChannelIDs = []uint64{in.OutgoingChanId}
×
UNCOV
410
        }
×
411

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

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

431
        return routing.NewRouteRequest(
3✔
432
                sourcePubKey, targetPubKey, amt, in.TimePref, restrictions,
3✔
433
                customRecords, routeHintEdges, blindedPathSet,
3✔
434
                finalCLTVDelta,
3✔
435
        )
3✔
436
}
437

438
func parseBlindedPaymentPaths(in *lnrpc.QueryRoutesRequest) (
439
        *routing.BlindedPaymentPathSet, error) {
3✔
440

3✔
441
        if len(in.PubKey) != 0 {
3✔
442
                return nil, fmt.Errorf("target pubkey: %x should not be set "+
×
443
                        "when blinded path is provided", in.PubKey)
×
444
        }
×
445

446
        if len(in.RouteHints) > 0 {
3✔
447
                return nil, errors.New("route hints and blinded path can't " +
×
448
                        "both be set")
×
449
        }
×
450

451
        if in.FinalCltvDelta != 0 {
3✔
452
                return nil, errors.New("final cltv delta should be " +
×
453
                        "zero for blinded paths")
×
454
        }
×
455

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

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

472
                if err := blindedPmt.Validate(); err != nil {
3✔
473
                        return nil, fmt.Errorf("invalid blinded path: %w", err)
×
474
                }
×
475

476
                paths[i] = blindedPmt
3✔
477
        }
478

479
        return routing.NewBlindedPaymentPathSet(paths)
3✔
480
}
481

482
func unmarshalBlindedPayment(rpcPayment *lnrpc.BlindedPaymentPath) (
483
        *routing.BlindedPayment, error) {
3✔
484

3✔
485
        if rpcPayment == nil {
3✔
486
                return nil, errors.New("nil blinded payment")
×
487
        }
×
488

489
        path, err := unmarshalBlindedPaymentPaths(rpcPayment.BlindedPath)
3✔
490
        if err != nil {
3✔
491
                return nil, err
×
492
        }
×
493

494
        features, err := UnmarshalFeatures(rpcPayment.Features)
3✔
495
        if err != nil {
3✔
496
                return nil, err
×
497
        }
×
498

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

510
func unmarshalBlindedPaymentPaths(rpcPath *lnrpc.BlindedPath) (
511
        *sphinx.BlindedPath, error) {
3✔
512

3✔
513
        if rpcPath == nil {
3✔
514
                return nil, errors.New("blinded path required when blinded " +
×
515
                        "route is provided")
×
516
        }
×
517

518
        introduction, err := btcec.ParsePubKey(rpcPath.IntroductionNode)
3✔
519
        if err != nil {
3✔
520
                return nil, err
×
521
        }
×
522

523
        blinding, err := btcec.ParsePubKey(rpcPath.BlindingPoint)
3✔
524
        if err != nil {
3✔
525
                return nil, err
×
526
        }
×
527

528
        if len(rpcPath.BlindedHops) < 1 {
3✔
529
                return nil, errors.New("at least 1 blinded hops required")
×
530
        }
×
531

532
        path := &sphinx.BlindedPath{
3✔
533
                IntroductionPoint: introduction,
3✔
534
                BlindingPoint:     blinding,
3✔
535
                BlindedHops: make(
3✔
536
                        []*sphinx.BlindedHopInfo, len(rpcPath.BlindedHops),
3✔
537
                ),
3✔
538
        }
3✔
539

3✔
540
        for i, hop := range rpcPath.BlindedHops {
6✔
541
                path.BlindedHops[i], err = unmarshalBlindedHop(hop)
3✔
542
                if err != nil {
3✔
543
                        return nil, err
×
544
                }
×
545
        }
546

547
        return path, nil
3✔
548
}
549

550
func unmarshalBlindedHop(rpcHop *lnrpc.BlindedHop) (*sphinx.BlindedHopInfo,
551
        error) {
3✔
552

3✔
553
        pubkey, err := btcec.ParsePubKey(rpcHop.BlindedNode)
3✔
554
        if err != nil {
3✔
555
                return nil, err
×
556
        }
×
557

558
        if len(rpcHop.EncryptedData) == 0 {
3✔
559
                return nil, errors.New("empty encrypted data not allowed")
×
560
        }
×
561

562
        return &sphinx.BlindedHopInfo{
3✔
563
                BlindedNodePub: pubkey,
3✔
564
                CipherText:     rpcHop.EncryptedData,
3✔
565
        }, nil
3✔
566
}
567

568
// rpcEdgeToPair looks up the provided channel and returns the channel endpoints
569
// as a directed pair.
570
func (r *RouterBackend) rpcEdgeToPair(e *lnrpc.EdgeLocator) (
UNCOV
571
        routing.DirectedNodePair, error) {
×
UNCOV
572

×
UNCOV
573
        a, b, err := r.FetchChannelEndpoints(e.ChannelId)
×
UNCOV
574
        if err != nil {
×
575
                return routing.DirectedNodePair{}, err
×
576
        }
×
577

UNCOV
578
        var pair routing.DirectedNodePair
×
UNCOV
579
        if e.DirectionReverse {
×
UNCOV
580
                pair.From, pair.To = b, a
×
UNCOV
581
        } else {
×
582
                pair.From, pair.To = a, b
×
583
        }
×
584

UNCOV
585
        return pair, nil
×
586
}
587

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

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

607
                resp.CustomChannelData = customData
3✔
608

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

619
        incomingAmt := route.TotalAmount
3✔
620
        for i, hop := range route.Hops {
6✔
621
                fee := route.HopFee(i)
3✔
622

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

634
                // Extract the MPP fields if present on this hop.
635
                var mpp *lnrpc.MPPRecord
3✔
636
                if hop.MPP != nil {
6✔
637
                        addr := hop.MPP.PaymentAddr()
3✔
638

3✔
639
                        mpp = &lnrpc.MPPRecord{
3✔
640
                                PaymentAddr:  addr[:],
3✔
641
                                TotalAmtMsat: int64(hop.MPP.TotalMsat()),
3✔
642
                        }
3✔
643
                }
3✔
644

645
                var amp *lnrpc.AMPRecord
3✔
646
                if hop.AMP != nil {
6✔
647
                        rootShare := hop.AMP.RootShare()
3✔
648
                        setID := hop.AMP.SetID()
3✔
649

3✔
650
                        amp = &lnrpc.AMPRecord{
3✔
651
                                RootShare:  rootShare[:],
3✔
652
                                SetId:      setID[:],
3✔
653
                                ChildIndex: hop.AMP.ChildIndex(),
3✔
654
                        }
3✔
655
                }
3✔
656

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

3✔
677
                if hop.BlindingPoint != nil {
6✔
678
                        blinding := hop.BlindingPoint.SerializeCompressed()
3✔
679
                        resp.Hops[i].BlindingPoint = blinding
3✔
680
                }
3✔
681
                incomingAmt = hop.AmtToForward
3✔
682
        }
683

684
        return resp, nil
3✔
685
}
686

687
// UnmarshallHopWithPubkey unmarshalls an rpc hop for which the pubkey has
688
// already been extracted.
689
func UnmarshallHopWithPubkey(rpcHop *lnrpc.Hop, pubkey route.Vertex) (*route.Hop,
690
        error) {
3✔
691

3✔
692
        customRecords := record.CustomSet(rpcHop.CustomRecords)
3✔
693
        if err := customRecords.Validate(); err != nil {
3✔
694
                return nil, err
×
695
        }
×
696

697
        mpp, err := UnmarshalMPP(rpcHop.MppRecord)
3✔
698
        if err != nil {
3✔
699
                return nil, err
×
700
        }
×
701

702
        amp, err := UnmarshalAMP(rpcHop.AmpRecord)
3✔
703
        if err != nil {
3✔
704
                return nil, err
×
705
        }
×
706

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

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

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

735
        return hop, nil
3✔
736
}
737

738
// UnmarshallHop unmarshalls an rpc hop that may or may not contain a node
739
// pubkey.
740
func (r *RouterBackend) UnmarshallHop(rpcHop *lnrpc.Hop,
741
        prevNodePubKey [33]byte) (*route.Hop, error) {
3✔
742

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

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

772
        return UnmarshallHopWithPubkey(rpcHop, pubKeyBytes)
3✔
773
}
774

775
// UnmarshallRoute unmarshalls an rpc route. For hops that don't specify a
776
// pubkey, the channel graph is queried.
777
func (r *RouterBackend) UnmarshallRoute(rpcroute *lnrpc.Route) (
778
        *route.Route, error) {
3✔
779

3✔
780
        prevNodePubKey := r.SelfNode
3✔
781

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

789
                hops[i] = routeHop
3✔
790

3✔
791
                prevNodePubKey = routeHop.PubKeyBytes
3✔
792
        }
793

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

804
        return route, nil
3✔
805
}
806

807
// extractIntentFromSendRequest attempts to parse the SendRequest details
808
// required to dispatch a client from the information presented by an RPC
809
// client.
810
func (r *RouterBackend) extractIntentFromSendRequest(
811
        rpcPayReq *SendPaymentRequest) (*routing.LightningPayment, error) {
3✔
812

3✔
813
        payIntent := &routing.LightningPayment{}
3✔
814

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

3✔
821
        // Pass along restrictions on the outgoing channels that may be used.
3✔
822
        payIntent.OutgoingChannelIDs = rpcPayReq.OutgoingChanIds
3✔
823

3✔
824
        // Add the deprecated single outgoing channel restriction if present.
3✔
825
        if rpcPayReq.OutgoingChanId != 0 {
3✔
826
                if payIntent.OutgoingChannelIDs != nil {
×
827
                        return nil, errors.New("outgoing_chan_id and " +
×
828
                                "outgoing_chan_ids are mutually exclusive")
×
829
                }
×
830

831
                payIntent.OutgoingChannelIDs = append(
×
832
                        payIntent.OutgoingChannelIDs, rpcPayReq.OutgoingChanId,
×
833
                )
×
834
        }
835

836
        // Pass along a last hop restriction if specified.
837
        if len(rpcPayReq.LastHopPubkey) > 0 {
3✔
838
                lastHop, err := route.NewVertexFromBytes(
×
839
                        rpcPayReq.LastHopPubkey,
×
840
                )
×
841
                if err != nil {
×
842
                        return nil, err
×
843
                }
×
844
                payIntent.LastHop = &lastHop
×
845
        }
846

847
        // Take the CLTV limit from the request if set, otherwise use the max.
848
        cltvLimit, err := ValidateCLTVLimit(
3✔
849
                uint32(rpcPayReq.CltvLimit), r.MaxTotalTimelock,
3✔
850
        )
3✔
851
        if err != nil {
3✔
852
                return nil, err
×
853
        }
×
854
        payIntent.CltvLimit = cltvLimit
3✔
855

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

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

873
        // Take fee limit from request.
874
        payIntent.FeeLimit, err = lnrpc.UnmarshallAmt(
3✔
875
                rpcPayReq.FeeLimitSat, rpcPayReq.FeeLimitMsat,
3✔
876
        )
3✔
877
        if err != nil {
3✔
878
                return nil, err
×
879
        }
×
880

881
        customRecords := record.CustomSet(rpcPayReq.DestCustomRecords)
3✔
882
        if err := customRecords.Validate(); err != nil {
3✔
883
                return nil, err
×
884
        }
×
885
        payIntent.DestCustomRecords = customRecords
3✔
886

3✔
887
        // Keysend payments do not support MPP payments.
3✔
888
        //
3✔
889
        // NOTE: There is no need to validate the `MaxParts` value here because
3✔
890
        // it is set to 1 somewhere else in case it's a keysend payment.
3✔
891
        if customRecords.IsKeysend() {
6✔
892
                if payIntent.MaxShardAmt != nil {
6✔
893
                        return nil, errors.New("keysend payments cannot " +
3✔
894
                                "specify a max shard amount - MPP not " +
3✔
895
                                "supported with keysend payments")
3✔
896
                }
3✔
897
        }
898

899
        firstHopRecords := lnwire.CustomRecords(rpcPayReq.FirstHopCustomRecords)
3✔
900
        if err := firstHopRecords.Validate(); err != nil {
3✔
901
                return nil, err
×
902
        }
×
903
        payIntent.FirstHopCustomRecords = firstHopRecords
3✔
904

3✔
905
        // If the experimental endorsement signal is not already set, propagate
3✔
906
        // a zero value field if configured to set this signal.
3✔
907
        if r.ShouldSetExpEndorsement() {
6✔
908
                if payIntent.FirstHopCustomRecords == nil {
6✔
909
                        payIntent.FirstHopCustomRecords = make(
3✔
910
                                map[uint64][]byte,
3✔
911
                        )
3✔
912
                }
3✔
913

914
                t := uint64(lnwire.ExperimentalEndorsementType)
3✔
915
                if _, set := payIntent.FirstHopCustomRecords[t]; !set {
6✔
916
                        payIntent.FirstHopCustomRecords[t] = []byte{
3✔
917
                                lnwire.ExperimentalUnendorsed,
3✔
918
                        }
3✔
919
                }
3✔
920
        }
921

922
        payIntent.PayAttemptTimeout = time.Second *
3✔
923
                time.Duration(rpcPayReq.TimeoutSeconds)
3✔
924

3✔
925
        // Route hints.
3✔
926
        routeHints, err := unmarshallRouteHints(
3✔
927
                rpcPayReq.RouteHints,
3✔
928
        )
3✔
929
        if err != nil {
3✔
930
                return nil, err
×
931
        }
×
932
        payIntent.RouteHints = routeHints
3✔
933

3✔
934
        // Unmarshall either sat or msat amount from request.
3✔
935
        reqAmt, err := lnrpc.UnmarshallAmt(
3✔
936
                rpcPayReq.Amt, rpcPayReq.AmtMsat,
3✔
937
        )
3✔
938
        if err != nil {
3✔
939
                return nil, err
×
940
        }
×
941

942
        // If the payment request field isn't blank, then the details of the
943
        // invoice are encoded entirely within the encoded payReq.  So we'll
944
        // attempt to decode it, populating the payment accordingly.
945
        if rpcPayReq.PaymentRequest != "" {
6✔
946
                switch {
3✔
947

948
                case len(rpcPayReq.Dest) > 0:
×
949
                        return nil, errors.New("dest and payment_request " +
×
950
                                "cannot appear together")
×
951

952
                case len(rpcPayReq.PaymentHash) > 0:
×
953
                        return nil, errors.New("payment_hash and payment_request " +
×
954
                                "cannot appear together")
×
955

956
                case rpcPayReq.FinalCltvDelta != 0:
×
957
                        return nil, errors.New("final_cltv_delta and payment_request " +
×
958
                                "cannot appear together")
×
959
                }
960

961
                payReq, err := zpay32.Decode(
3✔
962
                        rpcPayReq.PaymentRequest, r.ActiveNetParams,
3✔
963
                )
3✔
964
                if err != nil {
3✔
965
                        return nil, err
×
966
                }
×
967

968
                // Next, we'll ensure that this payreq hasn't already expired.
969
                err = ValidatePayReqExpiry(payReq)
3✔
970
                if err != nil {
3✔
971
                        return nil, err
×
972
                }
×
973

974
                // If the amount was not included in the invoice, then we let
975
                // the payer specify the amount of satoshis they wish to send.
976
                // We override the amount to pay with the amount provided from
977
                // the payment request.
978
                if payReq.MilliSat == nil {
3✔
979
                        if reqAmt == 0 {
×
980
                                return nil, errors.New("amount must be " +
×
981
                                        "specified when paying a zero amount " +
×
982
                                        "invoice")
×
983
                        }
×
984

985
                        payIntent.Amount = reqAmt
×
986
                } else {
3✔
987
                        if reqAmt != 0 {
3✔
988
                                return nil, errors.New("amount must not be " +
×
989
                                        "specified when paying a non-zero " +
×
990
                                        " amount invoice")
×
991
                        }
×
992

993
                        payIntent.Amount = *payReq.MilliSat
3✔
994
                }
995

996
                if !payReq.Features.HasFeature(lnwire.MPPOptional) &&
3✔
997
                        !payReq.Features.HasFeature(lnwire.AMPOptional) {
3✔
998

×
999
                        payIntent.MaxParts = 1
×
1000
                }
×
1001

1002
                payAddr := payReq.PaymentAddr
3✔
1003
                if payReq.Features.HasFeature(lnwire.AMPOptional) {
6✔
1004
                        // The opt-in AMP flag is required to pay an AMP
3✔
1005
                        // invoice.
3✔
1006
                        if !rpcPayReq.Amp {
3✔
1007
                                return nil, fmt.Errorf("the AMP flag (--amp " +
×
1008
                                        "or SendPaymentRequest.Amp) must be " +
×
1009
                                        "set to pay an AMP invoice")
×
1010
                        }
×
1011

1012
                        // Generate random SetID and root share.
1013
                        var setID [32]byte
3✔
1014
                        _, err = rand.Read(setID[:])
3✔
1015
                        if err != nil {
3✔
1016
                                return nil, err
×
1017
                        }
×
1018

1019
                        var rootShare [32]byte
3✔
1020
                        _, err = rand.Read(rootShare[:])
3✔
1021
                        if err != nil {
3✔
1022
                                return nil, err
×
1023
                        }
×
1024
                        err := payIntent.SetAMP(&routing.AMPOptions{
3✔
1025
                                SetID:     setID,
3✔
1026
                                RootShare: rootShare,
3✔
1027
                        })
3✔
1028
                        if err != nil {
3✔
1029
                                return nil, err
×
1030
                        }
×
1031

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

1052
                destKey := payReq.Destination.SerializeCompressed()
3✔
1053
                copy(payIntent.Target[:], destKey)
3✔
1054

3✔
1055
                payIntent.FinalCLTVDelta = uint16(payReq.MinFinalCLTVExpiry())
3✔
1056
                payIntent.RouteHints = append(
3✔
1057
                        payIntent.RouteHints, payReq.RouteHints...,
3✔
1058
                )
3✔
1059
                payIntent.DestFeatures = payReq.Features
3✔
1060
                payIntent.PaymentAddr = payAddr
3✔
1061
                payIntent.PaymentRequest = []byte(rpcPayReq.PaymentRequest)
3✔
1062
                payIntent.Metadata = payReq.Metadata
3✔
1063

3✔
1064
                if len(payReq.BlindedPaymentPaths) > 0 {
6✔
1065
                        pathSet, err := BuildBlindedPathSet(
3✔
1066
                                payReq.BlindedPaymentPaths,
3✔
1067
                        )
3✔
1068
                        if err != nil {
3✔
1069
                                return nil, err
×
1070
                        }
×
1071
                        payIntent.BlindedPathSet = pathSet
3✔
1072

3✔
1073
                        // Replace the target node with the target public key
3✔
1074
                        // of the blinded path set.
3✔
1075
                        copy(
3✔
1076
                                payIntent.Target[:],
3✔
1077
                                pathSet.TargetPubKey().SerializeCompressed(),
3✔
1078
                        )
3✔
1079

3✔
1080
                        pathFeatures := pathSet.Features()
3✔
1081
                        if !pathFeatures.IsEmpty() {
3✔
1082
                                payIntent.DestFeatures = pathFeatures.Clone()
×
1083
                        }
×
1084
                }
1085
        } else {
3✔
1086
                // Otherwise, If the payment request field was not specified
3✔
1087
                // (and a custom route wasn't specified), construct the payment
3✔
1088
                // from the other fields.
3✔
1089

3✔
1090
                // Payment destination.
3✔
1091
                target, err := route.NewVertexFromBytes(rpcPayReq.Dest)
3✔
1092
                if err != nil {
3✔
1093
                        return nil, err
×
1094
                }
×
1095
                payIntent.Target = target
3✔
1096

3✔
1097
                // Final payment CLTV delta.
3✔
1098
                if rpcPayReq.FinalCltvDelta != 0 {
6✔
1099
                        payIntent.FinalCLTVDelta =
3✔
1100
                                uint16(rpcPayReq.FinalCltvDelta)
3✔
1101
                } else {
6✔
1102
                        payIntent.FinalCLTVDelta = r.DefaultFinalCltvDelta
3✔
1103
                }
3✔
1104

1105
                // Amount.
1106
                if reqAmt == 0 {
3✔
1107
                        return nil, errors.New("amount must be specified")
×
1108
                }
×
1109

1110
                payIntent.Amount = reqAmt
3✔
1111

3✔
1112
                // Parse destination feature bits.
3✔
1113
                features, err := UnmarshalFeatures(rpcPayReq.DestFeatures)
3✔
1114
                if err != nil {
3✔
1115
                        return nil, err
×
1116
                }
×
1117

1118
                // Validate the features if any was specified.
1119
                if features != nil {
6✔
1120
                        err = feature.ValidateDeps(features)
3✔
1121
                        if err != nil {
3✔
1122
                                return nil, err
×
1123
                        }
×
1124
                }
1125

1126
                // If this is an AMP payment, we must generate the initial
1127
                // randomness.
1128
                if rpcPayReq.Amp {
6✔
1129
                        // If no destination features were specified, we set
3✔
1130
                        // those necessary for AMP payments.
3✔
1131
                        if features == nil {
6✔
1132
                                ampFeatures := []lnrpc.FeatureBit{
3✔
1133
                                        lnrpc.FeatureBit_TLV_ONION_OPT,
3✔
1134
                                        lnrpc.FeatureBit_PAYMENT_ADDR_OPT,
3✔
1135
                                        lnrpc.FeatureBit_AMP_OPT,
3✔
1136
                                }
3✔
1137

3✔
1138
                                features, err = UnmarshalFeatures(ampFeatures)
3✔
1139
                                if err != nil {
3✔
1140
                                        return nil, err
×
1141
                                }
×
1142
                        }
1143

1144
                        // First make sure the destination supports AMP.
1145
                        if !features.HasFeature(lnwire.AMPOptional) {
3✔
1146
                                return nil, fmt.Errorf("destination doesn't " +
×
1147
                                        "support AMP payments")
×
1148
                        }
×
1149

1150
                        // If no payment address is set, generate a random one.
1151
                        var payAddr [32]byte
3✔
1152
                        if len(rpcPayReq.PaymentAddr) == 0 {
6✔
1153
                                _, err = rand.Read(payAddr[:])
3✔
1154
                                if err != nil {
3✔
1155
                                        return nil, err
×
1156
                                }
×
1157
                        } else {
×
1158
                                copy(payAddr[:], rpcPayReq.PaymentAddr)
×
1159
                        }
×
1160
                        payIntent.PaymentAddr = fn.Some(payAddr)
3✔
1161

3✔
1162
                        // Generate random SetID and root share.
3✔
1163
                        var setID [32]byte
3✔
1164
                        _, err = rand.Read(setID[:])
3✔
1165
                        if err != nil {
3✔
1166
                                return nil, err
×
1167
                        }
×
1168

1169
                        var rootShare [32]byte
3✔
1170
                        _, err = rand.Read(rootShare[:])
3✔
1171
                        if err != nil {
3✔
1172
                                return nil, err
×
1173
                        }
×
1174
                        err := payIntent.SetAMP(&routing.AMPOptions{
3✔
1175
                                SetID:     setID,
3✔
1176
                                RootShare: rootShare,
3✔
1177
                        })
3✔
1178
                        if err != nil {
3✔
1179
                                return nil, err
×
1180
                        }
×
1181
                } else {
3✔
1182
                        // Payment hash.
3✔
1183
                        paymentHash, err := lntypes.MakeHash(rpcPayReq.PaymentHash)
3✔
1184
                        if err != nil {
3✔
1185
                                return nil, err
×
1186
                        }
×
1187

1188
                        err = payIntent.SetPaymentHash(paymentHash)
3✔
1189
                        if err != nil {
3✔
1190
                                return nil, err
×
1191
                        }
×
1192

1193
                        // If the payment addresses is specified, then we'll
1194
                        // also populate that now as well.
1195
                        if len(rpcPayReq.PaymentAddr) != 0 {
3✔
1196
                                var payAddr [32]byte
×
1197
                                copy(payAddr[:], rpcPayReq.PaymentAddr)
×
1198

×
1199
                                payIntent.PaymentAddr = fn.Some(payAddr)
×
1200
                        }
×
1201
                }
1202

1203
                payIntent.DestFeatures = features
3✔
1204
        }
1205

1206
        // Do bounds checking with the block padding so the router isn't
1207
        // left with a zombie payment in case the user messes up.
1208
        err = routing.ValidateCLTVLimit(
3✔
1209
                payIntent.CltvLimit, payIntent.FinalCLTVDelta, true,
3✔
1210
        )
3✔
1211
        if err != nil {
3✔
1212
                return nil, err
×
1213
        }
×
1214

1215
        // Check for disallowed payments to self.
1216
        if !rpcPayReq.AllowSelfPayment && payIntent.Target == r.SelfNode {
3✔
1217
                return nil, errors.New("self-payments not allowed")
×
1218
        }
×
1219

1220
        return payIntent, nil
3✔
1221
}
1222

1223
// BuildBlindedPathSet marshals a set of zpay32.BlindedPaymentPath and uses
1224
// the result to build a new routing.BlindedPaymentPathSet.
1225
func BuildBlindedPathSet(paths []*zpay32.BlindedPaymentPath) (
1226
        *routing.BlindedPaymentPathSet, error) {
3✔
1227

3✔
1228
        marshalledPaths := make([]*routing.BlindedPayment, len(paths))
3✔
1229
        for i, path := range paths {
6✔
1230
                paymentPath := marshalBlindedPayment(path)
3✔
1231

3✔
1232
                err := paymentPath.Validate()
3✔
1233
                if err != nil {
3✔
1234
                        return nil, err
×
1235
                }
×
1236

1237
                marshalledPaths[i] = paymentPath
3✔
1238
        }
1239

1240
        return routing.NewBlindedPaymentPathSet(marshalledPaths)
3✔
1241
}
1242

1243
// marshalBlindedPayment marshals a zpay32.BLindedPaymentPath into a
1244
// routing.BlindedPayment.
1245
func marshalBlindedPayment(
1246
        path *zpay32.BlindedPaymentPath) *routing.BlindedPayment {
3✔
1247

3✔
1248
        return &routing.BlindedPayment{
3✔
1249
                BlindedPath: &sphinx.BlindedPath{
3✔
1250
                        IntroductionPoint: path.Hops[0].BlindedNodePub,
3✔
1251
                        BlindingPoint:     path.FirstEphemeralBlindingPoint,
3✔
1252
                        BlindedHops:       path.Hops,
3✔
1253
                },
3✔
1254
                BaseFee:             path.FeeBaseMsat,
3✔
1255
                ProportionalFeeRate: path.FeeRate,
3✔
1256
                CltvExpiryDelta:     path.CltvExpiryDelta,
3✔
1257
                HtlcMinimum:         path.HTLCMinMsat,
3✔
1258
                HtlcMaximum:         path.HTLCMaxMsat,
3✔
1259
                Features:            path.Features,
3✔
1260
        }
3✔
1261
}
3✔
1262

1263
// unmarshallRouteHints unmarshalls a list of route hints.
1264
func unmarshallRouteHints(rpcRouteHints []*lnrpc.RouteHint) (
1265
        [][]zpay32.HopHint, error) {
3✔
1266

3✔
1267
        routeHints := make([][]zpay32.HopHint, 0, len(rpcRouteHints))
3✔
1268
        for _, rpcRouteHint := range rpcRouteHints {
6✔
1269
                routeHint := make(
3✔
1270
                        []zpay32.HopHint, 0, len(rpcRouteHint.HopHints),
3✔
1271
                )
3✔
1272
                for _, rpcHint := range rpcRouteHint.HopHints {
6✔
1273
                        hint, err := unmarshallHopHint(rpcHint)
3✔
1274
                        if err != nil {
3✔
1275
                                return nil, err
×
1276
                        }
×
1277

1278
                        routeHint = append(routeHint, hint)
3✔
1279
                }
1280
                routeHints = append(routeHints, routeHint)
3✔
1281
        }
1282

1283
        return routeHints, nil
3✔
1284
}
1285

1286
// unmarshallHopHint unmarshalls a single hop hint.
1287
func unmarshallHopHint(rpcHint *lnrpc.HopHint) (zpay32.HopHint, error) {
3✔
1288
        pubBytes, err := hex.DecodeString(rpcHint.NodeId)
3✔
1289
        if err != nil {
3✔
1290
                return zpay32.HopHint{}, err
×
1291
        }
×
1292

1293
        pubkey, err := btcec.ParsePubKey(pubBytes)
3✔
1294
        if err != nil {
3✔
1295
                return zpay32.HopHint{}, err
×
1296
        }
×
1297

1298
        return zpay32.HopHint{
3✔
1299
                NodeID:                    pubkey,
3✔
1300
                ChannelID:                 rpcHint.ChanId,
3✔
1301
                FeeBaseMSat:               rpcHint.FeeBaseMsat,
3✔
1302
                FeeProportionalMillionths: rpcHint.FeeProportionalMillionths,
3✔
1303
                CLTVExpiryDelta:           uint16(rpcHint.CltvExpiryDelta),
3✔
1304
        }, nil
3✔
1305
}
1306

1307
// MarshalFeatures converts a feature vector into a list of uint32's.
1308
func MarshalFeatures(feats *lnwire.FeatureVector) []lnrpc.FeatureBit {
3✔
1309
        var featureBits []lnrpc.FeatureBit
3✔
1310
        for feature := range feats.Features() {
6✔
1311
                featureBits = append(featureBits, lnrpc.FeatureBit(feature))
3✔
1312
        }
3✔
1313

1314
        return featureBits
3✔
1315
}
1316

1317
// UnmarshalFeatures converts a list of uint32's into a valid feature vector.
1318
// This method checks that feature bit pairs aren't assigned together, and
1319
// validates transitive dependencies.
1320
func UnmarshalFeatures(
1321
        rpcFeatures []lnrpc.FeatureBit) (*lnwire.FeatureVector, error) {
3✔
1322

3✔
1323
        // If no destination features are specified we'll return nil to signal
3✔
1324
        // that the router should try to use the graph as a fallback.
3✔
1325
        if rpcFeatures == nil {
6✔
1326
                return nil, nil
3✔
1327
        }
3✔
1328

1329
        raw := lnwire.NewRawFeatureVector()
3✔
1330
        for _, bit := range rpcFeatures {
6✔
1331
                err := raw.SafeSet(lnwire.FeatureBit(bit))
3✔
1332
                if err != nil {
3✔
1333
                        return nil, err
×
1334
                }
×
1335
        }
1336

1337
        return lnwire.NewFeatureVector(raw, lnwire.Features), nil
3✔
1338
}
1339

1340
// ValidatePayReqExpiry checks if the passed payment request has expired. In
1341
// the case it has expired, an error will be returned.
1342
func ValidatePayReqExpiry(payReq *zpay32.Invoice) error {
3✔
1343
        expiry := payReq.Expiry()
3✔
1344
        validUntil := payReq.Timestamp.Add(expiry)
3✔
1345
        if time.Now().After(validUntil) {
3✔
1346
                return fmt.Errorf("invoice expired. Valid until %v", validUntil)
×
1347
        }
×
1348

1349
        return nil
3✔
1350
}
1351

1352
// ValidateCLTVLimit returns a valid CLTV limit given a value and a maximum. If
1353
// the value exceeds the maximum, then an error is returned. If the value is 0,
1354
// then the maximum is used.
1355
func ValidateCLTVLimit(val, max uint32) (uint32, error) {
3✔
1356
        switch {
3✔
1357
        case val == 0:
3✔
1358
                return max, nil
3✔
1359
        case val > max:
×
1360
                return 0, fmt.Errorf("total time lock of %v exceeds max "+
×
1361
                        "allowed %v", val, max)
×
1362
        default:
×
1363
                return val, nil
×
1364
        }
1365
}
1366

1367
// UnmarshalMPP accepts the mpp_total_amt_msat and mpp_payment_addr fields from
1368
// an RPC request and converts into an record.MPP object. An error is returned
1369
// if the payment address is not 0 or 32 bytes. If the total amount and payment
1370
// address are zero-value, the return value will be nil signaling there is no
1371
// MPP record to attach to this hop. Otherwise, a non-nil reocrd will be
1372
// contained combining the provided values.
1373
func UnmarshalMPP(reqMPP *lnrpc.MPPRecord) (*record.MPP, error) {
3✔
1374
        // If no MPP record was submitted, assume the user wants to send a
3✔
1375
        // regular payment.
3✔
1376
        if reqMPP == nil {
6✔
1377
                return nil, nil
3✔
1378
        }
3✔
1379

1380
        reqTotal := reqMPP.TotalAmtMsat
3✔
1381
        reqAddr := reqMPP.PaymentAddr
3✔
1382

3✔
1383
        switch {
3✔
1384
        // No MPP fields were provided.
UNCOV
1385
        case reqTotal == 0 && len(reqAddr) == 0:
×
UNCOV
1386
                return nil, fmt.Errorf("missing total_msat and payment_addr")
×
1387

1388
        // Total is present, but payment address is missing.
UNCOV
1389
        case reqTotal > 0 && len(reqAddr) == 0:
×
UNCOV
1390
                return nil, fmt.Errorf("missing payment_addr")
×
1391

1392
        // Payment address is present, but total is missing.
UNCOV
1393
        case reqTotal == 0 && len(reqAddr) > 0:
×
UNCOV
1394
                return nil, fmt.Errorf("missing total_msat")
×
1395
        }
1396

1397
        addr, err := lntypes.MakeHash(reqAddr)
3✔
1398
        if err != nil {
3✔
UNCOV
1399
                return nil, fmt.Errorf("unable to parse "+
×
UNCOV
1400
                        "payment_addr: %v", err)
×
UNCOV
1401
        }
×
1402

1403
        total := lnwire.MilliSatoshi(reqTotal)
3✔
1404

3✔
1405
        return record.NewMPP(total, addr), nil
3✔
1406
}
1407

1408
func UnmarshalAMP(reqAMP *lnrpc.AMPRecord) (*record.AMP, error) {
3✔
1409
        if reqAMP == nil {
6✔
1410
                return nil, nil
3✔
1411
        }
3✔
1412

1413
        reqRootShare := reqAMP.RootShare
3✔
1414
        reqSetID := reqAMP.SetId
3✔
1415

3✔
1416
        switch {
3✔
UNCOV
1417
        case len(reqRootShare) != 32:
×
UNCOV
1418
                return nil, errors.New("AMP root_share must be 32 bytes")
×
1419

UNCOV
1420
        case len(reqSetID) != 32:
×
UNCOV
1421
                return nil, errors.New("AMP set_id must be 32 bytes")
×
1422
        }
1423

1424
        var (
3✔
1425
                rootShare [32]byte
3✔
1426
                setID     [32]byte
3✔
1427
        )
3✔
1428
        copy(rootShare[:], reqRootShare)
3✔
1429
        copy(setID[:], reqSetID)
3✔
1430

3✔
1431
        return record.NewAMP(rootShare, setID, reqAMP.ChildIndex), nil
3✔
1432
}
1433

1434
// MarshalHTLCAttempt constructs an RPC HTLCAttempt from the db representation.
1435
func (r *RouterBackend) MarshalHTLCAttempt(
1436
        htlc channeldb.HTLCAttempt) (*lnrpc.HTLCAttempt, error) {
3✔
1437

3✔
1438
        route, err := r.MarshallRoute(&htlc.Route)
3✔
1439
        if err != nil {
3✔
1440
                return nil, err
×
1441
        }
×
1442

1443
        rpcAttempt := &lnrpc.HTLCAttempt{
3✔
1444
                AttemptId:     htlc.AttemptID,
3✔
1445
                AttemptTimeNs: MarshalTimeNano(htlc.AttemptTime),
3✔
1446
                Route:         route,
3✔
1447
        }
3✔
1448

3✔
1449
        switch {
3✔
1450
        case htlc.Settle != nil:
3✔
1451
                rpcAttempt.Status = lnrpc.HTLCAttempt_SUCCEEDED
3✔
1452
                rpcAttempt.ResolveTimeNs = MarshalTimeNano(
3✔
1453
                        htlc.Settle.SettleTime,
3✔
1454
                )
3✔
1455
                rpcAttempt.Preimage = htlc.Settle.Preimage[:]
3✔
1456

1457
        case htlc.Failure != nil:
3✔
1458
                rpcAttempt.Status = lnrpc.HTLCAttempt_FAILED
3✔
1459
                rpcAttempt.ResolveTimeNs = MarshalTimeNano(
3✔
1460
                        htlc.Failure.FailTime,
3✔
1461
                )
3✔
1462

3✔
1463
                var err error
3✔
1464
                rpcAttempt.Failure, err = marshallHtlcFailure(htlc.Failure)
3✔
1465
                if err != nil {
3✔
1466
                        return nil, err
×
1467
                }
×
1468
        default:
3✔
1469
                rpcAttempt.Status = lnrpc.HTLCAttempt_IN_FLIGHT
3✔
1470
        }
1471

1472
        return rpcAttempt, nil
3✔
1473
}
1474

1475
// marshallHtlcFailure marshalls htlc fail info from the database to its rpc
1476
// representation.
1477
func marshallHtlcFailure(failure *channeldb.HTLCFailInfo) (*lnrpc.Failure,
1478
        error) {
3✔
1479

3✔
1480
        rpcFailure := &lnrpc.Failure{
3✔
1481
                FailureSourceIndex: failure.FailureSourceIndex,
3✔
1482
        }
3✔
1483

3✔
1484
        switch failure.Reason {
3✔
1485
        case channeldb.HTLCFailUnknown:
×
1486
                rpcFailure.Code = lnrpc.Failure_UNKNOWN_FAILURE
×
1487

1488
        case channeldb.HTLCFailUnreadable:
×
1489
                rpcFailure.Code = lnrpc.Failure_UNREADABLE_FAILURE
×
1490

1491
        case channeldb.HTLCFailInternal:
×
1492
                rpcFailure.Code = lnrpc.Failure_INTERNAL_FAILURE
×
1493

1494
        case channeldb.HTLCFailMessage:
3✔
1495
                err := marshallWireError(failure.Message, rpcFailure)
3✔
1496
                if err != nil {
3✔
1497
                        return nil, err
×
1498
                }
×
1499

1500
        default:
×
1501
                return nil, errors.New("unknown htlc failure reason")
×
1502
        }
1503

1504
        return rpcFailure, nil
3✔
1505
}
1506

1507
// MarshalTimeNano converts a time.Time into its nanosecond representation. If
1508
// the time is zero, this method simply returns 0, since calling UnixNano() on a
1509
// zero-valued time is undefined.
1510
func MarshalTimeNano(t time.Time) int64 {
3✔
1511
        if t.IsZero() {
3✔
UNCOV
1512
                return 0
×
UNCOV
1513
        }
×
1514
        return t.UnixNano()
3✔
1515
}
1516

1517
// marshallError marshall an error as received from the switch to rpc structs
1518
// suitable for returning to the caller of an rpc method.
1519
//
1520
// Because of difficulties with using protobuf oneof constructs in some
1521
// languages, the decision was made here to use a single message format for all
1522
// failure messages with some fields left empty depending on the failure type.
1523
func marshallError(sendError error) (*lnrpc.Failure, error) {
3✔
1524
        response := &lnrpc.Failure{}
3✔
1525

3✔
1526
        if sendError == htlcswitch.ErrUnreadableFailureMessage {
3✔
1527
                response.Code = lnrpc.Failure_UNREADABLE_FAILURE
×
1528
                return response, nil
×
1529
        }
×
1530

1531
        rtErr, ok := sendError.(htlcswitch.ClearTextError)
3✔
1532
        if !ok {
3✔
1533
                return nil, sendError
×
1534
        }
×
1535

1536
        err := marshallWireError(rtErr.WireMessage(), response)
3✔
1537
        if err != nil {
3✔
1538
                return nil, err
×
1539
        }
×
1540

1541
        // If the ClearTextError received is a ForwardingError, the error
1542
        // originated from a node along the route, not locally on our outgoing
1543
        // link. We set failureSourceIdx to the index of the node where the
1544
        // failure occurred. If the error is not a ForwardingError, the failure
1545
        // occurred at our node, so we leave the index as 0 to indicate that
1546
        // we failed locally.
1547
        fErr, ok := rtErr.(*htlcswitch.ForwardingError)
3✔
1548
        if ok {
3✔
1549
                response.FailureSourceIndex = uint32(fErr.FailureSourceIdx)
×
1550
        }
×
1551

1552
        return response, nil
3✔
1553
}
1554

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

3✔
1564
        switch onionErr := msg.(type) {
3✔
1565
        case *lnwire.FailIncorrectDetails:
3✔
1566
                response.Code = lnrpc.Failure_INCORRECT_OR_UNKNOWN_PAYMENT_DETAILS
3✔
1567
                response.Height = onionErr.Height()
3✔
1568

1569
        case *lnwire.FailIncorrectPaymentAmount:
×
1570
                response.Code = lnrpc.Failure_INCORRECT_PAYMENT_AMOUNT
×
1571

1572
        case *lnwire.FailFinalIncorrectCltvExpiry:
×
1573
                response.Code = lnrpc.Failure_FINAL_INCORRECT_CLTV_EXPIRY
×
1574
                response.CltvExpiry = onionErr.CltvExpiry
×
1575

1576
        case *lnwire.FailFinalIncorrectHtlcAmount:
×
1577
                response.Code = lnrpc.Failure_FINAL_INCORRECT_HTLC_AMOUNT
×
1578
                response.HtlcMsat = uint64(onionErr.IncomingHTLCAmount)
×
1579

1580
        case *lnwire.FailFinalExpiryTooSoon:
×
1581
                response.Code = lnrpc.Failure_FINAL_EXPIRY_TOO_SOON
×
1582

1583
        case *lnwire.FailInvalidRealm:
×
1584
                response.Code = lnrpc.Failure_INVALID_REALM
×
1585

1586
        case *lnwire.FailExpiryTooSoon:
×
1587
                response.Code = lnrpc.Failure_EXPIRY_TOO_SOON
×
1588
                response.ChannelUpdate = marshallChannelUpdate(&onionErr.Update)
×
1589

1590
        case *lnwire.FailExpiryTooFar:
×
1591
                response.Code = lnrpc.Failure_EXPIRY_TOO_FAR
×
1592

1593
        case *lnwire.FailInvalidOnionVersion:
3✔
1594
                response.Code = lnrpc.Failure_INVALID_ONION_VERSION
3✔
1595
                response.OnionSha_256 = onionErr.OnionSHA256[:]
3✔
1596

1597
        case *lnwire.FailInvalidOnionHmac:
×
1598
                response.Code = lnrpc.Failure_INVALID_ONION_HMAC
×
1599
                response.OnionSha_256 = onionErr.OnionSHA256[:]
×
1600

1601
        case *lnwire.FailInvalidOnionKey:
×
1602
                response.Code = lnrpc.Failure_INVALID_ONION_KEY
×
1603
                response.OnionSha_256 = onionErr.OnionSHA256[:]
×
1604

1605
        case *lnwire.FailAmountBelowMinimum:
×
1606
                response.Code = lnrpc.Failure_AMOUNT_BELOW_MINIMUM
×
1607
                response.ChannelUpdate = marshallChannelUpdate(&onionErr.Update)
×
1608
                response.HtlcMsat = uint64(onionErr.HtlcMsat)
×
1609

1610
        case *lnwire.FailFeeInsufficient:
3✔
1611
                response.Code = lnrpc.Failure_FEE_INSUFFICIENT
3✔
1612
                response.ChannelUpdate = marshallChannelUpdate(&onionErr.Update)
3✔
1613
                response.HtlcMsat = uint64(onionErr.HtlcMsat)
3✔
1614

1615
        case *lnwire.FailIncorrectCltvExpiry:
×
1616
                response.Code = lnrpc.Failure_INCORRECT_CLTV_EXPIRY
×
1617
                response.ChannelUpdate = marshallChannelUpdate(&onionErr.Update)
×
1618
                response.CltvExpiry = onionErr.CltvExpiry
×
1619

1620
        case *lnwire.FailChannelDisabled:
3✔
1621
                response.Code = lnrpc.Failure_CHANNEL_DISABLED
3✔
1622
                response.ChannelUpdate = marshallChannelUpdate(&onionErr.Update)
3✔
1623
                response.Flags = uint32(onionErr.Flags)
3✔
1624

1625
        case *lnwire.FailTemporaryChannelFailure:
3✔
1626
                response.Code = lnrpc.Failure_TEMPORARY_CHANNEL_FAILURE
3✔
1627
                response.ChannelUpdate = marshallChannelUpdate(onionErr.Update)
3✔
1628

1629
        case *lnwire.FailRequiredNodeFeatureMissing:
×
1630
                response.Code = lnrpc.Failure_REQUIRED_NODE_FEATURE_MISSING
×
1631

1632
        case *lnwire.FailRequiredChannelFeatureMissing:
×
1633
                response.Code = lnrpc.Failure_REQUIRED_CHANNEL_FEATURE_MISSING
×
1634

1635
        case *lnwire.FailUnknownNextPeer:
3✔
1636
                response.Code = lnrpc.Failure_UNKNOWN_NEXT_PEER
3✔
1637

1638
        case *lnwire.FailTemporaryNodeFailure:
×
1639
                response.Code = lnrpc.Failure_TEMPORARY_NODE_FAILURE
×
1640

1641
        case *lnwire.FailPermanentNodeFailure:
×
1642
                response.Code = lnrpc.Failure_PERMANENT_NODE_FAILURE
×
1643

1644
        case *lnwire.FailPermanentChannelFailure:
3✔
1645
                response.Code = lnrpc.Failure_PERMANENT_CHANNEL_FAILURE
3✔
1646

1647
        case *lnwire.FailMPPTimeout:
×
1648
                response.Code = lnrpc.Failure_MPP_TIMEOUT
×
1649

1650
        case *lnwire.InvalidOnionPayload:
3✔
1651
                response.Code = lnrpc.Failure_INVALID_ONION_PAYLOAD
3✔
1652

1653
        case *lnwire.FailInvalidBlinding:
3✔
1654
                response.Code = lnrpc.Failure_INVALID_ONION_BLINDING
3✔
1655
                response.OnionSha_256 = onionErr.OnionSHA256[:]
3✔
1656

1657
        case nil:
×
1658
                response.Code = lnrpc.Failure_UNKNOWN_FAILURE
×
1659

1660
        default:
×
1661
                return fmt.Errorf("cannot marshall failure %T", onionErr)
×
1662
        }
1663

1664
        return nil
3✔
1665
}
1666

1667
// marshallChannelUpdate marshalls a channel update as received over the wire to
1668
// the router rpc format.
1669
func marshallChannelUpdate(update *lnwire.ChannelUpdate1) *lnrpc.ChannelUpdate {
3✔
1670
        if update == nil {
3✔
1671
                return nil
×
1672
        }
×
1673

1674
        return &lnrpc.ChannelUpdate{
3✔
1675
                Signature:       update.Signature.RawBytes(),
3✔
1676
                ChainHash:       update.ChainHash[:],
3✔
1677
                ChanId:          update.ShortChannelID.ToUint64(),
3✔
1678
                Timestamp:       update.Timestamp,
3✔
1679
                MessageFlags:    uint32(update.MessageFlags),
3✔
1680
                ChannelFlags:    uint32(update.ChannelFlags),
3✔
1681
                TimeLockDelta:   uint32(update.TimeLockDelta),
3✔
1682
                HtlcMinimumMsat: uint64(update.HtlcMinimumMsat),
3✔
1683
                BaseFee:         update.BaseFee,
3✔
1684
                FeeRate:         update.FeeRate,
3✔
1685
                HtlcMaximumMsat: uint64(update.HtlcMaximumMsat),
3✔
1686
                ExtraOpaqueData: update.ExtraOpaqueData,
3✔
1687
        }
3✔
1688
}
1689

1690
// MarshallPayment marshall a payment to its rpc representation.
1691
func (r *RouterBackend) MarshallPayment(payment *channeldb.MPPayment) (
1692
        *lnrpc.Payment, error) {
3✔
1693

3✔
1694
        // Fetch the payment's preimage and the total paid in fees.
3✔
1695
        var (
3✔
1696
                fee      lnwire.MilliSatoshi
3✔
1697
                preimage lntypes.Preimage
3✔
1698
        )
3✔
1699
        for _, htlc := range payment.HTLCs {
6✔
1700
                // If any of the htlcs have settled, extract a valid
3✔
1701
                // preimage.
3✔
1702
                if htlc.Settle != nil {
6✔
1703
                        preimage = htlc.Settle.Preimage
3✔
1704
                        fee += htlc.Route.TotalFees()
3✔
1705
                }
3✔
1706
        }
1707

1708
        msatValue := int64(payment.Info.Value)
3✔
1709
        satValue := int64(payment.Info.Value.ToSatoshis())
3✔
1710

3✔
1711
        status, err := convertPaymentStatus(
3✔
1712
                payment.Status, r.UseStatusInitiated,
3✔
1713
        )
3✔
1714
        if err != nil {
3✔
1715
                return nil, err
×
1716
        }
×
1717

1718
        htlcs := make([]*lnrpc.HTLCAttempt, 0, len(payment.HTLCs))
3✔
1719
        for _, dbHTLC := range payment.HTLCs {
6✔
1720
                htlc, err := r.MarshalHTLCAttempt(dbHTLC)
3✔
1721
                if err != nil {
3✔
1722
                        return nil, err
×
1723
                }
×
1724

1725
                htlcs = append(htlcs, htlc)
3✔
1726
        }
1727

1728
        paymentID := payment.Info.PaymentIdentifier
3✔
1729
        creationTimeNS := MarshalTimeNano(payment.Info.CreationTime)
3✔
1730

3✔
1731
        failureReason, err := marshallPaymentFailureReason(
3✔
1732
                payment.FailureReason,
3✔
1733
        )
3✔
1734
        if err != nil {
3✔
1735
                return nil, err
×
1736
        }
×
1737

1738
        return &lnrpc.Payment{
3✔
1739
                // TODO: set this to setID for AMP-payments?
3✔
1740
                PaymentHash:           hex.EncodeToString(paymentID[:]),
3✔
1741
                Value:                 satValue,
3✔
1742
                ValueMsat:             msatValue,
3✔
1743
                ValueSat:              satValue,
3✔
1744
                CreationDate:          payment.Info.CreationTime.Unix(),
3✔
1745
                CreationTimeNs:        creationTimeNS,
3✔
1746
                Fee:                   int64(fee.ToSatoshis()),
3✔
1747
                FeeSat:                int64(fee.ToSatoshis()),
3✔
1748
                FeeMsat:               int64(fee),
3✔
1749
                PaymentPreimage:       hex.EncodeToString(preimage[:]),
3✔
1750
                PaymentRequest:        string(payment.Info.PaymentRequest),
3✔
1751
                Status:                status,
3✔
1752
                Htlcs:                 htlcs,
3✔
1753
                PaymentIndex:          payment.SequenceNum,
3✔
1754
                FailureReason:         failureReason,
3✔
1755
                FirstHopCustomRecords: payment.Info.FirstHopCustomRecords,
3✔
1756
        }, nil
3✔
1757
}
1758

1759
// convertPaymentStatus converts a channeldb.PaymentStatus to the type expected
1760
// by the RPC.
1761
func convertPaymentStatus(dbStatus channeldb.PaymentStatus, useInit bool) (
1762
        lnrpc.Payment_PaymentStatus, error) {
3✔
1763

3✔
1764
        switch dbStatus {
3✔
1765
        case channeldb.StatusInitiated:
3✔
1766
                // If the client understands the new status, return it.
3✔
1767
                if useInit {
6✔
1768
                        return lnrpc.Payment_INITIATED, nil
3✔
1769
                }
3✔
1770

1771
                // Otherwise remain the old behavior.
1772
                return lnrpc.Payment_IN_FLIGHT, nil
3✔
1773

1774
        case channeldb.StatusInFlight:
3✔
1775
                return lnrpc.Payment_IN_FLIGHT, nil
3✔
1776

1777
        case channeldb.StatusSucceeded:
3✔
1778
                return lnrpc.Payment_SUCCEEDED, nil
3✔
1779

1780
        case channeldb.StatusFailed:
3✔
1781
                return lnrpc.Payment_FAILED, nil
3✔
1782

1783
        default:
×
1784
                return 0, fmt.Errorf("unhandled payment status %v", dbStatus)
×
1785
        }
1786
}
1787

1788
// marshallPaymentFailureReason marshalls the failure reason to the corresponding rpc
1789
// type.
1790
func marshallPaymentFailureReason(reason *channeldb.FailureReason) (
1791
        lnrpc.PaymentFailureReason, error) {
3✔
1792

3✔
1793
        if reason == nil {
6✔
1794
                return lnrpc.PaymentFailureReason_FAILURE_REASON_NONE, nil
3✔
1795
        }
3✔
1796

1797
        switch *reason {
3✔
1798
        case channeldb.FailureReasonTimeout:
×
1799
                return lnrpc.PaymentFailureReason_FAILURE_REASON_TIMEOUT, nil
×
1800

1801
        case channeldb.FailureReasonNoRoute:
3✔
1802
                return lnrpc.PaymentFailureReason_FAILURE_REASON_NO_ROUTE, nil
3✔
1803

1804
        case channeldb.FailureReasonError:
3✔
1805
                return lnrpc.PaymentFailureReason_FAILURE_REASON_ERROR, nil
3✔
1806

1807
        case channeldb.FailureReasonPaymentDetails:
3✔
1808
                return lnrpc.PaymentFailureReason_FAILURE_REASON_INCORRECT_PAYMENT_DETAILS, nil
3✔
1809

1810
        case channeldb.FailureReasonInsufficientBalance:
3✔
1811
                return lnrpc.PaymentFailureReason_FAILURE_REASON_INSUFFICIENT_BALANCE, nil
3✔
1812

1813
        case channeldb.FailureReasonCanceled:
3✔
1814
                return lnrpc.PaymentFailureReason_FAILURE_REASON_CANCELED, nil
3✔
1815
        }
1816

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