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

lightningnetwork / lnd / 14388908780

10 Apr 2025 07:39PM UTC coverage: 56.811% (-12.3%) from 69.08%
14388908780

Pull #9702

github

web-flow
Merge f006bbf4d into b732525a9
Pull Request #9702: multi: make payment address mandatory

28 of 42 new or added lines in 11 files covered. (66.67%)

23231 existing lines in 283 files now uncovered.

107286 of 188846 relevant lines covered (56.81%)

22749.28 hits per line

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

11.39
/lnrpc/routerrpc/router_server.go
1
package routerrpc
2

3
import (
4
        "bytes"
5
        "context"
6
        crand "crypto/rand"
7
        "errors"
8
        "fmt"
9
        "os"
10
        "path/filepath"
11
        "sync/atomic"
12
        "time"
13

14
        "github.com/btcsuite/btcd/btcutil"
15
        "github.com/btcsuite/btcd/wire"
16
        "github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
17
        "github.com/lightningnetwork/lnd/aliasmgr"
18
        "github.com/lightningnetwork/lnd/channeldb"
19
        "github.com/lightningnetwork/lnd/fn/v2"
20
        "github.com/lightningnetwork/lnd/lnrpc"
21
        "github.com/lightningnetwork/lnd/lnrpc/invoicesrpc"
22
        "github.com/lightningnetwork/lnd/lntypes"
23
        "github.com/lightningnetwork/lnd/lnwire"
24
        "github.com/lightningnetwork/lnd/macaroons"
25
        "github.com/lightningnetwork/lnd/routing"
26
        "github.com/lightningnetwork/lnd/routing/route"
27
        "github.com/lightningnetwork/lnd/zpay32"
28
        "google.golang.org/grpc"
29
        "google.golang.org/grpc/codes"
30
        "google.golang.org/grpc/status"
31
        "gopkg.in/macaroon-bakery.v2/bakery"
32
)
33

34
const (
35
        // subServerName is the name of the sub rpc server. We'll use this name
36
        // to register ourselves, and we also require that the main
37
        // SubServerConfigDispatcher instance recognize as the name of our
38
        subServerName = "RouterRPC"
39

40
        // routeFeeLimitSat is the maximum routing fee that we allow to occur
41
        // when estimating a routing fee.
42
        routeFeeLimitSat = 100_000_000
43

44
        // DefaultPaymentTimeout is the default value of time we should spend
45
        // when attempting to fulfill the payment.
46
        DefaultPaymentTimeout int32 = 60
47
)
48

49
var (
50
        errServerShuttingDown = errors.New("routerrpc server shutting down")
51

52
        // ErrInterceptorAlreadyExists is an error returned when a new stream is
53
        // opened and there is already one active interceptor. The user must
54
        // disconnect prior to open another stream.
55
        ErrInterceptorAlreadyExists = errors.New("interceptor already exists")
56

57
        errMissingPaymentAttempt = errors.New("missing payment attempt")
58

59
        errMissingRoute = errors.New("missing route")
60

61
        errUnexpectedFailureSource = errors.New("unexpected failure source")
62

63
        // ErrAliasAlreadyExists is returned if a new SCID alias is attempted
64
        // to be added that already exists.
65
        ErrAliasAlreadyExists = errors.New("alias already exists")
66

67
        // ErrNoValidAlias is returned if an alias is not in the valid range for
68
        // allowed SCID aliases.
69
        ErrNoValidAlias = errors.New("not a valid alias")
70

71
        // macaroonOps are the set of capabilities that our minted macaroon (if
72
        // it doesn't already exist) will have.
73
        macaroonOps = []bakery.Op{
74
                {
75
                        Entity: "offchain",
76
                        Action: "read",
77
                },
78
                {
79
                        Entity: "offchain",
80
                        Action: "write",
81
                },
82
        }
83

84
        // macPermissions maps RPC calls to the permissions they require.
85
        macPermissions = map[string][]bakery.Op{
86
                "/routerrpc.Router/SendPaymentV2": {{
87
                        Entity: "offchain",
88
                        Action: "write",
89
                }},
90
                "/routerrpc.Router/SendToRouteV2": {{
91
                        Entity: "offchain",
92
                        Action: "write",
93
                }},
94
                "/routerrpc.Router/SendToRoute": {{
95
                        Entity: "offchain",
96
                        Action: "write",
97
                }},
98
                "/routerrpc.Router/TrackPaymentV2": {{
99
                        Entity: "offchain",
100
                        Action: "read",
101
                }},
102
                "/routerrpc.Router/TrackPayments": {{
103
                        Entity: "offchain",
104
                        Action: "read",
105
                }},
106
                "/routerrpc.Router/EstimateRouteFee": {{
107
                        Entity: "offchain",
108
                        Action: "read",
109
                }},
110
                "/routerrpc.Router/QueryMissionControl": {{
111
                        Entity: "offchain",
112
                        Action: "read",
113
                }},
114
                "/routerrpc.Router/XImportMissionControl": {{
115
                        Entity: "offchain",
116
                        Action: "write",
117
                }},
118
                "/routerrpc.Router/GetMissionControlConfig": {{
119
                        Entity: "offchain",
120
                        Action: "read",
121
                }},
122
                "/routerrpc.Router/SetMissionControlConfig": {{
123
                        Entity: "offchain",
124
                        Action: "write",
125
                }},
126
                "/routerrpc.Router/QueryProbability": {{
127
                        Entity: "offchain",
128
                        Action: "read",
129
                }},
130
                "/routerrpc.Router/ResetMissionControl": {{
131
                        Entity: "offchain",
132
                        Action: "write",
133
                }},
134
                "/routerrpc.Router/BuildRoute": {{
135
                        Entity: "offchain",
136
                        Action: "read",
137
                }},
138
                "/routerrpc.Router/SubscribeHtlcEvents": {{
139
                        Entity: "offchain",
140
                        Action: "read",
141
                }},
142
                "/routerrpc.Router/SendPayment": {{
143
                        Entity: "offchain",
144
                        Action: "write",
145
                }},
146
                "/routerrpc.Router/TrackPayment": {{
147
                        Entity: "offchain",
148
                        Action: "read",
149
                }},
150
                "/routerrpc.Router/HtlcInterceptor": {{
151
                        Entity: "offchain",
152
                        Action: "write",
153
                }},
154
                "/routerrpc.Router/UpdateChanStatus": {{
155
                        Entity: "offchain",
156
                        Action: "write",
157
                }},
158
                "/routerrpc.Router/XAddLocalChanAliases": {{
159
                        Entity: "offchain",
160
                        Action: "write",
161
                }},
162
                "/routerrpc.Router/XDeleteLocalChanAliases": {{
163
                        Entity: "offchain",
164
                        Action: "write",
165
                }},
166
        }
167

168
        // DefaultRouterMacFilename is the default name of the router macaroon
169
        // that we expect to find via a file handle within the main
170
        // configuration file in this package.
171
        DefaultRouterMacFilename = "router.macaroon"
172
)
173

174
// FetchChannelEndpoints returns the pubkeys of both endpoints of the
175
// given channel id if it exists in the graph.
176
type FetchChannelEndpoints func(chanID uint64) (route.Vertex, route.Vertex,
177
        error)
178

179
// ServerShell is a shell struct holding a reference to the actual sub-server.
180
// It is used to register the gRPC sub-server with the root server before we
181
// have the necessary dependencies to populate the actual sub-server.
182
type ServerShell struct {
183
        RouterServer
184
}
185

186
// Server is a stand-alone sub RPC server which exposes functionality that
187
// allows clients to route arbitrary payment through the Lightning Network.
188
type Server struct {
189
        started                  int32 // To be used atomically.
190
        shutdown                 int32 // To be used atomically.
191
        forwardInterceptorActive int32 // To be used atomically.
192

193
        // Required by the grpc-gateway/v2 library for forward compatibility.
194
        // Must be after the atomically used variables to not break struct
195
        // alignment.
196
        UnimplementedRouterServer
197

198
        cfg *Config
199

200
        quit chan struct{}
201
}
202

203
// A compile time check to ensure that Server fully implements the RouterServer
204
// gRPC service.
205
var _ RouterServer = (*Server)(nil)
206

207
// New creates a new instance of the RouterServer given a configuration struct
208
// that contains all external dependencies. If the target macaroon exists, and
209
// we're unable to create it, then an error will be returned. We also return
210
// the set of permissions that we require as a server. At the time of writing
211
// of this documentation, this is the same macaroon as the admin macaroon.
UNCOV
212
func New(cfg *Config) (*Server, lnrpc.MacaroonPerms, error) {
×
UNCOV
213
        // If the path of the router macaroon wasn't generated, then we'll
×
UNCOV
214
        // assume that it's found at the default network directory.
×
UNCOV
215
        if cfg.RouterMacPath == "" {
×
UNCOV
216
                cfg.RouterMacPath = filepath.Join(
×
UNCOV
217
                        cfg.NetworkDir, DefaultRouterMacFilename,
×
UNCOV
218
                )
×
UNCOV
219
        }
×
220

221
        // Now that we know the full path of the router macaroon, we can check
222
        // to see if we need to create it or not. If stateless_init is set
223
        // then we don't write the macaroons.
UNCOV
224
        macFilePath := cfg.RouterMacPath
×
UNCOV
225
        if cfg.MacService != nil && !cfg.MacService.StatelessInit &&
×
UNCOV
226
                !lnrpc.FileExists(macFilePath) {
×
UNCOV
227

×
UNCOV
228
                log.Infof("Making macaroons for Router RPC Server at: %v",
×
UNCOV
229
                        macFilePath)
×
UNCOV
230

×
UNCOV
231
                // At this point, we know that the router macaroon doesn't yet,
×
UNCOV
232
                // exist, so we need to create it with the help of the main
×
UNCOV
233
                // macaroon service.
×
UNCOV
234
                routerMac, err := cfg.MacService.NewMacaroon(
×
UNCOV
235
                        context.Background(), macaroons.DefaultRootKeyID,
×
UNCOV
236
                        macaroonOps...,
×
UNCOV
237
                )
×
UNCOV
238
                if err != nil {
×
239
                        return nil, nil, err
×
240
                }
×
UNCOV
241
                routerMacBytes, err := routerMac.M().MarshalBinary()
×
UNCOV
242
                if err != nil {
×
243
                        return nil, nil, err
×
244
                }
×
UNCOV
245
                err = os.WriteFile(macFilePath, routerMacBytes, 0644)
×
UNCOV
246
                if err != nil {
×
247
                        _ = os.Remove(macFilePath)
×
248
                        return nil, nil, err
×
249
                }
×
250
        }
251

UNCOV
252
        routerServer := &Server{
×
UNCOV
253
                cfg:  cfg,
×
UNCOV
254
                quit: make(chan struct{}),
×
UNCOV
255
        }
×
UNCOV
256

×
UNCOV
257
        return routerServer, macPermissions, nil
×
258
}
259

