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

lightningnetwork / lnd / 13974489001

20 Mar 2025 04:32PM UTC coverage: 56.292% (-2.9%) from 59.168%
13974489001

Pull #8754

github

web-flow
Merge aed149e6b into ea050d06f
Pull Request #8754: Add `Outbound` Remote Signer implementation

594 of 1713 new or added lines in 26 files covered. (34.68%)

23052 existing lines in 272 files now uncovered.

105921 of 188165 relevant lines covered (56.29%)

23796.34 hits per line

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

11.22
/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
        injected                 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.
NEW
212
func New() (*Server, lnrpc.MacaroonPerms, error) {
×
NEW
213
        routerServer := &Server{
×
NEW
214
                cfg:  &Config{},
×
NEW
215
                quit: make(chan struct{}),
×
NEW
216
        }
×
NEW
217

×
NEW
218
        return routerServer, macPermissions, nil
×
NEW
219
}
×
220

221
// Stop signals any active goroutines for a graceful closure.
222
//
223
// NOTE: This is part of the lnrpc.SubServer interface.
NEW
224
func (s *Server) Stop() error {
×
NEW
225
        if atomic.AddInt32(&s.shutdown, 1) != 1 {
×
NEW
226
                return nil
×
NEW
227
        }
×
228

NEW
229
        close(s.quit)
×
NEW
230

×
NEW
231
        return nil
×
232
}
233

234
// InjectDependencies populates the sub-server's dependencies. If the
235
// finalizeDependencies boolean is true, then the sub-server will finalize its
236
// dependencies and return an error if any required dependencies are missing.
237
//
238
// NOTE: This is part of the lnrpc.SubServer interface.
239
func (s *Server) InjectDependencies(
240
        configRegistry lnrpc.SubServerConfigDispatcher,
NEW
241
        finalizeDependencies bool) error {
×
NEW
242

×
NEW
243
        if finalizeDependencies && atomic.AddInt32(&s.injected, 1) != 1 {
×
NEW
244
                return lnrpc.ErrDependenciesFinalized
×
NEW
245
        }
×
246

NEW
247
        cfg, err := getConfig(configRegistry, finalizeDependencies)
×
NEW
248
        if err != nil {
×
NEW
249
                return err
×
NEW
250
        }
×
251

NEW
252
        if finalizeDependencies {
×
NEW
253
                s.cfg = cfg
×
NEW
254

×
NEW
255
                return nil
×
NEW
256
        }
×
257

258
        // If the path of the router macaroon wasn't generated, then we'll
259
        // assume that it's found at the default network directory.
UNCOV
260
        if cfg.RouterMacPath == "" {
×
UNCOV
261
                cfg.RouterMacPath = filepath.Join(
×
UNCOV
262
                        cfg.NetworkDir, DefaultRouterMacFilename,
×
UNCOV
263
                )
×
UNCOV
264
        }
×
265

266
        // Now that we know the full path of the router macaroon, we can check
267
        // to see if we need to create it or not. If stateless_init is set
268
        // then we don't write the macaroons.
UNCOV
269
        macFilePath := cfg.RouterMacPath
×
UNCOV
270
        if cfg.MacService != nil && !cfg.MacService.StatelessInit &&
×
UNCOV
271
                !lnrpc.FileExists(macFilePath) {
×
UNCOV
272

×
UNCOV
273
                log.Infof("Making macaroons for Router RPC Server at: %v",
×
UNCOV
274
                        macFilePath)
×
UNCOV
275

×
UNCOV
276
                // At this point, we know that the router macaroon doesn't yet,
×
UNCOV
277
                // exist, so we need to create it with the help of the main
×
UNCOV
278
                // macaroon service.
×
UNCOV
279
                routerMac, err := cfg.MacService.NewMacaroon(
×
UNCOV
280
                        context.Background(), macaroons.DefaultRootKeyID,
×
UNCOV
281
                        macaroonOps...,
×
UNCOV
282
                )
×
UNCOV
283
                if err != nil {
×
NEW
284
                        return err
×
285
                }
×
UNCOV
286
                routerMacBytes, err := routerMac.M().MarshalBinary()
×
UNCOV
287
                if err != nil {
×
NEW
288
                        return err
×
289
                }
×
UNCOV
290
                err = os.WriteFile(macFilePath, routerMacBytes, 0644)
×
UNCOV
291
                if err != nil {
×
292
                        _ = os.Remove(macFilePath)
×
NEW
293
                        return err
×
294
                }
×
295
        }
296

NEW
297
        s.cfg = cfg
×
UNCOV
298

×
UNCOV
299
        return nil
×
300
}
301

302
// Name returns a unique string representation of the sub-server. This can be
303
// used to identify the sub-server and also de-duplicate them.
304
//
305
// NOTE: This is part of the lnrpc.SubServer interface.
UNCOV
306
func (s *Server) Name() string {
×
UNCOV
307
        return subServerName
×
UNCOV
308
}
×
309

310
// RegisterWithRootServer will be called by the root gRPC server to direct a
311
// sub RPC server to register itself with the main gRPC root server. Until this
312
// is called, each sub-server won't be able to have requests routed towards it.
313
//
314
// NOTE: This is part of the lnrpc.GrpcHandler interface.
UNCOV
315
func (r *ServerShell) RegisterWithRootServer(grpcServer *grpc.Server) error {
×
UNCOV
316
        // We make sure that we register it with the main gRPC server to ensure
×
UNCOV
317
        // all our methods are routed properly.
×
UNCOV
318
        RegisterRouterServer(grpcServer, r)
×
UNCOV
319

×
UNCOV
320
        log.Debugf("Router RPC server successfully registered with root gRPC " +
×
UNCOV
321
                "server")
×
UNCOV
322

×
UNCOV
323
        return nil
×
UNCOV
324
}
×
325

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

×
UNCOV
334
        // We make sure that we register it with the main REST server to ensure
×
UNCOV
335
        // all our methods are routed properly.
×
UNCOV
336
        err := RegisterRouterHandlerFromEndpoint(ctx, mux, dest, opts)
×
UNCOV
337
        if err != nil {
×
338
                log.Errorf("Could not register Router REST server "+
×
339
                        "with root REST server: %v", err)
×
340
                return err
×
341
        }
×
342

UNCOV
343
        log.Debugf("Router REST server successfully registered with " +
×
UNCOV
344
                "root REST server")
×
UNCOV
345
        return nil
×
346
}
347

348
// CreateSubServer creates an instance of the sub-server, and returns the
349
// macaroon permissions that the sub-server wishes to pass on to the root server
350
// for all methods routed towards it.
351
//
352
// NOTE: This is part of the lnrpc.GrpcHandler interface.
353
func (r *ServerShell) CreateSubServer() (
UNCOV
354
        lnrpc.SubServer, lnrpc.MacaroonPerms, error) {
×
UNCOV
355

×
NEW
356
        subServer, macPermissions, err := New()
×
UNCOV
357
        if err != nil {
×
358
                return nil, nil, err
×
359
        }
×
360

UNCOV
361
        r.RouterServer = subServer
×
UNCOV
362
        return subServer, macPermissions, nil
×
363
}
364

365
// SendPaymentV2 attempts to route a payment described by the passed
366
// PaymentRequest to the final destination. If we are unable to route the
367
// payment, or cannot find a route that satisfies the constraints in the
368
// PaymentRequest, then an error will be returned. Otherwise, the payment
369
// pre-image, along with the final route will be returned.
370
func (s *Server) SendPaymentV2(req *SendPaymentRequest,
UNCOV
371
        stream Router_SendPaymentV2Server) error {
×
UNCOV
372

×
UNCOV
373
        // Set payment request attempt timeout.
×
UNCOV
374
        if req.TimeoutSeconds == 0 {
×
UNCOV
375
                req.TimeoutSeconds = DefaultPaymentTimeout
×
UNCOV
376
        }
×
377

UNCOV
378
        payment, err := s.cfg.RouterBackend.extractIntentFromSendRequest(req)
×
UNCOV
379
        if err != nil {
×
380
                return err
×
381
        }
×
382

383
        // Get the payment hash.
UNCOV
384
        payHash := payment.Identifier()
×
UNCOV
385

×
UNCOV
386
        // Init the payment in db.
×
UNCOV
387
        paySession, shardTracker, err := s.cfg.Router.PreparePayment(payment)
×
UNCOV
388
        if err != nil {
×
389
                log.Errorf("SendPayment async error for payment %x: %v",
×
390
                        payment.Identifier(), err)
×
391

×
392
                // Transform user errors to grpc code.
×
393
                if errors.Is(err, channeldb.ErrPaymentExists) ||
×
394
                        errors.Is(err, channeldb.ErrPaymentInFlight) ||
×
395
                        errors.Is(err, channeldb.ErrAlreadyPaid) {
×
396

×
397
                        return status.Error(
×
398
                                codes.AlreadyExists, err.Error(),
×
399
                        )
×
400
                }
×
401

402
                return err
×
403
        }
404

405
        // Subscribe to the payment before sending it to make sure we won't
406
        // miss events.
UNCOV
407
        sub, err := s.subscribePayment(payHash)
×
UNCOV
408
        if err != nil {
×
409
                return err
×
410
        }
×
411

412
        // The payment context is influenced by two user-provided parameters,
413
        // the cancelable flag and the payment attempt timeout.
414
        // If the payment is cancelable, we will use the stream context as the
415
        // payment context. That way, if the user ends the stream, the payment
416
        // loop will be canceled.
417
        // The second context parameter is the timeout. If the user provides a
418
        // timeout, we will additionally wrap the context in a deadline. If the
419
        // user provided 'cancelable' and ends the stream before the timeout is
420
        // reached the payment will be canceled.
UNCOV
421
        ctx := context.Background()
×
UNCOV
422
        if req.Cancelable {
×
UNCOV
423
                ctx = stream.Context()
×
UNCOV
424
        }
×
425

426
        // Send the payment asynchronously.
UNCOV
427
        s.cfg.Router.SendPaymentAsync(ctx, payment, paySession, shardTracker)
×
UNCOV
428

×
UNCOV
429
        // Track the payment and return.
×
UNCOV
430
        return s.trackPayment(sub, payHash, stream, req.NoInflightUpdates)
×
431
}
432

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

