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

lightningnetwork / lnd / 15736109134

18 Jun 2025 02:46PM UTC coverage: 58.197% (-10.1%) from 68.248%
15736109134

Pull #9752

github

web-flow
Merge d2634a68c into 31c74f20f
Pull Request #9752: routerrpc: reject payment to invoice that don't have payment secret or blinded paths

6 of 13 new or added lines in 2 files covered. (46.15%)

28331 existing lines in 455 files now uncovered.

97860 of 168153 relevant lines covered (58.2%)

1.81 hits per line

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

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

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

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

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

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

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

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

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

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

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

70
        MissionControl MissionControl
71

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

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

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

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

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

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

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

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

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

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

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

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

123
        // Clock is the clock used to validate payment requests expiry.
124
        // It is useful for testing.
125
        Clock clock.Clock
126
}
127

128
// MissionControl defines the mission control dependencies of routerrpc.
129
type MissionControl interface {
130
        // GetProbability is expected to return the success probability of a
131
        // payment from fromNode to toNode.
132
        GetProbability(fromNode, toNode route.Vertex,
133
                amt lnwire.MilliSatoshi, capacity btcutil.Amount) float64
134

135
        // ResetHistory resets the history of MissionControl returning it to a
136
        // state as if no payment attempts have been made.
137
        ResetHistory() error
138

139
        // GetHistorySnapshot takes a snapshot from the current mission control
140
        // state and actual probability estimates.
141
        GetHistorySnapshot() *routing.MissionControlSnapshot
142

143
        // ImportHistory imports the mission control snapshot to our internal
144
        // state. This import will only be applied in-memory, and will not be
145
        // persisted across restarts.
146
        ImportHistory(snapshot *routing.MissionControlSnapshot, force bool) error
147

148
        // GetPairHistorySnapshot returns the stored history for a given node
149
        // pair.
150
        GetPairHistorySnapshot(fromNode,
151
                toNode route.Vertex) routing.TimedPairResult
152

153
        // GetConfig gets mission control's current config.
154
        GetConfig() *routing.MissionControlConfig
155

156
        // SetConfig sets mission control's config to the values provided, if
157
        // they are valid.
158
        SetConfig(cfg *routing.MissionControlConfig) error
159
}
160

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

3✔
173
        routeReq, err := r.parseQueryRoutesRequest(in)
3✔
174
        if err != nil {
3✔
UNCOV
175
                return nil, err
×
UNCOV
176
        }
×
177

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

186
        // For each valid route, we'll convert the result into the format
187
        // required by the RPC system.
188
        rpcRoute, err := r.MarshallRoute(route)
3✔
189
        if err != nil {
3✔
190
                return nil, err
×
191
        }
×
192

193
        routeResp := &lnrpc.QueryRoutesResponse{
3✔
194
                Routes:      []*lnrpc.Route{rpcRoute},
3✔
195
                SuccessProb: successProb,
3✔
196
        }
3✔
197

3✔
198
        return routeResp, nil
3✔
199
}
200

201
func parsePubKey(key string) (route.Vertex, error) {
3✔
202
        pubKeyBytes, err := hex.DecodeString(key)
3✔
203
        if err != nil {
3✔
204
                return route.Vertex{}, err
×
205
        }
×
206

207
        return route.NewVertexFromBytes(pubKeyBytes)
3✔
208
}
209

210
func (r *RouterBackend) parseIgnored(in *lnrpc.QueryRoutesRequest) (
211
        map[route.Vertex]struct{}, map[routing.DirectedNodePair]struct{},
212
        error) {
3✔
213

3✔
214
        ignoredNodes := make(map[route.Vertex]struct{})
3✔
215
        for _, ignorePubKey := range in.IgnoredNodes {
3✔
UNCOV
216
                ignoreVertex, err := route.NewVertexFromBytes(ignorePubKey)
×
UNCOV
217
                if err != nil {
×
218
                        return nil, nil, err
×
219
                }
×
UNCOV
220
                ignoredNodes[ignoreVertex] = struct{}{}
×
221
        }
222

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

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

×
232
                        continue
×
233
                }
UNCOV
234
                ignoredPairs[pair] = struct{}{}
×
235
        }
236

237
        // Add ignored pairs to set.
238
        for _, ignorePair := range in.IgnoredPairs {
3✔
UNCOV
239
                from, err := route.NewVertexFromBytes(ignorePair.From)
×
UNCOV
240
                if err != nil {
×
241
                        return nil, nil, err
×
242
                }
×
243

UNCOV
244
                to, err := route.NewVertexFromBytes(ignorePair.To)
×
UNCOV
245
                if err != nil {
×
246
                        return nil, nil, err
×
247
                }
×
248

UNCOV
249
                pair := routing.NewDirectedNodePair(from, to)
×
UNCOV
250
                ignoredPairs[pair] = struct{}{}
×
251
        }
252

253
        return ignoredNodes, ignoredPairs, nil
3✔
254
}
255

256
func (r *RouterBackend) parseQueryRoutesRequest(in *lnrpc.QueryRoutesRequest) (
257
        *routing.RouteRequest, error) {
3✔
258

3✔
259
        // Parse the hex-encoded source public key into a full public key that
3✔
260
        // we can properly manipulate.
3✔
261

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

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

282
        // Unmarshall restrictions from request.
283
        feeLimit := lnrpc.CalculateFeeLimit(in.FeeLimit, amt)
3✔
284

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

292
        cltvLimit, err := ValidateCLTVLimit(in.CltvLimit, maxTotalTimelock)
3✔
293
        if err != nil {
3✔
294
                return nil, err
×
295
        }
×
296

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

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

3✔
311
                // destinationFeatures is the set of features for the
3✔
312
                // destination node.
3✔
313
                destinationFeatures *lnwire.FeatureVector
3✔
314
        )
3✔
315

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

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

3✔
337
                // Convert route hints to an edge map.
3✔
338
                routeHints, err := unmarshallRouteHints(in.RouteHints)
3✔
339
                if err != nil {
3✔
340
                        return nil, err
×
341
                }
×
342

343
                routeHintEdges, err = routing.RouteHintsToEdges(
3✔
344
                        routeHints, *targetPubKey,
3✔
345
                )
3✔
346
                if err != nil {
3✔
347
                        return nil, err
×
348
                }
×
349

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

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

367
                // Parse destination feature bits.
368
                destinationFeatures, err = UnmarshalFeatures(in.DestFeatures)
3✔
369
                if err != nil {
3✔
370
                        return nil, err
×
371
                }
×
372
        }
373

374
        // We need to subtract the final delta before passing it into path
375
        // finding. The optimal path is independent of the final cltv delta and
376
        // the path finding algorithm is unaware of this value.
377
        cltvLimit -= uint32(finalCLTVDelta)
3✔
378

3✔
379
        ignoredNodes, ignoredPairs, err := r.parseIgnored(in)
3✔
380
        if err != nil {
3✔
381
                return nil, err
×
382
        }
×
383

384
        restrictions := &routing.RestrictParams{
3✔
385
                FeeLimit: feeLimit,
3✔
386
                ProbabilitySource: func(fromNode, toNode route.Vertex,
3✔
387
                        amt lnwire.MilliSatoshi,
3✔
388
                        capacity btcutil.Amount) float64 {
6✔
389

3✔
390
                        if _, ok := ignoredNodes[fromNode]; ok {
3✔
UNCOV
391
                                return 0
×
UNCOV
392
                        }
×
393

394
                        pair := routing.DirectedNodePair{
3✔
395
                                From: fromNode,
3✔
396
                                To:   toNode,
3✔
397
                        }
3✔
398
                        if _, ok := ignoredPairs[pair]; ok {
3✔
UNCOV
399
                                return 0
×
UNCOV
400
                        }
×
401

402
                        if !in.UseMissionControl {
6✔
403
                                return 1
3✔
404
                        }
3✔
405

UNCOV
406
                        return r.MissionControl.GetProbability(
×
UNCOV
407
                                fromNode, toNode, amt, capacity,
×
UNCOV
408
                        )
×
409
                },
410
                DestCustomRecords:     record.CustomSet(in.DestCustomRecords),
411
                CltvLimit:             cltvLimit,
412
                DestFeatures:          destinationFeatures,
413
                BlindedPaymentPathSet: blindedPathSet,
414
        }
415

416
        // Pass along an outgoing channel restriction if specified.