260
// Start launches any helper goroutines required for the rpcServer to function.
261
//
262
// NOTE: This is part of the lnrpc.SubServer interface.
UNCOV
263
func (s *Server) Start() error {
×
UNCOV
264
        if atomic.AddInt32(&s.started, 1) != 1 {
×
265
                return nil
×
266
        }
×
267

UNCOV
268
        return nil
×
269
}
270

271
// Stop signals any active goroutines for a graceful closure.
272
//
273
// NOTE: This is part of the lnrpc.SubServer interface.
UNCOV
274
func (s *Server) Stop() error {
×
UNCOV
275
        if atomic.AddInt32(&s.shutdown, 1) != 1 {
×
276
                return nil
×
277
        }
×
278

UNCOV
279
        close(s.quit)
×
UNCOV
280
        return nil
×
281
}
282

283
// Name returns a unique string representation of the sub-server. This can be
284
// used to identify the sub-server and also de-duplicate them.
285
//
286
// NOTE: This is part of the lnrpc.SubServer interface.
UNCOV
287
func (s *Server) Name() string {
×
UNCOV
288
        return subServerName
×
UNCOV
289
}
×
290

291
// RegisterWithRootServer will be called by the root gRPC server to direct a
292
// sub RPC server to register itself with the main gRPC root server. Until this
293
// is called, each sub-server won't be able to have requests routed towards it.
294
//
295
// NOTE: This is part of the lnrpc.GrpcHandler interface.
UNCOV
296
func (r *ServerShell) RegisterWithRootServer(grpcServer *grpc.Server) error {
×
UNCOV
297
        // We make sure that we register it with the main gRPC server to ensure
×
UNCOV
298
        // all our methods are routed properly.
×
UNCOV
299
        RegisterRouterServer(grpcServer, r)
×
UNCOV
300

×
UNCOV
301
        log.Debugf("Router RPC server successfully registered with root gRPC " +
×
UNCOV
302
                "server")
×
UNCOV
303

×
UNCOV
304
        return nil
×
UNCOV
305
}
×
306

307
// RegisterWithRestServer will be called by the root REST mux to direct a sub
308
// RPC server to register itself with the main REST mux server. Until this is
309
// called, each sub-server won't be able to have requests routed towards it.
310
//
311
// NOTE: This is part of the lnrpc.GrpcHandler interface.
312
func (r *ServerShell) RegisterWithRestServer(ctx context.Context,
UNCOV
313
        mux *runtime.ServeMux, dest string, opts []grpc.DialOption) error {
×
UNCOV
314

×
UNCOV
315
        // We make sure that we register it with the main REST server to ensure
×
UNCOV
316
        // all our methods are routed properly.
×
UNCOV
317
        err := RegisterRouterHandlerFromEndpoint(ctx, mux, dest, opts)
×
UNCOV
318
        if err != nil {
×
319
                log.Errorf("Could not register Router REST server "+
×
320
                        "with root REST server: %v", err)
×
321
                return err
×
322
        }
×
323

UNCOV
324
        log.Debugf("Router REST server successfully registered with " +
×
UNCOV
325
                "root REST server")
×
UNCOV
326
        return nil
×
327
}
328

329
// CreateSubServer populates the subserver's dependencies using the passed
330
// SubServerConfigDispatcher. This method should fully initialize the
331
// sub-server instance, making it ready for action. It returns the macaroon
332
// permissions that the sub-server wishes to pass on to the root server for all
333
// methods routed towards it.
334
//
335
// NOTE: This is part of the lnrpc.GrpcHandler interface.
336
func (r *ServerShell) CreateSubServer(configRegistry lnrpc.SubServerConfigDispatcher) (
UNCOV
337
        lnrpc.SubServer, lnrpc.MacaroonPerms, error) {
×
UNCOV
338

×
UNCOV
339
        subServer, macPermissions, err := createNewSubServer(configRegistry)
×
UNCOV
340
        if err != nil {
×
341
                return nil, nil, err
×
342
        }
×
343

UNCOV
344
        r.RouterServer = subServer
×
UNCOV
345
        return subServer, macPermissions, nil
×
346
}
347

348
// SendPaymentV2 attempts to route a payment described by the passed
349
// PaymentRequest to the final destination. If we are unable to route the
350
// payment, or cannot find a route that satisfies the constraints in the
351
// PaymentRequest, then an error will be returned. Otherwise, the payment
352
// pre-image, along with the final route will be returned.
353
func (s *Server) SendPaymentV2(req *SendPaymentRequest,
UNCOV
354
        stream Router_SendPaymentV2Server) error {
×
UNCOV
355

×
UNCOV
356
        // Set payment request attempt timeout.
×
UNCOV
357
        if req.TimeoutSeconds == 0 {
×
UNCOV
358
                req.TimeoutSeconds = DefaultPaymentTimeout
×
UNCOV
359
        }
×
360

UNCOV
361
        payment, err := s.cfg.RouterBackend.extractIntentFromSendRequest(req)
×
UNCOV
362
        if err != nil {
×
UNCOV
363
                return err
×
UNCOV
364
        }
×
365

366
        // Get the payment hash.
UNCOV
367
        payHash := payment.Identifier()
×
UNCOV
368

×
UNCOV
369
        // Init the payment in db.
×
UNCOV
370
        paySession, shardTracker, err := s.cfg.Router.PreparePayment(payment)
×
UNCOV
371
        if err != nil {
×
372
                log.Errorf("SendPayment async error for payment %x: %v",
×
373
                        payment.Identifier(), err)
×
374

×
375
                // Transform user errors to grpc code.
×
376
                if errors.Is(err, channeldb.ErrPaymentExists) ||
×
377
                        errors.Is(err, channeldb.ErrPaymentInFlight) ||
×
378
                        errors.Is(err, channeldb.ErrAlreadyPaid) {
×
379

×
380
                        return status.Error(
×
381
                                codes.AlreadyExists, err.Error(),
×
382
                        )
×
383
                }
×
384

385
                return err
×
386
        }
387

388
        // Subscribe to the payment before sending it to make sure we won't
389
        // miss events.
UNCOV
390
        sub, err := s.subscribePayment(payHash)
×
UNCOV
391
        if err != nil {
×
392
                return err
×
393
        }
×
394

395
        // The payment context is influenced by two user-provided parameters,
396
        // the cancelable flag and the payment attempt timeout.
397
        // If the payment is cancelable, we will use the stream context as the
398
        // payment context. That way, if the user ends the stream, the payment
399
        // loop will be canceled.
400
        // The second context parameter is the timeout. If the user provides a
401
        // timeout, we will additionally wrap the context in a deadline. If the
402
        // user provided 'cancelable' and ends the stream before the timeout is
403
        // reached the payment will be canceled.
UNCOV
404
        ctx := context.Background()
×
UNCOV
405
        if req.Cancelable {
×
UNCOV
406
                ctx = stream.Context()
×
UNCOV
407
        }
×
408

409
        // Send the payment asynchronously.
UNCOV
410
        s.cfg.Router.SendPaymentAsync(ctx, payment, paySession, shardTracker)
×
UNCOV
411

×
UNCOV
412
        // Track the payment and return.
×
UNCOV
413
        return s.trackPayment(sub, payHash, stream, req.NoInflightUpdates)
×
414
}
415

416
// EstimateRouteFee allows callers to obtain an expected value w.r.t how much it
417
// may cost to send an HTLC to the target end destination. This method sends
418
// probe payments to the target node, based on target invoice parameters and a
419
// random payment hash that makes it impossible for the target to settle the
420
// htlc. The probing stops if a user-provided timeout is reached. If provided
421
// with a destination key and amount, this method will perform a local graph
422
// based fee estimation.
423
func (s *Server) EstimateRouteFee(ctx context.Context,
UNCOV
424
        req *RouteFeeRequest) (*RouteFeeResponse, error) {
×
UNCOV
425

×
UNCOV
426
        isProbeDestination := len(req.Dest) > 0
×
UNCOV
427
        isProbeInvoice := len(req.PaymentRequest) > 0
×
UNCOV
428

×
UNCOV
429
        switch {
×
430
        case isProbeDestination == isProbeInvoice:
×
431
                return nil, errors.New("specify either a destination or an " +
×
432
                        "invoice")
×
433

UNCOV
434
        case isProbeDestination:
×
UNCOV
435
                switch {
×
436
                case len(req.Dest) != 33:
×
437
                        return nil, errors.New("invalid length destination key")
×
438

439
                case req.AmtSat <= 0:
×
440
                        return nil, errors.New("amount must be greater than 0")
×
441

UNCOV
442
                default:
×
UNCOV
443
                        return s.probeDestination(req.Dest, req.AmtSat)
×
444
                }
445

UNCOV
446
        case isProbeInvoice:
×
UNCOV
447
                return s.probePaymentRequest(
×
UNCOV
448
                        ctx, req.PaymentRequest, req.Timeout,
×
UNCOV
449
                )
×
450
        }
451

452
        return &RouteFeeResponse{}, nil
×
453
}
454

455
// probeDestination estimates fees along a route to a destination based on the
456
// contents of the local graph.
457
func (s *Server) probeDestination(dest []byte, amtSat int64) (*RouteFeeResponse,
UNCOV
458
        error) {
×
UNCOV
459

×
UNCOV
460
        destNode, err := route.NewVertexFromBytes(dest)
×
UNCOV
461
        if err != nil {
×
462
                return nil, err
×
463
        }
×
464

465
        // Next, we'll convert the amount in satoshis to mSAT, which are the
466
        // native unit of LN.
UNCOV
467
        amtMsat := lnwire.NewMSatFromSatoshis(btcutil.Amount(amtSat))
×
UNCOV
468

×
UNCOV
469
        // Finally, we'll query for a route to the destination that can carry
×
UNCOV
470
        // that target amount, we'll only request a single route. Set a
×
UNCOV
471
        // restriction for the default CLTV limit, otherwise we can find a route
×
UNCOV
472
        // that exceeds it and is useless to us.
×
UNCOV
473
        mc := s.cfg.RouterBackend.MissionControl
×
UNCOV
474
        routeReq, err := routing.NewRouteRequest(
×
UNCOV
475
                s.cfg.RouterBackend.SelfNode, &destNode, amtMsat, 0,
×
UNCOV
476
                &routing.RestrictParams{
×
UNCOV
477
                        FeeLimit:          routeFeeLimitSat,
×
UNCOV
478
                        CltvLimit:         s.cfg.RouterBackend.MaxTotalTimelock,
×
UNCOV
479
                        ProbabilitySource: mc.GetProbability,
×
UNCOV
480
                }, nil, nil, nil, s.cfg.RouterBackend.DefaultFinalCltvDelta,
×
UNCOV
481
        )
×
UNCOV
482
        if err != nil {
×
483
                return nil, err
×
484
        }
×
485

UNCOV
486
        route, _, err := s.cfg.Router.FindRoute(routeReq)
×
UNCOV
487
        if err != nil {
×
UNCOV
488
                return nil, err
×
UNCOV
489
        }
×
490

491
        // We are adding a block padding to the total time lock to account for
492
        // the safety buffer that the payment session will add to the last hop's
493
        // cltv delta. This is to prevent the htlc from failing if blocks are
494
        // mined while it is in flight.
UNCOV
495
        timeLockDelay := route.TotalTimeLock + uint32(routing.BlockPadding)
×
UNCOV
496

×
UNCOV
497
        return &RouteFeeResponse{
×
UNCOV
498
                RoutingFeeMsat: int64(route.TotalFees()),
×
UNCOV
499
                TimeLockDelay:  int64(timeLockDelay),
×
UNCOV
500
                FailureReason:  lnrpc.PaymentFailureReason_FAILURE_REASON_NONE,
×
UNCOV
501
        }, nil
×
502
}
503

