-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
router_backend.go
1811 lines (1503 loc) · 50.7 KB
/
router_backend.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package routerrpc
import (
"context"
"crypto/rand"
"encoding/hex"
"errors"
"fmt"
math "math"
"time"
"github.com/btcsuite/btcd/btcec/v2"
"github.com/btcsuite/btcd/btcutil"
"github.com/btcsuite/btcd/chaincfg"
"github.com/btcsuite/btcd/wire"
sphinx "github.com/lightningnetwork/lightning-onion"
"github.com/lightningnetwork/lnd/channeldb"
"github.com/lightningnetwork/lnd/feature"
"github.com/lightningnetwork/lnd/fn/v2"
"github.com/lightningnetwork/lnd/htlcswitch"
"github.com/lightningnetwork/lnd/lnrpc"
"github.com/lightningnetwork/lnd/lntypes"
"github.com/lightningnetwork/lnd/lnwire"
"github.com/lightningnetwork/lnd/record"
"github.com/lightningnetwork/lnd/routing"
"github.com/lightningnetwork/lnd/routing/route"
"github.com/lightningnetwork/lnd/subscribe"
"github.com/lightningnetwork/lnd/zpay32"
"google.golang.org/protobuf/proto"
)
const (
// DefaultMaxParts is the default number of splits we'll possibly use
// for MPP when the user is attempting to send a payment.
//
// TODO(roasbeef): make this value dynamic based on expected number of
// attempts for given amount.
DefaultMaxParts = 16
)
// RouterBackend contains the backend implementation of the router rpc sub
// server calls.
type RouterBackend struct {
// SelfNode is the vertex of the node sending the payment.
SelfNode route.Vertex
// FetchChannelCapacity is a closure that we'll use the fetch the total
// capacity of a channel to populate in responses.
FetchChannelCapacity func(chanID uint64) (btcutil.Amount, error)
// FetchAmountPairCapacity determines the maximal channel capacity
// between two nodes given a certain amount.
FetchAmountPairCapacity func(nodeFrom, nodeTo route.Vertex,
amount lnwire.MilliSatoshi) (btcutil.Amount, error)
// FetchChannelEndpoints returns the pubkeys of both endpoints of the
// given channel id.
FetchChannelEndpoints func(chanID uint64) (route.Vertex,
route.Vertex, error)
// FindRoute is a closure that abstracts away how we locate/query for
// routes.
FindRoute func(*routing.RouteRequest) (*route.Route, float64, error)
MissionControl MissionControl
// ActiveNetParams are the network parameters of the primary network
// that the route is operating on. This is necessary so we can ensure
// that we receive payment requests that send to destinations on our
// network.
ActiveNetParams *chaincfg.Params
// Tower is the ControlTower instance that is used to track pending
// payments.
Tower routing.ControlTower
// MaxTotalTimelock is the maximum total time lock a route is allowed to
// have.
MaxTotalTimelock uint32
// DefaultFinalCltvDelta is the default value used as final cltv delta
// when an RPC caller doesn't specify a value.
DefaultFinalCltvDelta uint16
// SubscribeHtlcEvents returns a subscription client for the node's
// htlc events.
SubscribeHtlcEvents func() (*subscribe.Client, error)
// InterceptableForwarder exposes the ability to intercept forward events
// by letting the router register a ForwardInterceptor.
InterceptableForwarder htlcswitch.InterceptableHtlcForwarder
// SetChannelEnabled exposes the ability to manually enable a channel.
SetChannelEnabled func(wire.OutPoint) error
// SetChannelDisabled exposes the ability to manually disable a channel
SetChannelDisabled func(wire.OutPoint) error
// SetChannelAuto exposes the ability to restore automatic channel state
// management after manually setting channel status.
SetChannelAuto func(wire.OutPoint) error
// UseStatusInitiated is a boolean that indicates whether the router
// should use the new status code `Payment_INITIATED`.
//
// TODO(yy): remove this config after the new status code is fully
// deployed to the network(v0.20.0).
UseStatusInitiated bool
// ParseCustomChannelData is a function that can be used to parse custom
// channel data from the first hop of a route.
ParseCustomChannelData func(message proto.Message) error
// ShouldSetExpEndorsement returns a boolean indicating whether the
// experimental endorsement bit should be set.
ShouldSetExpEndorsement func() bool
}
// MissionControl defines the mission control dependencies of routerrpc.
type MissionControl interface {
// GetProbability is expected to return the success probability of a
// payment from fromNode to toNode.
GetProbability(fromNode, toNode route.Vertex,
amt lnwire.MilliSatoshi, capacity btcutil.Amount) float64
// ResetHistory resets the history of MissionControl returning it to a
// state as if no payment attempts have been made.
ResetHistory() error
// GetHistorySnapshot takes a snapshot from the current mission control
// state and actual probability estimates.
GetHistorySnapshot() *routing.MissionControlSnapshot
// ImportHistory imports the mission control snapshot to our internal
// state. This import will only be applied in-memory, and will not be
// persisted across restarts.
ImportHistory(snapshot *routing.MissionControlSnapshot, force bool) error
// GetPairHistorySnapshot returns the stored history for a given node
// pair.
GetPairHistorySnapshot(fromNode,
toNode route.Vertex) routing.TimedPairResult
// GetConfig gets mission control's current config.
GetConfig() *routing.MissionControlConfig
// SetConfig sets mission control's config to the values provided, if
// they are valid.
SetConfig(cfg *routing.MissionControlConfig) error
}
// QueryRoutes attempts to query the daemons' Channel Router for a possible
// route to a target destination capable of carrying a specific amount of
// satoshis within the route's flow. The returned route contains the full
// details required to craft and send an HTLC, also including the necessary
// information that should be present within the Sphinx packet encapsulated
// within the HTLC.
//
// TODO(roasbeef): should return a slice of routes in reality * create separate
// PR to send based on well formatted route
func (r *RouterBackend) QueryRoutes(ctx context.Context,
in *lnrpc.QueryRoutesRequest) (*lnrpc.QueryRoutesResponse, error) {
routeReq, err := r.parseQueryRoutesRequest(in)
if err != nil {
return nil, err
}
// Query the channel router for a possible path to the destination that
// can carry `in.Amt` satoshis _including_ the total fee required on
// the route
route, successProb, err := r.FindRoute(routeReq)
if err != nil {
return nil, err
}
// For each valid route, we'll convert the result into the format
// required by the RPC system.
rpcRoute, err := r.MarshallRoute(route)
if err != nil {
return nil, err
}
routeResp := &lnrpc.QueryRoutesResponse{
Routes: []*lnrpc.Route{rpcRoute},
SuccessProb: successProb,
}
return routeResp, nil
}
func parsePubKey(key string) (route.Vertex, error) {
pubKeyBytes, err := hex.DecodeString(key)
if err != nil {
return route.Vertex{}, err
}
return route.NewVertexFromBytes(pubKeyBytes)
}
func (r *RouterBackend) parseIgnored(in *lnrpc.QueryRoutesRequest) (
map[route.Vertex]struct{}, map[routing.DirectedNodePair]struct{},
error) {
ignoredNodes := make(map[route.Vertex]struct{})
for _, ignorePubKey := range in.IgnoredNodes {
ignoreVertex, err := route.NewVertexFromBytes(ignorePubKey)
if err != nil {
return nil, nil, err
}
ignoredNodes[ignoreVertex] = struct{}{}
}
ignoredPairs := make(map[routing.DirectedNodePair]struct{})
// Convert deprecated ignoredEdges to pairs.
for _, ignoredEdge := range in.IgnoredEdges {
pair, err := r.rpcEdgeToPair(ignoredEdge)
if err != nil {
log.Warnf("Ignore channel %v skipped: %v",
ignoredEdge.ChannelId, err)
continue
}
ignoredPairs[pair] = struct{}{}
}
// Add ignored pairs to set.
for _, ignorePair := range in.IgnoredPairs {
from, err := route.NewVertexFromBytes(ignorePair.From)
if err != nil {
return nil, nil, err
}
to, err := route.NewVertexFromBytes(ignorePair.To)
if err != nil {
return nil, nil, err
}
pair := routing.NewDirectedNodePair(from, to)
ignoredPairs[pair] = struct{}{}
}
return ignoredNodes, ignoredPairs, nil
}
func (r *RouterBackend) parseQueryRoutesRequest(in *lnrpc.QueryRoutesRequest) (
*routing.RouteRequest, error) {
// Parse the hex-encoded source public key into a full public key that
// we can properly manipulate.
var sourcePubKey route.Vertex
if in.SourcePubKey != "" {
var err error
sourcePubKey, err = parsePubKey(in.SourcePubKey)
if err != nil {
return nil, err
}
} else {
// If no source is specified, use self.
sourcePubKey = r.SelfNode
}
// Currently, within the bootstrap phase of the network, we limit the
// largest payment size allotted to (2^32) - 1 mSAT or 4.29 million
// satoshis.
amt, err := lnrpc.UnmarshallAmt(in.Amt, in.AmtMsat)
if err != nil {
return nil, err
}
// Unmarshall restrictions from request.
feeLimit := lnrpc.CalculateFeeLimit(in.FeeLimit, amt)
// Since QueryRoutes allows having a different source other than
// ourselves, we'll only apply our max time lock if we are the source.
maxTotalTimelock := r.MaxTotalTimelock
if sourcePubKey != r.SelfNode {
maxTotalTimelock = math.MaxUint32
}
cltvLimit, err := ValidateCLTVLimit(in.CltvLimit, maxTotalTimelock)
if err != nil {
return nil, err
}
// If we have a blinded path set, we'll get a few of our fields from
// inside of the path rather than the request's fields.
var (
targetPubKey *route.Vertex
routeHintEdges map[route.Vertex][]routing.AdditionalEdge
blindedPathSet *routing.BlindedPaymentPathSet
// finalCLTVDelta varies depending on whether we're sending to
// a blinded route or an unblinded node. For blinded paths,
// our final cltv is already baked into the path so we restrict
// this value to zero on the API. Bolt11 invoices have a
// default, so we'll fill that in for the non-blinded case.
finalCLTVDelta uint16
// destinationFeatures is the set of features for the
// destination node.
destinationFeatures *lnwire.FeatureVector
)
// Validate that the fields provided in the request are sane depending
// on whether it is using a blinded path or not.
if len(in.BlindedPaymentPaths) > 0 {
blindedPathSet, err = parseBlindedPaymentPaths(in)
if err != nil {
return nil, err
}
pathFeatures := blindedPathSet.Features()
if pathFeatures != nil {
destinationFeatures = pathFeatures.Clone()
}
} else {
// If we do not have a blinded path, a target pubkey must be
// set.
pk, err := parsePubKey(in.PubKey)
if err != nil {
return nil, err
}
targetPubKey = &pk
// Convert route hints to an edge map.
routeHints, err := unmarshallRouteHints(in.RouteHints)
if err != nil {
return nil, err
}
routeHintEdges, err = routing.RouteHintsToEdges(
routeHints, *targetPubKey,
)
if err != nil {
return nil, err
}
// Set a non-zero final CLTV delta for payments that are not
// to blinded paths, as bolt11 has a default final cltv delta
// value that is used in the absence of a value.
finalCLTVDelta = r.DefaultFinalCltvDelta
if in.FinalCltvDelta != 0 {
finalCLTVDelta = uint16(in.FinalCltvDelta)
}
// Do bounds checking without block padding so we don't give
// routes that will leave the router in a zombie payment state.
err = routing.ValidateCLTVLimit(
cltvLimit, finalCLTVDelta, false,
)
if err != nil {
return nil, err
}
// Parse destination feature bits.
destinationFeatures, err = UnmarshalFeatures(in.DestFeatures)
if err != nil {
return nil, err
}
}
// We need to subtract the final delta before passing it into path
// finding. The optimal path is independent of the final cltv delta and
// the path finding algorithm is unaware of this value.
cltvLimit -= uint32(finalCLTVDelta)
ignoredNodes, ignoredPairs, err := r.parseIgnored(in)
if err != nil {
return nil, err
}
restrictions := &routing.RestrictParams{
FeeLimit: feeLimit,
ProbabilitySource: func(fromNode, toNode route.Vertex,
amt lnwire.MilliSatoshi,
capacity btcutil.Amount) float64 {
if _, ok := ignoredNodes[fromNode]; ok {
return 0
}
pair := routing.DirectedNodePair{
From: fromNode,
To: toNode,
}
if _, ok := ignoredPairs[pair]; ok {
return 0
}
if !in.UseMissionControl {
return 1
}
return r.MissionControl.GetProbability(
fromNode, toNode, amt, capacity,
)
},
DestCustomRecords: record.CustomSet(in.DestCustomRecords),
CltvLimit: cltvLimit,
DestFeatures: destinationFeatures,
BlindedPaymentPathSet: blindedPathSet,
}
// Pass along an outgoing channel restriction if specified.
if in.OutgoingChanId != 0 {
restrictions.OutgoingChannelIDs = []uint64{in.OutgoingChanId}
}
// Pass along a last hop restriction if specified.
if len(in.LastHopPubkey) > 0 {
lastHop, err := route.NewVertexFromBytes(
in.LastHopPubkey,
)
if err != nil {
return nil, err
}
restrictions.LastHop = &lastHop
}
// If we have any TLV records destined for the final hop, then we'll
// attempt to decode them now into a form that the router can more
// easily manipulate.
customRecords := record.CustomSet(in.DestCustomRecords)
if err := customRecords.Validate(); err != nil {
return nil, err
}
return routing.NewRouteRequest(
sourcePubKey, targetPubKey, amt, in.TimePref, restrictions,
customRecords, routeHintEdges, blindedPathSet,
finalCLTVDelta,
)
}
func parseBlindedPaymentPaths(in *lnrpc.QueryRoutesRequest) (
*routing.BlindedPaymentPathSet, error) {
if len(in.PubKey) != 0 {
return nil, fmt.Errorf("target pubkey: %x should not be set "+
"when blinded path is provided", in.PubKey)
}
if len(in.RouteHints) > 0 {
return nil, errors.New("route hints and blinded path can't " +
"both be set")
}
if in.FinalCltvDelta != 0 {
return nil, errors.New("final cltv delta should be " +
"zero for blinded paths")
}
// For blinded paths, we get one set of features for the relaying
// intermediate nodes and the final destination. We don't allow the
// destination feature bit field for regular payments to be set, as
// this could lead to ambiguity.
if len(in.DestFeatures) > 0 {
return nil, errors.New("destination features should " +
"be populated in blinded path")
}
paths := make([]*routing.BlindedPayment, len(in.BlindedPaymentPaths))
for i, paymentPath := range in.BlindedPaymentPaths {
blindedPmt, err := unmarshalBlindedPayment(paymentPath)
if err != nil {
return nil, fmt.Errorf("parse blinded payment: %w", err)
}
if err := blindedPmt.Validate(); err != nil {
return nil, fmt.Errorf("invalid blinded path: %w", err)
}
paths[i] = blindedPmt
}
return routing.NewBlindedPaymentPathSet(paths)
}
func unmarshalBlindedPayment(rpcPayment *lnrpc.BlindedPaymentPath) (
*routing.BlindedPayment, error) {
if rpcPayment == nil {
return nil, errors.New("nil blinded payment")
}
path, err := unmarshalBlindedPaymentPaths(rpcPayment.BlindedPath)
if err != nil {
return nil, err
}
features, err := UnmarshalFeatures(rpcPayment.Features)
if err != nil {
return nil, err
}
return &routing.BlindedPayment{
BlindedPath: path,
CltvExpiryDelta: uint16(rpcPayment.TotalCltvDelta),
BaseFee: uint32(rpcPayment.BaseFeeMsat),
ProportionalFeeRate: rpcPayment.ProportionalFeeRate,
HtlcMinimum: rpcPayment.HtlcMinMsat,
HtlcMaximum: rpcPayment.HtlcMaxMsat,
Features: features,
}, nil
}
func unmarshalBlindedPaymentPaths(rpcPath *lnrpc.BlindedPath) (
*sphinx.BlindedPath, error) {
if rpcPath == nil {
return nil, errors.New("blinded path required when blinded " +
"route is provided")
}
introduction, err := btcec.ParsePubKey(rpcPath.IntroductionNode)
if err != nil {
return nil, err
}
blinding, err := btcec.ParsePubKey(rpcPath.BlindingPoint)
if err != nil {
return nil, err
}
if len(rpcPath.BlindedHops) < 1 {
return nil, errors.New("at least 1 blinded hops required")
}
path := &sphinx.BlindedPath{
IntroductionPoint: introduction,
BlindingPoint: blinding,
BlindedHops: make(
[]*sphinx.BlindedHopInfo, len(rpcPath.BlindedHops),
),
}
for i, hop := range rpcPath.BlindedHops {
path.BlindedHops[i], err = unmarshalBlindedHop(hop)
if err != nil {
return nil, err
}
}
return path, nil
}
func unmarshalBlindedHop(rpcHop *lnrpc.BlindedHop) (*sphinx.BlindedHopInfo,
error) {
pubkey, err := btcec.ParsePubKey(rpcHop.BlindedNode)
if err != nil {
return nil, err
}
if len(rpcHop.EncryptedData) == 0 {
return nil, errors.New("empty encrypted data not allowed")
}
return &sphinx.BlindedHopInfo{
BlindedNodePub: pubkey,
CipherText: rpcHop.EncryptedData,
}, nil
}
// rpcEdgeToPair looks up the provided channel and returns the channel endpoints
// as a directed pair.
func (r *RouterBackend) rpcEdgeToPair(e *lnrpc.EdgeLocator) (
routing.DirectedNodePair, error) {
a, b, err := r.FetchChannelEndpoints(e.ChannelId)
if err != nil {
return routing.DirectedNodePair{}, err
}
var pair routing.DirectedNodePair
if e.DirectionReverse {
pair.From, pair.To = b, a
} else {
pair.From, pair.To = a, b
}
return pair, nil
}
// MarshallRoute marshalls an internal route to an rpc route struct.
func (r *RouterBackend) MarshallRoute(route *route.Route) (*lnrpc.Route, error) {
resp := &lnrpc.Route{
TotalTimeLock: route.TotalTimeLock,
TotalFees: int64(route.TotalFees().ToSatoshis()),
TotalFeesMsat: int64(route.TotalFees()),
TotalAmt: int64(route.TotalAmount.ToSatoshis()),
TotalAmtMsat: int64(route.TotalAmount),
Hops: make([]*lnrpc.Hop, len(route.Hops)),
FirstHopAmountMsat: int64(route.FirstHopAmount.Val.Int()),
}
// Encode the route's custom channel data (if available).
if len(route.FirstHopWireCustomRecords) > 0 {
customData, err := route.FirstHopWireCustomRecords.Serialize()
if err != nil {
return nil, err
}
resp.CustomChannelData = customData
// Allow the aux data parser to parse the custom records into
// a human-readable JSON (if available).
if r.ParseCustomChannelData != nil {
err := r.ParseCustomChannelData(resp)
if err != nil {
return nil, err
}
}
}
incomingAmt := route.TotalAmount
for i, hop := range route.Hops {
fee := route.HopFee(i)
// Channel capacity is not a defining property of a route. For
// backwards RPC compatibility, we retrieve it here from the
// graph.
chanCapacity, err := r.FetchChannelCapacity(hop.ChannelID)
if err != nil {
// If capacity cannot be retrieved, this may be a
// not-yet-received or private channel. Then report
// amount that is sent through the channel as capacity.
chanCapacity = incomingAmt.ToSatoshis()
}
// Extract the MPP fields if present on this hop.
var mpp *lnrpc.MPPRecord
if hop.MPP != nil {
addr := hop.MPP.PaymentAddr()
mpp = &lnrpc.MPPRecord{
PaymentAddr: addr[:],
TotalAmtMsat: int64(hop.MPP.TotalMsat()),
}
}
var amp *lnrpc.AMPRecord
if hop.AMP != nil {
rootShare := hop.AMP.RootShare()
setID := hop.AMP.SetID()
amp = &lnrpc.AMPRecord{
RootShare: rootShare[:],
SetId: setID[:],
ChildIndex: hop.AMP.ChildIndex(),
}
}
resp.Hops[i] = &lnrpc.Hop{
ChanId: hop.ChannelID,
ChanCapacity: int64(chanCapacity),
AmtToForward: int64(hop.AmtToForward.ToSatoshis()),
AmtToForwardMsat: int64(hop.AmtToForward),
Fee: int64(fee.ToSatoshis()),
FeeMsat: int64(fee),
Expiry: uint32(hop.OutgoingTimeLock),
PubKey: hex.EncodeToString(
hop.PubKeyBytes[:],
),
CustomRecords: hop.CustomRecords,
TlvPayload: !hop.LegacyPayload,
MppRecord: mpp,
AmpRecord: amp,
Metadata: hop.Metadata,
EncryptedData: hop.EncryptedData,
TotalAmtMsat: uint64(hop.TotalAmtMsat),
}
if hop.BlindingPoint != nil {
blinding := hop.BlindingPoint.SerializeCompressed()
resp.Hops[i].BlindingPoint = blinding
}
incomingAmt = hop.AmtToForward
}
return resp, nil
}
// UnmarshallHopWithPubkey unmarshalls an rpc hop for which the pubkey has
// already been extracted.
func UnmarshallHopWithPubkey(rpcHop *lnrpc.Hop, pubkey route.Vertex) (*route.Hop,
error) {
customRecords := record.CustomSet(rpcHop.CustomRecords)
if err := customRecords.Validate(); err != nil {
return nil, err
}
mpp, err := UnmarshalMPP(rpcHop.MppRecord)
if err != nil {
return nil, err
}
amp, err := UnmarshalAMP(rpcHop.AmpRecord)
if err != nil {
return nil, err
}
hop := &route.Hop{
OutgoingTimeLock: rpcHop.Expiry,
AmtToForward: lnwire.MilliSatoshi(rpcHop.AmtToForwardMsat),
PubKeyBytes: pubkey,
ChannelID: rpcHop.ChanId,
CustomRecords: customRecords,
LegacyPayload: false,
MPP: mpp,
AMP: amp,
EncryptedData: rpcHop.EncryptedData,
TotalAmtMsat: lnwire.MilliSatoshi(rpcHop.TotalAmtMsat),
}
haveBlindingPoint := len(rpcHop.BlindingPoint) != 0
if haveBlindingPoint {
hop.BlindingPoint, err = btcec.ParsePubKey(
rpcHop.BlindingPoint,
)
if err != nil {
return nil, fmt.Errorf("blinding point: %w", err)
}
}
if haveBlindingPoint && len(rpcHop.EncryptedData) == 0 {
return nil, errors.New("encrypted data should be present if " +
"blinding point is provided")
}
return hop, nil
}
// UnmarshallHop unmarshalls an rpc hop that may or may not contain a node
// pubkey.
func (r *RouterBackend) UnmarshallHop(rpcHop *lnrpc.Hop,
prevNodePubKey [33]byte) (*route.Hop, error) {
var pubKeyBytes [33]byte
if rpcHop.PubKey != "" {
// Unmarshall the provided hop pubkey.
pubKey, err := hex.DecodeString(rpcHop.PubKey)
if err != nil {
return nil, fmt.Errorf("cannot decode pubkey %s",
rpcHop.PubKey)
}
copy(pubKeyBytes[:], pubKey)
} else {
// If no pub key is given of the hop, the local channel graph
// needs to be queried to complete the information necessary for
// routing. Discard edge policies, because they may be nil.
node1, node2, err := r.FetchChannelEndpoints(rpcHop.ChanId)
if err != nil {
return nil, err
}
switch {
case prevNodePubKey == node1:
pubKeyBytes = node2
case prevNodePubKey == node2:
pubKeyBytes = node1
default:
return nil, fmt.Errorf("channel edge does not match " +
"expected node")
}
}
return UnmarshallHopWithPubkey(rpcHop, pubKeyBytes)
}
// UnmarshallRoute unmarshalls an rpc route. For hops that don't specify a
// pubkey, the channel graph is queried.
func (r *RouterBackend) UnmarshallRoute(rpcroute *lnrpc.Route) (
*route.Route, error) {
prevNodePubKey := r.SelfNode
hops := make([]*route.Hop, len(rpcroute.Hops))
for i, hop := range rpcroute.Hops {
routeHop, err := r.UnmarshallHop(hop, prevNodePubKey)
if err != nil {
return nil, err
}
hops[i] = routeHop
prevNodePubKey = routeHop.PubKeyBytes
}
route, err := route.NewRouteFromHops(
lnwire.MilliSatoshi(rpcroute.TotalAmtMsat),
rpcroute.TotalTimeLock,
r.SelfNode,
hops,
)
if err != nil {
return nil, err
}
return route, nil
}
// extractIntentFromSendRequest attempts to parse the SendRequest details
// required to dispatch a client from the information presented by an RPC
// client.
func (r *RouterBackend) extractIntentFromSendRequest(
rpcPayReq *SendPaymentRequest) (*routing.LightningPayment, error) {
payIntent := &routing.LightningPayment{}
// Pass along time preference.
if rpcPayReq.TimePref < -1 || rpcPayReq.TimePref > 1 {
return nil, errors.New("time preference out of range")
}
payIntent.TimePref = rpcPayReq.TimePref
// Pass along restrictions on the outgoing channels that may be used.
payIntent.OutgoingChannelIDs = rpcPayReq.OutgoingChanIds
// Add the deprecated single outgoing channel restriction if present.
if rpcPayReq.OutgoingChanId != 0 {
if payIntent.OutgoingChannelIDs != nil {
return nil, errors.New("outgoing_chan_id and " +
"outgoing_chan_ids are mutually exclusive")
}
payIntent.OutgoingChannelIDs = append(
payIntent.OutgoingChannelIDs, rpcPayReq.OutgoingChanId,
)
}
// Pass along a last hop restriction if specified.
if len(rpcPayReq.LastHopPubkey) > 0 {
lastHop, err := route.NewVertexFromBytes(
rpcPayReq.LastHopPubkey,
)
if err != nil {
return nil, err
}
payIntent.LastHop = &lastHop
}
// Take the CLTV limit from the request if set, otherwise use the max.
cltvLimit, err := ValidateCLTVLimit(
uint32(rpcPayReq.CltvLimit), r.MaxTotalTimelock,
)
if err != nil {
return nil, err
}
payIntent.CltvLimit = cltvLimit
// Attempt to parse the max parts value set by the user, if this value
// isn't set, then we'll use the current default value for this
// setting.
maxParts := rpcPayReq.MaxParts
if maxParts == 0 {
maxParts = DefaultMaxParts
}
payIntent.MaxParts = maxParts
// If this payment had a max shard amount specified, then we'll apply
// that now, which'll force us to always make payment splits smaller
// than this.
if rpcPayReq.MaxShardSizeMsat > 0 {
shardAmtMsat := lnwire.MilliSatoshi(rpcPayReq.MaxShardSizeMsat)
payIntent.MaxShardAmt = &shardAmtMsat
}
// Take fee limit from request.
payIntent.FeeLimit, err = lnrpc.UnmarshallAmt(
rpcPayReq.FeeLimitSat, rpcPayReq.FeeLimitMsat,
)
if err != nil {
return nil, err
}
// Set payment attempt timeout.
if rpcPayReq.TimeoutSeconds == 0 {
return nil, errors.New("timeout_seconds must be specified")
}
customRecords := record.CustomSet(rpcPayReq.DestCustomRecords)
if err := customRecords.Validate(); err != nil {
return nil, err
}
payIntent.DestCustomRecords = customRecords
firstHopRecords := lnwire.CustomRecords(rpcPayReq.FirstHopCustomRecords)
if err := firstHopRecords.Validate(); err != nil {
return nil, err
}
payIntent.FirstHopCustomRecords = firstHopRecords
// If the experimental endorsement signal is not already set, propagate
// a zero value field if configured to set this signal.
if r.ShouldSetExpEndorsement() {
if payIntent.FirstHopCustomRecords == nil {
payIntent.FirstHopCustomRecords = make(
map[uint64][]byte,
)
}
t := uint64(lnwire.ExperimentalEndorsementType)
if _, set := payIntent.FirstHopCustomRecords[t]; !set {
payIntent.FirstHopCustomRecords[t] = []byte{
lnwire.ExperimentalUnendorsed,
}
}
}
payIntent.PayAttemptTimeout = time.Second *
time.Duration(rpcPayReq.TimeoutSeconds)
// Route hints.
routeHints, err := unmarshallRouteHints(
rpcPayReq.RouteHints,
)
if err != nil {
return nil, err
}
payIntent.RouteHints = routeHints
// Unmarshall either sat or msat amount from request.
reqAmt, err := lnrpc.UnmarshallAmt(
rpcPayReq.Amt, rpcPayReq.AmtMsat,
)
if err != nil {
return nil, err
}
// If the payment request field isn't blank, then the details of the
// invoice are encoded entirely within the encoded payReq. So we'll
// attempt to decode it, populating the payment accordingly.
if rpcPayReq.PaymentRequest != "" {
switch {
case len(rpcPayReq.Dest) > 0:
return nil, errors.New("dest and payment_request " +
"cannot appear together")
case len(rpcPayReq.PaymentHash) > 0:
return nil, errors.New("payment_hash and payment_request " +
"cannot appear together")
case rpcPayReq.FinalCltvDelta != 0:
return nil, errors.New("final_cltv_delta and payment_request " +
"cannot appear together")
}
payReq, err := zpay32.Decode(
rpcPayReq.PaymentRequest, r.ActiveNetParams,
)
if err != nil {
return nil, err
}
// Next, we'll ensure that this payreq hasn't already expired.
err = ValidatePayReqExpiry(payReq)
if err != nil {
return nil, err
}
// If the amount was not included in the invoice, then we let
// the payer specify the amount of satoshis they wish to send.
// We override the amount to pay with the amount provided from
// the payment request.
if payReq.MilliSat == nil {
if reqAmt == 0 {
return nil, errors.New("amount must be " +
"specified when paying a zero amount " +
"invoice")
}
payIntent.Amount = reqAmt
} else {
if reqAmt != 0 {
return nil, errors.New("amount must not be " +
"specified when paying a non-zero " +
" amount invoice")
}
payIntent.Amount = *payReq.MilliSat
}
if !payReq.Features.HasFeature(lnwire.MPPOptional) &&
!payReq.Features.HasFeature(lnwire.AMPOptional) {
payIntent.MaxParts = 1
}
payAddr := payReq.PaymentAddr
if payReq.Features.HasFeature(lnwire.AMPOptional) {
// The opt-in AMP flag is required to pay an AMP
// invoice.
if !rpcPayReq.Amp {
return nil, fmt.Errorf("the AMP flag (--amp " +