×
UNCOV
443
        isProbeDestination := len(req.Dest) > 0
×
UNCOV
444
        isProbeInvoice := len(req.PaymentRequest) > 0
×
UNCOV
445

×
UNCOV
446
        switch {
×
447
        case isProbeDestination == isProbeInvoice:
×
448
                return nil, errors.New("specify either a destination or an " +
×
449
                        "invoice")
×
450

UNCOV
451
        case isProbeDestination:
×
UNCOV
452
                switch {
×
453
                case len(req.Dest) != 33:
×
454
                        return nil, errors.New("invalid length destination key")
×
455

456
                case req.AmtSat <= 0:
×
457
                        return nil, errors.New("amount must be greater than 0")
×
458

UNCOV
459
                default:
×
UNCOV
460
                        return s.probeDestination(req.Dest, req.AmtSat)
×
461
                }
462

UNCOV
463
        case isProbeInvoice:
×
UNCOV
464
                return s.probePaymentRequest(
×
UNCOV
465
                        ctx, req.PaymentRequest, req.Timeout,
×
UNCOV
466
                )
×
467
        }
468

469
        return &RouteFeeResponse{}, nil
×
470
}
471

472
// probeDestination estimates fees along a route to a destination based on the
473
// contents of the local graph.
474
func (s *Server) probeDestination(dest []byte, amtSat int64) (*RouteFeeResponse,
UNCOV
475
        error) {
×
UNCOV
476

×
UNCOV
477
        destNode, err := route.NewVertexFromBytes(dest)
×
UNCOV
478
        if err != nil {
×
479
                return nil, err
×
480
        }
×
481

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

×
UNCOV
486
        // Finally, we'll query for a route to the destination that can carry
×
UNCOV
487
        // that target amount, we'll only request a single route. Set a
×
UNCOV
488
        // restriction for the default CLTV limit, otherwise we can find a route
×
UNCOV
489
        // that exceeds it and is useless to us.
×
UNCOV
490
        mc := s.cfg.RouterBackend.MissionControl
×
UNCOV
491
        routeReq, err := routing.NewRouteRequest(
×
UNCOV
492
                s.cfg.RouterBackend.SelfNode, &destNode, amtMsat, 0,
×
UNCOV
493
                &routing.RestrictParams{
×
UNCOV
494
                        FeeLimit:          routeFeeLimitSat,
×
UNCOV
495
                        CltvLimit:         s.cfg.RouterBackend.MaxTotalTimelock,
×
UNCOV
496
                        ProbabilitySource: mc.GetProbability,
×
UNCOV
497
                }, nil, nil, nil, s.cfg.RouterBackend.DefaultFinalCltvDelta,
×
UNCOV
498
        )
×
UNCOV
499
        if err != nil {
×
500
                return nil, err
×
501
        }
×
502

UNCOV
503
        route, _, err := s.cfg.Router.FindRoute(routeReq)
×
UNCOV
504
        if err != nil {
×
UNCOV
505
                return nil, err
×
UNCOV
506
        }
×
507

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

×
UNCOV
514
        return &RouteFeeResponse{
×
UNCOV
515
                RoutingFeeMsat: int64(route.TotalFees()),
×
UNCOV
516
                TimeLockDelay:  int64(timeLockDelay),
×
UNCOV
517
                FailureReason:  lnrpc.PaymentFailureReason_FAILURE_REASON_NONE,
×
UNCOV
518
        }, nil
×
519
}
520

521
// probePaymentRequest estimates fees along a route to a destination that is
522
// specified in an invoice. The estimation duration is limited by a timeout. In
523
// case that route hints are provided, this method applies a heuristic to
524
// identify LSPs which might block probe payments. In that case, fees are
525
// manually calculated and added to the probed fee estimation up until the LSP
526
// node. If the route hints don't indicate an LSP, they are passed as arguments
527
// to the SendPayment_V2 method, which enable it to send probe payments to the
528
// payment request destination.
529
func (s *Server) probePaymentRequest(ctx context.Context, paymentRequest string,
UNCOV
530
        timeout uint32) (*RouteFeeResponse, error) {
×
UNCOV
531

×
UNCOV
532
        payReq, err := zpay32.Decode(
×
UNCOV
533
                paymentRequest, s.cfg.RouterBackend.ActiveNetParams,
×
UNCOV
534
        )
×
UNCOV
535
        if err != nil {
×
536
                return nil, err
×
537
        }
×
538

UNCOV
539
        if *payReq.MilliSat <= 0 {
×
540
                return nil, errors.New("payment request amount must be " +
×
541
                        "greater than 0")
×
542
        }
×
543

544
        // Generate random payment hash, so we can be sure that the target of
545
        // the probe payment doesn't have the preimage to settle the htlc.
UNCOV
546
        var paymentHash lntypes.Hash
×
UNCOV
547
        _, err = crand.Read(paymentHash[:])
×
UNCOV
548
        if err != nil {
×
549
                return nil, fmt.Errorf("cannot generate random probe "+
×
550
                        "preimage: %w", err)
×
551
        }
×
552

UNCOV
553
        amtMsat := int64(*payReq.MilliSat)
×
UNCOV
554
        probeRequest := &SendPaymentRequest{
×
UNCOV
555
                TimeoutSeconds:   int32(timeout),
×
UNCOV
556
                Dest:             payReq.Destination.SerializeCompressed(),
×
UNCOV
557
                MaxParts:         1,
×
UNCOV
558
                AllowSelfPayment: false,
×
UNCOV
559
                AmtMsat:          amtMsat,
×
UNCOV
560
                PaymentHash:      paymentHash[:],
×
UNCOV
561
                FeeLimitSat:      routeFeeLimitSat,
×
UNCOV
562
                FinalCltvDelta:   int32(payReq.MinFinalCLTVExpiry()),
×
UNCOV
563
                DestFeatures:     MarshalFeatures(payReq.Features),
×
UNCOV
564
        }
×
UNCOV
565

×
UNCOV
566
        // If the payment addresses is specified, then we'll also populate that
×
UNCOV
567
        // now as well.
×
UNCOV
568
        payReq.PaymentAddr.WhenSome(func(addr [32]byte) {
×
UNCOV
569
                copy(probeRequest.PaymentAddr, addr[:])
×
UNCOV
570
        })
×
571

UNCOV
572
        hints := payReq.RouteHints
×
UNCOV
573

×
UNCOV
574
        // If the hints don't indicate an LSP then chances are that our probe
×
UNCOV
575
        // payment won't be blocked along the route to the destination. We send
×
UNCOV
576
        // a probe payment with unmodified route hints.
×
UNCOV
577
        if !isLSP(hints, s.cfg.RouterBackend.FetchChannelEndpoints) {
×
UNCOV
578
                probeRequest.RouteHints = invoicesrpc.CreateRPCRouteHints(hints)
×
UNCOV
579
                return s.sendProbePayment(ctx, probeRequest)
×
UNCOV
580
        }
×
581

582
        // If the heuristic indicates an LSP we modify the route hints to allow
583
        // probing the LSP.
UNCOV
584
        lspAdjustedRouteHints, lspHint, err := prepareLspRouteHints(
×
UNCOV
585
                hints, *payReq.MilliSat,
×
UNCOV
586
        )
×
UNCOV
587
        if err != nil {
×
588
                return nil, err
×
589
        }
×
590

591
        // The adjusted route hints serve the payment probe to find the last
592
        // public hop to the LSP on the route.
UNCOV
593
        probeRequest.Dest = lspHint.NodeID.SerializeCompressed()
×
UNCOV
594
        if len(lspAdjustedRouteHints) > 0 {
×
595
                probeRequest.RouteHints = invoicesrpc.CreateRPCRouteHints(
×
596
                        lspAdjustedRouteHints,
×
597
                )
×
598
        }
×
599

600
        // The payment probe will be able to calculate the fee up until the LSP
601
        // node. The fee of the last hop has to be calculated manually. Since
602
        // the last hop's fee amount has to be sent across the payment path we
603
        // have to add it to the original payment amount. Only then will the
604
        // payment probe be able to determine the correct fee to the last hop
605
        // prior to the private destination. For example, if the user wants to
606
        // send 1000 sats to a private destination and the last hop's fee is 10
607
        // sats, then 1010 sats will have to arrive at the last hop. This means
608
        // that the probe has to be dispatched with 1010 sats to correctly
609
        // calculate the routing fee.
610
        //
611
        // Calculate the hop fee for the last hop manually.
UNCOV
612
        hopFee := lspHint.HopFee(*payReq.MilliSat)
×
UNCOV
613
        if err != nil {
×
614
                return nil, err
×
615
        }
×
616

617
        // Add the last hop's fee to the requested payment amount that we want
618
        // to get an estimate for.
UNCOV
619
        probeRequest.AmtMsat += int64(hopFee)
×
UNCOV
620

×
UNCOV
621
        // Use the hop hint's cltv delta as the payment request's final cltv
×
UNCOV
622
        // delta. The actual final cltv delta of the invoice will be added to
×
UNCOV
623
        // the payment probe's cltv delta.
×
UNCOV
624
        probeRequest.FinalCltvDelta = int32(lspHint.CLTVExpiryDelta)
×
UNCOV
625

×
UNCOV
626
        // Dispatch the payment probe with adjusted fee amount.
×
UNCOV
627
        resp, err := s.sendProbePayment(ctx, probeRequest)
×
UNCOV
628
        if err != nil {
×
629
                return nil, err
×
630
        }
×
631

632
        // If the payment probe failed we only return the failure reason and
633
        // leave the probe result params unaltered.
UNCOV
634
        if resp.FailureReason != lnrpc.PaymentFailureReason_FAILURE_REASON_NONE { //nolint:ll
×
635
                return resp, nil
×
636
        }
×
637

638
        // The probe succeeded, so we can add the last hop's fee to fee the
639
        // payment probe returned.
UNCOV
640
        resp.RoutingFeeMsat += int64(hopFee)
×
UNCOV
641

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

×
UNCOV
646
        return resp, nil
×
647
}
648