504
// probePaymentRequest estimates fees along a route to a destination that is
505
// specified in an invoice. The estimation duration is limited by a timeout. In
506
// case that route hints are provided, this method applies a heuristic to
507
// identify LSPs which might block probe payments. In that case, fees are
508
// manually calculated and added to the probed fee estimation up until the LSP
509
// node. If the route hints don't indicate an LSP, they are passed as arguments
510
// to the SendPayment_V2 method, which enable it to send probe payments to the
511
// payment request destination.
512
func (s *Server) probePaymentRequest(ctx context.Context, paymentRequest string,
UNCOV
513
        timeout uint32) (*RouteFeeResponse, error) {
×
UNCOV
514

×
UNCOV
515
        payReq, err := zpay32.Decode(
×
UNCOV
516
                paymentRequest, s.cfg.RouterBackend.ActiveNetParams,
×
UNCOV
517
        )
×
UNCOV
518
        if err != nil {
×
519
                return nil, err
×
520
        }
×
521

UNCOV
522
        if payReq.MilliSat == nil || *payReq.MilliSat <= 0 {
×
523
                return nil, errors.New("payment request amount must be " +
×
524
                        "greater than 0")
×
525
        }
×
526

527
        // Generate random payment hash, so we can be sure that the target of
528
        // the probe payment doesn't have the preimage to settle the htlc.
UNCOV
529
        var paymentHash lntypes.Hash
×
UNCOV
530
        _, err = crand.Read(paymentHash[:])
×
UNCOV
531
        if err != nil {
×
532
                return nil, fmt.Errorf("cannot generate random probe "+
×
533
                        "preimage: %w", err)
×
534
        }
×
535

UNCOV
536
        amtMsat := int64(*payReq.MilliSat)
×
UNCOV
537
        probeRequest := &SendPaymentRequest{
×
UNCOV
538
                TimeoutSeconds:   int32(timeout),
×
UNCOV
539
                Dest:             payReq.Destination.SerializeCompressed(),
×
UNCOV
540
                MaxParts:         1,
×
UNCOV
541
                AllowSelfPayment: false,
×
UNCOV
542
                AmtMsat:          amtMsat,
×
UNCOV
543
                PaymentHash:      paymentHash[:],
×
UNCOV
544
                FeeLimitSat:      routeFeeLimitSat,
×
NEW
545
                PaymentAddr:      payReq.PaymentAddr[:],
×
UNCOV
546
                FinalCltvDelta:   int32(payReq.MinFinalCLTVExpiry()),
×
UNCOV
547
                DestFeatures:     MarshalFeatures(payReq.Features),
×
UNCOV
548
        }
×
UNCOV
549

×
UNCOV
550
        hints := payReq.RouteHints
×
UNCOV
551

×
UNCOV
552
        // If the hints don't indicate an LSP then chances are that our probe
×
UNCOV
553
        // payment won't be blocked along the route to the destination. We send
×
UNCOV
554
        // a probe payment with unmodified route hints.
×
UNCOV
555
        if !isLSP(hints, s.cfg.RouterBackend.FetchChannelEndpoints) {
×
UNCOV
556
                probeRequest.RouteHints = invoicesrpc.CreateRPCRouteHints(hints)
×
UNCOV
557
                return s.sendProbePayment(ctx, probeRequest)
×
UNCOV
558
        }
×
559

560
        // If the heuristic indicates an LSP we modify the route hints to allow
561
        // probing the LSP.
UNCOV
562
        lspAdjustedRouteHints, lspHint, err := prepareLspRouteHints(
×
UNCOV
563
                hints, *payReq.MilliSat,
×
UNCOV
564
        )
×
UNCOV
565
        if err != nil {
×
566
                return nil, err
×
567
        }
×
568

569
        // The adjusted route hints serve the payment probe to find the last
570
        // public hop to the LSP on the route.
UNCOV
571
        probeRequest.Dest = lspHint.NodeID.SerializeCompressed()
×
UNCOV
572
        if len(lspAdjustedRouteHints) > 0 {
×
573
                probeRequest.RouteHints = invoicesrpc.CreateRPCRouteHints(
×
574
                        lspAdjustedRouteHints,
×
575
                )
×
576
        }
×
577

578
        // The payment probe will be able to calculate the fee up until the LSP
579
        // node. The fee of the last hop has to be calculated manually. Since
580
        // the last hop's fee amount has to be sent across the payment path we
581
        // have to add it to the original payment amount. Only then will the
582
        // payment probe be able to determine the correct fee to the last hop
583
        // prior to the private destination. For example, if the user wants to
584
        // send 1000 sats to a private destination and the last hop's fee is 10
585
        // sats, then 1010 sats will have to arrive at the last hop. This means
586
        // that the probe has to be dispatched with 1010 sats to correctly
587
        // calculate the routing fee.
588
        //
589
        // Calculate the hop fee for the last hop manually.
UNCOV
590
        hopFee := lspHint.HopFee(*payReq.MilliSat)
×
UNCOV
591
        if err != nil {
×
592
                return nil, err
×
593
        }
×
594

595
        // Add the last hop's fee to the requested payment amount that we want
596
        // to get an estimate for.
UNCOV
597
        probeRequest.AmtMsat += int64(hopFee)
×
UNCOV
598

×
UNCOV
599
        // Use the hop hint's cltv delta as the payment request's final cltv
×
UNCOV
600
        // delta. The actual final cltv delta of the invoice will be added to
×
UNCOV
601
        // the payment probe's cltv delta.
×
UNCOV
602
        probeRequest.FinalCltvDelta = int32(lspHint.CLTVExpiryDelta)
×
UNCOV
603

×
UNCOV
604
        // Dispatch the payment probe with adjusted fee amount.
×
UNCOV
605
        resp, err := s.sendProbePayment(ctx, probeRequest)
×
UNCOV
606
        if err != nil {
×
607
                return nil, err
×
608
        }
×
609

610
        // If the payment probe failed we only return the failure reason and
611
        // leave the probe result params unaltered.
UNCOV
612
        if resp.FailureReason != lnrpc.PaymentFailureReason_FAILURE_REASON_NONE { //nolint:ll
×
613
                return resp, nil
×
614
        }
×
615

616
        // The probe succeeded, so we can add the last hop's fee to fee the
617
        // payment probe returned.
UNCOV
618
        resp.RoutingFeeMsat += int64(hopFee)
×
UNCOV
619

×
UNCOV
620
        // Add the final cltv delta of the invoice to the payment probe's total
×
UNCOV
621
        // cltv delta. This is the cltv delta for the hop behind the LSP.
×
UNCOV
622
        resp.TimeLockDelay += int64(payReq.MinFinalCLTVExpiry())
×
UNCOV
623

×
UNCOV
624
        return resp, nil
×
625
}
626

627
// isLSP checks if the route hints indicate an LSP. An LSP is indicated with
628
// true if the destination hop hint in each route hint has the same node id,
629
// false otherwise. If the destination hop hint of any route hint contains a
630
// public channel, the function returns false because we can directly send a
631
// probe to the final destination.
632
func isLSP(routeHints [][]zpay32.HopHint,
633
        fetchChannelEndpoints FetchChannelEndpoints) bool {
9✔
634

9✔
635
        if len(routeHints) == 0 || len(routeHints[0]) == 0 {
10✔
636
                return false
1✔
637
        }
1✔
638

639
        destHopHint := routeHints[0][len(routeHints[0])-1]
8✔
640

8✔
641
        // If the destination hop hint of the first route hint contains a public
8✔
642
        // channel we can send a probe to it directly, hence we don't signal an
8✔
643
        // LSP.
8✔
644
        _, _, err := fetchChannelEndpoints(destHopHint.ChannelID)
8✔
645
        if err == nil {
9✔
646
                return false
1✔
647
        }
1✔
648

649
        for i := 1; i < len(routeHints); i++ {
12✔
650
                // Skip empty route hints.
5✔
651
                if len(routeHints[i]) == 0 {
5✔
652
                        continue
×
653
                }
654

655
                lastHop := routeHints[i][len(routeHints[i])-1]
5✔
656

5✔
657
                // If the last hop hint of any route hint contains a public
5✔
658
                // channel we can send a probe to it directly, hence we don't
5✔
659
                // signal an LSP.
5✔
660
                _, _, err = fetchChannelEndpoints(lastHop.ChannelID)
5✔
661
                if err == nil {
6✔
662
                        return false
1✔
663
                }
1✔
664

665
                idMatchesRefNode := bytes.Equal(
4✔
666
                        lastHop.NodeID.SerializeCompressed(),
4✔
667
                        destHopHint.NodeID.SerializeCompressed(),
4✔
668
                )
4✔
669
                if !idMatchesRefNode {
5✔
670
                        return false
1✔
671
                }
1✔
672
        }
673

674
        // We ensured that the destination hop hint doesn't contain a public
675
        // channel, and that all destination hop hints of all route hints match,
676
        // so we signal an LSP.
677
        return true
5✔
678
}
679

