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

lightningnetwork / lnd / 13725358077

07 Mar 2025 04:51PM UTC coverage: 58.224% (-10.4%) from 68.615%
13725358077

Pull #9458

github

web-flow
Merge bf4c6625f into ab2dc09eb
Pull Request #9458: multi+server.go: add initial permissions for some peers

346 of 549 new or added lines in 10 files covered. (63.02%)

27466 existing lines in 443 files now uncovered.

94609 of 162492 relevant lines covered (58.22%)

1.81 hits per line

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

68.13
/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 {
3✔
869
                shardAmtMsat := lnwire.MilliSatoshi(rpcPayReq.MaxShardSizeMsat)
×
870
                payIntent.MaxShardAmt = &shardAmtMsat
×
871
        }
×
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
        firstHopRecords := lnwire.CustomRecords(rpcPayReq.FirstHopCustomRecords)
3✔
888
        if err := firstHopRecords.Validate(); err != nil {
3✔
889
                return nil, err
×
890
        }
×
891
        payIntent.FirstHopCustomRecords = firstHopRecords
3✔
892

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

902
                t := uint64(lnwire.ExperimentalEndorsementType)
3✔
903
                if _, set := payIntent.FirstHopCustomRecords[t]; !set {
6✔
904
                        payIntent.FirstHopCustomRecords[t] = []byte{
3✔
905
                                lnwire.ExperimentalUnendorsed,
3✔
906
                        }
3✔
907
                }
3✔
908
        }
909

910
        payIntent.PayAttemptTimeout = time.Second *
3✔
911
                time.Duration(rpcPayReq.TimeoutSeconds)
3✔
912

3✔
913
        // Route hints.
3✔
914
        routeHints, err := unmarshallRouteHints(
3✔
915
                rpcPayReq.RouteHints,
3✔
916
        )
3✔
917
        if err != nil {
3✔
918
                return nil, err
×
919
        }
×
920
        payIntent.RouteHints = routeHints
3✔
921

3✔
922
        // Unmarshall either sat or msat amount from request.
3✔
923
        reqAmt, err := lnrpc.UnmarshallAmt(
3✔
924
                rpcPayReq.Amt, rpcPayReq.AmtMsat,
3✔
925
        )
3✔
926
        if err != nil {
3✔
927
                return nil, err
×
928
        }
×
929

930
        // If the payment request field isn't blank, then the details of the
931
        // invoice are encoded entirely within the encoded payReq.  So we'll
932
        // attempt to decode it, populating the payment accordingly.
933
        if rpcPayReq.PaymentRequest != "" {
6✔
934
                switch {
3✔
935

936
                case len(rpcPayReq.Dest) > 0:
×
937
                        return nil, errors.New("dest and payment_request " +
×
938
                                "cannot appear together")
×
939

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

944
                case rpcPayReq.FinalCltvDelta != 0:
×
945
                        return nil, errors.New("final_cltv_delta and payment_request " +
×
946
                                "cannot appear together")
×
947
                }
948

949
                payReq, err := zpay32.Decode(
3✔
950
                        rpcPayReq.PaymentRequest, r.ActiveNetParams,
3✔
951
                )
3✔
952
                if err != nil {
3✔
953
                        return nil, err
×
954
                }
×
955

956
                // Next, we'll ensure that this payreq hasn't already expired.
957
                err = ValidatePayReqExpiry(payReq)
3✔
958
                if err != nil {
3✔
959
                        return nil, err
×
960
                }
×
961

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

973
                        payIntent.Amount = reqAmt
×
974
                } else {
3✔
975
                        if reqAmt != 0 {
3✔
976
                                return nil, errors.New("amount must not be " +
×
977
                                        "specified when paying a non-zero " +
×
978
                                        " amount invoice")
×
979
                        }
×
980

981
                        payIntent.Amount = *payReq.MilliSat
3✔
982
                }
983

984
                if !payReq.Features.HasFeature(lnwire.MPPOptional) &&
3✔
985
                        !payReq.Features.HasFeature(lnwire.AMPOptional) {
3✔
986

×
987
                        payIntent.MaxParts = 1
×
988
                }
×
989

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

1000
                        // Generate random SetID and root share.
1001
                        var setID [32]byte
3✔
1002
                        _, err = rand.Read(setID[:])
3✔
1003
                        if err != nil {
3✔
1004
                                return nil, err
×
1005
                        }
×
1006

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

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

1040
                destKey := payReq.Destination.SerializeCompressed()
3✔
1041
                copy(payIntent.Target[:], destKey)
3✔
1042

3✔
1043
                payIntent.FinalCLTVDelta = uint16(payReq.MinFinalCLTVExpiry())
3✔
1044
                payIntent.RouteHints = append(
3✔
1045
                        payIntent.RouteHints, payReq.RouteHints...,
3✔
1046
                )
3✔
1047
                payIntent.DestFeatures = payReq.Features
3✔
1048
                payIntent.PaymentAddr = payAddr