649
// isLSP checks if the route hints indicate an LSP. An LSP is indicated with
650
// true if the destination hop hint in each route hint has the same node id,
651
// false otherwise. If the destination hop hint of any route hint contains a
652
// public channel, the function returns false because we can directly send a
653
// probe to the final destination.
654
func isLSP(routeHints [][]zpay32.HopHint,
655
        fetchChannelEndpoints FetchChannelEndpoints) bool {
9✔
656

9✔
657
        if len(routeHints) == 0 || len(routeHints[0]) == 0 {
10✔
658
                return false
1✔
659
        }
1✔
660

661
        destHopHint := routeHints[0][len(routeHints[0])-1]
8✔
662

8✔
663
        // If the destination hop hint of the first route hint contains a public
8✔
664
        // channel we can send a probe to it directly, hence we don't signal an
8✔
665
        // LSP.
8✔
666
        _, _, err := fetchChannelEndpoints(destHopHint.ChannelID)
8✔
667
        if err == nil {
9✔
668
                return false
1✔
669
        }
1✔
670

671
        for i := 1; i < len(routeHints); i++ {
12✔
672
                // Skip empty route hints.
5✔
673
                if len(routeHints[i]) == 0 {
5✔
674
                        continue
×
675
                }
676

677
                lastHop := routeHints[i][len(routeHints[i])-1]
5✔
678

5✔
679
                // If the last hop hint of any route hint contains a public
5✔
680
                // channel we can send a probe to it directly, hence we don't
5✔
681
                // signal an LSP.
5✔
682
                _, _, err = fetchChannelEndpoints(lastHop.ChannelID)
5✔
683
                if err == nil {
6✔
684
                        return false
1✔
685
                }
1✔
686

687
                idMatchesRefNode := bytes.Equal(
4✔
688
                        lastHop.NodeID.SerializeCompressed(),
4✔
689
                        destHopHint.NodeID.SerializeCompressed(),
4✔
690
                )
4✔
691
                if !idMatchesRefNode {
5✔
692
                        return false
1✔
693
                }
1✔
694
        }
695

696
        // We ensured that the destination hop hint doesn't contain a public
697
        // channel, and that all destination hop hints of all route hints match,
698
        // so we signal an LSP.
699
        return true
5✔
700
}
701

702
// prepareLspRouteHints assumes that the isLsp heuristic returned true for the
703
// route hints passed in here. It constructs a modified list of route hints that
704
// allows the caller to probe the LSP, which itself is returned as a separate
705
// hop hint.
706
func prepareLspRouteHints(routeHints [][]zpay32.HopHint,
707
        amt lnwire.MilliSatoshi) ([][]zpay32.HopHint, *zpay32.HopHint, error) {
5✔
708

5✔
709
        if len(routeHints) == 0 {
5✔
710
                return nil, nil, fmt.Errorf("no route hints provided")
×
711
        }
×
712

713
        // Create the LSP hop hint. We are probing for the worst case fee and
714
        // cltv delta. So we look for the max values amongst all LSP hop hints.
715
        refHint := routeHints[0][len(routeHints[0])-1]
5✔
716
        refHint.CLTVExpiryDelta = maxLspCltvDelta(routeHints)
5✔
717
        refHint.FeeBaseMSat, refHint.FeeProportionalMillionths = maxLspFee(
5✔
718
                routeHints, amt,
5✔
719
        )
5✔
720

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

5✔
725
        // Strip off the LSP hop hint from all route hints.
5✔
726
        for i := 0; i < len(routeHints); i++ {
13✔
727
                hint := routeHints[i]
8✔
728
                if len(hint) > 1 {
13✔
729
                        adjustedHints = append(
5✔
730
                                adjustedHints, hint[:len(hint)-1],
5✔
731
                        )
5✔
732
                }
5✔
733
        }
734

735
        return adjustedHints, &refHint, nil
5✔
736
}
737

738
// maxLspFee returns base fee and fee rate amongst all LSP route hints that
739
// results in the overall highest fee for the given amount.
740
func maxLspFee(routeHints [][]zpay32.HopHint, amt lnwire.MilliSatoshi) (uint32,
741
        uint32) {
5✔
742

5✔
743
        var maxFeePpm uint32
5✔
744
        var maxBaseFee uint32
5✔
745
        var maxTotalFee lnwire.MilliSatoshi
5✔
746
        for _, rh := range routeHints {
13✔
747
                lastHop := rh[len(rh)-1]
8✔
748
                lastHopFee := lastHop.HopFee(amt)
8✔
749
                if lastHopFee > maxTotalFee {
14✔
750
                        maxTotalFee = lastHopFee
6✔
751
                        maxBaseFee = lastHop.FeeBaseMSat
6✔
752
                        maxFeePpm = lastHop.FeeProportionalMillionths
6✔
753
                }
6✔
754
        }
755

756
        return maxBaseFee, maxFeePpm
5✔
757
}
758

759
// maxLspCltvDelta returns the maximum cltv delta amongst all LSP route hints.
760
func maxLspCltvDelta(routeHints [][]zpay32.HopHint) uint16 {
5✔
761
        var maxCltvDelta uint16
5✔
762
        for _, rh := range routeHints {
13✔
763
                rhLastHop := rh[len(rh)-1]
8✔
764
                if rhLastHop.CLTVExpiryDelta > maxCltvDelta {
12✔
765
                        maxCltvDelta = rhLastHop.CLTVExpiryDelta
4✔
766
                }
4✔
767
        }
768

769
        return maxCltvDelta
5✔
770
}
771

772
// probePaymentStream is a custom implementation of the grpc.ServerStream
773
// interface. It is used to send payment status updates to the caller on the
774
// stream channel.
775
type probePaymentStream struct {
776
        Router_SendPaymentV2Server
777

778
        stream chan *lnrpc.Payment
779
        ctx    context.Context //nolint:containedctx
780
}
781

782
// Send sends a payment status update to a payment stream that the caller can
783
// evaluate.
UNCOV
784
func (p *probePaymentStream) Send(response *lnrpc.Payment) error {
×
UNCOV
785
        select {
×
UNCOV
786
        case p.stream <- response:
×
787

788
        case <-p.ctx.Done():
×
789
                return p.ctx.Err()
×
790
        }
791

UNCOV
792
        return nil
×
793
}
794

795
// Context returns the context of the stream.
UNCOV
796
func (p *probePaymentStream) Context() context.Context {
×
UNCOV
797
        return p.ctx
×
UNCOV
798
}
×
799