680
// prepareLspRouteHints assumes that the isLsp heuristic returned true for the
681
// route hints passed in here. It constructs a modified list of route hints that
682
// allows the caller to probe the LSP, which itself is returned as a separate
683
// hop hint.
684
func prepareLspRouteHints(routeHints [][]zpay32.HopHint,
685
        amt lnwire.MilliSatoshi) ([][]zpay32.HopHint, *zpay32.HopHint, error) {
5✔
686

5✔
687
        if len(routeHints) == 0 {
5✔
688
                return nil, nil, fmt.Errorf("no route hints provided")
×
689
        }
×
690

691
        // Create the LSP hop hint. We are probing for the worst case fee and
692
        // cltv delta. So we look for the max values amongst all LSP hop hints.
693
        refHint := routeHints[0][len(routeHints[0])-1]
5✔
694
        refHint.CLTVExpiryDelta = maxLspCltvDelta(routeHints)
5✔
695
        refHint.FeeBaseMSat, refHint.FeeProportionalMillionths = maxLspFee(
5✔
696
                routeHints, amt,
5✔
697
        )
5✔
698

5✔
699
        // We construct a modified list of route hints that allows the caller to
5✔
700
        // probe the LSP.
5✔
701
        adjustedHints := make([][]zpay32.HopHint, 0, len(routeHints))
5✔
702

5✔
703
        // Strip off the LSP hop hint from all route hints.
5✔
704
        for i := 0; i < len(routeHints); i++ {
13✔
705
                hint := routeHints[i]
8✔
706
                if len(hint) > 1 {
13✔
707
                        adjustedHints = append(
5✔
708
                                adjustedHints, hint[:len(hint)-1],
5✔
709
                        )
5✔
710
                }
5✔
711
        }
712

713
        return adjustedHints, &refHint, nil
5✔
714
}
715

716
// maxLspFee returns base fee and fee rate amongst all LSP route hints that
717
// results in the overall highest fee for the given amount.
718
func maxLspFee(routeHints [][]zpay32.HopHint, amt lnwire.MilliSatoshi) (uint32,
719
        uint32) {
5✔
720

5✔
721
        var maxFeePpm uint32
5✔
722
        var maxBaseFee uint32
5✔
723
        var maxTotalFee lnwire.MilliSatoshi
5✔
724
        for _, rh := range routeHints {
13✔
725
                lastHop := rh[len(rh)-1]
8✔
726
                lastHopFee := lastHop.HopFee(amt)
8✔
727
                if lastHopFee > maxTotalFee {
14✔
728
                        maxTotalFee = lastHopFee
6✔
729
                        maxBaseFee = lastHop.FeeBaseMSat
6✔
730
                        maxFeePpm = lastHop.FeeProportionalMillionths
6✔
731
                }
6✔
732
        }
733

734
        return maxBaseFee, maxFeePpm
5✔
735
}
736

737
// maxLspCltvDelta returns the maximum cltv delta amongst all LSP route hints.
738
func maxLspCltvDelta(routeHints [][]zpay32.HopHint) uint16 {
5✔
739
        var maxCltvDelta uint16
5✔
740
        for _, rh := range routeHints {
13✔
741
                rhLastHop := rh[len(rh)-1]
8✔
742
                if rhLastHop.CLTVExpiryDelta > maxCltvDelta {
12✔
743
                        maxCltvDelta = rhLastHop.CLTVExpiryDelta
4✔
744
                }
4✔
745
        }
746

747
        return maxCltvDelta
5✔
748
}
749

750
// probePaymentStream is a custom implementation of the grpc.ServerStream
751
// interface. It is used to send payment status updates to the caller on the
752
// stream channel.
753
type probePaymentStream struct {
754
        Router_SendPaymentV2Server
755

756
        stream chan *lnrpc.Payment
757
        ctx    context.Context //nolint:containedctx
758
}
759

760
// Send sends a payment status update to a payment stream that the caller can
761
// evaluate.
UNCOV
762
func (p *probePaymentStream) Send(response *lnrpc.Payment) error {
×
UNCOV
763
        select {
×
UNCOV
764
        case p.stream <- response:
×
765

766
        case <-p.ctx.Done():
×
767
                return p.ctx.Err()
×
768
        }
769

UNCOV
770
        return nil
×
771
}
772

773
// Context returns the context of the stream.
UNCOV
774
func (p *probePaymentStream) Context() context.Context {
×
UNCOV
775
        return p.ctx
×
UNCOV
776
}
×
777

778
// sendProbePayment sends a payment to a target node in order to obtain
779
// potential routing fees for it. The payment request has to contain a payment
780
// hash that is guaranteed to be unknown to the target node, so it cannot settle
781
// the payment. This method invokes a payment request loop in a goroutine and
782
// awaits payment status updates.
783
func (s *Server) sendProbePayment(ctx context.Context,
UNCOV
784
        req *SendPaymentRequest) (*RouteFeeResponse, error) {
×
UNCOV
785

×
UNCOV
786
        // We'll launch a goroutine to send the payment probes.
×
UNCOV
787
        errChan := make(chan error, 1)
×
UNCOV
788
        defer close(errChan)
×
UNCOV
789

×
UNCOV
790
        paymentStream := &probePaymentStream{
×
UNCOV
791
                stream: make(chan *lnrpc.Payment),
×
UNCOV
792
                ctx:    ctx,
×
UNCOV
793
        }
×
UNCOV
794
        go func() {
×
UNCOV
795
                err := s.SendPaymentV2(req, paymentStream)
×
UNCOV
796
                if err != nil {
×
797
                        select {
×
798
                        case errChan <- err:
×
799

800
                        case <-paymentStream.ctx.Done():
×
801
                                return
×
802
                        }
803
                }
804
        }()
805

UNCOV
806
        for {
×
UNCOV
807
                select {
×
UNCOV
808
                case payment := <-paymentStream.stream:
×
UNCOV
809
                        switch payment.Status {
×
810
                        case lnrpc.Payment_INITIATED:
×
UNCOV
811
                        case lnrpc.Payment_IN_FLIGHT:
×
812
                        case lnrpc.Payment_SUCCEEDED:
×
813
                                return nil, errors.New("warning, the fee " +
×
814
                                        "estimation payment probe " +
×
815
                                        "unexpectedly succeeded. Please reach" +
×
816
                                        "out to the probe destination to " +
×
817
                                        "negotiate a refund. Otherwise the " +
×
818
                                        "payment probe amount is lost forever")
×
819

UNCOV
820
                        case lnrpc.Payment_FAILED:
×
UNCOV
821
                                // Incorrect payment details point to a
×
UNCOV
822
                                // successful probe.
×
UNCOV
823
                                //nolint:ll
×
UNCOV
824
                                if payment.FailureReason == lnrpc.PaymentFailureReason_FAILURE_REASON_INCORRECT_PAYMENT_DETAILS {
×
UNCOV
825
                                        return paymentDetails(payment)
×
UNCOV
826
                                }
×
827

UNCOV
828
                                return &RouteFeeResponse{
×
UNCOV
829
                                        RoutingFeeMsat: 0,
×
UNCOV
830
                                        TimeLockDelay:  0,
×
UNCOV
831
                                        FailureReason:  payment.FailureReason,
×
UNCOV
832
                                }, nil
×
833

834
                        default:
×
835
                                return nil, errors.New("unexpected payment " +
×
836
                                        "status")
×
837
                        }
838

839
                case err := <-errChan:
×
840
                        return nil, err
×
841

842
                case <-s.quit:
×
843
                        return nil, errServerShuttingDown
×
844
                }
845
        }
846
}
847

UNCOV
848
func paymentDetails(payment *lnrpc.Payment) (*RouteFeeResponse, error) {
×
UNCOV
849
        fee, timeLock, err := timelockAndFee(payment)
×
UNCOV
850
        if errors.Is(err, errUnexpectedFailureSource) {
×
851
                return nil, err
×
852
        }
×
853

UNCOV
854
        return &RouteFeeResponse{
×
UNCOV
855
                RoutingFeeMsat: fee,
×
UNCOV
856
                TimeLockDelay:  timeLock,
×
UNCOV
857
                FailureReason:  lnrpc.PaymentFailureReason_FAILURE_REASON_NONE,
×
UNCOV
858
        }, nil
×
859
}
860

861
// timelockAndFee returns the fee and total time lock of the last payment
862
// attempt.
UNCOV
863
func timelockAndFee(p *lnrpc.Payment) (int64, int64, error) {
×
UNCOV
864
        if len(p.Htlcs) == 0 {
×
865
                return 0, 0, nil
×
866
        }
×
867

UNCOV
868
        lastAttempt := p.Htlcs[len(p.Htlcs)-1]
×
UNCOV
869
        if lastAttempt == nil {
×
870
                return 0, 0, errMissingPaymentAttempt
×
871
        }
×
872

UNCOV
873
        lastRoute := lastAttempt.Route
×
UNCOV
874
        if lastRoute == nil {
×
875
                return 0, 0, errMissingRoute
×
876
        }
×
877

UNCOV
878
        hopFailureIndex := lastAttempt.Failure.FailureSourceIndex
×
UNCOV
879
        finalHopIndex := uint32(len(lastRoute.Hops))
×
UNCOV
880
        if hopFailureIndex != finalHopIndex {
×
881
                return 0, 0, errUnexpectedFailureSource
×
882
        }
×
883

UNCOV
884
        return lastRoute.TotalFeesMsat, int64(lastRoute.TotalTimeLock), nil
×
885
}
886

887
// SendToRouteV2 sends a payment through a predefined route. The response of
888
// this call contains structured error information.
889
func (s *Server) SendToRouteV2(ctx context.Context,
UNCOV
890
        req *SendToRouteRequest) (*lnrpc.HTLCAttempt, error) {
×
UNCOV
891

×
UNCOV
892
        if req.Route == nil {
×
893
                return nil, fmt.Errorf("unable to send, no routes provided")
×
894
        }
×
895

UNCOV
896
        route, err := s.cfg.RouterBackend.UnmarshallRoute(req.Route)
×
UNCOV
897
        if err != nil {
×
898
                return nil, err
×
899
        }
×
900

UNCOV
901
        hash, err := lntypes.MakeHash(req.PaymentHash)
×
UNCOV
902
        if err != nil {
×
903
                return nil, err
×
904
        }
×
905

UNCOV
906
        firstHopRecords := lnwire.CustomRecords(req.FirstHopCustomRecords)
×
UNCOV
907
        if err := firstHopRecords.Validate(); err != nil {
×
908
                return nil, err
×
909
        }
×
910

UNCOV
911
        var attempt *channeldb.HTLCAttempt
×
UNCOV
912

×
UNCOV
913
        // Pass route to the router. This call returns the full htlc attempt
×
UNCOV
914
        // information as it is stored in the database. It is possible that both
×
UNCOV
915
        // the attempt return value and err are non-nil. This can happen when
×
UNCOV
916
        // the attempt was already initiated before the error happened. In that
×
UNCOV
917
        // case, we give precedence to the attempt information as stored in the
×
UNCOV
918
        // db.
×
UNCOV
919
        if req.SkipTempErr {
×
920
                attempt, err = s.cfg.Router.SendToRouteSkipTempErr(
×
921
                        hash, route, firstHopRecords,
×
922
                )
×
UNCOV
923
        } else {
×
UNCOV
924
                attempt, err = s.cfg.Router.SendToRoute(
×
UNCOV
925
                        hash, route, firstHopRecords,
×
UNCOV
926
                )
×
UNCOV
927
        }
×
UNCOV
928
        if attempt != nil {
×
UNCOV
929
                rpcAttempt, err := s.cfg.RouterBackend.MarshalHTLCAttempt(
×
UNCOV
930
                        *attempt,
×
UNCOV
931
                )
×
UNCOV
932
                if err != nil {
×
933
                        return nil, err
×
934
                }
×
UNCOV
935
                return rpcAttempt, nil
×
936
        }
937

938
        // Transform user errors to grpc code.
939
        switch {
×
940
        case errors.Is(err, channeldb.ErrPaymentExists):
×
941
                fallthrough
×
942

943
        case errors.Is(err, channeldb.ErrPaymentInFlight):
×
944
                fallthrough
×
945

946
        case errors.Is(err, channeldb.ErrAlreadyPaid):
×
947
                return nil, status.Error(
×
948
                        codes.AlreadyExists, err.Error(),
×
949
                )
×
950
        }
951

952
        return nil, err
×
953
}
954