3✔
1049
                payIntent.PaymentRequest = []byte(rpcPayReq.PaymentRequest)
3✔
1050
                payIntent.Metadata = payReq.Metadata
3✔
1051

3✔
1052
                if len(payReq.BlindedPaymentPaths) > 0 {
6✔
1053
                        pathSet, err := BuildBlindedPathSet(
3✔
1054
                                payReq.BlindedPaymentPaths,
3✔
1055
                        )
3✔
1056
                        if err != nil {
3✔
1057
                                return nil, err
×
1058
                        }
×
1059
                        payIntent.BlindedPathSet = pathSet
3✔
1060

3✔
1061
                        // Replace the target node with the target public key
3✔
1062
                        // of the blinded path set.
3✔
1063
                        copy(
3✔
1064
                                payIntent.Target[:],
3✔
1065
                                pathSet.TargetPubKey().SerializeCompressed(),
3✔
1066
                        )
3✔
1067

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

3✔
1078
                // Payment destination.
3✔
1079
                target, err := route.NewVertexFromBytes(rpcPayReq.Dest)
3✔
1080
                if err != nil {
3✔
1081
                        return nil, err
×
1082
                }
×
1083
                payIntent.Target = target
3✔
1084

3✔
1085
                // Final payment CLTV delta.
3✔
1086
                if rpcPayReq.FinalCltvDelta != 0 {
6✔
1087
                        payIntent.FinalCLTVDelta =
3✔
1088
                                uint16(rpcPayReq.FinalCltvDelta)
3✔
1089
                } else {
6✔
1090
                        payIntent.FinalCLTVDelta = r.DefaultFinalCltvDelta
3✔
1091
                }
3✔
1092

1093
                // Amount.
1094
                if reqAmt == 0 {
3✔
1095
                        return nil, errors.New("amount must be specified")
×
1096
                }
×
1097

1098
                payIntent.Amount = reqAmt
3✔
1099

3✔
1100
                // Parse destination feature bits.
3✔
1101
                features, err := UnmarshalFeatures(rpcPayReq.DestFeatures)
3✔
1102
                if err != nil {
3✔
1103
                        return nil, err
×
1104
                }
×
1105

1106
                // Validate the features if any was specified.
1107
                if features != nil {
6✔
1108
                        err = feature.ValidateDeps(features)
3✔
1109
                        if err != nil {
3✔
1110
                                return nil, err
×
1111
                        }
×
1112
                }
1113

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

3✔
1126
                                features, err = UnmarshalFeatures(ampFeatures)
3✔
1127
                                if err != nil {
3✔
1128
                                        return nil, err
×
1129
                                }
×
1130
                        }
1131

1132
                        // First make sure the destination supports AMP.
1133
                        if !features.HasFeature(lnwire.AMPOptional) {
3✔
1134
                                return nil, fmt.Errorf("destination doesn't " +
×
1135
                                        "support AMP payments")
×
1136
                        }
×
1137

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

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

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

1176
                        err = payIntent.SetPaymentHash(paymentHash)
3✔
1177
                        if err != nil {
3✔
1178
                                return nil, err
×
1179
                        }
×
1180

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

×
1187
                                payIntent.PaymentAddr = fn.Some(payAddr)
×
1188
                        }
×
1189
                }
1190

1191
                payIntent.DestFeatures = features
3✔
1192
        }
1193

1194
        // Do bounds checking with the block padding so the router isn't
1195
        // left with a zombie payment in case the user messes up.
1196
        err = routing.ValidateCLTVLimit(
3✔
1197
                payIntent.CltvLimit, payIntent.FinalCLTVDelta, true,
3✔
1198
        )
3✔
1199
        if err != nil {
3✔
1200
                return nil, err
×
1201
        }
×
1202

1203
        // Check for disallowed payments to self.
1204
        if !rpcPayReq.AllowSelfPayment && payIntent.Target == r.SelfNode {
3✔
1205
                return nil, errors.New("self-payments not allowed")
×
1206
        }
×
1207

1208
        return payIntent, nil
3✔
1209
}
1210

1211
// BuildBlindedPathSet marshals a set of zpay32.BlindedPaymentPath and uses
1212
// the result to build a new routing.BlindedPaymentPathSet.
1213
func BuildBlindedPathSet(paths []*zpay32.BlindedPaymentPath) (
1214
        *routing.BlindedPaymentPathSet, error) {
3✔
1215

3✔
1216
        marshalledPaths := make([]*routing.BlindedPayment, len(paths))
3✔
1217
        for i, path := range paths {
6✔
1218
                paymentPath := marshalBlindedPayment(path)
3✔
1219

3✔
1220
                err := paymentPath.Validate()
3✔
1221
                if err != nil {
3✔
1222
                        return nil, err
×
1223
                }
×
1224

1225
                marshalledPaths[i] = paymentPath
3✔
1226
        }
1227

1228
        return routing.NewBlindedPaymentPathSet(marshalledPaths)
3✔
1229
}
1230