800
// sendProbePayment sends a payment to a target node in order to obtain
801
// potential routing fees for it. The payment request has to contain a payment
802
// hash that is guaranteed to be unknown to the target node, so it cannot settle
803
// the payment. This method invokes a payment request loop in a goroutine and
804
// awaits payment status updates.
805
func (s *Server) sendProbePayment(ctx context.Context,
UNCOV
806
        req *SendPaymentRequest) (*RouteFeeResponse, error) {
×
UNCOV
807

×
UNCOV
808
        // We'll launch a goroutine to send the payment probes.
×
UNCOV
809
        errChan := make(chan error, 1)
×
UNCOV
810
        defer close(errChan)
×
UNCOV
811

×
UNCOV
812
        paymentStream := &probePaymentStream{
×
UNCOV
813
                stream: make(chan *lnrpc.Payment),
×
UNCOV
814
                ctx:    ctx,
×
UNCOV
815
        }
×
UNCOV
816
        go func() {
×
UNCOV
817
                err := s.SendPaymentV2(req, paymentStream)
×
UNCOV
818
                if err != nil {
×
819
                        select {
×
820
                        case errChan <- err:
×
821

822
                        case <-paymentStream.ctx.Done():
×
823
                                return
×
824
                        }
825
                }
826
        }()
827

UNCOV
828
        for {
×
UNCOV
829
                select {
×
UNCOV
830
                case payment := <-paymentStream.stream:
×
UNCOV
831
                        switch payment.Status {
×
832
                        case lnrpc.Payment_INITIATED:
×
UNCOV
833
                        case lnrpc.Payment_IN_FLIGHT:
×
834
                        case lnrpc.Payment_SUCCEEDED:
×
835
                                return nil, errors.New("warning, the fee " +
×
836
                                        "estimation payment probe " +
×
837
                                        "unexpectedly succeeded. Please reach" +
×
838
                                        "out to the probe destination to " +
×
839
                                        "negotiate a refund. Otherwise the " +
×
840
                                        "payment probe amount is lost forever")
×
841

UNCOV
842
                        case lnrpc.Payment_FAILED:
×
UNCOV
843
                                // Incorrect payment details point to a
×
UNCOV
844
                                // successful probe.
×
UNCOV
845
                                //nolint:ll
×
UNCOV
846
                                if payment.FailureReason == lnrpc.PaymentFailureReason_FAILURE_REASON_INCORRECT_PAYMENT_DETAILS {
×
UNCOV
847
                                        return paymentDetails(payment)
×
UNCOV
848
                                }
×
849

UNCOV
850
                                return &RouteFeeResponse{
×
UNCOV
851
                                        RoutingFeeMsat: 0,
×
UNCOV
852
                                        TimeLockDelay:  0,
×
UNCOV
853
                                        FailureReason:  payment.FailureReason,
×
UNCOV
854
                                }, nil
×
855

856
                        default:
×
857
                                return nil, errors.New("unexpected payment " +
×
858
                                        "status")
×
859
                        }
860

861
                case err := <-errChan:
×
862
                        return nil, err
×
863

864
                case <-s.quit:
×
865
                        return nil, errServerShuttingDown
×
866
                }
867
        }
868
}
869

UNCOV
870
func paymentDetails(payment *lnrpc.Payment) (*RouteFeeResponse, error) {
×
UNCOV
871
        fee, timeLock, err := timelockAndFee(payment)
×
UNCOV
872
        if errors.Is(err, errUnexpectedFailureSource) {
×
873
                return nil, err
×
874
        }
×
875

UNCOV
876
        return &RouteFeeResponse{
×
UNCOV
877
                RoutingFeeMsat: fee,
×
UNCOV
878
                TimeLockDelay:  timeLock,
×
UNCOV
879
                FailureReason:  lnrpc.PaymentFailureReason_FAILURE_REASON_NONE,
×
UNCOV
880
        }, nil
×
881
}
882

883
// timelockAndFee returns the fee and total time lock of the last payment
884
// attempt.
UNCOV
885
func timelockAndFee(p *lnrpc.Payment) (int64, int64, error) {
×
UNCOV
886
        if len(p.Htlcs) == 0 {
×
887
                return 0, 0, nil
×
888
        }
×
889

UNCOV
890
        lastAttempt := p.Htlcs[len(p.Htlcs)-1]
×
UNCOV
891
        if lastAttempt == nil {
×
892
                return 0, 0, errMissingPaymentAttempt
×
893
        }
×
894

UNCOV
895
        lastRoute := lastAttempt.Route
×
UNCOV
896
        if lastRoute == nil {
×
897
                return 0, 0, errMissingRoute
×
898
        }
×
899

UNCOV
900
        hopFailureIndex := lastAttempt.Failure.FailureSourceIndex
×
UNCOV
901
        finalHopIndex := uint32(len(lastRoute.Hops))
×
UNCOV
902
        if hopFailureIndex != finalHopIndex {
×
903
                return 0, 0, errUnexpectedFailureSource
×
904
        }
×
905

UNCOV
906
        return lastRoute.TotalFeesMsat, int64(lastRoute.TotalTimeLock), nil
×
907
}
908

909
// SendToRouteV2 sends a payment through a predefined route. The response of
910
// this call contains structured error information.
911
func (s *Server) SendToRouteV2(ctx context.Context,
UNCOV
912
        req *SendToRouteRequest) (*lnrpc.HTLCAttempt, error) {
×
UNCOV
913

×
UNCOV
914
        if req.Route == nil {
×
915
                return nil, fmt.Errorf("unable to send, no routes provided")
×
916
        }
×
917

UNCOV
918
        route, err := s.cfg.RouterBackend.UnmarshallRoute(req.Route)
×
UNCOV
919
        if err != nil {
×
920
                return nil, err
×
921
        }
×
922

UNCOV
923
        hash, err := lntypes.MakeHash(req.PaymentHash)
×
UNCOV
924
        if err != nil {
×
925
                return nil, err
×
926
        }
×
927

UNCOV
928
        firstHopRecords := lnwire.CustomRecords(req.FirstHopCustomRecords)
×
UNCOV
929
        if err := firstHopRecords.Validate(); err != nil {
×
930
                return nil, err
×
931
        }
×
932

UNCOV
933
        var attempt *channeldb.HTLCAttempt
×
UNCOV
934

×
UNCOV
935
        // Pass route to the router. This call returns the full htlc attempt
×
UNCOV
936
        // information as it is stored in the database. It is possible that both
×
UNCOV
937
        // the attempt return value and err are non-nil. This can happen when
×
UNCOV
938
        // the attempt was already initiated before the error happened. In that
×
UNCOV
939
        // case, we give precedence to the attempt information as stored in the
×
UNCOV
940
        // db.
×
UNCOV
941
        if req.SkipTempErr {
×
942
                attempt, err = s.cfg.Router.SendToRouteSkipTempErr(
×
943
                        hash, route, firstHopRecords,
×
944
                )
×
UNCOV
945
        } else {
×
UNCOV
946
                attempt, err = s.cfg.Router.SendToRoute(
×
UNCOV
947
                        hash, route, firstHopRecords,
×
UNCOV
948
                )
×
UNCOV
949
        }
×
UNCOV
950
        if attempt != nil {
×
UNCOV
951
                rpcAttempt, err := s.cfg.RouterBackend.MarshalHTLCAttempt(
×
UNCOV
952
                        *attempt,
×
UNCOV
953
                )
×
UNCOV
954
                if err != nil {
×
955
                        return nil, err
×
956
                }
×
UNCOV
957
                return rpcAttempt, nil
×
958
        }
959

960
        // Transform user errors to grpc code.
961
        switch {
×
962
        case errors.Is(err, channeldb.ErrPaymentExists):
×
963
                fallthrough
×
964

965
        case errors.Is(err, channeldb.ErrPaymentInFlight):
×
966
                fallthrough
×
967

968
        case errors.Is(err, channeldb.ErrAlreadyPaid):
×
969
                return nil, status.Error(
×
970
                        codes.AlreadyExists, err.Error(),
×
971
                )
×
972
        }
973

974
        return nil, err
×
975
}
976

977
// ResetMissionControl clears all mission control state and starts with a clean
978
// slate.
979
func (s *Server) ResetMissionControl(ctx context.Context,
UNCOV
980
        req *ResetMissionControlRequest) (*ResetMissionControlResponse, error) {
×
UNCOV
981

×
UNCOV
982
        err := s.cfg.RouterBackend.MissionControl.ResetHistory()
×
UNCOV
983
        if err != nil {
×
984
                return nil, err
×
985
        }
×
986

UNCOV
987
        return &ResetMissionControlResponse{}, nil
×
988
}
989

