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

lightningnetwork / lnd / 15561477203

10 Jun 2025 01:54PM UTC coverage: 58.351% (-10.1%) from 68.487%
15561477203

Pull #9356

github

web-flow
Merge 6440b25db into c6d6d4c0b
Pull Request #9356: lnrpc: add incoming/outgoing channel ids filter to forwarding history request

33 of 36 new or added lines in 2 files covered. (91.67%)

28366 existing lines in 455 files now uncovered.

97715 of 167461 relevant lines covered (58.35%)

1.81 hits per line

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

67.79
/lnrpc/routerrpc/router_backend.go
1
package routerrpc
2

3
import (
4
        "context"
5
        "crypto/rand"
6
        "encoding/hex"
7
        "errors"
8
        "fmt"
9
        math "math"
10
        "time"
11

12
        "github.com/btcsuite/btcd/btcec/v2"
13
        "github.com/btcsuite/btcd/btcutil"
14
        "github.com/btcsuite/btcd/chaincfg"
15
        "github.com/btcsuite/btcd/wire"
16
        sphinx "github.com/lightningnetwork/lightning-onion"
17
        "github.com/lightningnetwork/lnd/channeldb"
18
        "github.com/lightningnetwork/lnd/feature"
19
        "github.com/lightningnetwork/lnd/fn/v2"
20
        "github.com/lightningnetwork/lnd/htlcswitch"
21
        "github.com/lightningnetwork/lnd/lnrpc"
22
        "github.com/lightningnetwork/lnd/lntypes"
23
        "github.com/lightningnetwork/lnd/lnwire"
24
        "github.com/lightningnetwork/lnd/record"
25
        "github.com/lightningnetwork/lnd/routing"
26
        "github.com/lightningnetwork/lnd/routing/route"
27
        "github.com/lightningnetwork/lnd/subscribe"
28
        "github.com/lightningnetwork/lnd/zpay32"
29
        "google.golang.org/protobuf/proto"
30
)
31

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

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

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

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

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

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

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

69
        MissionControl MissionControl
70

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3✔
168
        routeReq, err := r.parseQueryRoutesRequest(in)
3✔
169
        if err != nil {
3✔
UNCOV
170
                return nil, err
×
UNCOV
171
        }
×
172

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

397
                        if !in.UseMissionControl {
6✔
398
                                return 1
3✔
399
                        }
3✔
400

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

551
        return path, nil
3✔
552
}
553

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

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

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

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

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

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

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

UNCOV
589
        return pair, nil
×
590
}
591

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

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

611
                resp.CustomChannelData = customData
3✔
612

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

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

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

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

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

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

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

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

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

688
        return resp, nil
3✔
689
}
690

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

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

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

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

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

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

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

739
        return hop, nil
3✔
740
}
741

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

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

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

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

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

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

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

793
                hops[i] = routeHop
3✔
794

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

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

808
        return route, nil
3✔
809
}
810

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

988
                // If the amount was not included in the invoice, then we let
989
                // the payer specify the amount of satoshis they wish to send.
990
                // We override the amount to pay with the amount provided from
991
                // the payment request.
992
                if payReq.MilliSat == nil {
3✔
993
                        if reqAmt == 0 {
×
994
                                return nil, errors.New("amount must be " +
×
995
                                        "specified when paying a zero amount " +
×
996
                                        "invoice")
×
997
                        }
×
998

999
                        payIntent.Amount = reqAmt
×
1000
                } else {
3✔
1001
                        if reqAmt != 0 {
3✔
1002
                                return nil, errors.New("amount must not be " +
×
1003
                                        "specified when paying a non-zero " +
×
1004
                                        " amount invoice")
×
1005
                        }
×
1006

1007
                        payIntent.Amount = *payReq.MilliSat
3✔
1008
                }
1009

1010
                if !payReq.Features.HasFeature(lnwire.MPPOptional) &&
3✔
1011
                        !payReq.Features.HasFeature(lnwire.AMPOptional) {
3✔
1012

×
1013
                        payIntent.MaxParts = 1
×
1014
                }
×
1015

1016
                payAddr := payReq.PaymentAddr