1231
// marshalBlindedPayment marshals a zpay32.BLindedPaymentPath into a
1232
// routing.BlindedPayment.
1233
func marshalBlindedPayment(
1234
        path *zpay32.BlindedPaymentPath) *routing.BlindedPayment {
3✔
1235

3✔
1236
        return &routing.BlindedPayment{
3✔
1237
                BlindedPath: &sphinx.BlindedPath{
3✔
1238
                        IntroductionPoint: path.Hops[0].BlindedNodePub,
3✔
1239
                        BlindingPoint:     path.FirstEphemeralBlindingPoint,
3✔
1240
                        BlindedHops:       path.Hops,
3✔
1241
                },
3✔
1242
                BaseFee:             path.FeeBaseMsat,
3✔
1243
                ProportionalFeeRate: path.FeeRate,
3✔
1244
                CltvExpiryDelta:     path.CltvExpiryDelta,
3✔
1245
                HtlcMinimum:         path.HTLCMinMsat,
3✔
1246
                HtlcMaximum:         path.HTLCMaxMsat,
3✔
1247
                Features:            path.Features,
3✔
1248
        }
3✔
1249
}
3✔
1250

1251
// unmarshallRouteHints unmarshalls a list of route hints.
1252
func unmarshallRouteHints(rpcRouteHints []*lnrpc.RouteHint) (
1253
        [][]zpay32.HopHint, error) {
3✔
1254

3✔
1255
        routeHints := make([][]zpay32.HopHint, 0, len(rpcRouteHints))
3✔
1256
        for _, rpcRouteHint := range rpcRouteHints {
6✔
1257
                routeHint := make(
3✔
1258
                        []zpay32.HopHint, 0, len(rpcRouteHint.HopHints),
3✔
1259
                )
3✔
1260
                for _, rpcHint := range rpcRouteHint.HopHints {
6✔
1261
                        hint, err := unmarshallHopHint(rpcHint)
3✔
1262
                        if err != nil {
3✔
1263
                                return nil, err
×
1264
                        }
×
1265

1266
                        routeHint = append(routeHint, hint)
3✔
1267
                }
1268
                routeHints = append(routeHints, routeHint)
3✔
1269
        }
1270

1271
        return routeHints, nil
3✔
1272
}
1273

1274
// unmarshallHopHint unmarshalls a single hop hint.
1275
func unmarshallHopHint(rpcHint *lnrpc.HopHint) (zpay32.HopHint, error) {
3✔
1276
        pubBytes, err := hex.DecodeString(rpcHint.NodeId)
3✔
1277
        if err != nil {
3✔
1278
                return zpay32.HopHint{}, err
×
1279
        }
×
1280

1281
        pubkey, err := btcec.ParsePubKey(pubBytes)
3✔
1282
        if err != nil {
3✔
1283
                return zpay32.HopHint{}, err
×
1284
        }
×
1285

1286
        return zpay32.HopHint{
3✔
1287
                NodeID:                    pubkey,
3✔
1288
                ChannelID:                 rpcHint.ChanId,
3✔
1289
                FeeBaseMSat:               rpcHint.FeeBaseMsat,
3✔
1290
                FeeProportionalMillionths: rpcHint.FeeProportionalMillionths,
3✔
1291
                CLTVExpiryDelta:           uint16(rpcHint.CltvExpiryDelta),
3✔
1292
        }, nil
3✔
1293
}
1294

1295
// MarshalFeatures converts a feature vector into a list of uint32's.
1296
func MarshalFeatures(feats *lnwire.FeatureVector) []lnrpc.FeatureBit {
3✔
1297
        var featureBits []lnrpc.FeatureBit
3✔
1298
        for feature := range feats.Features() {
6✔
1299
                featureBits = append(featureBits, lnrpc.FeatureBit(feature))
3✔
1300
        }
3✔
1301

1302
        return featureBits
3✔
1303
}
1304

1305
// UnmarshalFeatures converts a list of uint32's into a valid feature vector.
1306
// This method checks that feature bit pairs aren't assigned together, and
1307
// validates transitive dependencies.
1308
func UnmarshalFeatures(
1309
        rpcFeatures []lnrpc.FeatureBit) (*lnwire.FeatureVector, error) {
3✔
1310

3✔
1311
        // If no destination features are specified we'll return nil to signal
3✔
1312
        // that the router should try to use the graph as a fallback.
3✔
1313
        if rpcFeatures == nil {
6✔
1314
                return nil, nil
3✔
1315
        }
3✔
1316

1317
        raw := lnwire.NewRawFeatureVector()
3✔
1318
        for _, bit := range rpcFeatures {
6✔
1319
                err := raw.SafeSet(lnwire.FeatureBit(bit))
3✔
1320
                if err != nil {
3✔
1321
                        return nil, err
×
1322
                }
×
1323
        }
1324

1325
        return lnwire.NewFeatureVector(raw, lnwire.Features), nil
3✔
1326
}
1327