417
        if in.OutgoingChanId != 0 {
3✔
UNCOV
418
                restrictions.OutgoingChannelIDs = []uint64{in.OutgoingChanId}
×
UNCOV
419
        }
×
420

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

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

440
        return routing.NewRouteRequest(
3✔
441
                sourcePubKey, targetPubKey, amt, in.TimePref, restrictions,
3✔
442
                customRecords, routeHintEdges, blindedPathSet,
3✔
443
                finalCLTVDelta,
3✔
444
        )
3✔
445
}
446

447
func parseBlindedPaymentPaths(in *lnrpc.QueryRoutesRequest) (
448
        *routing.BlindedPaymentPathSet, error) {
3✔
449

3✔
450
        if len(in.PubKey) != 0 {
3✔
451
                return nil, fmt.Errorf("target pubkey: %x should not be set "+
×
452
                        "when blinded path is provided", in.PubKey)
×
453
        }
×
454

455
        if len(in.RouteHints) > 0 {
3✔
456
                return nil, errors.New("route hints and blinded path can't " +
×
457
                        "both be set")
×
458
        }
×
459

460
        if in.FinalCltvDelta != 0 {
3✔
461
                return nil, errors.New("final cltv delta should be " +
×
462
                        "zero for blinded paths")
×
463
        }
×
464

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

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

481
                if err := blindedPmt.Validate(); err != nil {
3✔
482
                        return nil, fmt.Errorf("invalid blinded path: %w", err)
×
483
                }
×
484

485
                paths[i] = blindedPmt
3✔
486
        }
487

488
        return routing.NewBlindedPaymentPathSet(paths)
3✔
489
}
490

491
func unmarshalBlindedPayment(rpcPayment *lnrpc.BlindedPaymentPath) (
492
        *routing.BlindedPayment, error) {
3✔
493

3✔
494
        if rpcPayment == nil {
3✔
495
                return nil, errors.New("nil blinded payment")
×
496
        }
×
497

498
        path, err := unmarshalBlindedPaymentPaths(rpcPayment.BlindedPath)
3✔
499
        if err != nil {
3✔
500
                return nil, err
×
501
        }
×
502

503
        features, err := UnmarshalFeatures(rpcPayment.Features)
3✔
504
        if err != nil {
3✔
505
                return nil, err
×
506
        }
×
507

508
        return &routing.BlindedPayment{
3✔
509
                BlindedPath:         path,
3✔
510
                CltvExpiryDelta:     uint16(rpcPayment.TotalCltvDelta),
3✔
511
                BaseFee:             uint32(rpcPayment.BaseFeeMsat),
3✔
512
                ProportionalFeeRate: rpcPayment.ProportionalFeeRate,
3✔
513
                HtlcMinimum:         rpcPayment.HtlcMinMsat,
3✔
514
                HtlcMaximum:         rpcPayment.HtlcMaxMsat,
3✔
515
                Features:            features,
3✔
516
        }, nil
3✔
517
}
518

519
func unmarshalBlindedPaymentPaths(rpcPath *lnrpc.BlindedPath) (
520
        *sphinx.BlindedPath, error) {
3✔
521

3✔
522
        if rpcPath == nil {
3✔
523
                return nil, errors.New("blinded path required when blinded " +
×
524
                        "route is provided")
×
525
        }
×
526

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

532
        blinding, err := btcec.ParsePubKey(rpcPath.BlindingPoint)
3✔
533
        if err != nil {
3✔
534
                return nil, err
×
535
        }
×
536

537
        if len(rpcPath.BlindedHops) < 1 {
3✔
538
                return nil, errors.New("at least 1 blinded hops required")
×
539
        }
×
540

541
        path := &sphinx.BlindedPath{
3✔
542
                IntroductionPoint: introduction,
3✔
543
                BlindingPoint:     blinding,
3✔
544
                BlindedHops: make(
3✔
545
                        []*sphinx.BlindedHopInfo, len(rpcPath.BlindedHops),
3✔
546
                ),
3✔
547
        }
3✔
548

3✔
549
        for i, hop := range rpcPath.BlindedHops {
6✔
550
                path.BlindedHops[i], err = unmarshalBlindedHop(hop)
3✔
551
                if err != nil {
3✔
552
                        return nil, err
×
553
                }
×
554
        }
555

556
        return path, nil
3✔
557
}
558

559
func unmarshalBlindedHop(rpcHop *lnrpc.BlindedHop) (*sphinx.BlindedHopInfo,
560
        error) {
3✔
561

3✔
562
        pubkey, err := btcec.ParsePubKey(rpcHop.BlindedNode)
3✔
563
        if err != nil {
3✔
564
                return nil, err
×
565
        }
×
566

567
        if len(rpcHop.EncryptedData) == 0 {
3✔
568
                return nil, errors.New("empty encrypted data not allowed")
×
569
        }
×
570

571
        return &sphinx.BlindedHopInfo{
3✔
572
                BlindedNodePub: pubkey,
3✔
573
                CipherText:     rpcHop.EncryptedData,
3✔
574
        }, nil
3✔
575
}
576

577
// rpcEdgeToPair looks up the provided channel and returns the channel endpoints
578
// as a directed pair.
579
func (r *RouterBackend) rpcEdgeToPair(e *lnrpc.EdgeLocator) (
UNCOV
580
        routing.DirectedNodePair, error) {
×
UNCOV
581

×
UNCOV
582
        a, b, err := r.FetchChannelEndpoints(e.ChannelId)
×
UNCOV
583
        if err != nil {
×
584
                return routing.DirectedNodePair{}, err
×
585
        }
×
586

UNCOV
587
        var pair routing.DirectedNodePair
×
UNCOV
588
        if e.DirectionReverse {
×
UNCOV
589
                pair.From, pair.To = b, a
×
UNCOV
590
        } else {
×
591
                pair.From, pair.To = a, b
×
592
        }
×
593

UNCOV
594
        return pair, nil
×
595
}
596

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

3✔
609
        // Encode the route's custom channel data (if available).
3✔
610
        if len(route.FirstHopWireCustomRecords) > 0 {
6✔
611
                customData, err := route.FirstHopWireCustomRecords.Serialize()
3✔
612
                if err != nil {
3✔
613
                        return nil, err
×
614
                }
×
615

616
                resp.CustomChannelData = customData
3✔
617

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

628
        incomingAmt := route.TotalAmount
3✔
629
        for i, hop := range route.Hops {
6✔
630
                fee := route.HopFee(i)
3✔
631

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

643
                // Extract the MPP fields if present on this hop.
644
                var mpp *lnrpc.MPPRecord
3✔
645
                if hop.MPP != nil {
6✔
646
                        addr := hop.MPP.PaymentAddr()
3✔
647

3✔
648
                        mpp = &lnrpc.MPPRecord{
3✔
649
                                PaymentAddr:  addr[:],
3✔
650
                                TotalAmtMsat: int64(hop.MPP.TotalMsat()),
3✔
651
                        }
3✔
652
                }
3✔
653

654
                var amp *lnrpc.AMPRecord
3✔
655
                if hop.AMP != nil {
6✔
656
                        rootShare := hop.AMP.RootShare()
3✔
657
                        setID := hop.AMP.SetID()
3✔
658

3✔
659
                        amp = &lnrpc.AMPRecord{
3✔
660
                                RootShare:  rootShare[:],
3✔
661
                                SetId:      setID[:],
3✔
662
                                ChildIndex: hop.AMP.ChildIndex(),
3✔
663
                        }
3✔
664
                }
3✔
665

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

3✔
686
                if hop.BlindingPoint != nil {
6✔
687
                        blinding := hop.BlindingPoint.SerializeCompressed()
3✔
688
                        resp.Hops[i].BlindingPoint = blinding
3✔
689
                }
3✔
690
                incomingAmt = hop.AmtToForward
3✔
691
        }
692

693
        return resp, nil
3✔
694
}
695