955
// ResetMissionControl clears all mission control state and starts with a clean
956
// slate.
957
func (s *Server) ResetMissionControl(ctx context.Context,
UNCOV
958
        req *ResetMissionControlRequest) (*ResetMissionControlResponse, error) {
×
UNCOV
959

×
UNCOV
960
        err := s.cfg.RouterBackend.MissionControl.ResetHistory()
×
UNCOV
961
        if err != nil {
×
962
                return nil, err
×
963
        }
×
964

UNCOV
965
        return &ResetMissionControlResponse{}, nil
×
966
}
967

968
// GetMissionControlConfig returns our current mission control config.
969
func (s *Server) GetMissionControlConfig(ctx context.Context,
970
        req *GetMissionControlConfigRequest) (*GetMissionControlConfigResponse,
UNCOV
971
        error) {
×
UNCOV
972

×
UNCOV
973
        // Query the current mission control config.
×
UNCOV
974
        cfg := s.cfg.RouterBackend.MissionControl.GetConfig()
×
UNCOV
975
        resp := &GetMissionControlConfigResponse{
×
UNCOV
976
                Config: &MissionControlConfig{
×
UNCOV
977
                        MaximumPaymentResults: uint32(cfg.MaxMcHistory),
×
UNCOV
978
                        MinimumFailureRelaxInterval: uint64(
×
UNCOV
979
                                cfg.MinFailureRelaxInterval.Seconds(),
×
UNCOV
980
                        ),
×
UNCOV
981
                },
×
UNCOV
982
        }
×
UNCOV
983

×
UNCOV
984
        // We only populate fields based on the current estimator.
×
UNCOV
985
        switch v := cfg.Estimator.Config().(type) {
×
UNCOV
986
        case routing.AprioriConfig:
×
UNCOV
987
                resp.Config.Model = MissionControlConfig_APRIORI
×
UNCOV
988
                aCfg := AprioriParameters{
×
UNCOV
989
                        HalfLifeSeconds:  uint64(v.PenaltyHalfLife.Seconds()),
×
UNCOV
990
                        HopProbability:   v.AprioriHopProbability,
×
UNCOV
991
                        Weight:           v.AprioriWeight,
×
UNCOV
992
                        CapacityFraction: v.CapacityFraction,
×
UNCOV
993
                }
×
UNCOV
994

×
UNCOV
995
                // Populate deprecated fields.
×
UNCOV
996
                resp.Config.HalfLifeSeconds = uint64(
×
UNCOV
997
                        v.PenaltyHalfLife.Seconds(),
×
UNCOV
998
                )
×
UNCOV
999
                resp.Config.HopProbability = float32(v.AprioriHopProbability)
×
UNCOV
1000
                resp.Config.Weight = float32(v.AprioriWeight)
×
UNCOV
1001

×
UNCOV
1002
                resp.Config.EstimatorConfig = &MissionControlConfig_Apriori{
×
UNCOV
1003
                        Apriori: &aCfg,
×
UNCOV
1004
                }
×
1005

UNCOV
1006
        case routing.BimodalConfig:
×
UNCOV
1007
                resp.Config.Model = MissionControlConfig_BIMODAL
×
UNCOV
1008
                bCfg := BimodalParameters{
×
UNCOV
1009
                        NodeWeight: v.BimodalNodeWeight,
×
UNCOV
1010
                        ScaleMsat:  uint64(v.BimodalScaleMsat),
×
UNCOV
1011
                        DecayTime:  uint64(v.BimodalDecayTime.Seconds()),
×
UNCOV
1012
                }
×
UNCOV
1013

×
UNCOV
1014
                resp.Config.EstimatorConfig = &MissionControlConfig_Bimodal{
×
UNCOV
1015
                        Bimodal: &bCfg,
×
UNCOV
1016
                }
×
1017

1018
        default:
×
1019
                return nil, fmt.Errorf("unknown estimator config type %T", v)
×
1020
        }
1021

UNCOV
1022
        return resp, nil
×
1023
}
1024

1025
// SetMissionControlConfig sets parameters in the mission control config.
1026
func (s *Server) SetMissionControlConfig(ctx context.Context,
1027
        req *SetMissionControlConfigRequest) (*SetMissionControlConfigResponse,
UNCOV
1028
        error) {
×
UNCOV
1029

×
UNCOV
1030
        mcCfg := &routing.MissionControlConfig{
×
UNCOV
1031
                MaxMcHistory: int(req.Config.MaximumPaymentResults),
×
UNCOV
1032
                MinFailureRelaxInterval: time.Duration(
×
UNCOV
1033
                        req.Config.MinimumFailureRelaxInterval,
×
UNCOV
1034
                ) * time.Second,
×
UNCOV
1035
        }
×
UNCOV
1036

×
UNCOV
1037
        switch req.Config.Model {
×
UNCOV
1038
        case MissionControlConfig_APRIORI:
×
UNCOV
1039
                var aprioriConfig routing.AprioriConfig
×
UNCOV
1040

×
UNCOV
1041
                // Determine the apriori config with backward compatibility
×
UNCOV
1042
                // should the api use deprecated fields.
×
UNCOV
1043
                switch v := req.Config.EstimatorConfig.(type) {
×
UNCOV
1044
                case *MissionControlConfig_Bimodal:
×
UNCOV
1045
                        return nil, fmt.Errorf("bimodal config " +
×
UNCOV
1046
                                "provided, but apriori model requested")
×
1047

UNCOV
1048
                case *MissionControlConfig_Apriori:
×
UNCOV
1049
                        aprioriConfig = routing.AprioriConfig{
×
UNCOV
1050
                                PenaltyHalfLife: time.Duration(
×
UNCOV
1051
                                        v.Apriori.HalfLifeSeconds,
×
UNCOV
1052
                                ) * time.Second,
×
UNCOV
1053
                                AprioriHopProbability: v.Apriori.HopProbability,
×
UNCOV
1054
                                AprioriWeight:         v.Apriori.Weight,
×
UNCOV
1055
                                CapacityFraction: v.Apriori.
×
UNCOV
1056
                                        CapacityFraction,
×
UNCOV
1057
                        }
×
1058

UNCOV
1059
                default:
×
UNCOV
1060
                        aprioriConfig = routing.AprioriConfig{
×
UNCOV
1061
                                PenaltyHalfLife: time.Duration(
×
UNCOV
1062
                                        int64(req.Config.HalfLifeSeconds),
×
UNCOV
1063
                                ) * time.Second,
×
UNCOV
1064
                                AprioriHopProbability: float64(
×
UNCOV
1065
                                        req.Config.HopProbability,
×
UNCOV
1066
                                ),
×
UNCOV
1067
                                AprioriWeight:    float64(req.Config.Weight),
×
UNCOV
1068
                                CapacityFraction: routing.DefaultCapacityFraction, //nolint:ll
×
UNCOV
1069
                        }
×
1070
                }
1071

UNCOV
1072
                estimator, err := routing.NewAprioriEstimator(aprioriConfig)
×
UNCOV
1073
                if err != nil {
×
1074
                        return nil, err
×
1075
                }
×
UNCOV
1076
                mcCfg.Estimator = estimator
×
1077

UNCOV
1078
        case MissionControlConfig_BIMODAL:
×
UNCOV
1079
                cfg, ok := req.Config.
×
UNCOV
1080
                        EstimatorConfig.(*MissionControlConfig_Bimodal)
×
UNCOV
1081
                if !ok {
×
1082
                        return nil, fmt.Errorf("bimodal estimator requested " +
×
1083
                                "but corresponding config not set")
×
1084
                }
×
UNCOV
1085
                bCfg := cfg.Bimodal
×
UNCOV
1086

×
UNCOV
1087
                bimodalConfig := routing.BimodalConfig{
×
UNCOV
1088
                        BimodalDecayTime: time.Duration(
×
UNCOV
1089
                                bCfg.DecayTime,
×
UNCOV
1090
                        ) * time.Second,
×
UNCOV
1091
                        BimodalScaleMsat:  lnwire.MilliSatoshi(bCfg.ScaleMsat),
×
UNCOV
1092
                        BimodalNodeWeight: bCfg.NodeWeight,
×
UNCOV
1093
                }
×
UNCOV
1094

×
UNCOV
1095
                estimator, err := routing.NewBimodalEstimator(bimodalConfig)
×
UNCOV
1096
                if err != nil {
×
1097
                        return nil, err
×
1098
                }
×
UNCOV
1099
                mcCfg.Estimator = estimator
×
1100

1101
        default:
×
1102
                return nil, fmt.Errorf("unknown estimator type %v",
×
1103
                        req.Config.Model)
×
1104
        }
1105

UNCOV
1106
        return &SetMissionControlConfigResponse{},
×
UNCOV
1107
                s.cfg.RouterBackend.MissionControl.SetConfig(mcCfg)
×
1108
}
1109