1328
// ValidatePayReqExpiry checks if the passed payment request has expired. In
1329
// the case it has expired, an error will be returned.
1330
func ValidatePayReqExpiry(payReq *zpay32.Invoice) error {
3✔
1331
        expiry := payReq.Expiry()
3✔
1332
        validUntil := payReq.Timestamp.Add(expiry)
3✔
1333
        if time.Now().After(validUntil) {
3✔
1334
                return fmt.Errorf("invoice expired. Valid until %v", validUntil)
×
1335
        }
×
1336

1337
        return nil
3✔
1338
}
1339

1340
// ValidateCLTVLimit returns a valid CLTV limit given a value and a maximum. If
1341
// the value exceeds the maximum, then an error is returned. If the value is 0,
1342
// then the maximum is used.
1343
func ValidateCLTVLimit(val, max uint32) (uint32, error) {
3✔
1344
        switch {
3✔
1345
        case val == 0:
3✔
1346
                return max, nil
3✔
1347
        case val > max:
×
1348
                return 0, fmt.Errorf("total time lock of %v exceeds max "+
×
1349
                        "allowed %v", val, max)
×
1350
        default:
×
1351
                return val, nil
×
1352
        }
1353
}
1354

1355
// UnmarshalMPP accepts the mpp_total_amt_msat and mpp_payment_addr fields from
1356
// an RPC request and converts into an record.MPP object. An error is returned
1357
// if the payment address is not 0 or 32 bytes. If the total amount and payment
1358
// address are zero-value, the return value will be nil signaling there is no
1359
// MPP record to attach to this hop. Otherwise, a non-nil reocrd will be
1360
// contained combining the provided values.
1361
func UnmarshalMPP(reqMPP *lnrpc.MPPRecord) (*record.MPP, error) {
3✔
1362
        // If no MPP record was submitted, assume the user wants to send a
3✔
1363
        // regular payment.
3✔
1364
        if reqMPP == nil {
6✔
1365
                return nil, nil
3✔
1366
        }
3✔
1367

1368
        reqTotal := reqMPP.TotalAmtMsat
3✔
1369
        reqAddr := reqMPP.PaymentAddr
3✔
1370

3✔
1371
        switch {
3✔
1372
        // No MPP fields were provided.
UNCOV
1373
        case reqTotal == 0 && len(reqAddr) == 0:
×
UNCOV
1374
                return nil, fmt.Errorf("missing total_msat and payment_addr")
×
1375

1376
        // Total is present, but payment address is missing.
UNCOV
1377
        case reqTotal > 0 && len(reqAddr) == 0:
×
UNCOV
1378
                return nil, fmt.Errorf("missing payment_addr")
×
1379

1380
        // Payment address is present, but total is missing.
UNCOV
1381
        case reqTotal == 0 && len(reqAddr) > 0:
×
UNCOV
1382
                return nil, fmt.Errorf("missing total_msat")
×
1383
        }
1384

1385
        addr, err := lntypes.MakeHash(reqAddr)
3✔
1386
        if err != nil {
3✔
UNCOV
1387
                return nil, fmt.Errorf("unable to parse "+
×
UNCOV
1388
                        "payment_addr: %v", err)
×
UNCOV
1389
        }
×
1390

1391
        total := lnwire.MilliSatoshi(reqTotal)
3✔
1392

3✔
1393
        return record.NewMPP(total, addr), nil
3✔
1394
}
1395

1396
func UnmarshalAMP(reqAMP *lnrpc.AMPRecord) (*record.AMP, error) {
3✔
1397
        if reqAMP == nil {
6✔
1398
                return nil, nil
3✔
1399
        }
3✔
1400

1401
        reqRootShare := reqAMP.RootShare
3✔
1402
        reqSetID := reqAMP.SetId
3✔
1403

3✔
1404
        switch {
3✔
UNCOV
1405
        case len(reqRootShare) != 32:
×
UNCOV
1406
                return nil, errors.New("AMP root_share must be 32 bytes")
×
1407

UNCOV
1408
        case len(reqSetID) != 32:
×
UNCOV
1409
                return nil, errors.New("AMP set_id must be 32 bytes")
×
1410
        }
1411

1412
        var (
3✔
1413
                rootShare [32]byte
3✔
1414
                setID     [32]byte
3✔
1415
        )
3✔
1416
        copy(rootShare[:], reqRootShare)
3✔
1417
        copy(setID[:], reqSetID)
3✔
1418

3✔
1419
        return record.NewAMP(rootShare, setID, reqAMP.ChildIndex), nil
3✔
1420
}
1421