696
// UnmarshallHopWithPubkey unmarshalls an rpc hop for which the pubkey has
697
// already been extracted.
698
func UnmarshallHopWithPubkey(rpcHop *lnrpc.Hop, pubkey route.Vertex) (*route.Hop,
699
        error) {
3✔
700

3✔
701
        customRecords := record.CustomSet(rpcHop.CustomRecords)
3✔
702
        if err := customRecords.Validate(); err != nil {
3✔
703
                return nil, err
×
704
        }
×
705

706
        mpp, err := UnmarshalMPP(rpcHop.MppRecord)
3✔
707
        if err != nil {
3✔
708
                return nil, err
×
709
        }
×
710

711
        amp, err := UnmarshalAMP(rpcHop.AmpRecord)
3✔
712
        if err != nil {
3✔
713
                return nil, err
×
714
        }
×
715

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

3✔
729
        haveBlindingPoint := len(rpcHop.BlindingPoint) != 0
3✔
730
        if haveBlindingPoint {
6✔
731
                hop.BlindingPoint, err = btcec.ParsePubKey(
3✔
732
                        rpcHop.BlindingPoint,
3✔
733
                )
3✔
734
                if err != nil {
3✔
735
                        return nil, fmt.Errorf("blinding point: %w", err)
×
736
                }
×
737
        }
738

739
        if haveBlindingPoint && len(rpcHop.EncryptedData) == 0 {
3✔
740
                return nil, errors.New("encrypted data should be present if " +
×
741
                        "blinding point is provided")
×
742
        }
×
743

744
        return hop, nil
3✔
745
}
746

747
// UnmarshallHop unmarshalls an rpc hop that may or may not contain a node
748
// pubkey.
749
func (r *RouterBackend) UnmarshallHop(rpcHop *lnrpc.Hop,
750
        prevNodePubKey [33]byte) (*route.Hop, error) {
3✔
751

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

770
                switch {
×
771
                case prevNodePubKey == node1:
×
772
                        pubKeyBytes = node2
×
773
                case prevNodePubKey == node2:
×
774
                        pubKeyBytes = node1
×
775
                default:
×
776
                        return nil, fmt.Errorf("channel edge does not match " +
×
777
                                "expected node")
×
778
                }
779
        }
780

781
        return UnmarshallHopWithPubkey(rpcHop, pubKeyBytes)
3✔
782
}
783

784
// UnmarshallRoute unmarshalls an rpc route. For hops that don't specify a
785
// pubkey, the channel graph is queried.
786
func (r *RouterBackend) UnmarshallRoute(rpcroute *lnrpc.Route) (
787
        *route.Route, error) {
3✔
788

3✔
789
        prevNodePubKey := r.SelfNode
3✔
790

3✔
791
        hops := make([]*route.Hop, len(rpcroute.Hops))
3✔
792
        for i, hop := range rpcroute.Hops {
6✔
793
                routeHop, err := r.UnmarshallHop(hop, prevNodePubKey)
3✔
794
                if err != nil {
3✔
795
                        return nil, err
×
796
                }
×
797

798
                hops[i] = routeHop
3✔
799

3✔
800
                prevNodePubKey = routeHop.PubKeyBytes
3✔
801
        }
802

803
        route, err := route.NewRouteFromHops(
3✔
804
                lnwire.MilliSatoshi(rpcroute.TotalAmtMsat),
3✔
805
                rpcroute.TotalTimeLock,
3✔
806
                r.SelfNode,
3✔
807
                hops,
3✔
808
        )
3✔
809
        if err != nil {
3✔
810
                return nil, err
×
811
        }
×
812

813
        return route, nil
3✔
814
}
815

816
// extractIntentFromSendRequest attempts to parse the SendRequest details
817
// required to dispatch a client from the information presented by an RPC
818
// client.
819
func (r *RouterBackend) extractIntentFromSendRequest(
820
        rpcPayReq *SendPaymentRequest) (*routing.LightningPayment, error) {
3✔
821

3✔
822
        payIntent := &routing.LightningPayment{}
3✔
823

3✔
824
        // Pass along time preference.
3✔
825
        if rpcPayReq.TimePref < -1 || rpcPayReq.TimePref > 1 {
3✔
UNCOV
826
                return nil, errors.New("time preference out of range")
×
UNCOV
827
        }
×
828
        payIntent.TimePref = rpcPayReq.TimePref
3✔
829

3✔
830
        // Pass along restrictions on the outgoing channels that may be used.
3✔
831
        payIntent.OutgoingChannelIDs = rpcPayReq.OutgoingChanIds
3✔
832

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

840
                payIntent.OutgoingChannelIDs = append(
×
841
                        payIntent.OutgoingChannelIDs, rpcPayReq.OutgoingChanId,
×
842
                )
×
843
        }
844

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

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

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

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

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

892
        // Take fee limit from request.
893
        payIntent.FeeLimit, err = lnrpc.UnmarshallAmt(
3✔
894
                rpcPayReq.FeeLimitSat, rpcPayReq.FeeLimitMsat,
3✔
895
        )
3✔
896
        if err != nil {
3✔
UNCOV
897
                return nil, err
×
UNCOV
898
        }
×
899

900
        customRecords := record.CustomSet(rpcPayReq.DestCustomRecords)
3✔
901
        if err := customRecords.Validate(); err != nil {
3✔
UNCOV
902
                return nil, err
×
UNCOV
903
        }
×
904
        payIntent.DestCustomRecords = customRecords
3✔
905

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

918
        firstHopRecords := lnwire.CustomRecords(rpcPayReq.FirstHopCustomRecords)
3✔
919
        if err := firstHopRecords.Validate(); err != nil {
3✔
UNCOV
920
                return nil, err
×
UNCOV
921
        }
×
922
        payIntent.FirstHopCustomRecords = firstHopRecords
3✔
923

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

933
                t := uint64(lnwire.ExperimentalEndorsementType)
3✔
934
                if _, set := payIntent.FirstHopCustomRecords[t]; !set {
6✔
935
                        payIntent.FirstHopCustomRecords[t] = []byte{
3✔
936
                                lnwire.ExperimentalUnendorsed,
3✔
937
                        }
3✔
938
                }
3✔
939
        }
940

941
        payIntent.PayAttemptTimeout = time.Second *
3✔
942
                time.Duration(rpcPayReq.TimeoutSeconds)
3✔
943

3✔
944
        // Route hints.
3✔
945
        routeHints, err := unmarshallRouteHints(
3✔
946
                rpcPayReq.RouteHints,
3✔
947
        )
3✔
948
        if err != nil {
3✔
949
                return nil, err
×
950
        }
×
951
        payIntent.RouteHints = routeHints
3✔
952

3✔
953
        // Unmarshall either sat or msat amount from request.
3✔
954
        reqAmt, err := lnrpc.UnmarshallAmt(
3✔
955
                rpcPayReq.Amt, rpcPayReq.AmtMsat,
3✔
956
        )
3✔
957
        if err != nil {
3✔
UNCOV
958
                return nil, err
×
UNCOV
959
        }
×
960

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

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

UNCOV
971
                case len(rpcPayReq.PaymentHash) > 0:
×
UNCOV
972
                        return nil, errors.New("payment_hash and payment_request " +
×
UNCOV
973
                                "cannot appear together")
×
974

UNCOV
975
                case rpcPayReq.FinalCltvDelta != 0:
×
UNCOV
976
                        return nil, errors.New("final_cltv_delta and payment_request " +
×
UNCOV
977
                                "cannot appear together")
×
978
                }
979

980
                payReq, err := zpay32.Decode(
3✔
981
                        rpcPayReq.PaymentRequest, r.ActiveNetParams,
3✔
982
                )
3✔
983
                if err != nil {
3✔
UNCOV
984
                        return nil, err
×
UNCOV
985
                }
×
986

987
                // Next, we'll ensure that this payreq hasn't already expired.
988
                err = ValidatePayReqExpiry(payReq, r.Clock)
3✔
989
                if err != nil {
3✔
UNCOV
990
                        return nil, err
×
UNCOV
991
                }
×
992

993
                // An invoice must include either a payment address or
994
                // blinded paths.
995
                if payReq.PaymentAddr.IsNone() &&
3✔
996
                        len(payReq.BlindedPaymentPaths) == 0 {
3✔
NEW
997

×
NEW
998
                        return nil, errors.New("payment request must contain " +
×
NEW
999
                                "either a payment address or blinded paths")
×
NEW
1000
                }
×
1001

1002
                // If the amount was not included in the invoice, then we let
1003
                // the payer specify the amount of satoshis they wish to send.
1004
                // We override the amount to pay with the amount provided from
1005
                // the payment request.
1006
                if payReq.MilliSat == nil {
3✔
1007
                        if reqAmt == 0 {
×
1008
                                return nil, errors.New("amount must be " +
×
1009
                                        "specified when paying a zero amount " +
×
1010
                                        "invoice")
×
1011
                        }
×
1012

1013
                        payIntent.Amount = reqAmt
×
1014
                } else {
3✔
1015
                        if reqAmt != 0 {
3✔
1016
                                return nil, errors.New("amount must not be " +
×
1017
                                        "specified when paying a non-zero " +
×
NEW
1018
                                        "amount invoice")
×
1019
                        }
×
1020

1021
                        payIntent.Amount = *payReq.MilliSat
3✔
1022
                }