1110
// QueryMissionControl exposes the internal mission control state to callers. It
1111
// is a development feature.
1112
func (s *Server) QueryMissionControl(_ context.Context,
1113
        _ *QueryMissionControlRequest) (*QueryMissionControlResponse, error) {
×
1114

×
1115
        snapshot := s.cfg.RouterBackend.MissionControl.GetHistorySnapshot()
×
1116

×
1117
        rpcPairs := make([]*PairHistory, 0, len(snapshot.Pairs))
×
1118
        for _, p := range snapshot.Pairs {
×
1119
                // Prevent binding to loop variable.
×
1120
                pair := p
×
1121

×
1122
                rpcPair := PairHistory{
×
1123
                        NodeFrom: pair.Pair.From[:],
×
1124
                        NodeTo:   pair.Pair.To[:],
×
1125
                        History:  toRPCPairData(&pair.TimedPairResult),
×
1126
                }
×
1127

×
1128
                rpcPairs = append(rpcPairs, &rpcPair)
×
1129
        }
×
1130

1131
        response := QueryMissionControlResponse{
×
1132
                Pairs: rpcPairs,
×
1133
        }
×
1134

×
1135
        return &response, nil
×
1136
}
1137

1138
// toRPCPairData marshalls mission control pair data to the rpc struct.
UNCOV
1139
func toRPCPairData(data *routing.TimedPairResult) *PairData {
×
UNCOV
1140
        rpcData := PairData{
×
UNCOV
1141
                FailAmtSat:     int64(data.FailAmt.ToSatoshis()),
×
UNCOV
1142
                FailAmtMsat:    int64(data.FailAmt),
×
UNCOV
1143
                SuccessAmtSat:  int64(data.SuccessAmt.ToSatoshis()),
×
UNCOV
1144
                SuccessAmtMsat: int64(data.SuccessAmt),
×
UNCOV
1145
        }
×
UNCOV
1146

×
UNCOV
1147
        if !data.FailTime.IsZero() {
×
UNCOV
1148
                rpcData.FailTime = data.FailTime.Unix()
×
UNCOV
1149
        }
×
1150

UNCOV
1151
        if !data.SuccessTime.IsZero() {
×
1152
                rpcData.SuccessTime = data.SuccessTime.Unix()
×
1153
        }
×
1154

UNCOV
1155
        return &rpcData
×
1156
}
1157

1158
// XImportMissionControl imports the state provided to our internal mission
1159
// control. Only entries that are fresher than our existing state will be used.
1160
func (s *Server) XImportMissionControl(_ context.Context,
1161
        req *XImportMissionControlRequest) (*XImportMissionControlResponse,
UNCOV
1162
        error) {
×
UNCOV
1163

×
UNCOV
1164
        if len(req.Pairs) == 0 {
×
1165
                return nil, errors.New("at least one pair required for import")
×
1166
        }
×
1167

UNCOV
1168
        snapshot := &routing.MissionControlSnapshot{
×
UNCOV
1169
                Pairs: make(
×
UNCOV
1170
                        []routing.MissionControlPairSnapshot, len(req.Pairs),
×
UNCOV
1171
                ),
×
UNCOV
1172
        }
×
UNCOV
1173

×
UNCOV
1174
        for i, pairResult := range req.Pairs {
×
UNCOV
1175
                pairSnapshot, err := toPairSnapshot(pairResult)
×
UNCOV
1176
                if err != nil {
×
UNCOV
1177
                        return nil, err
×
UNCOV
1178
                }
×
1179

UNCOV
1180
                snapshot.Pairs[i] = *pairSnapshot
×
1181
        }
1182

UNCOV
1183
        err := s.cfg.RouterBackend.MissionControl.ImportHistory(
×
UNCOV
1184
                snapshot, req.Force,
×
UNCOV
1185
        )
×
UNCOV
1186
        if err != nil {
×
1187
                return nil, err
×
1188
        }
×
1189

UNCOV
1190
        return &XImportMissionControlResponse{}, nil
×
1191
}
1192

1193
func toPairSnapshot(pairResult *PairHistory) (*routing.MissionControlPairSnapshot,
UNCOV
1194
        error) {
×
UNCOV
1195

×
UNCOV
1196
        from, err := route.NewVertexFromBytes(pairResult.NodeFrom)
×
UNCOV
1197
        if err != nil {
×
1198
                return nil, err
×
1199
        }
×
1200

UNCOV
1201
        to, err := route.NewVertexFromBytes(pairResult.NodeTo)
×
UNCOV
1202
        if err != nil {
×
1203
                return nil, err
×
1204
        }
×
1205

UNCOV
1206
        pairPrefix := fmt.Sprintf("pair: %v -> %v:", from, to)
×
UNCOV
1207

×
UNCOV
1208
        if from == to {
×
1209
                return nil, fmt.Errorf("%v source and destination node must "+
×
1210
                        "differ", pairPrefix)
×
1211
        }
×
1212

UNCOV
1213
        failAmt, failTime, err := getPair(
×
UNCOV
1214
                lnwire.MilliSatoshi(pairResult.History.FailAmtMsat),
×
UNCOV
1215
                btcutil.Amount(pairResult.History.FailAmtSat),
×
UNCOV
1216
                pairResult.History.FailTime,
×
UNCOV
1217
                true,
×
UNCOV
1218
        )
×
UNCOV
1219
        if err != nil {
×
UNCOV
1220
                return nil, fmt.Errorf("%v invalid failure: %w", pairPrefix,
×
UNCOV
1221
                        err)
×
UNCOV
1222
        }
×
1223

UNCOV
1224
        successAmt, successTime, err := getPair(
×
UNCOV
1225
                lnwire.MilliSatoshi(pairResult.History.SuccessAmtMsat),
×
UNCOV
1226
                btcutil.Amount(pairResult.History.SuccessAmtSat),
×
UNCOV
1227
                pairResult.History.SuccessTime,
×
UNCOV
1228
                false,
×
UNCOV
1229
        )
×
UNCOV
1230
        if err != nil {
×
1231
                return nil, fmt.Errorf("%v invalid success: %w", pairPrefix,
×
1232
                        err)
×
1233
        }
×
1234

UNCOV
1235
        if successAmt == 0 && failAmt == 0 {
×
1236
                return nil, fmt.Errorf("%v: either success or failure result "+
×
1237
                        "required", pairPrefix)
×
1238
        }
×
1239

UNCOV
1240
        pair := routing.NewDirectedNodePair(from, to)
×
UNCOV
1241

×
UNCOV
1242
        result := &routing.TimedPairResult{
×
UNCOV
1243
                FailAmt:     failAmt,
×
UNCOV
1244
                FailTime:    failTime,
×
UNCOV
1245
                SuccessAmt:  successAmt,
×
UNCOV
1246
                SuccessTime: successTime,
×
UNCOV
1247
        }
×
UNCOV
1248

×
UNCOV
1249
        return &routing.MissionControlPairSnapshot{
×
UNCOV
1250
                Pair:            pair,
×
UNCOV
1251
                TimedPairResult: *result,
×
UNCOV
1252
        }, nil
×
1253
}
1254

1255
// getPair validates the values provided for a mission control result and
1256
// returns the msat amount and timestamp for it. `isFailure` can be used to
1257
// default values to 0 instead of returning an error.
1258
func getPair(amtMsat lnwire.MilliSatoshi, amtSat btcutil.Amount,
1259
        timestamp int64, isFailure bool) (lnwire.MilliSatoshi, time.Time,
UNCOV
1260
        error) {
×
UNCOV
1261

×
UNCOV
1262
        amt, err := getMsatPairValue(amtMsat, amtSat)
×
UNCOV
1263
        if err != nil {
×
UNCOV
1264
                return 0, time.Time{}, err
×
UNCOV
1265
        }
×
1266

UNCOV
1267
        var (
×
UNCOV
1268
                timeSet   = timestamp != 0
×
UNCOV
1269
                amountSet = amt != 0
×
UNCOV
1270
        )
×
UNCOV
1271

×
UNCOV
1272
        switch {
×
1273
        // If a timestamp and amount if provided, return those values.
UNCOV
1274
        case timeSet && amountSet:
×
UNCOV
1275
                return amt, time.Unix(timestamp, 0), nil
×
1276

1277
        // Return an error if it does have a timestamp without an amount, and
1278
        // it's not expected to be a failure.
1279
        case !isFailure && timeSet && !amountSet:
×
1280
                return 0, time.Time{}, errors.New("non-zero timestamp " +
×
1281
                        "requires non-zero amount for success pairs")
×
1282

1283
        // Return an error if it does have an amount without a timestamp, and
1284
        // it's not expected to be a failure.
1285
        case !isFailure && !timeSet && amountSet:
×
1286
                return 0, time.Time{}, errors.New("non-zero amount for " +
×
1287
                        "success pairs requires non-zero timestamp")
×
1288

UNCOV
1289
        default:
×
UNCOV
1290
                return 0, time.Time{}, nil
×
1291
        }
1292
}
1293

1294
// getMsatPairValue checks the msat and sat values set for a pair and ensures
1295
// that the values provided are either the same, or only a single value is set.
1296
func getMsatPairValue(msatValue lnwire.MilliSatoshi,
UNCOV
1297
        satValue btcutil.Amount) (lnwire.MilliSatoshi, error) {
×
UNCOV
1298

×
UNCOV
1299
        // If our msat value converted to sats equals our sat value, we just
×
UNCOV
1300
        // return the msat value, since the values are the same.
×
UNCOV
1301
        if msatValue.ToSatoshis() == satValue {
×
UNCOV
1302
                return msatValue, nil
×
UNCOV
1303
        }
×
1304

1305
        // If we have no msatValue, we can just return our state value even if
1306
        // it is zero, because it's impossible that we have mismatched values.
UNCOV
1307
        if msatValue == 0 {
×
1308
                return lnwire.MilliSatoshi(satValue * 1000), nil
×
1309
        }
×
1310

1311
        // Likewise, we can just use msat value if we have no sat value set.
UNCOV
1312
        if satValue == 0 {
×
1313
                return msatValue, nil
×
1314
        }
×
1315

1316
        // If our values are non-zero but not equal, we have invalid amounts
1317
        // set, so we fail.
UNCOV
1318
        return 0, fmt.Errorf("msat: %v and sat: %v values not equal", msatValue,
×
UNCOV
1319
                satValue)
×
1320
}
1321

1322
// TrackPaymentV2 returns a stream of payment state updates. The stream is
1323
// closed when the payment completes.
1324
func (s *Server) TrackPaymentV2(request *TrackPaymentRequest,
UNCOV
1325
        stream Router_TrackPaymentV2Server) error {
×
UNCOV
1326

×
UNCOV
1327
        payHash, err := lntypes.MakeHash(request.PaymentHash)
×
UNCOV
1328
        if err != nil {
×
1329
                return err
×
1330
        }
×
1331

UNCOV
1332
        log.Debugf("TrackPayment called for payment %v", payHash)
×
UNCOV
1333

×
UNCOV
1334
        // Make the subscription.
×
UNCOV
1335
        sub, err := s.subscribePayment(payHash)
×
UNCOV
1336
        if err != nil {
×
1337
                return err
×
1338
        }
×
1339

UNCOV
1340
        return s.trackPayment(sub, payHash, stream, request.NoInflightUpdates)
×
1341
}
1342