1422
// MarshalHTLCAttempt constructs an RPC HTLCAttempt from the db representation.
1423
func (r *RouterBackend) MarshalHTLCAttempt(
1424
        htlc channeldb.HTLCAttempt) (*lnrpc.HTLCAttempt, error) {
3✔
1425

3✔
1426
        route, err := r.MarshallRoute(&htlc.Route)
3✔
1427
        if err != nil {
3✔
1428
                return nil, err
×
1429
        }
×
1430

1431
        rpcAttempt := &lnrpc.HTLCAttempt{
3✔
1432
                AttemptId:     htlc.AttemptID,
3✔
1433
                AttemptTimeNs: MarshalTimeNano(htlc.AttemptTime),
3✔
1434
                Route:         route,
3✔
1435
        }
3✔
1436

3✔
1437
        switch {
3✔
1438
        case htlc.Settle != nil:
3✔
1439
                rpcAttempt.Status = lnrpc.HTLCAttempt_SUCCEEDED
3✔
1440
                rpcAttempt.ResolveTimeNs = MarshalTimeNano(
3✔
1441
                        htlc.Settle.SettleTime,
3✔
1442
                )
3✔
1443
                rpcAttempt.Preimage = htlc.Settle.Preimage[:]
3✔
1444

1445
        case htlc.Failure != nil:
3✔
1446
                rpcAttempt.Status = lnrpc.HTLCAttempt_FAILED
3✔
1447
                rpcAttempt.ResolveTimeNs = MarshalTimeNano(
3✔
1448
                        htlc.Failure.FailTime,
3✔
1449
                )
3✔
1450

3✔
1451
                var err error
3✔
1452
                rpcAttempt.Failure, err = marshallHtlcFailure(htlc.Failure)
3✔
1453
                if err != nil {
3✔
1454
                        return nil, err
×
1455
                }
×
1456
        default:
3✔
1457
                rpcAttempt.Status = lnrpc.HTLCAttempt_IN_FLIGHT
3✔
1458
        }
1459

1460
        return rpcAttempt, nil
3✔
1461
}
1462

1463
// marshallHtlcFailure marshalls htlc fail info from the database to its rpc
1464
// representation.
1465
func marshallHtlcFailure(failure *channeldb.HTLCFailInfo) (*lnrpc.Failure,
1466
        error) {
3✔
1467

3✔
1468
        rpcFailure := &lnrpc.Failure{
3✔
1469
                FailureSourceIndex: failure.FailureSourceIndex,
3✔
1470
        }
3✔
1471

3✔
1472
        switch failure.Reason {
3✔
1473
        case channeldb.HTLCFailUnknown:
×
1474
                rpcFailure.Code = lnrpc.Failure_UNKNOWN_FAILURE
×
1475

1476
        case channeldb.HTLCFailUnreadable:
×
1477
                rpcFailure.Code = lnrpc.Failure_UNREADABLE_FAILURE
×
1478

1479
        case channeldb.HTLCFailInternal:
×
1480
                rpcFailure.Code = lnrpc.Failure_INTERNAL_FAILURE
×
1481

1482
        case channeldb.HTLCFailMessage:
3✔
1483
                err := marshallWireError(failure.Message, rpcFailure)
3✔
1484
                if err != nil {
3✔
1485
                        return nil, err
×
1486
                }
×
1487

1488
        default:
×
1489
                return nil, errors.New("unknown htlc failure reason")
×
1490
        }
1491

1492
        return rpcFailure, nil
3✔
1493
}
1494

1495
// MarshalTimeNano converts a time.Time into its nanosecond representation. If
1496
// the time is zero, this method simply returns 0, since calling UnixNano() on a
1497
// zero-valued time is undefined.
1498
func MarshalTimeNano(t time.Time) int64 {
3✔
1499
        if t.IsZero() {
3✔
UNCOV
1500
                return 0
×
UNCOV
1501
        }
×
1502
        return t.UnixNano()
3✔
1503
}
1504

1505
// marshallError marshall an error as received from the switch to rpc structs
1506
// suitable for returning to the caller of an rpc method.
1507
//
1508
// Because of difficulties with using protobuf oneof constructs in some
1509
// languages, the decision was made here to use a single message format for all
1510
// failure messages with some fields left empty depending on the failure type.
1511
func marshallError(sendError error) (*lnrpc.Failure, error) {
3✔
1512
        response := &lnrpc.Failure{}
3✔
1513

3✔
1514
        if sendError == htlcswitch.ErrUnreadableFailureMessage {
3✔
1515
                response.Code = lnrpc.Failure_UNREADABLE_FAILURE
×
1516
                return response, nil
×
1517
        }
×
1518

1519
        rtErr, ok := sendError.(htlcswitch.ClearTextError)
3✔
1520
        if !ok {
3✔
1521
                return nil, sendError
×
1522
        }
×
1523

1524
        err := marshallWireError(rtErr.WireMessage(), response)
3✔
1525
        if err != nil {
3✔
1526
                return nil, err
×
1527
        }
×
1528

1529
        // If the ClearTextError received is a ForwardingError, the error
1530
        // originated from a node along the route, not locally on our outgoing
1531
        // link. We set failureSourceIdx to the index of the node where the
1532
        // failure occurred. If the error is not a ForwardingError, the failure
1533
        // occurred at our node, so we leave the index as 0 to indicate that
1534
        // we failed locally.
1535
        fErr, ok := rtErr.(*htlcswitch.ForwardingError)
3✔
1536
        if ok {
3✔
1537
                response.FailureSourceIndex = uint32(fErr.FailureSourceIdx)
×
1538
        }
×
1539

1540
        return response, nil
3✔
1541
}
1542