1023

1024
                if !payReq.Features.HasFeature(lnwire.MPPOptional) &&
3✔
1025
                        !payReq.Features.HasFeature(lnwire.AMPOptional) {
3✔
1026

×
1027
                        payIntent.MaxParts = 1
×
1028
                }
×
1029

1030
                payAddr := payReq.PaymentAddr
3✔
1031
                if payReq.Features.HasFeature(lnwire.AMPOptional) {
6✔
1032
                        // The opt-in AMP flag is required to pay an AMP
3✔
1033
                        // invoice.
3✔
1034
                        if !rpcPayReq.Amp {
3✔
1035
                                return nil, fmt.Errorf("the AMP flag (--amp " +
×
1036
                                        "or SendPaymentRequest.Amp) must be " +
×
1037
                                        "set to pay an AMP invoice")
×
1038
                        }
×
1039

1040
                        // Generate random SetID and root share.
1041
                        var setID [32]byte
3✔
1042
                        _, err = rand.Read(setID[:])
3✔
1043
                        if err != nil {
3✔
1044
                                return nil, err
×
1045
                        }
×
1046

1047
                        var rootShare [32]byte
3✔
1048
                        _, err = rand.Read(rootShare[:])
3✔
1049
                        if err != nil {
3✔
1050
                                return nil, err
×
1051
                        }
×
1052
                        err := payIntent.SetAMP(&routing.AMPOptions{
3✔
1053
                                SetID:     setID,
3✔
1054
                                RootShare: rootShare,
3✔
1055
                        })
3✔
1056
                        if err != nil {
3✔
1057
                                return nil, err
×
1058
                        }
×
1059

1060
                        // For AMP invoices, we'll allow users to override the
1061
                        // included payment addr to allow the invoice to be
1062
                        // pseudo-reusable, e.g. the invoice parameters are
1063
                        // reused (amt, cltv, hop hints, etc) even though the
1064
                        // payments will share different payment hashes.
1065
                        //
1066
                        // NOTE: This will only work when the peer has
1067
                        // spontaneous AMP payments enabled.
1068
                        if len(rpcPayReq.PaymentAddr) > 0 {
6✔
1069
                                var addr [32]byte
3✔
1070
                                copy(addr[:], rpcPayReq.PaymentAddr)
3✔
1071
                                payAddr = fn.Some(addr)
3✔
1072
                        }
3✔
1073
                } else {
3✔
1074
                        err = payIntent.SetPaymentHash(*payReq.PaymentHash)
3✔
1075
                        if err != nil {
3✔
1076
                                return nil, err
×
1077
                        }
×
1078
                }
1079

1080
                destKey := payReq.Destination.SerializeCompressed()
3✔
1081
                copy(payIntent.Target[:], destKey)
3✔
1082

3✔
1083
                payIntent.FinalCLTVDelta = uint16(payReq.MinFinalCLTVExpiry())
3✔
1084
                payIntent.RouteHints = append(
3✔
1085
                        payIntent.RouteHints, payReq.RouteHints...,
3✔
1086
                )
3✔
1087
                payIntent.DestFeatures = payReq.Features
3✔
1088
                payIntent.PaymentAddr = payAddr
3✔
1089
                payIntent.PaymentRequest = []byte(rpcPayReq.PaymentRequest)
3✔
1090
                payIntent.Metadata = payReq.Metadata
3✔
1091

3✔
1092
                if len(payReq.BlindedPaymentPaths) > 0 {
6✔
1093
                        pathSet, err := BuildBlindedPathSet(
3✔
1094
                                payReq.BlindedPaymentPaths,
3✔
1095
                        )
3✔
1096
                        if err != nil {
3✔
1097
                                return nil, err
×
1098
                        }
×
1099
                        payIntent.BlindedPathSet = pathSet
3✔
1100

3✔
1101
                        // Replace the target node with the target public key
3✔
1102
                        // of the blinded path set.
3✔
1103
                        copy(
3✔
1104
                                payIntent.Target[:],
3✔
1105
                                pathSet.TargetPubKey().SerializeCompressed(),
3✔
1106
                        )
3✔
1107

3✔
1108
                        pathFeatures := pathSet.Features()
3✔
1109
                        if !pathFeatures.IsEmpty() {
3✔
1110
                                payIntent.DestFeatures = pathFeatures.Clone()
×
1111
                        }
×
1112
                }
1113
        } else {
3✔
1114
                // Otherwise, If the payment request field was not specified
3✔
1115
                // (and a custom route wasn't specified), construct the payment
3✔
1116
                // from the other fields.
3✔
1117

3✔
1118
                // Payment destination.
3✔
1119
                target, err := route.NewVertexFromBytes(rpcPayReq.Dest)
3✔
1120
                if err != nil {
3✔
UNCOV
1121
                        return nil, err
×
UNCOV
1122
                }
×
1123
                payIntent.Target = target
3✔
1124

3✔
1125
                // Final payment CLTV delta.
3✔
1126
                if rpcPayReq.FinalCltvDelta != 0 {
6✔
1127
                        payIntent.FinalCLTVDelta =
3✔
1128
                                uint16(rpcPayReq.FinalCltvDelta)
3✔
1129
                } else {
6✔
1130
                        payIntent.FinalCLTVDelta = r.DefaultFinalCltvDelta
3✔
1131
                }
3✔
1132

1133
                // Amount.
1134
                if reqAmt == 0 {
3✔
UNCOV
1135
                        return nil, errors.New("amount must be specified")
×
UNCOV
1136
                }
×
1137

1138
                payIntent.Amount = reqAmt
3✔
1139

3✔
1140
                // Parse destination feature bits.
3✔
1141
                features, err := UnmarshalFeatures(rpcPayReq.DestFeatures)
3✔
1142
                if err != nil {
3✔
1143
                        return nil, err
×
1144
                }
×
1145

1146
                // Validate the features if any was specified.
1147
                if features != nil {
6✔
1148
                        err = feature.ValidateDeps(features)
3✔
1149
                        if err != nil {
3✔
1150
                                return nil, err
×
1151
                        }
×
1152
                }
1153

1154
                // If this is an AMP payment, we must generate the initial
1155
                // randomness.
1156
                if rpcPayReq.Amp {
6✔
1157
                        // If no destination features were specified, we set
3✔
1158
                        // those necessary for AMP payments.
3✔
1159
                        if features == nil {
6✔
1160
                                ampFeatures := []lnrpc.FeatureBit{
3✔
1161
                                        lnrpc.FeatureBit_TLV_ONION_OPT,
3✔
1162
                                        lnrpc.FeatureBit_PAYMENT_ADDR_OPT,
3✔
1163
                                        lnrpc.FeatureBit_AMP_OPT,
3✔
1164
                                }
3✔
1165

3✔
1166
                                features, err = UnmarshalFeatures(ampFeatures)
3✔
1167
                                if err != nil {
3✔
1168
                                        return nil, err
×
1169
                                }
×
1170
                        }
1171

1172
                        // First make sure the destination supports AMP.
1173
                        if !features.HasFeature(lnwire.AMPOptional) {
3✔
UNCOV
1174
                                return nil, fmt.Errorf("destination doesn't " +
×
UNCOV
1175
                                        "support AMP payments")
×
UNCOV
1176
                        }
×
1177

1178
                        // If no payment address is set, generate a random one.
1179
                        var payAddr [32]byte
3✔
1180
                        if len(rpcPayReq.PaymentAddr) == 0 {
6✔
1181
                                _, err = rand.Read(payAddr[:])
3✔
1182
                                if err != nil {
3✔
1183
                                        return nil, err
×
1184
                                }
×
1185
                        } else {
×
1186
                                copy(payAddr[:], rpcPayReq.PaymentAddr)
×
1187
                        }
×
1188
                        payIntent.PaymentAddr = fn.Some(payAddr)
3✔
1189

3✔
1190
                        // Generate random SetID and root share.
3✔
1191
                        var setID [32]byte
3✔
1192
                        _, err = rand.Read(setID[:])
3✔
1193
                        if err != nil {
3✔
1194
                                return nil, err
×
1195
                        }
×
1196

1197
                        var rootShare [32]byte
3✔
1198
                        _, err = rand.Read(rootShare[:])
3✔
1199
                        if err != nil {
3✔
1200
                                return nil, err
×
1201
                        }
×
1202
                        err := payIntent.SetAMP(&routing.AMPOptions{
3✔
1203
                                SetID:     setID,
3✔
1204
                                RootShare: rootShare,
3✔
1205
                        })
3✔
1206
                        if err != nil {
3✔
1207
                                return nil, err
×
1208
                        }
×
1209
                } else {
3✔
1210
                        // Payment hash.
3✔
1211
                        paymentHash, err := lntypes.MakeHash(rpcPayReq.PaymentHash)
3✔
1212
                        if err != nil {
3✔
UNCOV
1213
                                return nil, err
×
UNCOV
1214
                        }
×
1215

1216
                        err = payIntent.SetPaymentHash(paymentHash)
3✔
1217
                        if err != nil {
3✔
1218
                                return nil, err
×
1219
                        }
×
1220

1221
                        // If the payment addresses is specified, then we'll
1222
                        // also populate that now as well.
1223
                        if len(rpcPayReq.PaymentAddr) != 0 {
3✔
1224
                                var payAddr [32]byte
×
1225
                                copy(payAddr[:], rpcPayReq.PaymentAddr)
×
1226

×
1227
                                payIntent.PaymentAddr = fn.Some(payAddr)
×
1228
                        }
×
1229
                }
1230

1231
                payIntent.DestFeatures = features
3✔
1232
        }