3✔
1017
                if payReq.Features.HasFeature(lnwire.AMPOptional) {
6✔
1018
                        // The opt-in AMP flag is required to pay an AMP
3✔
1019
                        // invoice.
3✔
1020
                        if !rpcPayReq.Amp {
3✔
1021
                                return nil, fmt.Errorf("the AMP flag (--amp " +
×
1022
                                        "or SendPaymentRequest.Amp) must be " +
×
1023
                                        "set to pay an AMP invoice")
×
1024
                        }
×
1025

1026
                        // Generate random SetID and root share.
1027
                        var setID [32]byte
3✔
1028
                        _, err = rand.Read(setID[:])
3✔
1029
                        if err != nil {
3✔
1030
                                return nil, err
×
1031
                        }
×
1032

1033
                        var rootShare [32]byte
3✔
1034
                        _, err = rand.Read(rootShare[:])
3✔
1035
                        if err != nil {
3✔
1036
                                return nil, err
×
1037
                        }
×
1038
                        err := payIntent.SetAMP(&routing.AMPOptions{
3✔
1039
                                SetID:     setID,
3✔
1040
                                RootShare: rootShare,
3✔
1041
                        })
3✔
1042
                        if err != nil {
3✔
1043
                                return nil, err
×
1044
                        }
×
1045

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

1066
                destKey := payReq.Destination.SerializeCompressed()
3✔
1067
                copy(payIntent.Target[:], destKey)
3✔
1068

3✔
1069
                payIntent.FinalCLTVDelta = uint16(payReq.MinFinalCLTVExpiry())
3✔
1070
                payIntent.RouteHints = append(
3✔
1071
                        payIntent.RouteHints, payReq.RouteHints...,
3✔
1072
                )
3✔
1073
                payIntent.DestFeatures = payReq.Features
3✔
1074
                payIntent.PaymentAddr = payAddr
3✔
1075
                payIntent.PaymentRequest = []byte(rpcPayReq.PaymentRequest)
3✔
1076
                payIntent.Metadata = payReq.Metadata
3✔
1077

3✔
1078
                if len(payReq.BlindedPaymentPaths) > 0 {
6✔
1079
                        pathSet, err := BuildBlindedPathSet(
3✔
1080
                                payReq.BlindedPaymentPaths,
3✔
1081
                        )
3✔
1082
                        if err != nil {
3✔
1083
                                return nil, err
×
1084
                        }
×
1085
                        payIntent.BlindedPathSet = pathSet
3✔
1086

3✔
1087
                        // Replace the target node with the target public key
3✔
1088
                        // of the blinded path set.
3✔
1089
                        copy(
3✔
1090
                                payIntent.Target[:],
3✔
1091
                                pathSet.TargetPubKey().SerializeCompressed(),
3✔
1092
                        )
3✔
1093

3✔
1094
                        pathFeatures := pathSet.Features()
3✔
1095
                        if !pathFeatures.IsEmpty() {
3✔
1096
                                payIntent.DestFeatures = pathFeatures.Clone()
×
1097
                        }
×
1098
                }
1099
        } else {
3✔
1100
                // Otherwise, If the payment request field was not specified
3✔
1101
                // (and a custom route wasn't specified), construct the payment
3✔
1102
                // from the other fields.
3✔
1103

3✔
1104
                // Payment destination.
3✔
1105
                target, err := route.NewVertexFromBytes(rpcPayReq.Dest)
3✔
1106
                if err != nil {
3✔
UNCOV
1107
                        return nil, err
×
UNCOV
1108
                }
×
1109
                payIntent.Target = target
3✔
1110

3✔
1111
                // Final payment CLTV delta.
3✔
1112
                if rpcPayReq.FinalCltvDelta != 0 {
6✔
1113
                        payIntent.FinalCLTVDelta =
3✔
1114
                                uint16(rpcPayReq.FinalCltvDelta)
3✔
1115
                } else {
6✔
1116
                        payIntent.FinalCLTVDelta = r.DefaultFinalCltvDelta
3✔
1117
                }
3✔
1118

1119
                // Amount.
1120
                if reqAmt == 0 {
3✔
UNCOV
1121
                        return nil, errors.New("amount must be specified")
×
UNCOV
1122
                }
×
1123

1124
                payIntent.Amount = reqAmt
3✔
1125

3✔
1126
                // Parse destination feature bits.
3✔
1127
                features, err := UnmarshalFeatures(rpcPayReq.DestFeatures)
3✔
1128
                if err != nil {
3✔
1129
                        return nil, err
×
1130
                }
×
1131

1132
                // Validate the features if any was specified.
1133
                if features != nil {
6✔
1134
                        err = feature.ValidateDeps(features)
3✔
1135
                        if err != nil {
3✔
1136
                                return nil, err
×
1137
                        }
×
1138
                }
1139

1140
                // If this is an AMP payment, we must generate the initial
1141
                // randomness.
1142
                if rpcPayReq.Amp {
6✔
1143
                        // If no destination features were specified, we set
3✔
1144
                        // those necessary for AMP payments.
3✔
1145
                        if features == nil {
6✔
1146
                                ampFeatures := []lnrpc.FeatureBit{
3✔
1147
                                        lnrpc.FeatureBit_TLV_ONION_OPT,
3✔
1148
                                        lnrpc.FeatureBit_PAYMENT_ADDR_OPT,
3✔
1149
                                        lnrpc.FeatureBit_AMP_OPT,
3✔
1150
                                }
3✔
1151

3✔
1152
                                features, err = UnmarshalFeatures(ampFeatures)
3✔
1153
                                if err != nil {
3✔
1154
                                        return nil, err
×
1155
                                }
×
1156
                        }
1157

1158
                        // First make sure the destination supports AMP.
1159
                        if !features.HasFeature(lnwire.AMPOptional) {
3✔
UNCOV
1160
                                return nil, fmt.Errorf("destination doesn't " +
×
UNCOV
1161
                                        "support AMP payments")
×
UNCOV
1162
                        }
×
1163

1164
                        // If no payment address is set, generate a random one.
1165
                        var payAddr [32]byte
3✔
1166
                        if len(rpcPayReq.PaymentAddr) == 0 {
6✔
1167
                                _, err = rand.Read(payAddr[:])
3✔
1168
                                if err != nil {
3✔
1169
                                        return nil, err
×
1170
                                }
×
1171
                        } else {
×
1172
                                copy(payAddr[:], rpcPayReq.PaymentAddr)
×
1173
                        }
×
1174
                        payIntent.PaymentAddr = fn.Some(payAddr)
3✔
1175

3✔
1176
                        // Generate random SetID and root share.
3✔
1177
                        var setID [32]byte
3✔
1178
                        _, err = rand.Read(setID[:])
3✔
1179
                        if err != nil {
3✔
1180
                                return nil, err
×
1181
                        }
×
1182

1183
                        var rootShare [32]byte
3✔
1184
                        _, err = rand.Read(rootShare[:])
3✔
1185
                        if err != nil {
3✔
1186
                                return nil, err
×
1187
                        }
×
1188
                        err := payIntent.SetAMP(&routing.AMPOptions{
3✔
1189
                                SetID:     setID,
3✔
1190
                                RootShare: rootShare,
3✔
1191
                        })
3✔
1192
                        if err != nil {
3✔
1193
                                return nil, err
×
1194
                        }
×
1195
                } else {
3✔
1196
                        // Payment hash.
3✔
1197
                        paymentHash, err := lntypes.MakeHash(rpcPayReq.PaymentHash)
3✔
1198
                        if err != nil {
3✔
UNCOV
1199
                                return nil, err
×
UNCOV
1200
                        }
×
1201

1202
                        err = payIntent.SetPaymentHash(paymentHash)
3✔
1203
                        if err != nil {
3✔
1204
                                return nil, err
×
1205
                        }
×
1206

1207
                        // If the payment addresses is specified, then we'll
1208
                        // also populate that now as well.
1209
                        if len(rpcPayReq.PaymentAddr) != 0 {
3✔
1210
                                var payAddr [32]byte
×
1211
                                copy(payAddr[:], rpcPayReq.PaymentAddr)
×
1212

×
1213
                                payIntent.PaymentAddr = fn.Some(payAddr)
×
1214
                        }
×
1215
                }
1216

1217
                payIntent.DestFeatures = features
3✔
1218
        }