1343
// subscribePayment subscribes to the payment updates for the given payment
1344
// hash.
1345
func (s *Server) subscribePayment(identifier lntypes.Hash) (
UNCOV
1346
        routing.ControlTowerSubscriber, error) {
×
UNCOV
1347

×
UNCOV
1348
        // Make the subscription.
×
UNCOV
1349
        router := s.cfg.RouterBackend
×
UNCOV
1350
        sub, err := router.Tower.SubscribePayment(identifier)
×
UNCOV
1351

×
UNCOV
1352
        switch {
×
1353
        case errors.Is(err, channeldb.ErrPaymentNotInitiated):
×
1354
                return nil, status.Error(codes.NotFound, err.Error())
×
1355

1356
        case err != nil:
×
1357
                return nil, err
×
1358
        }
1359

UNCOV
1360
        return sub, nil
×
1361
}
1362

1363
// trackPayment writes payment status updates to the provided stream.
1364
func (s *Server) trackPayment(subscription routing.ControlTowerSubscriber,
1365
        identifier lntypes.Hash, stream Router_TrackPaymentV2Server,
UNCOV
1366
        noInflightUpdates bool) error {
×
UNCOV
1367

×
UNCOV
1368
        err := s.trackPaymentStream(
×
UNCOV
1369
                stream.Context(), subscription, noInflightUpdates, stream.Send,
×
UNCOV
1370
        )
×
UNCOV
1371
        switch {
×
UNCOV
1372
        case err == nil:
×
UNCOV
1373
                return nil
×
1374

1375
        // If the context is canceled, we don't return an error.
UNCOV
1376
        case errors.Is(err, context.Canceled):
×
UNCOV
1377
                log.Infof("Payment stream %v canceled", identifier)
×
UNCOV
1378

×
UNCOV
1379
                return nil
×
1380

1381
        default:
×
1382
        }
1383

1384
        // Otherwise, we will log and return the error as the stream has
1385
        // received an error from the payment lifecycle.
1386
        log.Errorf("TrackPayment got error for payment %v: %v", identifier, err)
×
1387

×
1388
        return err
×
1389
}
1390

1391
// TrackPayments returns a stream of payment state updates.
1392
func (s *Server) TrackPayments(request *TrackPaymentsRequest,
1393
        stream Router_TrackPaymentsServer) error {
3✔
1394

3✔
1395
        log.Debug("TrackPayments called")
3✔
1396

3✔
1397
        router := s.cfg.RouterBackend
3✔
1398

3✔
1399
        // Subscribe to payments.
3✔
1400
        subscription, err := router.Tower.SubscribeAllPayments()
3✔
1401
        if err != nil {
3✔
1402
                return err
×
1403
        }
×
1404

1405
        // Stream updates to the client.
1406
        err = s.trackPaymentStream(
3✔
1407
                stream.Context(), subscription, request.NoInflightUpdates,
3✔
1408
                stream.Send,
3✔
1409
        )
3✔
1410

3✔
1411
        if errors.Is(err, context.Canceled) {
6✔
1412
                log.Debugf("TrackPayments payment stream canceled.")
3✔
1413
        }
3✔
1414

1415
        return err
3✔
1416
}
1417

1418
// trackPaymentStream streams payment updates to the client.
1419
func (s *Server) trackPaymentStream(context context.Context,
1420
        subscription routing.ControlTowerSubscriber, noInflightUpdates bool,
1421
        send func(*lnrpc.Payment) error) error {
3✔
1422

3✔
1423
        defer subscription.Close()
3✔
1424

3✔
1425
        // Stream updates back to the client.
3✔
1426
        for {
10✔
1427
                select {
7✔
1428
                case item, ok := <-subscription.Updates():
4✔
1429
                        if !ok {
4✔
UNCOV
1430
                                // No more payment updates.
×
UNCOV
1431
                                return nil
×
UNCOV
1432
                        }
×
1433
                        result := item.(*channeldb.MPPayment)
4✔
1434

4✔
1435
                        log.Tracef("Payment %v updated to state %v",
4✔
1436
                                result.Info.PaymentIdentifier, result.Status)
4✔
1437

4✔
1438
                        // Skip in-flight updates unless requested.
4✔
1439
                        if noInflightUpdates {
6✔
1440
                                if result.Status == channeldb.StatusInitiated {
2✔
UNCOV
1441
                                        continue
×
1442
                                }
1443
                                if result.Status == channeldb.StatusInFlight {
3✔
1444
                                        continue
1✔
1445
                                }
1446
                        }
1447

1448
                        rpcPayment, err := s.cfg.RouterBackend.MarshallPayment(
3✔
1449
                                result,
3✔
1450
                        )
3✔
1451
                        if err != nil {
3✔
1452
                                return err
×
1453
                        }
×
1454

1455
                        // Send event to the client.
1456
                        err = send(rpcPayment)
3✔
1457
                        if err != nil {
3✔
1458
                                return err
×
1459
                        }
×
1460

1461
                case <-s.quit:
×
1462
                        return errServerShuttingDown
×
1463

1464
                case <-context.Done():
3✔
1465
                        return context.Err()
3✔
1466
                }
1467
        }
1468
}
1469

1470
// BuildRoute builds a route from a list of hop addresses.
1471
func (s *Server) BuildRoute(_ context.Context,
UNCOV
1472
        req *BuildRouteRequest) (*BuildRouteResponse, error) {
×
UNCOV
1473

×
UNCOV
1474
        if len(req.HopPubkeys) == 0 {
×
1475
                return nil, errors.New("no hops specified")
×
1476
        }
×
1477

1478
        // Unmarshall hop list.
UNCOV
1479
        hops := make([]route.Vertex, len(req.HopPubkeys))
×
UNCOV
1480
        for i, pubkeyBytes := range req.HopPubkeys {
×
UNCOV
1481
                pubkey, err := route.NewVertexFromBytes(pubkeyBytes)
×
UNCOV
1482
                if err != nil {
×
1483
                        return nil, err
×
1484
                }
×
UNCOV
1485
                hops[i] = pubkey
×
1486
        }
1487

1488
        // Prepare BuildRoute call parameters from rpc request.
UNCOV
1489
        var amt fn.Option[lnwire.MilliSatoshi]
×
UNCOV
1490
        if req.AmtMsat != 0 {
×
UNCOV
1491
                rpcAmt := lnwire.MilliSatoshi(req.AmtMsat)
×
UNCOV
1492
                amt = fn.Some(rpcAmt)
×
UNCOV
1493
        }
×
1494

UNCOV
1495
        var outgoingChan *uint64
×
UNCOV
1496
        if req.OutgoingChanId != 0 {
×
1497
                outgoingChan = &req.OutgoingChanId
×
1498
        }
×
1499

NEW
1500
        var payAddr *[32]byte
×
UNCOV
1501
        if len(req.PaymentAddr) != 0 {
×
UNCOV
1502
                var backingPayAddr [32]byte
×
UNCOV
1503
                copy(backingPayAddr[:], req.PaymentAddr)
×
UNCOV
1504

×
NEW
1505
                payAddr = &backingPayAddr
×
UNCOV
1506
        }
×
1507

UNCOV
1508
        if req.FinalCltvDelta == 0 {
×
1509
                req.FinalCltvDelta = int32(
×
1510
                        s.cfg.RouterBackend.DefaultFinalCltvDelta,
×
1511
                )
×
1512
        }
×
1513

UNCOV
1514
        var firstHopBlob fn.Option[[]byte]
×
UNCOV
1515
        if len(req.FirstHopCustomRecords) > 0 {
×
1516
                firstHopRecords := lnwire.CustomRecords(
×
1517
                        req.FirstHopCustomRecords,
×
1518
                )
×
1519
                if err := firstHopRecords.Validate(); err != nil {
×
1520
                        return nil, err
×
1521
                }
×
1522

1523
                firstHopData, err := firstHopRecords.Serialize()
×
1524
                if err != nil {
×
1525
                        return nil, err
×
1526
                }
×
1527
                firstHopBlob = fn.Some(firstHopData)
×
1528
        }
1529

1530
        // Build the route and return it to the caller.
UNCOV
1531
        route, err := s.cfg.Router.BuildRoute(
×
UNCOV
1532
                amt, hops, outgoingChan, req.FinalCltvDelta, payAddr,
×
UNCOV
1533
                firstHopBlob,
×
UNCOV
1534
        )
×
UNCOV
1535
        if err != nil {
×
1536
                return nil, err
×
1537
        }
×
1538

UNCOV
1539
        rpcRoute, err := s.cfg.RouterBackend.MarshallRoute(route)
×
UNCOV
1540
        if err != nil {
×
1541
                return nil, err
×
1542
        }
×
1543

UNCOV
1544
        routeResp := &BuildRouteResponse{
×
UNCOV
1545
                Route: rpcRoute,
×
UNCOV
1546
        }
×
UNCOV
1547

×
UNCOV
1548
        return routeResp, nil
×
1549
}
1550

1551
// SubscribeHtlcEvents creates a uni-directional stream from the server to
1552
// the client which delivers a stream of htlc events.
1553
func (s *Server) SubscribeHtlcEvents(_ *SubscribeHtlcEventsRequest,
UNCOV
1554
        stream Router_SubscribeHtlcEventsServer) error {
×
UNCOV
1555

×
UNCOV
1556
        htlcClient, err := s.cfg.RouterBackend.SubscribeHtlcEvents()
×
UNCOV
1557
        if err != nil {
×
1558
                return err
×
1559
        }
×
UNCOV
1560
        defer htlcClient.Cancel()
×
UNCOV
1561

×
UNCOV
1562
        // Send out an initial subscribed event so that the caller knows the
×
UNCOV
1563
        // point from which new events will be transmitted.
×
UNCOV
1564
        if err := stream.Send(&HtlcEvent{
×
UNCOV
1565
                Event: &HtlcEvent_SubscribedEvent{
×
UNCOV
1566
                        SubscribedEvent: &SubscribedEvent{},
×
UNCOV
1567
                },
×
UNCOV
1568
        }); err != nil {
×
1569
                return err
×
1570
        }
×
1571

UNCOV
1572
        for {
×
UNCOV
1573
                select {
×
UNCOV
1574
                case event := <-htlcClient.Updates():
×
UNCOV
1575
                        rpcEvent, err := rpcHtlcEvent(event)
×
UNCOV
1576
                        if err != nil {
×
1577
                                return err
×
1578
                        }
×
1579

UNCOV
1580
                        if err := stream.Send(rpcEvent); err != nil {
×
1581
                                return err
×
1582
                        }
×
1583

1584
                // If the stream's context is cancelled, return an error.
UNCOV
1585
                case <-stream.Context().Done():
×
UNCOV
1586
                        log.Debugf("htlc event stream cancelled")
×
UNCOV
1587
                        return stream.Context().Err()
×
1588

1589
                // If the subscribe client terminates, exit with an error.
1590
                case <-htlcClient.Quit():
×
1591
                        return errors.New("htlc event subscription terminated")
×
1592

1593
                // If the server has been signalled to shut down, exit.
1594
                case <-s.quit:
×
1595
                        return errServerShuttingDown
×
1596
                }
1597
        }
1598
}
1599