1233

1234
        // Validate that the MPP parameters are compatible with the
1235
        // payment amount. In other words, the parameters are invalid if
1236
        // they do not permit sending the full payment amount.
1237
        if payIntent.MaxShardAmt != nil {
3✔
UNCOV
1238
                maxPossibleAmount := (*payIntent.MaxShardAmt) *
×
UNCOV
1239
                        lnwire.MilliSatoshi(payIntent.MaxParts)
×
UNCOV
1240

×
UNCOV
1241
                if payIntent.Amount > maxPossibleAmount {
×
UNCOV
1242
                        return nil, fmt.Errorf("payment amount %v exceeds "+
×
UNCOV
1243
                                "maximum possible amount %v with max_parts=%v "+
×
UNCOV
1244
                                "and max_shard_size_msat=%v", payIntent.Amount,
×
UNCOV
1245
                                maxPossibleAmount, payIntent.MaxParts,
×
UNCOV
1246
                                *payIntent.MaxShardAmt,
×
UNCOV
1247
                        )
×
UNCOV
1248
                }
×
1249
        }
1250

1251
        // Do bounds checking with the block padding so the router isn't
1252
        // left with a zombie payment in case the user messes up.
1253
        err = routing.ValidateCLTVLimit(
3✔
1254
                payIntent.CltvLimit, payIntent.FinalCLTVDelta, true,
3✔
1255
        )
3✔
1256
        if err != nil {
3✔
1257
                return nil, err
×
1258
        }
×
1259

1260
        // Check for disallowed payments to self.
1261
        if !rpcPayReq.AllowSelfPayment && payIntent.Target == r.SelfNode {
3✔
UNCOV
1262
                return nil, errors.New("self-payments not allowed")
×
UNCOV
1263
        }
×
1264

1265
        return payIntent, nil
3✔
1266
}
1267

1268
// BuildBlindedPathSet marshals a set of zpay32.BlindedPaymentPath and uses
1269
// the result to build a new routing.BlindedPaymentPathSet.
1270
func BuildBlindedPathSet(paths []*zpay32.BlindedPaymentPath) (
1271
        *routing.BlindedPaymentPathSet, error) {
3✔
1272

3✔
1273
        marshalledPaths := make([]*routing.BlindedPayment, len(paths))
3✔
1274
        for i, path := range paths {
6✔
1275
                paymentPath := marshalBlindedPayment(path)
3✔
1276

3✔
1277
                err := paymentPath.Validate()
3✔
1278
                if err != nil {
3✔
1279
                        return nil, err
×
1280
                }
×
1281

1282
                marshalledPaths[i] = paymentPath
3✔
1283
        }
1284

1285
        return routing.NewBlindedPaymentPathSet(marshalledPaths)
3✔
1286
}
1287

1288
// marshalBlindedPayment marshals a zpay32.BLindedPaymentPath into a
1289
// routing.BlindedPayment.
1290
func marshalBlindedPayment(
1291
        path *zpay32.BlindedPaymentPath) *routing.BlindedPayment {
3✔
1292

3✔
1293
        return &routing.BlindedPayment{
3✔
1294
                BlindedPath: &sphinx.BlindedPath{
3✔
1295
                        IntroductionPoint: path.Hops[0].BlindedNodePub,
3✔
1296
                        BlindingPoint:     path.FirstEphemeralBlindingPoint,
3✔
1297
                        BlindedHops:       path.Hops,
3✔
1298
                },
3✔
1299
                BaseFee:             path.FeeBaseMsat,
3✔
1300
                ProportionalFeeRate: path.FeeRate,
3✔
1301
                CltvExpiryDelta:     path.CltvExpiryDelta,
3✔
1302
                HtlcMinimum:         path.HTLCMinMsat,
3✔
1303
                HtlcMaximum:         path.HTLCMaxMsat,
3✔
1304
                Features:            path.Features,
3✔
1305
        }
3✔
1306
}
3✔
1307

1308
// unmarshallRouteHints unmarshalls a list of route hints.
1309
func unmarshallRouteHints(rpcRouteHints []*lnrpc.RouteHint) (
1310
        [][]zpay32.HopHint, error) {
3✔
1311

3✔
1312
        routeHints := make([][]zpay32.HopHint, 0, len(rpcRouteHints))
3✔
1313
        for _, rpcRouteHint := range rpcRouteHints {
6✔
1314
                routeHint := make(
3✔
1315
                        []zpay32.HopHint, 0, len(rpcRouteHint.HopHints),
3✔
1316
                )
3✔
1317
                for _, rpcHint := range rpcRouteHint.HopHints {
6✔
1318
                        hint, err := unmarshallHopHint(rpcHint)
3✔
1319
                        if err != nil {
3✔
1320
                                return nil, err
×
1321
                        }
×
1322

1323
                        routeHint = append(routeHint, hint)
3✔
1324
                }
1325
                routeHints = append(routeHints, routeHint)
3✔
1326
        }
1327

1328
        return routeHints, nil
3✔
1329
}
1330

1331
// unmarshallHopHint unmarshalls a single hop hint.
1332
func unmarshallHopHint(rpcHint *lnrpc.HopHint) (zpay32.HopHint, error) {
3✔
1333
        pubBytes, err := hex.DecodeString(rpcHint.NodeId)
3✔
1334
        if err != nil {
3✔
1335
                return zpay32.HopHint{}, err
×
1336
        }
×
1337

1338
        pubkey, err := btcec.ParsePubKey(pubBytes)
3✔
1339
        if err != nil {
3✔
1340
                return zpay32.HopHint{}, err
×
1341
        }
×
1342

1343
        return zpay32.HopHint{
3✔
1344
                NodeID:                    pubkey,
3✔
1345
                ChannelID:                 rpcHint.ChanId,
3✔
1346
                FeeBaseMSat:               rpcHint.FeeBaseMsat,
3✔
1347
                FeeProportionalMillionths: rpcHint.FeeProportionalMillionths,
3✔
1348
                CLTVExpiryDelta:           uint16(rpcHint.CltvExpiryDelta),
3✔
1349
        }, nil
3✔
1350
}
1351

1352
// MarshalFeatures converts a feature vector into a list of uint32's.
1353
func MarshalFeatures(feats *lnwire.FeatureVector) []lnrpc.FeatureBit {
3✔
1354
        var featureBits []lnrpc.FeatureBit
3✔
1355
        for feature := range feats.Features() {
6✔
1356
                featureBits = append(featureBits, lnrpc.FeatureBit(feature))
3✔
1357
        }
3✔
1358

1359
        return featureBits
3✔
1360
}
1361