1543
// marshallError marshall an error as received from the switch to rpc structs
1544
// suitable for returning to the caller of an rpc method.
1545
//
1546
// Because of difficulties with using protobuf oneof constructs in some
1547
// languages, the decision was made here to use a single message format for all
1548
// failure messages with some fields left empty depending on the failure type.
1549
func marshallWireError(msg lnwire.FailureMessage,
1550
        response *lnrpc.Failure) error {
3✔
1551

3✔
1552
        switch onionErr := msg.(type) {
3✔
1553
        case *lnwire.FailIncorrectDetails:
3✔
1554
                response.Code = lnrpc.Failure_INCORRECT_OR_UNKNOWN_PAYMENT_DETAILS
3✔
1555
                response.Height = onionErr.Height()
3✔
1556

1557
        case *lnwire.FailIncorrectPaymentAmount:
×
1558
                response.Code = lnrpc.Failure_INCORRECT_PAYMENT_AMOUNT
×
1559

1560
        case *lnwire.FailFinalIncorrectCltvExpiry:
×
1561
                response.Code = lnrpc.Failure_FINAL_INCORRECT_CLTV_EXPIRY
×
1562
                response.CltvExpiry = onionErr.CltvExpiry
×
1563

1564
        case *lnwire.FailFinalIncorrectHtlcAmount:
×
1565
                response.Code = lnrpc.Failure_FINAL_INCORRECT_HTLC_AMOUNT
×
1566
                response.HtlcMsat = uint64(onionErr.IncomingHTLCAmount)
×
1567

1568
        case *lnwire.FailFinalExpiryTooSoon:
×
1569
                response.Code = lnrpc.Failure_FINAL_EXPIRY_TOO_SOON
×
1570

1571
        case *lnwire.FailInvalidRealm:
×
1572
                response.Code = lnrpc.Failure_INVALID_REALM
×
1573

1574
        case *lnwire.FailExpiryTooSoon:
×
1575
                response.Code = lnrpc.Failure_EXPIRY_TOO_SOON
×
1576
                response.ChannelUpdate = marshallChannelUpdate(&onionErr.Update)
×
1577

1578
        case *lnwire.FailExpiryTooFar:
×
1579
                response.Code = lnrpc.Failure_EXPIRY_TOO_FAR
×
1580

1581
        case *lnwire.FailInvalidOnionVersion:
3✔
1582
                response.Code = lnrpc.Failure_INVALID_ONION_VERSION
3✔
1583
                response.OnionSha_256 = onionErr.OnionSHA256[:]
3✔
1584

1585
        case *lnwire.FailInvalidOnionHmac:
×
1586
                response.Code = lnrpc.Failure_INVALID_ONION_HMAC
×
1587
                response.OnionSha_256 = onionErr.OnionSHA256[:]
×
1588

1589
        case *lnwire.FailInvalidOnionKey:
×
1590
                response.Code = lnrpc.Failure_INVALID_ONION_KEY
×
1591
                response.OnionSha_256 = onionErr.OnionSHA256[:]
×
1592

1593
        case *lnwire.FailAmountBelowMinimum:
×
1594
                response.Code = lnrpc.Failure_AMOUNT_BELOW_MINIMUM
×
1595
                response.ChannelUpdate = marshallChannelUpdate(&onionErr.Update)
×
1596
                response.HtlcMsat = uint64(onionErr.HtlcMsat)
×
1597

1598
        case *lnwire.FailFeeInsufficient:
3✔
1599
                response.Code = lnrpc.Failure_FEE_INSUFFICIENT
3✔
1600
                response.ChannelUpdate = marshallChannelUpdate(&onionErr.Update)
3✔
1601
                response.HtlcMsat = uint64(onionErr.HtlcMsat)
3✔
1602

1603
        case *lnwire.FailIncorrectCltvExpiry:
×
1604
                response.Code = lnrpc.Failure_INCORRECT_CLTV_EXPIRY
×
1605
                response.ChannelUpdate = marshallChannelUpdate(&onionErr.Update)
×
1606
                response.CltvExpiry = onionErr.CltvExpiry
×
1607

1608
        case *lnwire.FailChannelDisabled:
3✔
1609
                response.Code = lnrpc.Failure_CHANNEL_DISABLED
3✔
1610
                response.ChannelUpdate = marshallChannelUpdate(&onionErr.Update)
3✔
1611
                response.Flags = uint32(onionErr.Flags)
3✔
1612

1613
        case *lnwire.FailTemporaryChannelFailure:
3✔
1614
                response.Code = lnrpc.Failure_TEMPORARY_CHANNEL_FAILURE
3✔
1615
                response.ChannelUpdate = marshallChannelUpdate(onionErr.Update)
3✔
1616

1617
        case *lnwire.FailRequiredNodeFeatureMissing:
×
1618
                response.Code = lnrpc.Failure_REQUIRED_NODE_FEATURE_MISSING
×
1619

1620
        case *lnwire.FailRequiredChannelFeatureMissing:
×
1621
                response.Code = lnrpc.Failure_REQUIRED_CHANNEL_FEATURE_MISSING
×
1622

1623
        case *lnwire.FailUnknownNextPeer:
3✔
1624
                response.Code = lnrpc.Failure_UNKNOWN_NEXT_PEER
3✔
1625

1626
        case *lnwire.FailTemporaryNodeFailure:
×
1627
                response.Code = lnrpc.Failure_TEMPORARY_NODE_FAILURE
×
1628

1629
        case *lnwire.FailPermanentNodeFailure:
×
1630
                response.Code = lnrpc.Failure_PERMANENT_NODE_FAILURE
×
1631

1632
        case *lnwire.FailPermanentChannelFailure:
3✔
1633
                response.Code = lnrpc.Failure_PERMANENT_CHANNEL_FAILURE
3✔
1634

1635
        case *lnwire.FailMPPTimeout:
×
1636
                response.Code = lnrpc.Failure_MPP_TIMEOUT
×
1637

1638
        case *lnwire.InvalidOnionPayload:
3✔
1639
                response.Code = lnrpc.Failure_INVALID_ONION_PAYLOAD
3✔
1640

1641
        case *lnwire.FailInvalidBlinding:
3✔
1642
                response.Code = lnrpc.Failure_INVALID_ONION_BLINDING
3✔
1643
                response.OnionSha_256 = onionErr.OnionSHA256[:]
3✔
1644

1645
        case nil:
×
1646
                response.Code = lnrpc.Failure_UNKNOWN_FAILURE
×
1647

1648
        default:
×
1649
                return fmt.Errorf("cannot marshall failure %T", onionErr)
×
1650
        }
1651

1652
        return nil
3✔
1653
}
1654