1600
// HtlcInterceptor is a bidirectional stream for streaming interception
1601
// requests to the caller.
1602
// Upon connection, it does the following:
1603
// 1. Check if there is already a live stream, if yes it rejects the request.
1604
// 2. Registered a ForwardInterceptor
1605
// 3. Delivers to the caller every √√ and detect his answer.
1606
// It uses a local implementation of holdForwardsStore to keep all the hold
1607
// forwards and find them when manual resolution is later needed.
UNCOV
1608
func (s *Server) HtlcInterceptor(stream Router_HtlcInterceptorServer) error {
×
UNCOV
1609
        // We ensure there is only one interceptor at a time.
×
UNCOV
1610
        if !atomic.CompareAndSwapInt32(&s.forwardInterceptorActive, 0, 1) {
×
1611
                return ErrInterceptorAlreadyExists
×
1612
        }
×
UNCOV
1613
        defer atomic.CompareAndSwapInt32(&s.forwardInterceptorActive, 1, 0)
×
UNCOV
1614

×
UNCOV
1615
        // Run the forward interceptor.
×
UNCOV
1616
        return newForwardInterceptor(
×
UNCOV
1617
                s.cfg.RouterBackend.InterceptableForwarder, stream,
×
UNCOV
1618
        ).run()
×
1619
}
1620

1621
// XAddLocalChanAliases is an experimental API that creates a set of new
1622
// channel SCID alias mappings. The final total set of aliases in the manager
1623
// after the add operation is returned. This is only a locally stored alias, and
1624
// will not be communicated to the channel peer via any message. Therefore,
1625
// routing over such an alias will only work if the peer also calls this same
1626
// RPC on their end. If an alias already exists, an error is returned.
1627
func (s *Server) XAddLocalChanAliases(_ context.Context,
UNCOV
1628
        in *AddAliasesRequest) (*AddAliasesResponse, error) {
×
UNCOV
1629

×
UNCOV
1630
        existingAliases := s.cfg.AliasMgr.ListAliases()
×
UNCOV
1631

×
UNCOV
1632
        // aliasExists checks if the new alias already exists in the alias map.
×
UNCOV
1633
        aliasExists := func(newAlias uint64,
×
UNCOV
1634
                baseScid lnwire.ShortChannelID) (bool, error) {
×
UNCOV
1635

×
UNCOV
1636
                // First check that we actually have a channel for the given
×
UNCOV
1637
                // base scid. This should succeed for any channel where the
×
UNCOV
1638
                // option-scid-alias feature bit was negotiated.
×
UNCOV
1639
                if _, ok := existingAliases[baseScid]; !ok {
×
1640
                        return false, fmt.Errorf("base scid %v not found",
×
1641
                                baseScid)
×
1642
                }
×
1643

UNCOV
1644
                for base, aliases := range existingAliases {
×
UNCOV
1645
                        for _, alias := range aliases {
×
UNCOV
1646
                                exists := alias.ToUint64() == newAlias
×
UNCOV
1647

×
UNCOV
1648
                                // Trying to add an alias that we already have
×
UNCOV
1649
                                // for another channel is wrong.
×
UNCOV
1650
                                if exists && base != baseScid {
×
1651
                                        return true, fmt.Errorf("%w: alias %v "+
×
1652
                                                "already exists for base scid "+
×
1653
                                                "%v", ErrAliasAlreadyExists,
×
1654
                                                alias, base)
×
1655
                                }
×
1656

UNCOV
1657
                                if exists {
×
UNCOV
1658
                                        return true, nil
×
UNCOV
1659
                                }
×
1660
                        }
1661
                }
1662

UNCOV
1663
                return false, nil
×
1664
        }
1665

UNCOV
1666
        for _, v := range in.AliasMaps {
×
UNCOV
1667
                baseScid := lnwire.NewShortChanIDFromInt(v.BaseScid)
×
UNCOV
1668

×
UNCOV
1669
                for _, rpcAlias := range v.Aliases {
×
UNCOV
1670
                        // If not, let's add it to the alias manager now.
×
UNCOV
1671
                        aliasScid := lnwire.NewShortChanIDFromInt(rpcAlias)
×
UNCOV
1672

×
UNCOV
1673
                        // But we only add it, if it's a valid alias, as defined
×
UNCOV
1674
                        // by the BOLT spec.
×
UNCOV
1675
                        if !aliasmgr.IsAlias(aliasScid) {
×
UNCOV
1676
                                return nil, fmt.Errorf("%w: SCID alias %v is "+
×
UNCOV
1677
                                        "not a valid alias", ErrNoValidAlias,
×
UNCOV
1678
                                        aliasScid)
×
UNCOV
1679
                        }
×
1680

UNCOV
1681
                        exists, err := aliasExists(rpcAlias, baseScid)
×
UNCOV
1682
                        if err != nil {
×
1683
                                return nil, err
×
1684
                        }
×
1685

1686
                        // If the alias already exists, we see that as an error.
1687
                        // This is to avoid "silent" collisions.
UNCOV
1688
                        if exists {
×
UNCOV
1689
                                return nil, fmt.Errorf("%w: SCID alias %v "+
×
UNCOV
1690
                                        "already exists", ErrAliasAlreadyExists,
×
UNCOV
1691
                                        rpcAlias)
×
UNCOV
1692
                        }
×
1693

UNCOV
1694
                        err = s.cfg.AliasMgr.AddLocalAlias(
×
UNCOV
1695
                                aliasScid, baseScid, false, true,
×
UNCOV
1696
                        )
×
UNCOV
1697
                        if err != nil {
×
1698
                                return nil, fmt.Errorf("error adding scid "+
×
1699
                                        "alias, base_scid=%v, alias_scid=%v: "+
×
1700
                                        "%w", baseScid, aliasScid, err)
×
1701
                        }
×
1702
                }
1703
        }
1704

UNCOV
1705
        return &AddAliasesResponse{
×
UNCOV
1706
                AliasMaps: lnrpc.MarshalAliasMap(s.cfg.AliasMgr.ListAliases()),
×
UNCOV
1707
        }, nil
×
1708
}
1709

1710
// XDeleteLocalChanAliases is an experimental API that deletes a set of alias
1711
// mappings. The final total set of aliases in the manager after the delete
1712
// operation is returned. The deletion will not be communicated to the channel
1713
// peer via any message.
1714
func (s *Server) XDeleteLocalChanAliases(_ context.Context,
1715
        in *DeleteAliasesRequest) (*DeleteAliasesResponse,
UNCOV
1716
        error) {
×
UNCOV
1717

×
UNCOV
1718
        for _, v := range in.AliasMaps {
×
UNCOV
1719
                baseScid := lnwire.NewShortChanIDFromInt(v.BaseScid)
×
UNCOV
1720

×
UNCOV
1721
                for _, alias := range v.Aliases {
×
UNCOV
1722
                        aliasScid := lnwire.NewShortChanIDFromInt(alias)
×
UNCOV
1723

×
UNCOV
1724
                        err := s.cfg.AliasMgr.DeleteLocalAlias(
×
UNCOV
1725
                                aliasScid, baseScid,
×
UNCOV
1726
                        )
×
UNCOV
1727
                        if err != nil {
×
1728
                                return nil, fmt.Errorf("error deleting scid "+
×
1729
                                        "alias, base_scid=%v, alias_scid=%v: "+
×
1730
                                        "%w", baseScid, aliasScid, err)
×
1731
                        }
×
1732
                }
1733
        }
1734

UNCOV
1735
        return &DeleteAliasesResponse{
×
UNCOV
1736
                AliasMaps: lnrpc.MarshalAliasMap(s.cfg.AliasMgr.ListAliases()),
×
UNCOV
1737
        }, nil
×
1738
}
1739

UNCOV
1740
func extractOutPoint(req *UpdateChanStatusRequest) (*wire.OutPoint, error) {
×
UNCOV
1741
        chanPoint := req.GetChanPoint()
×
UNCOV
1742
        txid, err := lnrpc.GetChanPointFundingTxid(chanPoint)
×
UNCOV
1743
        if err != nil {
×
1744
                return nil, err
×
1745
        }
×
UNCOV
1746
        index := chanPoint.OutputIndex
×
UNCOV
1747
        return wire.NewOutPoint(txid, index), nil
×
1748
}
1749

1750
// UpdateChanStatus allows channel state to be set manually.
1751
func (s *Server) UpdateChanStatus(_ context.Context,
UNCOV
1752
        req *UpdateChanStatusRequest) (*UpdateChanStatusResponse, error) {
×
UNCOV
1753

×
UNCOV
1754
        outPoint, err := extractOutPoint(req)
×
UNCOV
1755
        if err != nil {
×
1756
                return nil, err
×
1757
        }
×
1758

UNCOV
1759
        action := req.GetAction()
×
UNCOV
1760

×
UNCOV
1761
        log.Debugf("UpdateChanStatus called for channel(%v) with "+
×
UNCOV
1762
                "action %v", outPoint, action)
×
UNCOV
1763

×
UNCOV
1764
        switch action {
×
UNCOV
1765
        case ChanStatusAction_ENABLE:
×
UNCOV
1766
                err = s.cfg.RouterBackend.SetChannelEnabled(*outPoint)
×
UNCOV
1767
        case ChanStatusAction_DISABLE:
×
UNCOV
1768
                err = s.cfg.RouterBackend.SetChannelDisabled(*outPoint)
×
UNCOV
1769
        case ChanStatusAction_AUTO:
×
UNCOV
1770
                err = s.cfg.RouterBackend.SetChannelAuto(*outPoint)
×
1771
        default:
×
1772
                err = fmt.Errorf("unrecognized ChannelStatusAction %v", action)
×
1773
        }
1774

UNCOV
1775
        if err != nil {
×
1776
                return nil, err
×
1777
        }
×
UNCOV
1778
        return &UpdateChanStatusResponse{}, nil
×
1779
}
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