1362
// UnmarshalFeatures converts a list of uint32's into a valid feature vector.
1363
// This method checks that feature bit pairs aren't assigned together, and
1364
// validates transitive dependencies.
1365
func UnmarshalFeatures(
1366
        rpcFeatures []lnrpc.FeatureBit) (*lnwire.FeatureVector, error) {
3✔
1367

3✔
1368
        // If no destination features are specified we'll return nil to signal
3✔
1369
        // that the router should try to use the graph as a fallback.
3✔
1370
        if rpcFeatures == nil {
6✔
1371
                return nil, nil
3✔
1372
        }
3✔
1373

1374
        raw := lnwire.NewRawFeatureVector()
3✔
1375
        for _, bit := range rpcFeatures {
6✔
1376
                err := raw.SafeSet(lnwire.FeatureBit(bit))
3✔
1377
                if err != nil {
3✔
1378
                        return nil, err
×
1379
                }
×
1380
        }
1381

1382
        return lnwire.NewFeatureVector(raw, lnwire.Features), nil
3✔
1383
}
1384

1385
// ValidatePayReqExpiry checks if the passed payment request has expired. In
1386
// the case it has expired, an error will be returned.
1387
func ValidatePayReqExpiry(payReq *zpay32.Invoice, clock clock.Clock) error {
3✔
1388
        expiry := payReq.Expiry()
3✔
1389
        validUntil := payReq.Timestamp.Add(expiry)
3✔
1390
        if clock.Now().After(validUntil) {
3✔
UNCOV
1391
                return fmt.Errorf("invoice expired. Valid until %v", validUntil)
×
UNCOV
1392
        }
×
1393

1394
        return nil
3✔
1395
}
1396

1397
// ValidateCLTVLimit returns a valid CLTV limit given a value and a maximum. If
1398
// the value exceeds the maximum, then an error is returned. If the value is 0,
1399
// then the maximum is used.
1400
func ValidateCLTVLimit(val, max uint32) (uint32, error) {
3✔
1401
        switch {
3✔
1402
        case val == 0:
3✔
1403
                return max, nil
3✔
UNCOV
1404
        case val > max:
×
UNCOV
1405
                return 0, fmt.Errorf("total time lock of %v exceeds max "+
×
UNCOV
1406
                        "allowed %v", val, max)
×
1407
        default:
×
1408
                return val, nil
×
1409
        }
1410
}
1411

1412
// UnmarshalMPP accepts the mpp_total_amt_msat and mpp_payment_addr fields from
1413
// an RPC request and converts into an record.MPP object. An error is returned
1414
// if the payment address is not 0 or 32 bytes. If the total amount and payment
1415
// address are zero-value, the return value will be nil signaling there is no
1416
// MPP record to attach to this hop. Otherwise, a non-nil reocrd will be
1417
// contained combining the provided values.
1418
func UnmarshalMPP(reqMPP *lnrpc.MPPRecord) (*record.MPP, error) {
3✔
1419
        // If no MPP record was submitted, assume the user wants to send a
3✔
1420
        // regular payment.
3✔
1421
        if reqMPP == nil {
6✔
1422
                return nil, nil
3✔
1423
        }
3✔
1424

1425
        reqTotal := reqMPP.TotalAmtMsat
3✔
1426
        reqAddr := reqMPP.PaymentAddr
3✔
1427

3✔
1428
        switch {
3✔
1429
        // No MPP fields were provided.
UNCOV
1430
        case reqTotal == 0 && len(reqAddr) == 0:
×
UNCOV
1431
                return nil, fmt.Errorf("missing total_msat and payment_addr")
×
1432

1433
        // Total is present, but payment address is missing.
UNCOV
1434
        case reqTotal > 0 && len(reqAddr) == 0:
×
UNCOV
1435
                return nil, fmt.Errorf("missing payment_addr")
×
1436

1437
        // Payment address is present, but total is missing.
UNCOV
1438
        case reqTotal == 0 && len(reqAddr) > 0:
×
UNCOV
1439
                return nil, fmt.Errorf("missing total_msat")
×
1440
        }
1441

1442
        addr, err := lntypes.MakeHash(reqAddr)
3✔
1443
        if err != nil {
3✔
UNCOV
1444
                return nil, fmt.Errorf("unable to parse "+
×
UNCOV
1445
                        "payment_addr: %v", err)
×
UNCOV
1446
        }
×
1447

1448
        total := lnwire.MilliSatoshi(reqTotal)
3✔
1449

3✔
1450
        return record.NewMPP(total, addr), nil
3✔
1451
}
1452

1453
func UnmarshalAMP(reqAMP *lnrpc.AMPRecord) (*record.AMP, error) {
3✔
1454
        if reqAMP == nil {
6✔
1455
                return nil, nil
3✔
1456
        }
3✔
1457

1458
        reqRootShare := reqAMP.RootShare
3✔
1459
        reqSetID := reqAMP.SetId
3✔
1460

3✔
1461
        switch {
3✔
UNCOV
1462
        case len(reqRootShare) != 32:
×
UNCOV
1463
                return nil, errors.New("AMP root_share must be 32 bytes")
×
1464

UNCOV
1465
        case len(reqSetID) != 32:
×
UNCOV
1466
                return nil, errors.New("AMP set_id must be 32 bytes")
×
1467
        }
1468

1469
        var (
3✔
1470
                rootShare [32]byte
3✔
1471
                setID     [32]byte
3✔
1472
        )
3✔
1473
        copy(rootShare[:], reqRootShare)
3✔
1474
        copy(setID[:], reqSetID)
3✔
1475

3✔
1476
        return record.NewAMP(rootShare, setID, reqAMP.ChildIndex), nil
3✔
1477
}
1478

1479
// MarshalHTLCAttempt constructs an RPC HTLCAttempt from the db representation.
1480
func (r *RouterBackend) MarshalHTLCAttempt(
1481
        htlc channeldb.HTLCAttempt) (*lnrpc.HTLCAttempt, error) {
3✔
1482

3✔
1483
        route, err := r.MarshallRoute(&htlc.Route)
3✔
1484
        if err != nil {
3✔
1485
                return nil, err
×
1486
        }
×
1487

1488
        rpcAttempt := &lnrpc.HTLCAttempt{
3✔
1489
                AttemptId:     htlc.AttemptID,
3✔
1490
                AttemptTimeNs: MarshalTimeNano(htlc.AttemptTime),
3✔
1491
                Route:         route,
3✔
1492
        }
3✔
1493

3✔
1494
        switch {
3✔
1495
        case htlc.Settle != nil:
3✔
1496
                rpcAttempt.Status = lnrpc.HTLCAttempt_SUCCEEDED
3✔
1497
                rpcAttempt.ResolveTimeNs = MarshalTimeNano(
3✔
1498
                        htlc.Settle.SettleTime,
3✔
1499
                )
3✔
1500
                rpcAttempt.Preimage = htlc.Settle.Preimage[:]
3✔
1501

1502
        case htlc.Failure != nil:
3✔
1503
                rpcAttempt.Status = lnrpc.HTLCAttempt_FAILED
3✔
1504
                rpcAttempt.ResolveTimeNs = MarshalTimeNano(
3✔
1505
                        htlc.Failure.FailTime,
3✔
1506
                )
3✔
1507

3✔
1508
                var err error
3✔
1509
                rpcAttempt.Failure, err = marshallHtlcFailure(htlc.Failure)
3✔
1510
                if err != nil {
3✔
1511
                        return nil, err
×
1512
                }
×
1513
        default:
3✔
1514
                rpcAttempt.Status = lnrpc.HTLCAttempt_IN_FLIGHT
3✔
1515
        }
1516

1517
        return rpcAttempt, nil
3✔
1518
}
1519

1520
// marshallHtlcFailure marshalls htlc fail info from the database to its rpc
1521
// representation.
1522
func marshallHtlcFailure(failure *channeldb.HTLCFailInfo) (*lnrpc.Failure,
1523
        error) {
3✔
1524

3✔
1525
        rpcFailure := &lnrpc.Failure{
3✔
1526
                FailureSourceIndex: failure.FailureSourceIndex,
3✔
1527
        }
3✔
1528

3✔
1529
        switch failure.Reason {
3✔
1530
        case channeldb.HTLCFailUnknown:
×
1531
                rpcFailure.Code = lnrpc.Failure_UNKNOWN_FAILURE
×
1532

1533
        case channeldb.HTLCFailUnreadable:
×
1534
                rpcFailure.Code = lnrpc.Failure_UNREADABLE_FAILURE
×
1535

1536
        case channeldb.HTLCFailInternal:
×
1537
                rpcFailure.Code = lnrpc.Failure_INTERNAL_FAILURE
×
1538

1539
        case channeldb.HTLCFailMessage:
3✔
1540
                err := marshallWireError(failure.Message, rpcFailure)
3✔
1541
                if err != nil {
3✔
1542
                        return nil, err
×
1543
                }
×
1544

1545
        default:
×
1546
                return nil, errors.New("unknown htlc failure reason")
×
1547
        }
1548

1549
        return rpcFailure, nil
3✔
1550
}
1551