1219

1220
        // Validate that the MPP parameters are compatible with the
1221
        // payment amount. In other words, the parameters are invalid if
1222
        // they do not permit sending the full payment amount.
1223
        if payIntent.MaxShardAmt != nil {
3✔
UNCOV
1224
                maxPossibleAmount := (*payIntent.MaxShardAmt) *
×
UNCOV
1225
                        lnwire.MilliSatoshi(payIntent.MaxParts)
×
UNCOV
1226

×
UNCOV
1227
                if payIntent.Amount > maxPossibleAmount {
×
UNCOV
1228
                        return nil, fmt.Errorf("payment amount %v exceeds "+
×
UNCOV
1229
                                "maximum possible amount %v with max_parts=%v "+
×
UNCOV
1230
                                "and max_shard_size_msat=%v", payIntent.Amount,
×
UNCOV
1231
                                maxPossibleAmount, payIntent.MaxParts,
×
UNCOV
1232
                                *payIntent.MaxShardAmt,
×
UNCOV
1233
                        )
×
UNCOV
1234
                }
×
1235
        }
1236

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

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

1251
        return payIntent, nil
3✔
1252
}
1253

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

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

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

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

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

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

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

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

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

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

1314
        return routeHints, nil
3✔
1315
}
1316

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

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

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

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

1345
        return featureBits
3✔
1346
}
1347

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

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

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

1368
        return lnwire.NewFeatureVector(raw, lnwire.Features), nil
3✔
1369
}
1370

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

1380
        return nil
3✔
1381
}
1382

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1503
        return rpcAttempt, nil
3✔
1504
}
1505

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

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

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

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

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

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

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

1535
        return rpcFailure, nil
3✔
1536
}
1537

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

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

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

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

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

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

1583
        return response, nil
3✔
1584
}
1585

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1666
        case *lnwire.FailUnknownNextPeer:
3✔
1667
                response.Code = lnrpc.Failure_UNKNOWN_NEXT_PEER
3✔
1668

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

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

1675
        case *lnwire.FailPermanentChannelFailure:
3✔
1676
                response.Code = lnrpc.Failure_PERMANENT_CHANNEL_FAILURE
3✔
1677

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

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

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

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

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

1695
        return nil
3✔
1696
}
1697

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1811
        case channeldb.StatusFailed:
3✔
1812
                return lnrpc.Payment_FAILED, nil
3✔
1813

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

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

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

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

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

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

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

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

1844
        case channeldb.FailureReasonCanceled:
3✔
1845
                return lnrpc.PaymentFailureReason_FAILURE_REASON_CANCELED, nil
3✔
1846
        }
1847

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