990
// GetMissionControlConfig returns our current mission control config.
991
func (s *Server) GetMissionControlConfig(ctx context.Context,
992
        req *GetMissionControlConfigRequest) (*GetMissionControlConfigResponse,
UNCOV
993
        error) {
×
UNCOV
994

×
UNCOV
995
        // Query the current mission control config.
×
UNCOV
996
        cfg := s.cfg.RouterBackend.MissionControl.GetConfig()
×
UNCOV
997
        resp := &GetMissionControlConfigResponse{
×
UNCOV
998
                Config: &MissionControlConfig{
×
UNCOV
999
                        MaximumPaymentResults: uint32(cfg.MaxMcHistory),
×
UNCOV
1000
                        MinimumFailureRelaxInterval: uint64(
×
UNCOV
1001
                                cfg.MinFailureRelaxInterval.Seconds(),
×
UNCOV
1002
                        ),
×
UNCOV
1003
                },
×
UNCOV
1004
        }
×
UNCOV
1005

×
UNCOV
1006
        // We only populate fields based on the current estimator.
×
UNCOV
1007
        switch v := cfg.Estimator.Config().(type) {
×
UNCOV
1008
        case routing.AprioriConfig:
×
UNCOV
1009
                resp.Config.Model = MissionControlConfig_APRIORI
×
UNCOV
1010
                aCfg := AprioriParameters{
×
UNCOV
1011
                        HalfLifeSeconds:  uint64(v.PenaltyHalfLife.Seconds()),
×
UNCOV
1012
                        HopProbability:   v.AprioriHopProbability,
×
UNCOV
1013
                        Weight:           v.AprioriWeight,
×
UNCOV
1014
                        CapacityFraction: v.CapacityFraction,
×
UNCOV
1015
                }
×
UNCOV
1016

×
UNCOV
1017
                // Populate deprecated fields.
×
UNCOV
1018
                resp.Config.HalfLifeSeconds = uint64(
×
UNCOV
1019
                        v.PenaltyHalfLife.Seconds(),
×
UNCOV
1020
                )
×
UNCOV
1021
                resp.Config.HopProbability = float32(v.AprioriHopProbability)
×
UNCOV
1022
                resp.Config.Weight = float32(v.AprioriWeight)
×
UNCOV
1023

×
UNCOV
1024
                resp.Config.EstimatorConfig = &MissionControlConfig_Apriori{
×
UNCOV
1025
                        Apriori: &aCfg,
×
UNCOV
1026
                }
×
1027

UNCOV
1028
        case routing.BimodalConfig:
×
UNCOV
1029
                resp.Config.Model = MissionControlConfig_BIMODAL
×
UNCOV
1030
                bCfg := BimodalParameters{
×
UNCOV
1031
                        NodeWeight: v.BimodalNodeWeight,
×
UNCOV
1032
                        ScaleMsat:  uint64(v.BimodalScaleMsat),
×
UNCOV
1033
                        DecayTime:  uint64(v.BimodalDecayTime.Seconds()),
×
UNCOV
1034
                }
×
UNCOV
1035

×
UNCOV
1036
                resp.Config.EstimatorConfig = &MissionControlConfig_Bimodal{
×
UNCOV
1037
                        Bimodal: &bCfg,
×
UNCOV
1038
                }
×
1039

1040
        default:
×
1041
                return nil, fmt.Errorf("unknown estimator config type %T", v)
×
1042
        }
1043

UNCOV
1044
        return resp, nil
×
1045
}
1046

1047
// SetMissionControlConfig sets parameters in the mission control config.
1048
func (s *Server) SetMissionControlConfig(ctx context.Context,
1049
        req *SetMissionControlConfigRequest) (*SetMissionControlConfigResponse,
UNCOV
1050
        error) {
×
UNCOV
1051

×
UNCOV
1052
        mcCfg := &routing.MissionControlConfig{
×
UNCOV
1053
                MaxMcHistory: int(req.Config.MaximumPaymentResults),
×
UNCOV
1054
                MinFailureRelaxInterval: time.Duration(
×
UNCOV
1055
                        req.Config.MinimumFailureRelaxInterval,
×
UNCOV
1056
                ) * time.Second,
×
UNCOV
1057
        }
×
UNCOV
1058

×
UNCOV
1059
        switch req.Config.Model {
×
UNCOV
1060
        case MissionControlConfig_APRIORI:
×
UNCOV
1061
                var aprioriConfig routing.AprioriConfig
×
UNCOV
1062

×
UNCOV
1063
                // Determine the apriori config with backward compatibility
×
UNCOV
1064
                // should the api use deprecated fields.
×
UNCOV
1065
                switch v := req.Config.EstimatorConfig.(type) {
×
UNCOV
1066
                case *MissionControlConfig_Bimodal:
×
UNCOV
1067
                        return nil, fmt.Errorf("bimodal config " +
×
UNCOV
1068
                                "provided, but apriori model requested")
×
1069

UNCOV
1070
                case *MissionControlConfig_Apriori:
×
UNCOV
1071
                        aprioriConfig = routing.AprioriConfig{
×
UNCOV
1072
                                PenaltyHalfLife: time.Duration(
×
UNCOV
1073
                                        v.Apriori.HalfLifeSeconds,
×
UNCOV
1074
                                ) * time.Second,
×
UNCOV
1075
                                AprioriHopProbability: v.Apriori.HopProbability,
×
UNCOV
1076
                                AprioriWeight:         v.Apriori.Weight,
×
UNCOV
1077
                                CapacityFraction: v.Apriori.
×
UNCOV
1078
                                        CapacityFraction,
×
UNCOV
1079
                        }
×
1080

UNCOV
1081
                default:
×
UNCOV
1082
                        aprioriConfig = routing.AprioriConfig{
×
UNCOV
1083
                                PenaltyHalfLife: time.Duration(
×
UNCOV
1084
                                        int64(req.Config.HalfLifeSeconds),
×
UNCOV
1085
                                ) * time.Second,
×
UNCOV
1086
                                AprioriHopProbability: float64(
×
UNCOV
1087
                                        req.Config.HopProbability,
×
UNCOV
1088
                                ),
×
UNCOV
1089
                                AprioriWeight:    float64(req.Config.Weight),
×
UNCOV
1090
                                CapacityFraction: routing.DefaultCapacityFraction, //nolint:ll
×
UNCOV
1091
                        }
×
1092
                }
1093

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

UNCOV
1100
        case MissionControlConfig_BIMODAL:
×
UNCOV
1101
                cfg, ok := req.Config.
×
UNCOV
1102
                        EstimatorConfig.(*MissionControlConfig_Bimodal)
×
UNCOV
1103
                if !ok {
×
1104
                        return nil, fmt.Errorf("bimodal estimator requested " +
×
1105
                                "but corresponding config not set")
×
1106
                }
×
UNCOV
1107
                bCfg := cfg.Bimodal
×
UNCOV
1108

×
UNCOV
1109
                bimodalConfig := routing.BimodalConfig{
×
UNCOV
1110
                        BimodalDecayTime: time.Duration(
×
UNCOV
1111
                                bCfg.DecayTime,
×
UNCOV
1112
                        ) * time.Second,
×
UNCOV
1113
                        BimodalScaleMsat:  lnwire.MilliSatoshi(bCfg.ScaleMsat),
×
UNCOV
1114
                        BimodalNodeWeight: bCfg.NodeWeight,
×
UNCOV
1115
                }
×
UNCOV
1116

×
UNCOV
1117
                estimator, err := routing.NewBimodalEstimator(bimodalConfig)
×
UNCOV
1118
                if err != nil {
×
1119
                        return nil, err
×
1120
                }
×
UNCOV
1121
                mcCfg.Estimator = estimator
×
1122

1123
        default:
×
1124
                return nil, fmt.Errorf("unknown estimator type %v",
×
1125
                        req.Config.Model)
×
1126
        }
1127

UNCOV
1128
        return &SetMissionControlConfigResponse{},
×
UNCOV
1129
                s.cfg.RouterBackend.MissionControl.SetConfig(mcCfg)
×
1130
}
1131

1132
// QueryMissionControl exposes the internal mission control state to callers. It
1133
// is a development feature.
1134
func (s *Server) QueryMissionControl(_ context.Context,
1135
        _ *QueryMissionControlRequest) (*QueryMissionControlResponse, error) {
×
1136

×
1137
        snapshot := s.cfg.RouterBackend.MissionControl.GetHistorySnapshot()
×
1138

×
1139
        rpcPairs := make([]*PairHistory, 0, len(snapshot.Pairs))
×
1140
        for _, p := range snapshot.Pairs {
×
1141
                // Prevent binding to loop variable.
×
1142
                pair := p
×
1143

×
1144
                rpcPair := PairHistory{
×
1145
                        NodeFrom: pair.Pair.From[:],
×
1146
                        NodeTo:   pair.Pair.To[:],
×
1147
                        History:  toRPCPairData(&pair.TimedPairResult),
×
1148
                }
×
1149

×
1150
                rpcPairs = append(rpcPairs, &rpcPair)
×
1151
        }
×
1152

1153
        response := QueryMissionControlResponse{
×
1154
                Pairs: rpcPairs,
×
1155
        }
×
1156

×
1157
        return &response, nil
×
1158
}
1159

1160
// toRPCPairData marshalls mission control pair data to the rpc struct.
UNCOV
1161
func toRPCPairData(data *routing.TimedPairResult) *PairData {
×
UNCOV
1162
        rpcData := PairData{
×
UNCOV
1163
                FailAmtSat:     int64(data.FailAmt.ToSatoshis()),
×
UNCOV
1164
                FailAmtMsat:    int64(data.FailAmt),
×
UNCOV
1165
                SuccessAmtSat:  int64(data.SuccessAmt.ToSatoshis()),
×
UNCOV
1166
                SuccessAmtMsat: int64(data.SuccessAmt),
×
UNCOV
1167
        }
×
UNCOV
1168

×
UNCOV
1169
        if !data.FailTime.IsZero() {
×
UNCOV
1170
                rpcData.FailTime = data.FailTime.Unix()
×
UNCOV
1171
        }
×
1172

UNCOV
1173
        if !data.SuccessTime.IsZero() {
×
1174
                rpcData.SuccessTime = data.SuccessTime.Unix()
×
1175
        }
×
1176

UNCOV
1177
        return &rpcData
×
1178
}
1179