1552
// MarshalTimeNano converts a time.Time into its nanosecond representation. If
1553
// the time is zero, this method simply returns 0, since calling UnixNano() on a
1554
// zero-valued time is undefined.
1555
func MarshalTimeNano(t time.Time) int64 {
3✔
1556
        if t.IsZero() {
3✔
UNCOV
1557
                return 0
×
UNCOV
1558
        }
×
1559
        return t.UnixNano()
3✔
1560
}
1561

1562
// marshallError marshall an error as received from the switch to rpc structs
1563
// suitable for returning to the caller of an rpc method.
1564
//
1565
// Because of difficulties with using protobuf oneof constructs in some
1566
// languages, the decision was made here to use a single message format for all
1567
// failure messages with some fields left empty depending on the failure type.
1568
func marshallError(sendError error) (*lnrpc.Failure, error) {
3✔
1569
        response := &lnrpc.Failure{}
3✔
1570

3✔
1571
        if sendError == htlcswitch.ErrUnreadableFailureMessage {
3✔
1572
                response.Code = lnrpc.Failure_UNREADABLE_FAILURE
×
1573
                return response, nil
×
1574
        }
×
1575

1576
        rtErr, ok := sendError.(htlcswitch.ClearTextError)
3✔
1577
        if !ok {
3✔
1578
                return nil, sendError
×
1579
        }
×
1580

1581
        err := marshallWireError(rtErr.WireMessage(), response)
3✔
1582
        if err != nil {
3✔
1583
                return nil, err
×
1584
        }
×
1585

1586
        // If the ClearTextError received is a ForwardingError, the error
1587
        // originated from a node along the route, not locally on our outgoing
1588
        // link. We set failureSourceIdx to the index of the node where the
1589
        // failure occurred. If the error is not a ForwardingError, the failure
1590
        // occurred at our node, so we leave the index as 0 to indicate that
1591
        // we failed locally.
1592
        fErr, ok := rtErr.(*htlcswitch.ForwardingError)
3✔
1593
        if ok {
3✔
1594
                response.FailureSourceIndex = uint32(fErr.FailureSourceIdx)
×
1595
        }
×
1596

1597
        return response, nil
3✔
1598
}
1599

1600
// marshallError marshall an error as received from the switch to rpc structs
1601
// suitable for returning to the caller of an rpc method.
1602
//
1603
// Because of difficulties with using protobuf oneof constructs in some
1604
// languages, the decision was made here to use a single message format for all
1605
// failure messages with some fields left empty depending on the failure type.
1606
func marshallWireError(msg lnwire.FailureMessage,
1607
        response *lnrpc.Failure) error {
3✔
1608

3✔
1609
        switch onionErr := msg.(type) {
3✔
1610
        case *lnwire.FailIncorrectDetails:
3✔
1611
                response.Code = lnrpc.Failure_INCORRECT_OR_UNKNOWN_PAYMENT_DETAILS
3✔
1612
                response.Height = onionErr.Height()
3✔
1613

1614
        case *lnwire.FailIncorrectPaymentAmount:
×
1615
                response.Code = lnrpc.Failure_INCORRECT_PAYMENT_AMOUNT
×
1616

1617
        case *lnwire.FailFinalIncorrectCltvExpiry:
×
1618
                response.Code = lnrpc.Failure_FINAL_INCORRECT_CLTV_EXPIRY
×
1619
                response.CltvExpiry = onionErr.CltvExpiry
×
1620

1621
        case *lnwire.FailFinalIncorrectHtlcAmount:
×
1622
                response.Code = lnrpc.Failure_FINAL_INCORRECT_HTLC_AMOUNT
×
1623
                response.HtlcMsat = uint64(onionErr.IncomingHTLCAmount)
×
1624

1625
        case *lnwire.FailFinalExpiryTooSoon:
×
1626
                response.Code = lnrpc.Failure_FINAL_EXPIRY_TOO_SOON
×
1627

1628
        case *lnwire.FailInvalidRealm:
×
1629
                response.Code = lnrpc.Failure_INVALID_REALM
×
1630

1631
        case *lnwire.FailExpiryTooSoon:
×
1632
                response.Code = lnrpc.Failure_EXPIRY_TOO_SOON
×
1633
                response.ChannelUpdate = marshallChannelUpdate(&onionErr.Update)
×
1634

1635
        case *lnwire.FailExpiryTooFar:
×
1636
                response.Code = lnrpc.Failure_EXPIRY_TOO_FAR
×
1637

1638
        case *lnwire.FailInvalidOnionVersion:
3✔
1639
                response.Code = lnrpc.Failure_INVALID_ONION_VERSION
3✔
1640
                response.OnionSha_256 = onionErr.OnionSHA256[:]
3✔
1641

1642
        case *lnwire.FailInvalidOnionHmac:
×
1643
                response.Code = lnrpc.Failure_INVALID_ONION_HMAC
×
1644
                response.OnionSha_256 = onionErr.OnionSHA256[:]
×
1645

1646
        case *lnwire.FailInvalidOnionKey:
×
1647
                response.Code = lnrpc.Failure_INVALID_ONION_KEY
×
1648
                response.OnionSha_256 = onionErr.OnionSHA256[:]
×
1649

1650
        case *lnwire.FailAmountBelowMinimum:
×
1651
                response.Code = lnrpc.Failure_AMOUNT_BELOW_MINIMUM
×
1652
                response.ChannelUpdate = marshallChannelUpdate(&onionErr.Update)
×
1653
                response.HtlcMsat = uint64(onionErr.HtlcMsat)
×
1654

1655
        case *lnwire.FailFeeInsufficient:
3✔
1656
                response.Code = lnrpc.Failure_FEE_INSUFFICIENT
3✔
1657
                response.ChannelUpdate = marshallChannelUpdate(&onionErr.Update)
3✔
1658
                response.HtlcMsat = uint64(onionErr.HtlcMsat)
3✔
1659

1660
        case *lnwire.FailIncorrectCltvExpiry:
×
1661
                response.Code = lnrpc.Failure_INCORRECT_CLTV_EXPIRY
×
1662
                response.ChannelUpdate = marshallChannelUpdate(&onionErr.Update)
×
1663
                response.CltvExpiry = onionErr.CltvExpiry
×
1664

1665
        case *lnwire.FailChannelDisabled:
3✔
1666
                response.Code = lnrpc.Failure_CHANNEL_DISABLED
3✔
1667
                response.ChannelUpdate = marshallChannelUpdate(&onionErr.Update)
3✔
1668
                response.Flags = uint32(onionErr.Flags)
3✔
1669

1670
        case *lnwire.FailTemporaryChannelFailure:
3✔
1671
                response.Code = lnrpc.Failure_TEMPORARY_CHANNEL_FAILURE
3✔
1672
                response.ChannelUpdate = marshallChannelUpdate(onionErr.Update)
3✔
1673

1674
        case *lnwire.FailRequiredNodeFeatureMissing:
×
1675
                response.Code = lnrpc.Failure_REQUIRED_NODE_FEATURE_MISSING
×
1676

1677
        case *lnwire.FailRequiredChannelFeatureMissing:
×
1678
                response.Code = lnrpc.Failure_REQUIRED_CHANNEL_FEATURE_MISSING
×
1679

1680
        case *lnwire.FailUnknownNextPeer:
3✔
1681
                response.Code = lnrpc.Failure_UNKNOWN_NEXT_PEER
3✔
1682

1683
        case *lnwire.FailTemporaryNodeFailure:
×
1684
                response.Code = lnrpc.Failure_TEMPORARY_NODE_FAILURE
×
1685

1686
        case *lnwire.FailPermanentNodeFailure:
×
1687
                response.Code = lnrpc.Failure_PERMANENT_NODE_FAILURE
×
1688

1689
        case *lnwire.FailPermanentChannelFailure:
3✔
1690
                response.Code = lnrpc.Failure_PERMANENT_CHANNEL_FAILURE
3✔
1691

1692
        case *lnwire.FailMPPTimeout:
×
1693
                response.Code = lnrpc.Failure_MPP_TIMEOUT
×
1694

1695
        case *lnwire.InvalidOnionPayload:
3✔
1696
                response.Code = lnrpc.Failure_INVALID_ONION_PAYLOAD
3✔
1697

1698
        case *lnwire.FailInvalidBlinding:
3✔
1699
                response.Code = lnrpc.Failure_INVALID_ONION_BLINDING
3✔
1700
                response.OnionSha_256 = onionErr.OnionSHA256[:]
3✔
1701

1702
        case nil:
×
1703
                response.Code = lnrpc.Failure_UNKNOWN_FAILURE
×
1704

1705
        default:
×
1706
                return fmt.Errorf("cannot marshall failure %T", onionErr)
×
1707
        }
1708

1709
        return nil
3✔
1710
}
1711