1655
// marshallChannelUpdate marshalls a channel update as received over the wire to
1656
// the router rpc format.
1657
func marshallChannelUpdate(update *lnwire.ChannelUpdate1) *lnrpc.ChannelUpdate {
3✔
1658
        if update == nil {
3✔
1659
                return nil
×
1660
        }
×
1661

1662
        return &lnrpc.ChannelUpdate{
3✔
1663
                Signature:       update.Signature.RawBytes(),
3✔
1664
                ChainHash:       update.ChainHash[:],
3✔
1665
                ChanId:          update.ShortChannelID.ToUint64(),
3✔
1666
                Timestamp:       update.Timestamp,
3✔
1667
                MessageFlags:    uint32(update.MessageFlags),
3✔
1668
                ChannelFlags:    uint32(update.ChannelFlags),
3✔
1669
                TimeLockDelta:   uint32(update.TimeLockDelta),
3✔
1670
                HtlcMinimumMsat: uint64(update.HtlcMinimumMsat),
3✔
1671
                BaseFee:         update.BaseFee,
3✔
1672
                FeeRate:         update.FeeRate,
3✔
1673
                HtlcMaximumMsat: uint64(update.HtlcMaximumMsat),
3✔
1674
                ExtraOpaqueData: update.ExtraOpaqueData,
3✔
1675
        }
3✔
1676
}
1677