1180
// XImportMissionControl imports the state provided to our internal mission
1181
// control. Only entries that are fresher than our existing state will be used.
1182
func (s *Server) XImportMissionControl(_ context.Context,
1183
        req *XImportMissionControlRequest) (*XImportMissionControlResponse,
UNCOV
1184
        error) {
×
UNCOV
1185

×
UNCOV
1186
        if len(req.Pairs) == 0 {
×
1187
                return nil, errors.New("at least one pair required for import")
×
1188
        }
×
1189

UNCOV
1190
        snapshot := &routing.MissionControlSnapshot{
×
UNCOV
1191
                Pairs: make(
×
UNCOV
1192
                        []routing.MissionControlPairSnapshot, len(req.Pairs),
×
UNCOV
1193
                ),
×
UNCOV
1194
        }
×
UNCOV
1195

×
UNCOV
1196
        for i, pairResult := range req.Pairs {
×
UNCOV
1197
                pairSnapshot, err := toPairSnapshot(pairResult)
×
UNCOV
1198
                if err != nil {
×
UNCOV
1199
                        return nil, err
×
UNCOV
1200
                }
×
1201

UNCOV
1202
                snapshot.Pairs[i] = *pairSnapshot
×
1203
        }
1204

UNCOV
1205
        err := s.cfg.RouterBackend.MissionControl.ImportHistory(
×
UNCOV
1206
                snapshot, req.Force,
×
UNCOV
1207
        )
×
UNCOV
1208
        if err != nil {
×
1209
                return nil, err
×
1210
        }
×
1211

UNCOV
1212
        return &XImportMissionControlResponse{}, nil
×
1213
}
1214

1215
func toPairSnapshot(pairResult *PairHistory) (*routing.MissionControlPairSnapshot,
UNCOV
1216
        error) {
×
UNCOV
1217

×
UNCOV
1218
        from, err := route.NewVertexFromBytes(pairResult.NodeFrom)
×
UNCOV
1219
        if err != nil {
×
1220
                return nil, err
×
1221
        }
×
1222

UNCOV
1223
        to, err := route.NewVertexFromBytes(pairResult.NodeTo)
×
UNCOV
1224
        if err != nil {
×
1225
                return nil, err
×
1226
        }
×
1227

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

×
UNCOV
1230
        if from == to {
×
1231
                return nil, fmt.Errorf("%v source and destination node must "+
×
1232
                        "differ", pairPrefix)
×
1233
        }
×
1234

UNCOV
1235
        failAmt, failTime, err := getPair(
×
UNCOV
1236
                lnwire.MilliSatoshi(pairResult.History.FailAmtMsat),
×
UNCOV
1237
                btcutil.Amount(pairResult.History.FailAmtSat),
×
UNCOV
1238
                pairResult.History.FailTime,
×
UNCOV
1239
                true,
×
UNCOV
1240
        )
×
UNCOV
1241
        if err != nil {
×
UNCOV
1242
                return nil, fmt.Errorf("%v invalid failure: %w", pairPrefix,
×
UNCOV
1243
                        err)
×
UNCOV
1244
        }
×
1245

UNCOV
1246
        successAmt, successTime, err := getPair(
×
UNCOV
1247
                lnwire.MilliSatoshi(pairResult.History.SuccessAmtMsat),
×
UNCOV
1248
                btcutil.Amount(pairResult.History.SuccessAmtSat),
×
UNCOV
1249
                pairResult.History.SuccessTime,
×
UNCOV
1250
                false,
×
UNCOV
1251
        )
×
UNCOV
1252
        if err != nil {
×
1253
                return nil, fmt.Errorf("%v invalid success: %w", pairPrefix,
×
1254
                        err)
×
1255
        }
×
1256

UNCOV
1257
        if successAmt == 0 && failAmt == 0 {
×
1258
                return nil, fmt.Errorf("%v: either success or failure result "+
×
1259
                        "required", pairPrefix)
×
1260
        }
×
1261

UNCOV
1262
        pair := routing.NewDirectedNodePair(from, to)
×
UNCOV
1263

×
UNCOV
1264
        result := &routing.TimedPairResult{
×
UNCOV
1265
                FailAmt:     failAmt,
×
UNCOV
1266
                FailTime:    failTime,
×
UNCOV
1267
                SuccessAmt:  successAmt,
×
UNCOV
1268
                SuccessTime: successTime,
×
UNCOV
1269
        }
×
UNCOV
1270

×
UNCOV
1271
        return &routing.MissionControlPairSnapshot{
×
UNCOV
1272
                Pair:            pair,
×
UNCOV
1273
                TimedPairResult: *result,
×
UNCOV
1274
        }, nil
×
1275
}
1276

1277
// getPair validates the values provided for a mission control result and
1278
// returns the msat amount and timestamp for it. `isFailure` can be used to
1279
// default values to 0 instead of returning an error.
1280
func getPair(amtMsat lnwire.MilliSatoshi, amtSat btcutil.Amount,
1281
        timestamp int64, isFailure bool) (lnwire.MilliSatoshi, time.Time,
UNCOV
1282
        error) {
×
UNCOV
1283

×
UNCOV
1284
        amt, err := getMsatPairValue(amtMsat, amtSat)
×
UNCOV
1285
        if err != nil {
×
UNCOV
1286
                return 0, time.Time{}, err
×
UNCOV
1287
        }
×
1288

UNCOV
1289
        var (
×
UNCOV
1290
                timeSet   = timestamp != 0
×
UNCOV
1291
                amountSet = amt != 0
×
UNCOV
1292
        )
×
UNCOV
1293

×
UNCOV
1294
        switch {
×
1295
        // If a timestamp and amount if provided, return those values.
UNCOV
1296
        case timeSet && amountSet:
×
UNCOV
1297
                return amt, time.Unix(timestamp, 0), nil
×
1298

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

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

UNCOV
1311
        default:
×
UNCOV
1312
                return 0, time.Time{}, nil
×
1313
        }
1314
}
1315

1316
// getMsatPairValue checks the msat and sat values set for a pair and ensures
1317
// that the values provided are either the same, or only a single value is set.
1318
func getMsatPairValue(msatValue lnwire.MilliSatoshi,
UNCOV
1319
        satValue btcutil.Amount) (lnwire.MilliSatoshi, error) {
×
UNCOV
1320

×
UNCOV
1321
        // If our msat value converted to sats equals our sat value, we just
×
UNCOV
1322
        // return the msat value, since the values are the same.
×
UNCOV
1323
        if msatValue.ToSatoshis() == satValue {
×
UNCOV
1324
                return msatValue, nil
×
UNCOV
1325
        }
×
1326

1327
        // If we have no msatValue, we can just return our state value even if
1328
        // it is zero, because it's impossible that we have mismatched values.
UNCOV
1329
        if msatValue == 0 {
×
1330
                return lnwire.MilliSatoshi(satValue * 1000), nil
×
1331
        }
×
1332

1333
        // Likewise, we can just use msat value if we have no sat value set.
UNCOV
1334
        if satValue == 0 {
×
1335
                return msatValue, nil
×
1336
        }
×
1337

1338
        // If our values are non-zero but not equal, we have invalid amounts
1339
        // set, so we fail.
UNCOV
1340
        return 0, fmt.Errorf("msat: %v and sat: %v values not equal", msatValue,
×
UNCOV
1341
                satValue)
×
1342
}
1343

1344
// TrackPaymentV2 returns a stream of payment state updates. The stream is
1345
// closed when the payment completes.
1346
func (s *Server) TrackPaymentV2(request *TrackPaymentRequest,
UNCOV
1347
        stream Router_TrackPaymentV2Server) error {
×
UNCOV
1348

×
UNCOV
1349
        payHash, err := lntypes.MakeHash(request.PaymentHash)
×
UNCOV
1350
        if err != nil {
×
1351
                return err
×
1352
        }
×
1353

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

×
UNCOV
1356
        // Make the subscription.
×
UNCOV
1357
        sub, err := s.subscribePayment(payHash)
×
UNCOV
1358
        if err != nil {
×
1359
                return err
×
1360
        }
×
1361

UNCOV
1362
        return s.trackPayment(sub, payHash, stream, request.NoInflightUpdates)
×
1363
}
1364

1365
// subscribePayment subscribes to the payment updates for the given payment
1366
// hash.
1367
func (s *Server) subscribePayment(identifier lntypes.Hash) (
UNCOV
1368
        routing.ControlTowerSubscriber, error) {
×
UNCOV
1369

×
UNCOV
1370
        // Make the subscription.
×
UNCOV
1371
        router := s.cfg.RouterBackend
×
UNCOV
1372
        sub, err := router.Tower.SubscribePayment(identifier)
×
UNCOV
1373

×
UNCOV
1374
        switch {
×
1375
        case errors.Is(err, channeldb.ErrPaymentNotInitiated):
×
1376
                return nil, status.Error(codes.NotFound, err.Error())
×
1377

1378
        case err != nil:
×
1379
                return nil, err
×
1380
        }
1381

UNCOV
1382
        return sub, nil
×
1383
}
1384

1385
// trackPayment writes payment status updates to the provided stream.
1386
func (s *Server) trackPayment(subscription routing.ControlTowerSubscriber,
1387
        identifier lntypes.Hash, stream Router_TrackPaymentV2Server,
UNCOV
1388
        noInflightUpdates bool) error {
×
UNCOV
1389

×
UNCOV
1390
        err := s.trackPaymentStream(
×
UNCOV
1391
                stream.Context(), subscription, noInflightUpdates, stream.Send,
×
UNCOV
1392
        )
×
UNCOV
1393
        switch {
×
UNCOV
1394
        case err == nil:
×
UNCOV
1395
                return nil
×
1396

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

×
UNCOV
1401
                return nil
×
1402

1403
        default:
×
1404
        }
1405

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

×
1410
        return err
×
1411
}
1412

