-
Notifications
You must be signed in to change notification settings - Fork 2.2k
Expand file tree
/
Copy pathrouter_server.go
More file actions
1984 lines (1659 loc) · 56.8 KB
/
router_server.go
File metadata and controls
1984 lines (1659 loc) · 56.8 KB
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"
crand "crypto/rand"
"errors"
"fmt"
"os"
"path/filepath"
"sync/atomic"
"time"
"github.com/btcsuite/btcd/btcutil"
"github.com/btcsuite/btcd/wire"
"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
"github.com/lightningnetwork/lnd/aliasmgr"
"github.com/lightningnetwork/lnd/fn/v2"
"github.com/lightningnetwork/lnd/lnrpc"
"github.com/lightningnetwork/lnd/lnrpc/invoicesrpc"
"github.com/lightningnetwork/lnd/lntypes"
"github.com/lightningnetwork/lnd/lnwire"
"github.com/lightningnetwork/lnd/macaroons"
paymentsdb "github.com/lightningnetwork/lnd/payments/db"
"github.com/lightningnetwork/lnd/routing"
"github.com/lightningnetwork/lnd/routing/route"
"github.com/lightningnetwork/lnd/zpay32"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"gopkg.in/macaroon-bakery.v2/bakery"
)
const (
// subServerName is the name of the sub rpc server. We'll use this name
// to register ourselves, and we also require that the main
// SubServerConfigDispatcher instance recognize as the name of our
subServerName = "RouterRPC"
// routeFeeLimitSat is the maximum routing fee that we allow to occur
// when estimating a routing fee.
routeFeeLimitSat = 100_000_000
// DefaultPaymentTimeout is the default value of time we should spend
// when attempting to fulfill the payment.
DefaultPaymentTimeout int32 = 60
// MaxLspsToProbe is the maximum number of LSPs to probe when
// estimating fees for worst-case fee estimation. This is a
// precautionary measure to prevent the estimation from taking too
// long, and it is also a griefing protection.
MaxLspsToProbe = 3
)
var (
errServerShuttingDown = errors.New("routerrpc server shutting down")
// ErrInterceptorAlreadyExists is an error returned when a new stream is
// opened and there is already one active interceptor. The user must
// disconnect prior to open another stream.
ErrInterceptorAlreadyExists = errors.New("interceptor already exists")
errMissingPaymentAttempt = errors.New("missing payment attempt")
errMissingRoute = errors.New("missing route")
errUnexpectedFailureSource = errors.New("unexpected failure source")
// ErrAliasAlreadyExists is returned if a new SCID alias is attempted
// to be added that already exists.
ErrAliasAlreadyExists = errors.New("alias already exists")
// ErrNoValidAlias is returned if an alias is not in the valid range for
// allowed SCID aliases.
ErrNoValidAlias = errors.New("not a valid alias")
// macaroonOps are the set of capabilities that our minted macaroon (if
// it doesn't already exist) will have.
macaroonOps = []bakery.Op{
{
Entity: "offchain",
Action: "read",
},
{
Entity: "offchain",
Action: "write",
},
}
// macPermissions maps RPC calls to the permissions they require.
macPermissions = map[string][]bakery.Op{
"/routerrpc.Router/SendPaymentV2": {{
Entity: "offchain",
Action: "write",
}},
"/routerrpc.Router/SendToRouteV2": {{
Entity: "offchain",
Action: "write",
}},
"/routerrpc.Router/SendToRoute": {{
Entity: "offchain",
Action: "write",
}},
"/routerrpc.Router/TrackPaymentV2": {{
Entity: "offchain",
Action: "read",
}},
"/routerrpc.Router/TrackPayments": {{
Entity: "offchain",
Action: "read",
}},
"/routerrpc.Router/EstimateRouteFee": {{
Entity: "offchain",
Action: "read",
}},
"/routerrpc.Router/QueryMissionControl": {{
Entity: "offchain",
Action: "read",
}},
"/routerrpc.Router/XImportMissionControl": {{
Entity: "offchain",
Action: "write",
}},
"/routerrpc.Router/GetMissionControlConfig": {{
Entity: "offchain",
Action: "read",
}},
"/routerrpc.Router/SetMissionControlConfig": {{
Entity: "offchain",
Action: "write",
}},
"/routerrpc.Router/QueryProbability": {{
Entity: "offchain",
Action: "read",
}},
"/routerrpc.Router/ResetMissionControl": {{
Entity: "offchain",
Action: "write",
}},
"/routerrpc.Router/BuildRoute": {{
Entity: "offchain",
Action: "read",
}},
"/routerrpc.Router/SubscribeHtlcEvents": {{
Entity: "offchain",
Action: "read",
}},
"/routerrpc.Router/SendPayment": {{
Entity: "offchain",
Action: "write",
}},
"/routerrpc.Router/TrackPayment": {{
Entity: "offchain",
Action: "read",
}},
"/routerrpc.Router/HtlcInterceptor": {{
Entity: "offchain",
Action: "write",
}},
"/routerrpc.Router/UpdateChanStatus": {{
Entity: "offchain",
Action: "write",
}},
"/routerrpc.Router/XAddLocalChanAliases": {{
Entity: "offchain",
Action: "write",
}},
"/routerrpc.Router/XDeleteLocalChanAliases": {{
Entity: "offchain",
Action: "write",
}},
}
// DefaultRouterMacFilename is the default name of the router macaroon
// that we expect to find via a file handle within the main
// configuration file in this package.
DefaultRouterMacFilename = "router.macaroon"
)
// HasNode returns true if the node exists in the graph (i.e., has public
// channels), false otherwise.
type HasNode func(nodePub route.Vertex) (bool, error)
// ServerShell is a shell struct holding a reference to the actual sub-server.
// It is used to register the gRPC sub-server with the root server before we
// have the necessary dependencies to populate the actual sub-server.
type ServerShell struct {
RouterServer
}
// Server is a stand-alone sub RPC server which exposes functionality that
// allows clients to route arbitrary payment through the Lightning Network.
type Server struct {
started int32 // To be used atomically.
shutdown int32 // To be used atomically.
forwardInterceptorActive int32 // To be used atomically.
// Required by the grpc-gateway/v2 library for forward compatibility.
// Must be after the atomically used variables to not break struct
// alignment.
UnimplementedRouterServer
cfg *Config
quit chan struct{}
}
// A compile time check to ensure that Server fully implements the RouterServer
// gRPC service.
var _ RouterServer = (*Server)(nil)
// New creates a new instance of the RouterServer given a configuration struct
// that contains all external dependencies. If the target macaroon exists, and
// we're unable to create it, then an error will be returned. We also return
// the set of permissions that we require as a server. At the time of writing
// of this documentation, this is the same macaroon as the admin macaroon.
func New(cfg *Config) (*Server, lnrpc.MacaroonPerms, error) {
// If the path of the router macaroon wasn't generated, then we'll
// assume that it's found at the default network directory.
if cfg.RouterMacPath == "" {
cfg.RouterMacPath = filepath.Join(
cfg.NetworkDir, DefaultRouterMacFilename,
)
}
// Now that we know the full path of the router macaroon, we can check
// to see if we need to create it or not. If stateless_init is set
// then we don't write the macaroons.
macFilePath := cfg.RouterMacPath
if cfg.MacService != nil && !cfg.MacService.StatelessInit &&
!lnrpc.FileExists(macFilePath) {
log.Infof("Making macaroons for Router RPC Server at: %v",
macFilePath)
// At this point, we know that the router macaroon doesn't yet,
// exist, so we need to create it with the help of the main
// macaroon service.
routerMac, err := cfg.MacService.NewMacaroon(
context.Background(), macaroons.DefaultRootKeyID,
macaroonOps...,
)
if err != nil {
return nil, nil, err
}
routerMacBytes, err := routerMac.M().MarshalBinary()
if err != nil {
return nil, nil, err
}
err = os.WriteFile(macFilePath, routerMacBytes, 0644)
if err != nil {
_ = os.Remove(macFilePath)
return nil, nil, err
}
}
routerServer := &Server{
cfg: cfg,
quit: make(chan struct{}),
}
return routerServer, macPermissions, nil
}
// Start launches any helper goroutines required for the rpcServer to function.
//
// NOTE: This is part of the lnrpc.SubServer interface.
func (s *Server) Start() error {
if atomic.AddInt32(&s.started, 1) != 1 {
return nil
}
return nil
}
// Stop signals any active goroutines for a graceful closure.
//
// NOTE: This is part of the lnrpc.SubServer interface.
func (s *Server) Stop() error {
if atomic.AddInt32(&s.shutdown, 1) != 1 {
return nil
}
close(s.quit)
return nil
}
// Name returns a unique string representation of the sub-server. This can be
// used to identify the sub-server and also de-duplicate them.
//
// NOTE: This is part of the lnrpc.SubServer interface.
func (s *Server) Name() string {
return subServerName
}
// RegisterWithRootServer will be called by the root gRPC server to direct a
// sub RPC server to register itself with the main gRPC root server. Until this
// is called, each sub-server won't be able to have requests routed towards it.
//
// NOTE: This is part of the lnrpc.GrpcHandler interface.
func (r *ServerShell) RegisterWithRootServer(grpcServer *grpc.Server) error {
// We make sure that we register it with the main gRPC server to ensure
// all our methods are routed properly.
RegisterRouterServer(grpcServer, r)
log.Debugf("Router RPC server successfully registered with root gRPC " +
"server")
return nil
}
// RegisterWithRestServer will be called by the root REST mux to direct a sub
// RPC server to register itself with the main REST mux server. Until this is
// called, each sub-server won't be able to have requests routed towards it.
//
// NOTE: This is part of the lnrpc.GrpcHandler interface.
func (r *ServerShell) RegisterWithRestServer(ctx context.Context,
mux *runtime.ServeMux, dest string, opts []grpc.DialOption) error {
// We make sure that we register it with the main REST server to ensure
// all our methods are routed properly.
err := RegisterRouterHandlerFromEndpoint(ctx, mux, dest, opts)
if err != nil {
log.Errorf("Could not register Router REST server "+
"with root REST server: %v", err)
return err
}
log.Debugf("Router REST server successfully registered with " +
"root REST server")
return nil
}
// CreateSubServer populates the subserver's dependencies using the passed
// SubServerConfigDispatcher. This method should fully initialize the
// sub-server instance, making it ready for action. It returns the macaroon
// permissions that the sub-server wishes to pass on to the root server for all
// methods routed towards it.
//
// NOTE: This is part of the lnrpc.GrpcHandler interface.
func (r *ServerShell) CreateSubServer(configRegistry lnrpc.SubServerConfigDispatcher) (
lnrpc.SubServer, lnrpc.MacaroonPerms, error) {
subServer, macPermissions, err := createNewSubServer(configRegistry)
if err != nil {
return nil, nil, err
}
r.RouterServer = subServer
return subServer, macPermissions, nil
}
// SendPaymentV2 attempts to route a payment described by the passed
// PaymentRequest to the final destination. If we are unable to route the
// payment, or cannot find a route that satisfies the constraints in the
// PaymentRequest, then an error will be returned. Otherwise, the payment
// pre-image, along with the final route will be returned.
func (s *Server) SendPaymentV2(req *SendPaymentRequest,
stream Router_SendPaymentV2Server) error {
// Set payment request attempt timeout.
if req.TimeoutSeconds == 0 {
req.TimeoutSeconds = DefaultPaymentTimeout
}
payment, err := s.cfg.RouterBackend.extractIntentFromSendRequest(req)
if err != nil {
return err
}
// Get the payment hash.
payHash := payment.Identifier()
// Init the payment in db.
paySession, shardTracker, err := s.cfg.Router.PreparePayment(payment)
if err != nil {
log.Errorf("SendPayment async error for payment %x: %v",
payment.Identifier(), err)
// Transform user errors to grpc code.
if errors.Is(err, paymentsdb.ErrPaymentExists) ||
errors.Is(err, paymentsdb.ErrPaymentInFlight) ||
errors.Is(err, paymentsdb.ErrAlreadyPaid) {
return status.Error(
codes.AlreadyExists, err.Error(),
)
}
return err
}
// Subscribe to the payment before sending it to make sure we won't
// miss events.
sub, err := s.subscribePayment(payHash)
if err != nil {
return err
}
// The payment context is influenced by two user-provided parameters,
// the cancelable flag and the payment attempt timeout.
// If the payment is cancelable, we will use the stream context as the
// payment context. That way, if the user ends the stream, the payment
// loop will be canceled.
// The second context parameter is the timeout. If the user provides a
// timeout, we will additionally wrap the context in a deadline. If the
// user provided 'cancelable' and ends the stream before the timeout is
// reached the payment will be canceled.
ctx := context.Background()
if req.Cancelable {
ctx = stream.Context()
}
// Send the payment asynchronously.
s.cfg.Router.SendPaymentAsync(ctx, payment, paySession, shardTracker)
// Track the payment and return.
return s.trackPayment(sub, payHash, stream, req.NoInflightUpdates)
}
// EstimateRouteFee allows callers to obtain an expected value w.r.t how much it
// may cost to send an HTLC to the target end destination. This method sends
// probe payments to the target node, based on target invoice parameters and a
// random payment hash that makes it impossible for the target to settle the
// htlc. The probing stops if a user-provided timeout is reached. If provided
// with a destination key and amount, this method will perform a local graph
// based fee estimation.
func (s *Server) EstimateRouteFee(ctx context.Context,
req *RouteFeeRequest) (*RouteFeeResponse, error) {
isProbeDestination := len(req.Dest) > 0
isProbeInvoice := len(req.PaymentRequest) > 0
switch {
case isProbeDestination == isProbeInvoice:
return nil, errors.New("specify either a destination or an " +
"invoice")
case isProbeDestination:
switch {
case len(req.Dest) != 33:
return nil, errors.New("invalid length destination key")
case req.AmtSat <= 0:
return nil, errors.New("amount must be greater than 0")
default:
return s.probeDestination(req.Dest, req.AmtSat)
}
case isProbeInvoice:
return s.probePaymentRequest(
ctx, req.PaymentRequest, req.Timeout,
)
}
return &RouteFeeResponse{}, nil
}
// probeDestination estimates fees along a route to a destination based on the
// contents of the local graph.
func (s *Server) probeDestination(dest []byte, amtSat int64) (*RouteFeeResponse,
error) {
destNode, err := route.NewVertexFromBytes(dest)
if err != nil {
return nil, err
}
// Next, we'll convert the amount in satoshis to mSAT, which are the
// native unit of LN.
amtMsat := lnwire.NewMSatFromSatoshis(btcutil.Amount(amtSat))
// Finally, we'll query for a route to the destination that can carry
// that target amount, we'll only request a single route. Set a
// restriction for the default CLTV limit, otherwise we can find a route
// that exceeds it and is useless to us.
mc := s.cfg.RouterBackend.MissionControl
routeReq, err := routing.NewRouteRequest(
s.cfg.RouterBackend.SelfNode, &destNode, amtMsat, 0,
&routing.RestrictParams{
FeeLimit: routeFeeLimitSat,
CltvLimit: s.cfg.RouterBackend.MaxTotalTimelock,
ProbabilitySource: mc.GetProbability,
}, nil, nil, nil, s.cfg.RouterBackend.DefaultFinalCltvDelta,
)
if err != nil {
return nil, err
}
route, _, err := s.cfg.Router.FindRoute(routeReq)
if err != nil {
return nil, err
}
// We are adding a block padding to the total time lock to account for
// the safety buffer that the payment session will add to the last hop's
// cltv delta. This is to prevent the htlc from failing if blocks are
// mined while it is in flight.
timeLockDelay := route.TotalTimeLock + uint32(routing.BlockPadding)
return &RouteFeeResponse{
RoutingFeeMsat: int64(route.TotalFees()),
TimeLockDelay: int64(timeLockDelay),
FailureReason: lnrpc.PaymentFailureReason_FAILURE_REASON_NONE,
}, nil
}
// probePaymentRequest estimates fees along a route to a destination that is
// specified in an invoice. The estimation duration is limited by a timeout. In
// case that route hints are provided, this method applies a heuristic to
// identify LSPs which might block probe payments. In that case, fees are
// manually calculated and added to the probed fee estimation up until the LSP
// node. If the route hints don't indicate an LSP, they are passed as arguments
// to the SendPayment_V2 method, which enable it to send probe payments to the
// payment request destination.
//
// NOTE: Be aware that because of the special heuristic that is applied to
// identify LSPs, the probe payment might use a different node id as the
// final destination (the assumed LSP node id).
func (s *Server) probePaymentRequest(ctx context.Context, paymentRequest string,
timeout uint32) (*RouteFeeResponse, error) {
payReq, err := zpay32.Decode(
paymentRequest, s.cfg.RouterBackend.ActiveNetParams,
)
if err != nil {
return nil, err
}
if payReq.MilliSat == nil || *payReq.MilliSat <= 0 {
return nil, errors.New("payment request amount must be " +
"greater than 0")
}
// Generate random payment hash, so we can be sure that the target of
// the probe payment doesn't have the preimage to settle the htlc.
var paymentHash lntypes.Hash
_, err = crand.Read(paymentHash[:])
if err != nil {
return nil, fmt.Errorf("cannot generate random probe "+
"preimage: %w", err)
}
amtMsat := int64(*payReq.MilliSat)
probeRequest := &SendPaymentRequest{
TimeoutSeconds: int32(timeout),
Dest: payReq.Destination.SerializeCompressed(),
MaxParts: 1,
AllowSelfPayment: false,
AmtMsat: amtMsat,
PaymentHash: paymentHash[:],
FeeLimitSat: routeFeeLimitSat,
FinalCltvDelta: int32(payReq.MinFinalCLTVExpiry()),
DestFeatures: MarshalFeatures(payReq.Features),
}
// If the payment addresses is specified, then we'll also populate that
// now as well.
payReq.PaymentAddr.WhenSome(func(addr [32]byte) {
probeRequest.PaymentAddr = make([]byte, lntypes.HashSize)
copy(probeRequest.PaymentAddr, addr[:])
})
hints := payReq.RouteHints
// If the hints don't indicate an LSP then chances are that our probe
// payment won't be blocked along the route to the destination. We send
// a probe payment with unmodified route hints.
invoiceTargetCompressed := payReq.Destination.SerializeCompressed()
if !isLSP(hints, invoiceTargetCompressed, s.cfg.RouterBackend.HasNode) {
log.Infof("No LSP detected, probing destination %x",
probeRequest.Dest)
probeRequest.RouteHints = invoicesrpc.CreateRPCRouteHints(hints)
return s.sendProbePayment(ctx, probeRequest)
}
// If the heuristic indicates an LSP, we filter and group route hints by
// public LSP nodes, then probe each unique LSP separately and return
// the route with the highest fee.
lspGroups, err := prepareLspRouteHints(
hints, *payReq.MilliSat, s.cfg.RouterBackend.HasNode,
)
if err != nil {
return nil, err
}
log.Infof("LSP detected, found %d unique public LSP node(s) to probe",
len(lspGroups))
// Probe up to MaxLspsToProbe LSPs and track the most expensive route
// for worst-case fee estimation.
if len(lspGroups) > MaxLspsToProbe {
log.Debugf("Limiting LSP probes from %d to %d for worst-case "+
"fee estimation", len(lspGroups), MaxLspsToProbe)
}
var (
worstCaseResp *RouteFeeResponse
worstCaseLspDest route.Vertex
probeCount int
)
for lspKey, group := range lspGroups {
if probeCount >= MaxLspsToProbe {
break
}
probeCount++
lspHint := group.LspHopHint
log.Infof("Probing LSP with destination: %v", lspKey)
// Create a new probe request for this LSP.
lspProbeRequest := &SendPaymentRequest{
TimeoutSeconds: probeRequest.TimeoutSeconds,
Dest: lspKey[:],
MaxParts: probeRequest.MaxParts,
AllowSelfPayment: probeRequest.AllowSelfPayment,
AmtMsat: amtMsat,
PaymentHash: probeRequest.PaymentHash,
FeeLimitSat: probeRequest.FeeLimitSat,
FinalCltvDelta: int32(lspHint.CLTVExpiryDelta),
DestFeatures: probeRequest.DestFeatures,
}
// Copy the payment address if present.
if len(probeRequest.PaymentAddr) > 0 {
lspProbeRequest.PaymentAddr = make(
[]byte, lntypes.HashSize,
)
copy(
lspProbeRequest.PaymentAddr,
probeRequest.PaymentAddr,
)
}
// Set the adjusted route hints for this LSP.
if len(group.AdjustedRouteHints) > 0 {
lspProbeRequest.RouteHints = invoicesrpc.
CreateRPCRouteHints(group.AdjustedRouteHints)
}
// Calculate the hop fee for the last hop manually.
hopFee := lspHint.HopFee(*payReq.MilliSat)
// Add the last hop's fee to the probe amount.
lspProbeRequest.AmtMsat += int64(hopFee)
// Dispatch the payment probe for this LSP.
resp, err := s.sendProbePayment(ctx, lspProbeRequest)
if err != nil {
log.Warnf("Failed to probe LSP %v: %v", lspKey, err)
continue
}
// If the probe failed, skip this LSP.
if resp.FailureReason !=
lnrpc.PaymentFailureReason_FAILURE_REASON_NONE {
log.Debugf("Probe to LSP %v failed with reason: %v",
lspKey, resp.FailureReason)
continue
}
// The probe succeeded, add the last hop's fee.
resp.RoutingFeeMsat += int64(hopFee)
// Add the final cltv delta of the invoice.
resp.TimeLockDelay += int64(payReq.MinFinalCLTVExpiry())
log.Infof("Probe to LSP %v succeeded with fee: %d msat",
lspKey, resp.RoutingFeeMsat)
// Track the most expensive route for worst-case estimation.
// We solely consider the routing fee for the worst-case
// estimation.
if worstCaseResp == nil ||
resp.RoutingFeeMsat > worstCaseResp.RoutingFeeMsat {
if worstCaseResp != nil {
log.Debugf("LSP %v has higher fee "+
"(%d msat) than current worst-case "+
"%v (%d msat), updating worst-case "+
"estimate", lspKey,
resp.RoutingFeeMsat, worstCaseLspDest,
worstCaseResp.RoutingFeeMsat)
}
worstCaseResp = resp
worstCaseLspDest = lspKey
} else {
log.Debugf("LSP %v fee (%d msat) is lower than "+
"current worst-case %v (%d msat), keeping "+
"worst-case estimate", lspKey,
resp.RoutingFeeMsat, worstCaseLspDest,
worstCaseResp.RoutingFeeMsat)
}
}
// If no LSP probe succeeded, return an error.
if worstCaseResp == nil {
return nil, fmt.Errorf("all LSP probe payments failed")
}
log.Infof("Returning worst-case route via LSP %v with fee: %d msat, "+
"timelock: %d", worstCaseLspDest, worstCaseResp.RoutingFeeMsat,
worstCaseResp.TimeLockDelay)
return worstCaseResp, nil
}
// isLSP checks if the route hints indicate an LSP setup. An LSP setup is
// identified when the invoice destination is private but the final hop in the
// route hints is a public node (the LSP). This function implements three rules:
//
// 1. If the invoice target is a public node (exists in graph) => isLsp = false
// We can route directly to the target, so no LSP is involved.
//
// 2. If at least one destination hop hint (last hop in route hint) is public
// => isLsp = true. The public destination hop is the LSP, and the actual
// invoice target is a private node behind it.
//
// 3. If all destination hop hints are private nodes => isLsp = false.
// We assume this is NOT an LSP setup. Instead, we expect the route hints
// contain public nodes earlier in the path (not the final hop) that our
// pathfinder can route to. For example:
// The pathfinder will route to PublicNode and use the hints from there.
// Note: If no public nodes exist anywhere in the route hints, the
// destination would be unreachable (malformed invoice), but we don't
// validate that here.
func isLSP(routeHints [][]zpay32.HopHint, invoiceTarget []byte,
hasNode HasNode) bool {
if len(routeHints) == 0 || len(routeHints[0]) == 0 {
log.Debugf("No route hints provided, this is not an LSP setup")
return false
}
// Rule 1: If the invoice target is a public node (exists in the graph),
// we can route directly to it, so it's not an LSP setup.
if len(invoiceTarget) > 0 {
var targetVertex route.Vertex
copy(targetVertex[:], invoiceTarget)
isPublic, err := hasNode(targetVertex)
if err != nil {
log.Warnf("Failed to check if invoice target %x is "+
"public: %v", invoiceTarget, err)
return false
}
if isPublic {
log.Infof("Invoice target %x is a public node in the "+
"graph, this is NOT an LSP setup",
invoiceTarget)
return false
}
}
for _, hopHints := range routeHints {
// Skip empty route hints.
if len(hopHints) == 0 {
continue
}
lastHop := hopHints[len(hopHints)-1]
lastHopNodeCompressed := lastHop.NodeID.SerializeCompressed()
// Check if this destination hop hint node is public.
// Rule 2: If we find a public node, we can exit early.
var lastHopVertex route.Vertex
copy(lastHopVertex[:], lastHopNodeCompressed)
isPublic, err := hasNode(lastHopVertex)
if err != nil {
log.Warnf("Failed to check if destination hop "+
"hint %x is public: %v", lastHopNodeCompressed,
err)
continue
}
if isPublic {
log.Infof("Destination hop hint %x is a public node, "+
"this is an LSP setup", lastHopNodeCompressed)
return true
}
}
// Rule 3: If all destination hop hints are private nodes (not in the
// graph), this is NOT an LSP setup. We assume the route hints contain
// public nodes earlier in the path that we can route through using
// standard pathfinding with the hints.
log.Infof("All destination hop hints are private, this is NOT an " +
"LSP setup")
return false
}
// LspRouteGroup represents a group of route hints that share the same public
// LSP destination node. This is needed when probing LSPs separately to find
// the route with the highest fee.
type LspRouteGroup struct {
// LspHopHint is the hop hint for the LSP node with worst-case fees and
// CLTV delta.
LspHopHint *zpay32.HopHint
// AdjustedRouteHints are the route hints with the LSP hop stripped off.
AdjustedRouteHints [][]zpay32.HopHint
}
// prepareLspRouteHints assumes that the isLsp heuristic returned true for the
// route hints passed in here. It filters route hints to only include those with
// public destination nodes, groups them by unique LSP node, and returns a map
// of LSP groups keyed by the LSP node's compressed public key.
func prepareLspRouteHints(routeHints [][]zpay32.HopHint,
amt lnwire.MilliSatoshi,
hasNode HasNode) (map[route.Vertex]*LspRouteGroup, error) {
// This should never happen, but we check for it for completeness.
// Because the isLSP heuristic already checked that the route hints are
// not empty.
if len(routeHints) == 0 {
return nil, fmt.Errorf("no route hints provided")
}
// Map to group route hints by LSP node pubkey.
lspGroups := make(map[route.Vertex]*LspRouteGroup)
for _, routeHint := range routeHints {
// Skip empty route hints.
if len(routeHint) == 0 {
continue
}
// Get the destination hop hint (last hop in the route).
destHop := routeHint[len(routeHint)-1]
destNodeCompressed := destHop.NodeID.SerializeCompressed()
// Check if this destination node is public.
var destVertex route.Vertex
copy(destVertex[:], destNodeCompressed)
isPublic, err := hasNode(destVertex)
if err != nil {
log.Warnf("Failed to check if dest hop hint %x is "+
"public: %v", destNodeCompressed, err)
continue
}
// Skip private destination nodes - we only probe public LSPs.
if !isPublic {
log.Debugf("Skipping route hint with private dest "+
"node %x", destNodeCompressed)
continue
}
// Use the compressed pubkey as the map key.
var lspKey route.Vertex
copy(lspKey[:], destNodeCompressed)
// Get or create the LSP group for this node.
group, exists := lspGroups[lspKey]
if !exists {
//nolint:ll
lspHop := zpay32.HopHint{
NodeID: destHop.NodeID,
ChannelID: destHop.ChannelID,
FeeBaseMSat: destHop.FeeBaseMSat,
FeeProportionalMillionths: destHop.FeeProportionalMillionths,
CLTVExpiryDelta: destHop.CLTVExpiryDelta,
}
group = &LspRouteGroup{
LspHopHint: &lspHop,
AdjustedRouteHints: make([][]zpay32.HopHint, 0),
}
lspGroups[lspKey] = group
}
// Update the LSP hop hint with worst-case (max) fees and CLTV.
hopFee := destHop.HopFee(amt)
currentMaxFee := group.LspHopHint.HopFee(amt)
if hopFee > currentMaxFee {
group.LspHopHint.FeeBaseMSat = destHop.FeeBaseMSat
group.LspHopHint.FeeProportionalMillionths = destHop.
FeeProportionalMillionths
}
if destHop.CLTVExpiryDelta > group.LspHopHint.CLTVExpiryDelta {
group.LspHopHint.CLTVExpiryDelta = destHop.
CLTVExpiryDelta
}
// Add the route hint with the LSP hop stripped off (if there
// are hops before the LSP).
if len(routeHint) > 1 {
group.AdjustedRouteHints = append(
group.AdjustedRouteHints,
routeHint[:len(routeHint)-1],
)
}
}
if len(lspGroups) == 0 {
return nil, fmt.Errorf("no public LSP nodes found in " +
"route hints")
}
log.Infof("Found %d unique public LSP node(s) in route hints",
len(lspGroups))
return lspGroups, nil
}
// probePaymentStream is a custom implementation of the grpc.ServerStream
// interface. It is used to send payment status updates to the caller on the
// stream channel.
type probePaymentStream struct {
Router_SendPaymentV2Server
stream chan *lnrpc.Payment
ctx context.Context //nolint:containedctx
}
// Send sends a payment status update to a payment stream that the caller can
// evaluate.
func (p *probePaymentStream) Send(response *lnrpc.Payment) error {
select {
case p.stream <- response:
case <-p.ctx.Done():
return p.ctx.Err()
}
return nil
}
// Context returns the context of the stream.
func (p *probePaymentStream) Context() context.Context {
return p.ctx
}
// sendProbePayment sends a payment to a target node in order to obtain
// potential routing fees for it. The payment request has to contain a payment
// hash that is guaranteed to be unknown to the target node, so it cannot settle
// the payment. This method invokes a payment request loop in a goroutine and
// awaits payment status updates.
func (s *Server) sendProbePayment(ctx context.Context,
req *SendPaymentRequest) (*RouteFeeResponse, error) {
// We'll launch a goroutine to send the payment probes.
errChan := make(chan error, 1)
defer close(errChan)
paymentStream := &probePaymentStream{
stream: make(chan *lnrpc.Payment),
ctx: ctx,
}
go func() {
err := s.SendPaymentV2(req, paymentStream)
if err != nil {
select {
case errChan <- err:
case <-paymentStream.ctx.Done():
return
}
}
}()
for {
select {
case payment := <-paymentStream.stream:
switch payment.Status {
case lnrpc.Payment_INITIATED:
case lnrpc.Payment_IN_FLIGHT:
case lnrpc.Payment_SUCCEEDED:
return nil, errors.New("warning, the fee " +
"estimation payment probe " +
"unexpectedly succeeded. Please reach" +
"out to the probe destination to " +
"negotiate a refund. Otherwise the " +
"payment probe amount is lost forever")
case lnrpc.Payment_FAILED:
// Incorrect payment details point to a
// successful probe.
//nolint:ll
if payment.FailureReason == lnrpc.PaymentFailureReason_FAILURE_REASON_INCORRECT_PAYMENT_DETAILS {
return paymentDetails(payment)
}
return &RouteFeeResponse{
RoutingFeeMsat: 0,
TimeLockDelay: 0,