1678
// MarshallPayment marshall a payment to its rpc representation.
1679
func (r *RouterBackend) MarshallPayment(payment *channeldb.MPPayment) (
1680
        *lnrpc.Payment, error) {
3✔
1681

3✔
1682
        // Fetch the payment's preimage and the total paid in fees.
3✔
1683
        var (
3✔
1684
                fee      lnwire.MilliSatoshi
3✔
1685
                preimage lntypes.Preimage
3✔
1686
        )
3✔
1687
        for _, htlc := range payment.HTLCs {
6✔
1688
                // If any of the htlcs have settled, extract a valid
3✔
1689
                // preimage.
3✔
1690
                if htlc.Settle != nil {
6✔
1691
                        preimage = htlc.Settle.Preimage
3✔
1692
                        fee += htlc.Route.TotalFees()
3✔
1693
                }
3✔
1694
        }
1695

1696
        msatValue := int64(payment.Info.Value)
3✔
1697
        satValue := int64(payment.Info.Value.ToSatoshis())
3✔
1698

3✔
1699
        status, err := convertPaymentStatus(
3✔
1700
                payment.Status, r.UseStatusInitiated,
3✔
1701
        )
3✔
1702
        if err != nil {
3✔
1703
                return nil, err
×
1704
        }
×
1705

1706
        htlcs := make([]*lnrpc.HTLCAttempt, 0, len(payment.HTLCs))
3✔
1707
        for _, dbHTLC := range payment.HTLCs {
6✔
1708
                htlc, err := r.MarshalHTLCAttempt(dbHTLC)
3✔
1709
                if err != nil {
3✔
1710
                        return nil, err
×
1711
                }
×
1712

1713
                htlcs = append(htlcs, htlc)
3✔
1714
        }
1715

1716
        paymentID := payment.Info.PaymentIdentifier
3✔
1717
        creationTimeNS := MarshalTimeNano(payment.Info.CreationTime)
3✔
1718

3✔
1719
        failureReason, err := marshallPaymentFailureReason(
3✔
1720
                payment.FailureReason,
3✔
1721
        )
3✔
1722
        if err != nil {
3✔
1723
                return nil, err
×
1724
        }
×
1725

1726
        return &lnrpc.Payment{
3✔
1727
                // TODO: set this to setID for AMP-payments?
3✔
1728
                PaymentHash:           hex.EncodeToString(paymentID[:]),
3✔
1729
                Value:                 satValue,
3✔
1730
                ValueMsat:             msatValue,
3✔
1731
                ValueSat:              satValue,
3✔
1732
                CreationDate:          payment.Info.CreationTime.Unix(),
3✔
1733
                CreationTimeNs:        creationTimeNS,
3✔
1734
                Fee:                   int64(fee.ToSatoshis()),
3✔
1735
                FeeSat:                int64(fee.ToSatoshis()),
3✔
1736
                FeeMsat:               int64(fee),
3✔
1737
                PaymentPreimage:       hex.EncodeToString(preimage[:]),
3✔
1738
                PaymentRequest:        string(payment.Info.PaymentRequest),
3✔
1739
                Status:                status,
3✔
1740
                Htlcs:                 htlcs,
3✔
1741
                PaymentIndex:          payment.SequenceNum,
3✔
1742
                FailureReason:         failureReason,
3✔
1743
                FirstHopCustomRecords: payment.Info.FirstHopCustomRecords,
3✔
1744
        }, nil
3✔
1745
}
1746

1747
// convertPaymentStatus converts a channeldb.PaymentStatus to the type expected
1748
// by the RPC.
1749
func convertPaymentStatus(dbStatus channeldb.PaymentStatus, useInit bool) (
1750
        lnrpc.Payment_PaymentStatus, error) {
3✔
1751

3✔
1752
        switch dbStatus {
3✔
1753
        case channeldb.StatusInitiated:
3✔
1754
                // If the client understands the new status, return it.
3✔
1755
                if useInit {
6✔
1756
                        return lnrpc.Payment_INITIATED, nil
3✔
1757
                }
3✔
1758

1759
                // Otherwise remain the old behavior.
1760
                return lnrpc.Payment_IN_FLIGHT, nil
3✔
1761

1762
        case channeldb.StatusInFlight:
3✔
1763
                return lnrpc.Payment_IN_FLIGHT, nil
3✔
1764

1765
        case channeldb.StatusSucceeded:
3✔
1766
                return lnrpc.Payment_SUCCEEDED, nil
3✔
1767

1768
        case channeldb.StatusFailed:
3✔
1769
                return lnrpc.Payment_FAILED, nil
3✔
1770

1771
        default:
×
1772
                return 0, fmt.Errorf("unhandled payment status %v", dbStatus)
×
1773
        }
1774
}
1775

1776
// marshallPaymentFailureReason marshalls the failure reason to the corresponding rpc
1777
// type.
1778
func marshallPaymentFailureReason(reason *channeldb.FailureReason) (
1779
        lnrpc.PaymentFailureReason, error) {
3✔
1780

3✔
1781
        if reason == nil {
6✔
1782
                return lnrpc.PaymentFailureReason_FAILURE_REASON_NONE, nil
3✔
1783
        }
3✔
1784

1785
        switch *reason {
3✔
1786
        case channeldb.FailureReasonTimeout:
×
1787
                return lnrpc.PaymentFailureReason_FAILURE_REASON_TIMEOUT, nil
×
1788

1789
        case channeldb.FailureReasonNoRoute:
3✔
1790
                return lnrpc.PaymentFailureReason_FAILURE_REASON_NO_ROUTE, nil
3✔
1791

1792
        case channeldb.FailureReasonError:
3✔
1793
                return lnrpc.PaymentFailureReason_FAILURE_REASON_ERROR, nil
3✔
1794

1795
        case channeldb.FailureReasonPaymentDetails:
3✔
1796
                return lnrpc.PaymentFailureReason_FAILURE_REASON_INCORRECT_PAYMENT_DETAILS, nil
3✔
1797

1798
        case channeldb.FailureReasonInsufficientBalance:
3✔
1799
                return lnrpc.PaymentFailureReason_FAILURE_REASON_INSUFFICIENT_BALANCE, nil
3✔
1800

1801
        case channeldb.FailureReasonCanceled:
3✔
1802
                return lnrpc.PaymentFailureReason_FAILURE_REASON_CANCELED, nil
3✔
1803
        }
1804

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