1413
// TrackPayments returns a stream of payment state updates.
1414
func (s *Server) TrackPayments(request *TrackPaymentsRequest,
1415
        stream Router_TrackPaymentsServer) error {
3✔
1416

3✔
1417
        log.Debug("TrackPayments called")
3✔
1418

3✔
1419
        router := s.cfg.RouterBackend
3✔
1420

3✔
1421
        // Subscribe to payments.
3✔
1422
        subscription, err := router.Tower.SubscribeAllPayments()
3✔
1423
        if err != nil {
3✔
1424
                return err
×
1425
        }
×
1426

1427
        // Stream updates to the client.
1428
        err = s.trackPaymentStream(
3✔
1429
                stream.Context(), subscription, request.NoInflightUpdates,
3✔
1430
                stream.Send,
3✔
1431
        )
3✔
1432

3✔
1433
        if errors.Is(err, context.Canceled) {
6✔
1434
                log.Debugf("TrackPayments payment stream canceled.")
3✔
1435
        }
3✔
1436

1437
        return err
3✔
1438
}
1439

1440
// trackPaymentStream streams payment updates to the client.
1441
func (s *Server) trackPaymentStream(context context.Context,
1442
        subscription routing.ControlTowerSubscriber, noInflightUpdates bool,
1443
        send func(*lnrpc.Payment) error) error {
3✔
1444

3✔
1445
        defer subscription.Close()
3✔
1446

3✔
1447
        // Stream updates back to the client.
3✔
1448
        for {
10✔
1449
                select {
7✔
1450
                case item, ok := <-subscription.Updates():
4✔
1451
                        if !ok {
4✔
UNCOV
1452
                                // No more payment updates.
×
UNCOV
1453
                                return nil
×
UNCOV
1454
                        }
×
1455
                        result := item.(*channeldb.MPPayment)
4✔
1456

4✔
1457
                        log.Tracef("Payment %v updated to state %v",
4✔
1458
                                result.Info.PaymentIdentifier, result.Status)
4✔
1459

4✔
1460
                        // Skip in-flight updates unless requested.
4✔
1461
                        if noInflightUpdates {
6✔
1462
                                if result.Status == channeldb.StatusInitiated {
2✔
1463
                                        continue
×
1464
                                }
1465
                                if result.Status == channeldb.StatusInFlight {
3✔
1466
                                        continue
1✔
1467
                                }
1468
                        }
1469

1470
                        rpcPayment, err := s.cfg.RouterBackend.MarshallPayment(
3✔
1471
                                result,
3✔
1472
                        )
3✔
1473
                        if err != nil {
3✔
1474
                                return err
×
1475
                        }
×
1476

1477
                        // Send event to the client.
1478
                        err = send(rpcPayment)
3✔
1479
                        if err != nil {
3✔
1480
                                return err
×
1481
                        }
×
1482

1483
                case <-s.quit:
×
1484
                        return errServerShuttingDown
×
1485

1486
                case <-context.Done():
3✔
1487
                        return context.Err()
3✔
1488
                }
1489
        }
1490
}
1491

1492
// BuildRoute builds a route from a list of hop addresses.
1493
func (s *Server) BuildRoute(_ context.Context,
UNCOV
1494
        req *BuildRouteRequest) (*BuildRouteResponse, error) {
×
UNCOV
1495

×
UNCOV
1496
        if len(req.HopPubkeys) == 0 {
×
1497
                return nil, errors.New("no hops specified")
×
1498
        }
×
1499

1500
        // Unmarshall hop list.
UNCOV
1501
        hops := make([]route.Vertex, len(req.HopPubkeys))
×
UNCOV
1502
        for i, pubkeyBytes := range req.HopPubkeys {
×
UNCOV
1503
                pubkey, err := route.NewVertexFromBytes(pubkeyBytes)
×
UNCOV
1504
                if err != nil {
×
1505
                        return nil, err
×
1506
                }
×
UNCOV
1507
                hops[i] = pubkey
×
1508
        }
1509

1510
        // Prepare BuildRoute call parameters from rpc request.
UNCOV
1511
        var amt fn.Option[lnwire.MilliSatoshi]
×
UNCOV
1512
        if req.AmtMsat != 0 {
×
UNCOV
1513
                rpcAmt := lnwire.MilliSatoshi(req.AmtMsat)
×
UNCOV
1514
                amt = fn.Some(rpcAmt)
×
UNCOV
1515
        }
×
1516

UNCOV
1517
        var outgoingChan *uint64
×
UNCOV
1518
        if req.OutgoingChanId != 0 {
×
1519
                outgoingChan = &req.OutgoingChanId
×
1520
        }
×
1521

UNCOV
1522
        var payAddr fn.Option[[32]byte]
×
UNCOV
1523
        if len(req.PaymentAddr) != 0 {
×
UNCOV
1524
                var backingPayAddr [32]byte
×
UNCOV
1525
                copy(backingPayAddr[:], req.PaymentAddr)
×
UNCOV
1526

×
UNCOV
1527
                payAddr = fn.Some(backingPayAddr)
×
UNCOV
1528
        }
×
1529

UNCOV
1530
        if req.FinalCltvDelta == 0 {
×
1531
                req.FinalCltvDelta = int32(
×
1532
                        s.cfg.RouterBackend.DefaultFinalCltvDelta,
×
1533
                )
×
1534
        }
×
1535

UNCOV
1536
        var firstHopBlob fn.Option[[]byte]
×
UNCOV
1537
        if len(req.FirstHopCustomRecords) > 0 {
×
1538
                firstHopRecords := lnwire.CustomRecords(
×
1539
                        req.FirstHopCustomRecords,
×
1540
                )
×
1541
                if err := firstHopRecords.Validate(); err != nil {
×
1542
                        return nil, err
×
1543
                }
×
1544

1545
                firstHopData, err := firstHopRecords.Serialize()
×
1546
                if err != nil {
×
1547
                        return nil, err
×
1548
                }
×
1549
                firstHopBlob = fn.Some(firstHopData)
×
1550
        }
1551

1552
        // Build the route and return it to the caller.
UNCOV
1553
        route, err := s.cfg.Router.BuildRoute(
×
UNCOV
1554
                amt, hops, outgoingChan, req.FinalCltvDelta, payAddr,
×
UNCOV
1555
                firstHopBlob,
×
UNCOV
1556
        )
×
UNCOV
1557
        if err != nil {
×
1558
                return nil, err
×
1559
        }
×
1560

UNCOV
1561
        rpcRoute, err := s.cfg.RouterBackend.MarshallRoute(route)
×
UNCOV
1562
        if err != nil {
×
1563
                return nil, err
×
1564
        }
×
1565

UNCOV
1566
        routeResp := &BuildRouteResponse{
×
UNCOV
1567
                Route: rpcRoute,
×
UNCOV
1568
        }
×
UNCOV
1569

×
UNCOV
1570
        return routeResp, nil
×
1571
}
1572

1573
// SubscribeHtlcEvents creates a uni-directional stream from the server to
1574
// the client which delivers a stream of htlc events.
1575
func (s *Server) SubscribeHtlcEvents(_ *SubscribeHtlcEventsRequest,
UNCOV
1576
        stream Router_SubscribeHtlcEventsServer) error {
×
UNCOV
1577

×
UNCOV
1578
        htlcClient, err := s.cfg.RouterBackend.SubscribeHtlcEvents()
×
UNCOV
1579
        if err != nil {
×
1580
                return err
×
1581
        }
×
UNCOV
1582
        defer htlcClient.Cancel()
×
UNCOV
1583

×
UNCOV
1584
        // Send out an initial subscribed event so that the caller knows the
×
UNCOV
1585
        // point from which new events will be transmitted.
×
UNCOV
1586
        if err := stream.Send(&HtlcEvent{
×
UNCOV
1587
                Event: &HtlcEvent_SubscribedEvent{
×
UNCOV
1588
                        SubscribedEvent: &SubscribedEvent{},
×
UNCOV
1589
                },
×
UNCOV
1590
        }); err != nil {
×
1591
                return err
×
1592
        }
×
1593

UNCOV
1594
        for {
×
UNCOV
1595
                select {
×
UNCOV
1596
                case event := <-htlcClient.Updates():
×
UNCOV
1597
                        rpcEvent, err := rpcHtlcEvent(event)
×
UNCOV
1598
                        if err != nil {
×
1599
                                return err
×
1600
                        }
×
1601

UNCOV
1602
                        if err := stream.Send(rpcEvent); err != nil {
×
1603
                                return err
×
1604
                        }
×
1605

1606
                // If the stream's context is cancelled, return an error.
UNCOV
1607
                case <-stream.Context().Done():
×
UNCOV
1608
                        log.Debugf("htlc event stream cancelled")
×
UNCOV
1609
                        return stream.Context().Err()
×
1610

1611
                // If the subscribe client terminates, exit with an error.
1612
                case <-htlcClient.Quit():
×
1613
                        return errors.New("htlc event subscription terminated")
×
1614

1615
                // If the server has been signalled to shut down, exit.
1616
                case <-s.quit:
×
1617
                        return errServerShuttingDown
×
1618
                }
1619
        }
1620
}
1621