1712
// marshallChannelUpdate marshalls a channel update as received over the wire to
1713
// the router rpc format.
1714
func marshallChannelUpdate(update *lnwire.ChannelUpdate1) *lnrpc.ChannelUpdate {
3✔
1715
        if update == nil {
3✔
1716
                return nil
×
1717
        }
×
1718

1719
        return &lnrpc.ChannelUpdate{
3✔
1720
                Signature:       update.Signature.RawBytes(),
3✔
1721
                ChainHash:       update.ChainHash[:],
3✔
1722
                ChanId:          update.ShortChannelID.ToUint64(),
3✔
1723
                Timestamp:       update.Timestamp,
3✔
1724
                MessageFlags:    uint32(update.MessageFlags),
3✔
1725
                ChannelFlags:    uint32(update.ChannelFlags),
3✔
1726
                TimeLockDelta:   uint32(update.TimeLockDelta),
3✔
1727
                HtlcMinimumMsat: uint64(update.HtlcMinimumMsat),
3✔
1728
                BaseFee:         update.BaseFee,
3✔
1729
                FeeRate:         update.FeeRate,
3✔
1730
                HtlcMaximumMsat: uint64(update.HtlcMaximumMsat),
3✔
1731
                ExtraOpaqueData: update.ExtraOpaqueData,
3✔
1732
        }
3✔
1733
}
1734

1735
// MarshallPayment marshall a payment to its rpc representation.
1736
func (r *RouterBackend) MarshallPayment(payment *channeldb.MPPayment) (
1737
        *lnrpc.Payment, error) {
3✔
1738

3✔
1739
        // Fetch the payment's preimage and the total paid in fees.
3✔
1740
        var (
3✔
1741
                fee      lnwire.MilliSatoshi
3✔
1742
                preimage lntypes.Preimage
3✔
1743
        )
3✔
1744
        for _, htlc := range payment.HTLCs {
6✔
1745
                // If any of the htlcs have settled, extract a valid
3✔
1746
                // preimage.
3✔
1747
                if htlc.Settle != nil {
6✔
1748
                        preimage = htlc.Settle.Preimage
3✔
1749
                        fee += htlc.Route.TotalFees()
3✔
1750
                }
3✔
1751
        }
1752

1753
        msatValue := int64(payment.Info.Value)
3✔
1754
        satValue := int64(payment.Info.Value.ToSatoshis())
3✔
1755

3✔
1756
        status, err := convertPaymentStatus(
3✔
1757
                payment.Status, r.UseStatusInitiated,
3✔
1758
        )
3✔
1759
        if err != nil {
3✔
1760
                return nil, err
×
1761
        }
×
1762

1763
        htlcs := make([]*lnrpc.HTLCAttempt, 0, len(payment.HTLCs))
3✔
1764
        for _, dbHTLC := range payment.HTLCs {
6✔
1765
                htlc, err := r.MarshalHTLCAttempt(dbHTLC)
3✔
1766
                if err != nil {
3✔
1767
                        return nil, err
×
1768
                }
×
1769

1770
                htlcs = append(htlcs, htlc)
3✔
1771
        }
1772

1773
        paymentID := payment.Info.PaymentIdentifier
3✔
1774
        creationTimeNS := MarshalTimeNano(payment.Info.CreationTime)
3✔
1775

3✔
1776
        failureReason, err := marshallPaymentFailureReason(
3✔
1777
                payment.FailureReason,
3✔
1778
        )
3✔
1779
        if err != nil {
3✔
1780
                return nil, err
×
1781
        }
×
1782

1783
        return &lnrpc.Payment{
3✔
1784
                // TODO: set this to setID for AMP-payments?
3✔
1785
                PaymentHash:           hex.EncodeToString(paymentID[:]),
3✔
1786
                Value:                 satValue,
3✔
1787
                ValueMsat:             msatValue,
3✔
1788
                ValueSat:              satValue,
3✔
1789
                CreationDate:          payment.Info.CreationTime.Unix(),
3✔
1790
                CreationTimeNs:        creationTimeNS,
3✔
1791
                Fee:                   int64(fee.ToSatoshis()),
3✔
1792
                FeeSat:                int64(fee.ToSatoshis()),
3✔
1793
                FeeMsat:               int64(fee),
3✔
1794
                PaymentPreimage:       hex.EncodeToString(preimage[:]),
3✔
1795
                PaymentRequest:        string(payment.Info.PaymentRequest),
3✔
1796
                Status:                status,
3✔
1797
                Htlcs:                 htlcs,
3✔
1798
                PaymentIndex:          payment.SequenceNum,
3✔
1799
                FailureReason:         failureReason,
3✔
1800
                FirstHopCustomRecords: payment.Info.FirstHopCustomRecords,
3✔
1801
        }, nil
3✔
1802
}
1803

1804
// convertPaymentStatus converts a channeldb.PaymentStatus to the type expected
1805
// by the RPC.
1806
func convertPaymentStatus(dbStatus channeldb.PaymentStatus, useInit bool) (
1807
        lnrpc.Payment_PaymentStatus, error) {
3✔
1808

3✔
1809
        switch dbStatus {
3✔
1810
        case channeldb.StatusInitiated:
3✔
1811
                // If the client understands the new status, return it.
3✔
1812
                if useInit {
6✔
1813
                        return lnrpc.Payment_INITIATED, nil
3✔
1814
                }
3✔
1815

1816
                // Otherwise remain the old behavior.
1817
                return lnrpc.Payment_IN_FLIGHT, nil
3✔
1818

1819
        case channeldb.StatusInFlight:
3✔
1820
                return lnrpc.Payment_IN_FLIGHT, nil
3✔
1821

1822
        case channeldb.StatusSucceeded:
3✔
1823
                return lnrpc.Payment_SUCCEEDED, nil
3✔
1824

1825
        case channeldb.StatusFailed:
3✔
1826
                return lnrpc.Payment_FAILED, nil
3✔
1827

1828
        default:
×
1829
                return 0, fmt.Errorf("unhandled payment status %v", dbStatus)
×
1830
        }
1831
}
1832

1833
// marshallPaymentFailureReason marshalls the failure reason to the corresponding rpc
1834
// type.
1835
func marshallPaymentFailureReason(reason *channeldb.FailureReason) (
1836
        lnrpc.PaymentFailureReason, error) {
3✔
1837

3✔
1838
        if reason == nil {
6✔
1839
                return lnrpc.PaymentFailureReason_FAILURE_REASON_NONE, nil
3✔
1840
        }
3✔
1841

1842
        switch *reason {
3✔
1843
        case channeldb.FailureReasonTimeout:
×
1844
                return lnrpc.PaymentFailureReason_FAILURE_REASON_TIMEOUT, nil
×
1845

1846
        case channeldb.FailureReasonNoRoute:
3✔
1847
                return lnrpc.PaymentFailureReason_FAILURE_REASON_NO_ROUTE, nil
3✔
1848

1849
        case channeldb.FailureReasonError:
3✔
1850
                return lnrpc.PaymentFailureReason_FAILURE_REASON_ERROR, nil
3✔
1851

1852
        case channeldb.FailureReasonPaymentDetails:
3✔
1853
                return lnrpc.PaymentFailureReason_FAILURE_REASON_INCORRECT_PAYMENT_DETAILS, nil
3✔
1854

1855
        case channeldb.FailureReasonInsufficientBalance:
3✔
1856
                return lnrpc.PaymentFailureReason_FAILURE_REASON_INSUFFICIENT_BALANCE, nil
3✔
1857

1858
        case channeldb.FailureReasonCanceled:
3✔
1859
                return lnrpc.PaymentFailureReason_FAILURE_REASON_CANCELED, nil
3✔
1860
        }
1861

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