1622
// HtlcInterceptor is a bidirectional stream for streaming interception
1623
// requests to the caller.
1624
// Upon connection, it does the following:
1625
// 1. Check if there is already a live stream, if yes it rejects the request.
1626
// 2. Registered a ForwardInterceptor
1627
// 3. Delivers to the caller every √√ and detect his answer.
1628
// It uses a local implementation of holdForwardsStore to keep all the hold
1629
// forwards and find them when manual resolution is later needed.
UNCOV
1630
func (s *Server) HtlcInterceptor(stream Router_HtlcInterceptorServer) error {
×
UNCOV
1631
        // We ensure there is only one interceptor at a time.
×
UNCOV
1632
        if !atomic.CompareAndSwapInt32(&s.forwardInterceptorActive, 0, 1) {
×
1633
                return ErrInterceptorAlreadyExists
×
1634
        }
×
UNCOV
1635
        defer atomic.CompareAndSwapInt32(&s.forwardInterceptorActive, 1, 0)
×
UNCOV
1636

×
UNCOV
1637
        // Run the forward interceptor.
×
UNCOV
1638
        return newForwardInterceptor(
×
UNCOV
1639
                s.cfg.RouterBackend.InterceptableForwarder, stream,
×
UNCOV
1640
        ).run()
×
1641
}
1642

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

×
UNCOV
1652
        existingAliases := s.cfg.AliasMgr.ListAliases()
×
UNCOV
1653

×
UNCOV
1654
        // aliasExists checks if the new alias already exists in the alias map.
×
UNCOV
1655
        aliasExists := func(newAlias uint64,
×
UNCOV
1656
                baseScid lnwire.ShortChannelID) (bool, error) {
×
UNCOV
1657

×
UNCOV
1658
                // First check that we actually have a channel for the given
×
UNCOV
1659
                // base scid. This should succeed for any channel where the
×
UNCOV
1660
                // option-scid-alias feature bit was negotiated.
×
UNCOV
1661
                if _, ok := existingAliases[baseScid]; !ok {
×
1662
                        return false, fmt.Errorf("base scid %v not found",
×
1663
                                baseScid)
×
1664
                }
×
1665

UNCOV
1666
                for base, aliases := range existingAliases {
×
UNCOV
1667
                        for _, alias := range aliases {
×
UNCOV
1668
                                exists := alias.ToUint64() == newAlias
×
UNCOV
1669

×
UNCOV
1670
                                // Trying to add an alias that we already have
×
UNCOV
1671
                                // for another channel is wrong.
×
UNCOV
1672
                                if exists && base != baseScid {
×
1673
                                        return true, fmt.Errorf("%w: alias %v "+
×
1674
                                                "already exists for base scid "+
×
1675
                                                "%v", ErrAliasAlreadyExists,
×
1676
                                                alias, base)
×
1677
                                }
×
1678

UNCOV
1679
                                if exists {
×
UNCOV
1680
                                        return true, nil
×
UNCOV
1681
                                }
×
1682
                        }
1683
                }
1684

UNCOV
1685
                return false, nil
×
1686
        }
1687

UNCOV
1688
        for _, v := range in.AliasMaps {
×
UNCOV
1689
                baseScid := lnwire.NewShortChanIDFromInt(v.BaseScid)
×
UNCOV
1690

×
UNCOV
1691
                for _, rpcAlias := range v.Aliases {
×
UNCOV
1692
                        // If not, let's add it to the alias manager now.
×
UNCOV
1693
                        aliasScid := lnwire.NewShortChanIDFromInt(rpcAlias)
×
UNCOV
1694

×
UNCOV
1695
                        // But we only add it, if it's a valid alias, as defined
×
UNCOV
1696
                        // by the BOLT spec.
×
UNCOV
1697
                        if !aliasmgr.IsAlias(aliasScid) {
×
UNCOV
1698
                                return nil, fmt.Errorf("%w: SCID alias %v is "+
×
UNCOV
1699
                                        "not a valid alias", ErrNoValidAlias,
×
UNCOV
1700
                                        aliasScid)
×
UNCOV
1701
                        }
×
1702

UNCOV
1703
                        exists, err := aliasExists(rpcAlias, baseScid)
×
UNCOV
1704
                        if err != nil {
×
1705
                                return nil, err
×
1706
                        }
×
1707

1708
                        // If the alias already exists, we see that as an error.
1709
                        // This is to avoid "silent" collisions.
UNCOV
1710
                        if exists {
×
UNCOV
1711
                                return nil, fmt.Errorf("%w: SCID alias %v "+
×
UNCOV
1712
                                        "already exists", ErrAliasAlreadyExists,
×
UNCOV
1713
                                        rpcAlias)
×
UNCOV
1714
                        }
×
1715

UNCOV
1716
                        err = s.cfg.AliasMgr.AddLocalAlias(
×
UNCOV
1717
                                aliasScid, baseScid, false, true,
×
UNCOV
1718
                        )
×
UNCOV
1719
                        if err != nil {
×
1720
                                return nil, fmt.Errorf("error adding scid "+
×
1721
                                        "alias, base_scid=%v, alias_scid=%v: "+
×
1722
                                        "%w", baseScid, aliasScid, err)
×
1723
                        }
×
1724
                }
1725
        }
1726

UNCOV
1727
        return &AddAliasesResponse{
×
UNCOV
1728
                AliasMaps: lnrpc.MarshalAliasMap(s.cfg.AliasMgr.ListAliases()),
×
UNCOV
1729
        }, nil
×
1730
}
1731

1732
// XDeleteLocalChanAliases is an experimental API that deletes a set of alias
1733
// mappings. The final total set of aliases in the manager after the delete
1734
// operation is returned. The deletion will not be communicated to the channel
1735
// peer via any message.
1736
func (s *Server) XDeleteLocalChanAliases(_ context.Context,
1737
        in *DeleteAliasesRequest) (*DeleteAliasesResponse,
UNCOV
1738
        error) {
×
UNCOV
1739

×
UNCOV
1740
        for _, v := range in.AliasMaps {
×
UNCOV
1741
                baseScid := lnwire.NewShortChanIDFromInt(v.BaseScid)
×
UNCOV
1742

×
UNCOV
1743
                for _, alias := range v.Aliases {
×
UNCOV
1744
                        aliasScid := lnwire.NewShortChanIDFromInt(alias)
×
UNCOV
1745

×
UNCOV
1746
                        err := s.cfg.AliasMgr.DeleteLocalAlias(
×
UNCOV
1747
                                aliasScid, baseScid,
×
UNCOV
1748
                        )
×
UNCOV
1749
                        if err != nil {
×
1750
                                return nil, fmt.Errorf("error deleting scid "+
×
1751
                                        "alias, base_scid=%v, alias_scid=%v: "+
×
1752
                                        "%w", baseScid, aliasScid, err)
×
1753
                        }
×
1754
                }
1755
        }
1756

UNCOV
1757
        return &DeleteAliasesResponse{
×
UNCOV
1758
                AliasMaps: lnrpc.MarshalAliasMap(s.cfg.AliasMgr.ListAliases()),
×
UNCOV
1759
        }, nil
×
1760
}
1761

UNCOV
1762
func extractOutPoint(req *UpdateChanStatusRequest) (*wire.OutPoint, error) {
×
UNCOV
1763
        chanPoint := req.GetChanPoint()
×
UNCOV
1764
        txid, err := lnrpc.GetChanPointFundingTxid(chanPoint)
×
UNCOV
1765
        if err != nil {
×
1766
                return nil, err
×
1767
        }
×
UNCOV
1768
        index := chanPoint.OutputIndex
×
UNCOV
1769
        return wire.NewOutPoint(txid, index), nil
×
1770
}
1771

1772
// UpdateChanStatus allows channel state to be set manually.
1773
func (s *Server) UpdateChanStatus(_ context.Context,
UNCOV
1774
        req *UpdateChanStatusRequest) (*UpdateChanStatusResponse, error) {
×
UNCOV
1775

×
UNCOV
1776
        outPoint, err := extractOutPoint(req)
×
UNCOV
1777
        if err != nil {
×
1778
                return nil, err
×
1779
        }
×
1780

UNCOV
1781
        action := req.GetAction()
×
UNCOV
1782

×
UNCOV
1783
        log.Debugf("UpdateChanStatus called for channel(%v) with "+
×
UNCOV
1784
                "action %v", outPoint, action)
×
UNCOV
1785

×
UNCOV
1786
        switch action {
×
UNCOV
1787
        case ChanStatusAction_ENABLE:
×
UNCOV
1788
                err = s.cfg.RouterBackend.SetChannelEnabled(*outPoint)
×
UNCOV
1789
        case ChanStatusAction_DISABLE:
×
UNCOV
1790
                err = s.cfg.RouterBackend.SetChannelDisabled(*outPoint)
×
UNCOV
1791
        case ChanStatusAction_AUTO:
×
UNCOV
1792
                err = s.cfg.RouterBackend.SetChannelAuto(*outPoint)
×
1793
        default:
×
1794
                err = fmt.Errorf("unrecognized ChannelStatusAction %v", action)
×
1795
        }
1796

UNCOV
1797
        if err != nil {
×
1798
                return nil, err
×
1799
        }
×
UNCOV
1800
        return &UpdateChanStatusResponse{}, nil
×
1801
}
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