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

lightningnetwork / lnd / 13458082814

21 Feb 2025 01:43PM UTC coverage: 58.831%. Remained the same
13458082814

Pull #9433

github

hieblmi
docs: update release notes
Pull Request #9433: routerrpc: fix estimateroutefee for public route hints

17 of 21 new or added lines in 1 file covered. (80.95%)

74 existing lines in 18 files now uncovered.

136365 of 231790 relevant lines covered (58.83%)

19280.79 hits per line

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

73.73
/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.
212
func New(cfg *Config) (*Server, lnrpc.MacaroonPerms, error) {
3✔
213
        // If the path of the router macaroon wasn't generated, then we'll
3✔
214
        // assume that it's found at the default network directory.
3✔
215
        if cfg.RouterMacPath == "" {
6✔
216
                cfg.RouterMacPath = filepath.Join(
3✔
217
                        cfg.NetworkDir, DefaultRouterMacFilename,
3✔
218
                )
3✔
219
        }
3✔
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.
224
        macFilePath := cfg.RouterMacPath
3✔
225
        if cfg.MacService != nil && !cfg.MacService.StatelessInit &&
3✔
226
                !lnrpc.FileExists(macFilePath) {
6✔
227

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

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

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

3✔
257
        return routerServer, macPermissions, nil
3✔
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.
263
func (s *Server) Start() error {
3✔
264
        if atomic.AddInt32(&s.started, 1) != 1 {
3✔
265
                return nil
×
266
        }
×
267

268
        return nil
3✔
269
}
270

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

279
        close(s.quit)
3✔
280
        return nil
3✔
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.
287
func (s *Server) Name() string {
3✔
288
        return subServerName
3✔
289
}
3✔
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.
296
func (r *ServerShell) RegisterWithRootServer(grpcServer *grpc.Server) error {
3✔
297
        // We make sure that we register it with the main gRPC server to ensure
3✔
298
        // all our methods are routed properly.
3✔
299
        RegisterRouterServer(grpcServer, r)
3✔
300

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

3✔
304
        return nil
3✔
305
}
3✔
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,
313
        mux *runtime.ServeMux, dest string, opts []grpc.DialOption) error {
3✔
314

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

324
        log.Debugf("Router REST server successfully registered with " +
3✔
325
                "root REST server")
3✔
326
        return nil
3✔
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) (
337
        lnrpc.SubServer, lnrpc.MacaroonPerms, error) {
3✔
338

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

344
        r.RouterServer = subServer
3✔
345
        return subServer, macPermissions, nil
3✔
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,
354
        stream Router_SendPaymentV2Server) error {
3✔
355

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

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

366
        // Get the payment hash.
367
        payHash := payment.Identifier()
3✔
368

3✔
369
        // Init the payment in db.
3✔
370
        paySession, shardTracker, err := s.cfg.Router.PreparePayment(payment)
3✔
371
        if err != nil {
3✔
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.
390
        sub, err := s.subscribePayment(payHash)
3✔
391
        if err != nil {
3✔
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.
404
        ctx := context.Background()
3✔
405
        if req.Cancelable {
6✔
406
                ctx = stream.Context()
3✔
407
        }
3✔
408

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

3✔
412
        // Track the payment and return.
3✔
413
        return s.trackPayment(sub, payHash, stream, req.NoInflightUpdates)
3✔
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,
424
        req *RouteFeeRequest) (*RouteFeeResponse, error) {
3✔
425

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

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

434
        case isProbeDestination:
3✔
435
                switch {
3✔
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

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

446
        case isProbeInvoice:
3✔
447
                return s.probePaymentRequest(
3✔
448
                        ctx, req.PaymentRequest, req.Timeout,
3✔
449
                )
3✔
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,
458
        error) {
3✔
459

3✔
460
        destNode, err := route.NewVertexFromBytes(dest)
3✔
461
        if err != nil {
3✔
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.
467
        amtMsat := lnwire.NewMSatFromSatoshis(btcutil.Amount(amtSat))
3✔
468

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

486
        route, _, err := s.cfg.Router.FindRoute(routeReq)
3✔
487
        if err != nil {
6✔
488
                return nil, err
3✔
489
        }
3✔
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.
495
        timeLockDelay := route.TotalTimeLock + uint32(routing.BlockPadding)
3✔
496

3✔
497
        return &RouteFeeResponse{
3✔
498
                RoutingFeeMsat: int64(route.TotalFees()),
3✔
499
                TimeLockDelay:  int64(timeLockDelay),
3✔
500
                FailureReason:  lnrpc.PaymentFailureReason_FAILURE_REASON_NONE,
3✔
501
        }, nil
3✔
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,
513
        timeout uint32) (*RouteFeeResponse, error) {
3✔
514

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

522
        if *payReq.MilliSat <= 0 {
3✔
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.
529
        var paymentHash lntypes.Hash
3✔
530
        _, err = crand.Read(paymentHash[:])
3✔
531
        if err != nil {
3✔
532
                return nil, fmt.Errorf("cannot generate random probe "+
×
533
                        "preimage: %w", err)
×
534
        }
×
535

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

3✔
549
        // If the payment addresses is specified, then we'll also populate that
3✔
550
        // now as well.
3✔
551
        payReq.PaymentAddr.WhenSome(func(addr [32]byte) {
6✔
552
                copy(probeRequest.PaymentAddr, addr[:])
3✔
553
        })
3✔
554

555
        hints := payReq.RouteHints
3✔
556

3✔
557
        // If the hints don't indicate an LSP then chances are that our probe
3✔
558
        // payment won't be blocked along the route to the destination. We send
3✔
559
        // a probe payment with unmodified route hints.
3✔
560
        if !isLSP(hints, s.cfg.RouterBackend.FetchChannelEndpoints) {
6✔
561
                probeRequest.RouteHints = invoicesrpc.CreateRPCRouteHints(hints)
3✔
562
                return s.sendProbePayment(ctx, probeRequest)
3✔
563
        }
3✔
564

565
        // If the heuristic indicates an LSP we modify the route hints to allow
566
        // probing the LSP.
567
        lspAdjustedRouteHints, lspHint, err := prepareLspRouteHints(
3✔
568
                hints, *payReq.MilliSat,
3✔
569
        )
3✔
570
        if err != nil {
3✔
571
                return nil, err
×
572
        }
×
573

574
        // The adjusted route hints serve the payment probe to find the last
575
        // public hop to the LSP on the route.
576
        probeRequest.Dest = lspHint.NodeID.SerializeCompressed()
3✔
577
        if len(lspAdjustedRouteHints) > 0 {
3✔
578
                probeRequest.RouteHints = invoicesrpc.CreateRPCRouteHints(
×
579
                        lspAdjustedRouteHints,
×
580
                )
×
581
        }
×
582

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

600
        // Add the last hop's fee to the requested payment amount that we want
601
        // to get an estimate for.
602
        probeRequest.AmtMsat += int64(hopFee)
3✔
603

3✔
604
        // Use the hop hint's cltv delta as the payment request's final cltv
3✔
605
        // delta. The actual final cltv delta of the invoice will be added to
3✔
606
        // the payment probe's cltv delta.
3✔
607
        probeRequest.FinalCltvDelta = int32(lspHint.CLTVExpiryDelta)
3✔
608

3✔
609
        // Dispatch the payment probe with adjusted fee amount.
3✔
610
        resp, err := s.sendProbePayment(ctx, probeRequest)
3✔
611
        if err != nil {
3✔
612
                return nil, err
×
613
        }
×
614

615
        // If the payment probe failed we only return the failure reason and
616
        // leave the probe result params unaltered.
617
        if resp.FailureReason != lnrpc.PaymentFailureReason_FAILURE_REASON_NONE { //nolint:ll
3✔
618
                return resp, nil
×
619
        }
×
620

621
        // The probe succeeded, so we can add the last hop's fee to fee the
622
        // payment probe returned.
623
        resp.RoutingFeeMsat += int64(hopFee)
3✔
624

3✔
625
        // Add the final cltv delta of the invoice to the payment probe's total
3✔
626
        // cltv delta. This is the cltv delta for the hop behind the LSP.
3✔
627
        resp.TimeLockDelay += int64(payReq.MinFinalCLTVExpiry())
3✔
628

3✔
629
        return resp, nil
3✔
630
}
631

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

3✔
640
        if len(routeHints) == 0 || len(routeHints[0]) == 0 {
6✔
641
                return false
3✔
642
        }
3✔
643

644
        destHopHint := routeHints[0][len(routeHints[0])-1]
3✔
645

3✔
646
        // If the destination hop hint of the first route hint contains a public
3✔
647
        // channel we can send a probe to it directly, hence we don't signal an
3✔
648
        // LSP.
3✔
649
        _, _, err := fetchChannelEndpoints(destHopHint.ChannelID)
3✔
650
        if err == nil {
3✔
NEW
651
                return false
×
NEW
652
        }
×
653

654
        refNodeID := destHopHint.NodeID
3✔
655
        for i := 1; i < len(routeHints); i++ {
6✔
656
                // Skip empty route hints.
3✔
657
                if len(routeHints[i]) == 0 {
3✔
658
                        continue
×
659
                }
660

661
                lastHop := routeHints[i][len(routeHints[i])-1]
3✔
662

3✔
663
                // If the last hop hint of any route hint contains a public
3✔
664
                // channel we can send a probe to it directly, hence we don't
3✔
665
                // signal an LSP.
3✔
666
                _, _, err = fetchChannelEndpoints(lastHop.ChannelID)
3✔
667
                if err == nil {
3✔
NEW
668
                        return false
×
NEW
669
                }
×
670

671
                idMatchesRefNode := bytes.Equal(
3✔
672
                        lastHop.NodeID.SerializeCompressed(),
3✔
673
                        refNodeID.SerializeCompressed(),
3✔
674
                )
3✔
675
                if !idMatchesRefNode {
6✔
676
                        return false
3✔
677
                }
3✔
678
        }
679

680
        // We ensured that the destination hop hint doesn't contain a public
681
        // channel, and that all destination hop hints of all route hints match,
682
        // so we signal an LSP.
683
        return true
3✔
684
}
685

686
// prepareLspRouteHints assumes that the isLsp heuristic returned true for the
687
// route hints passed in here. It constructs a modified list of route hints that
688
// allows the caller to probe the LSP, which itself is returned as a separate
689
// hop hint.
690
func prepareLspRouteHints(routeHints [][]zpay32.HopHint,
691
        amt lnwire.MilliSatoshi) ([][]zpay32.HopHint, *zpay32.HopHint, error) {
3✔
692

3✔
693
        if len(routeHints) == 0 {
3✔
694
                return nil, nil, fmt.Errorf("no route hints provided")
×
695
        }
×
696

697
        // Create the LSP hop hint. We are probing for the worst case fee and
698
        // cltv delta. So we look for the max values amongst all LSP hop hints.
699
        refHint := routeHints[0][len(routeHints[0])-1]
3✔
700
        refHint.CLTVExpiryDelta = maxLspCltvDelta(routeHints)
3✔
701
        refHint.FeeBaseMSat, refHint.FeeProportionalMillionths = maxLspFee(
3✔
702
                routeHints, amt,
3✔
703
        )
3✔
704

3✔
705
        // We construct a modified list of route hints that allows the caller to
3✔
706
        // probe the LSP.
3✔
707
        adjustedHints := make([][]zpay32.HopHint, 0, len(routeHints))
3✔
708

3✔
709
        // Strip off the LSP hop hint from all route hints.
3✔
710
        for i := 0; i < len(routeHints); i++ {
6✔
711
                hint := routeHints[i]
3✔
712
                if len(hint) > 1 {
3✔
713
                        adjustedHints = append(
×
714
                                adjustedHints, hint[:len(hint)-1],
×
715
                        )
×
716
                }
×
717
        }
718

719
        return adjustedHints, &refHint, nil
3✔
720
}
721

722
// maxLspFee returns base fee and fee rate amongst all LSP route hints that
723
// results in the overall highest fee for the given amount.
724
func maxLspFee(routeHints [][]zpay32.HopHint, amt lnwire.MilliSatoshi) (uint32,
725
        uint32) {
3✔
726

3✔
727
        var maxFeePpm uint32
3✔
728
        var maxBaseFee uint32
3✔
729
        var maxTotalFee lnwire.MilliSatoshi
3✔
730
        for _, rh := range routeHints {
6✔
731
                lastHop := rh[len(rh)-1]
3✔
732
                lastHopFee := lastHop.HopFee(amt)
3✔
733
                if lastHopFee > maxTotalFee {
6✔
734
                        maxTotalFee = lastHopFee
3✔
735
                        maxBaseFee = lastHop.FeeBaseMSat
3✔
736
                        maxFeePpm = lastHop.FeeProportionalMillionths
3✔
737
                }
3✔
738
        }
739

740
        return maxBaseFee, maxFeePpm
3✔
741
}
742

743
// maxLspCltvDelta returns the maximum cltv delta amongst all LSP route hints.
744
func maxLspCltvDelta(routeHints [][]zpay32.HopHint) uint16 {
3✔
745
        var maxCltvDelta uint16
3✔
746
        for _, rh := range routeHints {
6✔
747
                rhLastHop := rh[len(rh)-1]
3✔
748
                if rhLastHop.CLTVExpiryDelta > maxCltvDelta {
6✔
749
                        maxCltvDelta = rhLastHop.CLTVExpiryDelta
3✔
750
                }
3✔
751
        }
752

753
        return maxCltvDelta
3✔
754
}
755

756
// probePaymentStream is a custom implementation of the grpc.ServerStream
757
// interface. It is used to send payment status updates to the caller on the
758
// stream channel.
759
type probePaymentStream struct {
760
        Router_SendPaymentV2Server
761

762
        stream chan *lnrpc.Payment
763
        ctx    context.Context //nolint:containedctx
764
}
765

766
// Send sends a payment status update to a payment stream that the caller can
767
// evaluate.
768
func (p *probePaymentStream) Send(response *lnrpc.Payment) error {
3✔
769
        select {
3✔
770
        case p.stream <- response:
3✔
771

772
        case <-p.ctx.Done():
×
773
                return p.ctx.Err()
×
774
        }
775

776
        return nil
3✔
777
}
778

779
// Context returns the context of the stream.
780
func (p *probePaymentStream) Context() context.Context {
3✔
781
        return p.ctx
3✔
782
}
3✔
783

784
// sendProbePayment sends a payment to a target node in order to obtain
785
// potential routing fees for it. The payment request has to contain a payment
786
// hash that is guaranteed to be unknown to the target node, so it cannot settle
787
// the payment. This method invokes a payment request loop in a goroutine and
788
// awaits payment status updates.
789
func (s *Server) sendProbePayment(ctx context.Context,
790
        req *SendPaymentRequest) (*RouteFeeResponse, error) {
3✔
791

3✔
792
        // We'll launch a goroutine to send the payment probes.
3✔
793
        errChan := make(chan error, 1)
3✔
794
        defer close(errChan)
3✔
795

3✔
796
        paymentStream := &probePaymentStream{
3✔
797
                stream: make(chan *lnrpc.Payment),
3✔
798
                ctx:    ctx,
3✔
799
        }
3✔
800
        go func() {
6✔
801
                err := s.SendPaymentV2(req, paymentStream)
3✔
802
                if err != nil {
3✔
803
                        select {
×
804
                        case errChan <- err:
×
805

806
                        case <-paymentStream.ctx.Done():
×
807
                                return
×
808
                        }
809
                }
810
        }()
811

812
        for {
6✔
813
                select {
3✔
814
                case payment := <-paymentStream.stream:
3✔
815
                        switch payment.Status {
3✔
816
                        case lnrpc.Payment_INITIATED:
×
817
                        case lnrpc.Payment_IN_FLIGHT:
3✔
818
                        case lnrpc.Payment_SUCCEEDED:
×
819
                                return nil, errors.New("warning, the fee " +
×
820
                                        "estimation payment probe " +
×
821
                                        "unexpectedly succeeded. Please reach" +
×
822
                                        "out to the probe destination to " +
×
823
                                        "negotiate a refund. Otherwise the " +
×
824
                                        "payment probe amount is lost forever")
×
825

826
                        case lnrpc.Payment_FAILED:
3✔
827
                                // Incorrect payment details point to a
3✔
828
                                // successful probe.
3✔
829
                                //nolint:ll
3✔
830
                                if payment.FailureReason == lnrpc.PaymentFailureReason_FAILURE_REASON_INCORRECT_PAYMENT_DETAILS {
6✔
831
                                        return paymentDetails(payment)
3✔
832
                                }
3✔
833

834
                                return &RouteFeeResponse{
3✔
835
                                        RoutingFeeMsat: 0,
3✔
836
                                        TimeLockDelay:  0,
3✔
837
                                        FailureReason:  payment.FailureReason,
3✔
838
                                }, nil
3✔
839

840
                        default:
×
841
                                return nil, errors.New("unexpected payment " +
×
842
                                        "status")
×
843
                        }
844

845
                case err := <-errChan:
×
846
                        return nil, err
×
847

848
                case <-s.quit:
×
849
                        return nil, errServerShuttingDown
×
850
                }
851
        }
852
}
853

854
func paymentDetails(payment *lnrpc.Payment) (*RouteFeeResponse, error) {
3✔
855
        fee, timeLock, err := timelockAndFee(payment)
3✔
856
        if errors.Is(err, errUnexpectedFailureSource) {
3✔
857
                return nil, err
×
858
        }
×
859

860
        return &RouteFeeResponse{
3✔
861
                RoutingFeeMsat: fee,
3✔
862
                TimeLockDelay:  timeLock,
3✔
863
                FailureReason:  lnrpc.PaymentFailureReason_FAILURE_REASON_NONE,
3✔
864
        }, nil
3✔
865
}
866

867
// timelockAndFee returns the fee and total time lock of the last payment
868
// attempt.
869
func timelockAndFee(p *lnrpc.Payment) (int64, int64, error) {
3✔
870
        if len(p.Htlcs) == 0 {
3✔
871
                return 0, 0, nil
×
872
        }
×
873

874
        lastAttempt := p.Htlcs[len(p.Htlcs)-1]
3✔
875
        if lastAttempt == nil {
3✔
876
                return 0, 0, errMissingPaymentAttempt
×
877
        }
×
878

879
        lastRoute := lastAttempt.Route
3✔
880
        if lastRoute == nil {
3✔
881
                return 0, 0, errMissingRoute
×
882
        }
×
883

884
        hopFailureIndex := lastAttempt.Failure.FailureSourceIndex
3✔
885
        finalHopIndex := uint32(len(lastRoute.Hops))
3✔
886
        if hopFailureIndex != finalHopIndex {
3✔
887
                return 0, 0, errUnexpectedFailureSource
×
888
        }
×
889

890
        return lastRoute.TotalFeesMsat, int64(lastRoute.TotalTimeLock), nil
3✔
891
}
892

893
// SendToRouteV2 sends a payment through a predefined route. The response of
894
// this call contains structured error information.
895
func (s *Server) SendToRouteV2(ctx context.Context,
896
        req *SendToRouteRequest) (*lnrpc.HTLCAttempt, error) {
3✔
897

3✔
898
        if req.Route == nil {
3✔
899
                return nil, fmt.Errorf("unable to send, no routes provided")
×
900
        }
×
901

902
        route, err := s.cfg.RouterBackend.UnmarshallRoute(req.Route)
3✔
903
        if err != nil {
3✔
904
                return nil, err
×
905
        }
×
906

907
        hash, err := lntypes.MakeHash(req.PaymentHash)
3✔
908
        if err != nil {
3✔
909
                return nil, err
×
910
        }
×
911

912
        firstHopRecords := lnwire.CustomRecords(req.FirstHopCustomRecords)
3✔
913
        if err := firstHopRecords.Validate(); err != nil {
3✔
914
                return nil, err
×
915
        }
×
916

917
        var attempt *channeldb.HTLCAttempt
3✔
918

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

944
        // Transform user errors to grpc code.
945
        switch {
×
946
        case errors.Is(err, channeldb.ErrPaymentExists):
×
947
                fallthrough
×
948

949
        case errors.Is(err, channeldb.ErrPaymentInFlight):
×
950
                fallthrough
×
951

952
        case errors.Is(err, channeldb.ErrAlreadyPaid):
×
953
                return nil, status.Error(
×
954
                        codes.AlreadyExists, err.Error(),
×
955
                )
×
956
        }
957

958
        return nil, err
×
959
}
960

961
// ResetMissionControl clears all mission control state and starts with a clean
962
// slate.
963
func (s *Server) ResetMissionControl(ctx context.Context,
964
        req *ResetMissionControlRequest) (*ResetMissionControlResponse, error) {
3✔
965

3✔
966
        err := s.cfg.RouterBackend.MissionControl.ResetHistory()
3✔
967
        if err != nil {
3✔
968
                return nil, err
×
969
        }
×
970

971
        return &ResetMissionControlResponse{}, nil
3✔
972
}
973

974
// GetMissionControlConfig returns our current mission control config.
975
func (s *Server) GetMissionControlConfig(ctx context.Context,
976
        req *GetMissionControlConfigRequest) (*GetMissionControlConfigResponse,
977
        error) {
3✔
978

3✔
979
        // Query the current mission control config.
3✔
980
        cfg := s.cfg.RouterBackend.MissionControl.GetConfig()
3✔
981
        resp := &GetMissionControlConfigResponse{
3✔
982
                Config: &MissionControlConfig{
3✔
983
                        MaximumPaymentResults: uint32(cfg.MaxMcHistory),
3✔
984
                        MinimumFailureRelaxInterval: uint64(
3✔
985
                                cfg.MinFailureRelaxInterval.Seconds(),
3✔
986
                        ),
3✔
987
                },
3✔
988
        }
3✔
989

3✔
990
        // We only populate fields based on the current estimator.
3✔
991
        switch v := cfg.Estimator.Config().(type) {
3✔
992
        case routing.AprioriConfig:
3✔
993
                resp.Config.Model = MissionControlConfig_APRIORI
3✔
994
                aCfg := AprioriParameters{
3✔
995
                        HalfLifeSeconds:  uint64(v.PenaltyHalfLife.Seconds()),
3✔
996
                        HopProbability:   v.AprioriHopProbability,
3✔
997
                        Weight:           v.AprioriWeight,
3✔
998
                        CapacityFraction: v.CapacityFraction,
3✔
999
                }
3✔
1000

3✔
1001
                // Populate deprecated fields.
3✔
1002
                resp.Config.HalfLifeSeconds = uint64(
3✔
1003
                        v.PenaltyHalfLife.Seconds(),
3✔
1004
                )
3✔
1005
                resp.Config.HopProbability = float32(v.AprioriHopProbability)
3✔
1006
                resp.Config.Weight = float32(v.AprioriWeight)
3✔
1007

3✔
1008
                resp.Config.EstimatorConfig = &MissionControlConfig_Apriori{
3✔
1009
                        Apriori: &aCfg,
3✔
1010
                }
3✔
1011

1012
        case routing.BimodalConfig:
3✔
1013
                resp.Config.Model = MissionControlConfig_BIMODAL
3✔
1014
                bCfg := BimodalParameters{
3✔
1015
                        NodeWeight: v.BimodalNodeWeight,
3✔
1016
                        ScaleMsat:  uint64(v.BimodalScaleMsat),
3✔
1017
                        DecayTime:  uint64(v.BimodalDecayTime.Seconds()),
3✔
1018
                }
3✔
1019

3✔
1020
                resp.Config.EstimatorConfig = &MissionControlConfig_Bimodal{
3✔
1021
                        Bimodal: &bCfg,
3✔
1022
                }
3✔
1023

1024
        default:
×
1025
                return nil, fmt.Errorf("unknown estimator config type %T", v)
×
1026
        }
1027

1028
        return resp, nil
3✔
1029
}
1030

1031
// SetMissionControlConfig sets parameters in the mission control config.
1032
func (s *Server) SetMissionControlConfig(ctx context.Context,
1033
        req *SetMissionControlConfigRequest) (*SetMissionControlConfigResponse,
1034
        error) {
3✔
1035

3✔
1036
        mcCfg := &routing.MissionControlConfig{
3✔
1037
                MaxMcHistory: int(req.Config.MaximumPaymentResults),
3✔
1038
                MinFailureRelaxInterval: time.Duration(
3✔
1039
                        req.Config.MinimumFailureRelaxInterval,
3✔
1040
                ) * time.Second,
3✔
1041
        }
3✔
1042

3✔
1043
        switch req.Config.Model {
3✔
1044
        case MissionControlConfig_APRIORI:
3✔
1045
                var aprioriConfig routing.AprioriConfig
3✔
1046

3✔
1047
                // Determine the apriori config with backward compatibility
3✔
1048
                // should the api use deprecated fields.
3✔
1049
                switch v := req.Config.EstimatorConfig.(type) {
3✔
1050
                case *MissionControlConfig_Bimodal:
3✔
1051
                        return nil, fmt.Errorf("bimodal config " +
3✔
1052
                                "provided, but apriori model requested")
3✔
1053

1054
                case *MissionControlConfig_Apriori:
3✔
1055
                        aprioriConfig = routing.AprioriConfig{
3✔
1056
                                PenaltyHalfLife: time.Duration(
3✔
1057
                                        v.Apriori.HalfLifeSeconds,
3✔
1058
                                ) * time.Second,
3✔
1059
                                AprioriHopProbability: v.Apriori.HopProbability,
3✔
1060
                                AprioriWeight:         v.Apriori.Weight,
3✔
1061
                                CapacityFraction: v.Apriori.
3✔
1062
                                        CapacityFraction,
3✔
1063
                        }
3✔
1064

1065
                default:
3✔
1066
                        aprioriConfig = routing.AprioriConfig{
3✔
1067
                                PenaltyHalfLife: time.Duration(
3✔
1068
                                        int64(req.Config.HalfLifeSeconds),
3✔
1069
                                ) * time.Second,
3✔
1070
                                AprioriHopProbability: float64(
3✔
1071
                                        req.Config.HopProbability,
3✔
1072
                                ),
3✔
1073
                                AprioriWeight:    float64(req.Config.Weight),
3✔
1074
                                CapacityFraction: routing.DefaultCapacityFraction, //nolint:ll
3✔
1075
                        }
3✔
1076
                }
1077

1078
                estimator, err := routing.NewAprioriEstimator(aprioriConfig)
3✔
1079
                if err != nil {
3✔
1080
                        return nil, err
×
1081
                }
×
1082
                mcCfg.Estimator = estimator
3✔
1083

1084
        case MissionControlConfig_BIMODAL:
3✔
1085
                cfg, ok := req.Config.
3✔
1086
                        EstimatorConfig.(*MissionControlConfig_Bimodal)
3✔
1087
                if !ok {
3✔
1088
                        return nil, fmt.Errorf("bimodal estimator requested " +
×
1089
                                "but corresponding config not set")
×
1090
                }
×
1091
                bCfg := cfg.Bimodal
3✔
1092

3✔
1093
                bimodalConfig := routing.BimodalConfig{
3✔
1094
                        BimodalDecayTime: time.Duration(
3✔
1095
                                bCfg.DecayTime,
3✔
1096
                        ) * time.Second,
3✔
1097
                        BimodalScaleMsat:  lnwire.MilliSatoshi(bCfg.ScaleMsat),
3✔
1098
                        BimodalNodeWeight: bCfg.NodeWeight,
3✔
1099
                }
3✔
1100

3✔
1101
                estimator, err := routing.NewBimodalEstimator(bimodalConfig)
3✔
1102
                if err != nil {
3✔
1103
                        return nil, err
×
1104
                }
×
1105
                mcCfg.Estimator = estimator
3✔
1106

1107
        default:
×
1108
                return nil, fmt.Errorf("unknown estimator type %v",
×
1109
                        req.Config.Model)
×
1110
        }
1111

1112
        return &SetMissionControlConfigResponse{},
3✔
1113
                s.cfg.RouterBackend.MissionControl.SetConfig(mcCfg)
3✔
1114
}
1115

1116
// QueryMissionControl exposes the internal mission control state to callers. It
1117
// is a development feature.
1118
func (s *Server) QueryMissionControl(_ context.Context,
1119
        _ *QueryMissionControlRequest) (*QueryMissionControlResponse, error) {
×
1120

×
1121
        snapshot := s.cfg.RouterBackend.MissionControl.GetHistorySnapshot()
×
1122

×
1123
        rpcPairs := make([]*PairHistory, 0, len(snapshot.Pairs))
×
1124
        for _, p := range snapshot.Pairs {
×
1125
                // Prevent binding to loop variable.
×
1126
                pair := p
×
1127

×
1128
                rpcPair := PairHistory{
×
1129
                        NodeFrom: pair.Pair.From[:],
×
1130
                        NodeTo:   pair.Pair.To[:],
×
1131
                        History:  toRPCPairData(&pair.TimedPairResult),
×
1132
                }
×
1133

×
1134
                rpcPairs = append(rpcPairs, &rpcPair)
×
1135
        }
×
1136

1137
        response := QueryMissionControlResponse{
×
1138
                Pairs: rpcPairs,
×
1139
        }
×
1140

×
1141
        return &response, nil
×
1142
}
1143

1144
// toRPCPairData marshalls mission control pair data to the rpc struct.
1145
func toRPCPairData(data *routing.TimedPairResult) *PairData {
3✔
1146
        rpcData := PairData{
3✔
1147
                FailAmtSat:     int64(data.FailAmt.ToSatoshis()),
3✔
1148
                FailAmtMsat:    int64(data.FailAmt),
3✔
1149
                SuccessAmtSat:  int64(data.SuccessAmt.ToSatoshis()),
3✔
1150
                SuccessAmtMsat: int64(data.SuccessAmt),
3✔
1151
        }
3✔
1152

3✔
1153
        if !data.FailTime.IsZero() {
6✔
1154
                rpcData.FailTime = data.FailTime.Unix()
3✔
1155
        }
3✔
1156

1157
        if !data.SuccessTime.IsZero() {
3✔
1158
                rpcData.SuccessTime = data.SuccessTime.Unix()
×
1159
        }
×
1160

1161
        return &rpcData
3✔
1162
}
1163

1164
// XImportMissionControl imports the state provided to our internal mission
1165
// control. Only entries that are fresher than our existing state will be used.
1166
func (s *Server) XImportMissionControl(_ context.Context,
1167
        req *XImportMissionControlRequest) (*XImportMissionControlResponse,
1168
        error) {
3✔
1169

3✔
1170
        if len(req.Pairs) == 0 {
3✔
1171
                return nil, errors.New("at least one pair required for import")
×
1172
        }
×
1173

1174
        snapshot := &routing.MissionControlSnapshot{
3✔
1175
                Pairs: make(
3✔
1176
                        []routing.MissionControlPairSnapshot, len(req.Pairs),
3✔
1177
                ),
3✔
1178
        }
3✔
1179

3✔
1180
        for i, pairResult := range req.Pairs {
6✔
1181
                pairSnapshot, err := toPairSnapshot(pairResult)
3✔
1182
                if err != nil {
6✔
1183
                        return nil, err
3✔
1184
                }
3✔
1185

1186
                snapshot.Pairs[i] = *pairSnapshot
3✔
1187
        }
1188

1189
        err := s.cfg.RouterBackend.MissionControl.ImportHistory(
3✔
1190
                snapshot, req.Force,
3✔
1191
        )
3✔
1192
        if err != nil {
3✔
1193
                return nil, err
×
1194
        }
×
1195

1196
        return &XImportMissionControlResponse{}, nil
3✔
1197
}
1198

1199
func toPairSnapshot(pairResult *PairHistory) (*routing.MissionControlPairSnapshot,
1200
        error) {
3✔
1201

3✔
1202
        from, err := route.NewVertexFromBytes(pairResult.NodeFrom)
3✔
1203
        if err != nil {
3✔
1204
                return nil, err
×
1205
        }
×
1206

1207
        to, err := route.NewVertexFromBytes(pairResult.NodeTo)
3✔
1208
        if err != nil {
3✔
1209
                return nil, err
×
1210
        }
×
1211

1212
        pairPrefix := fmt.Sprintf("pair: %v -> %v:", from, to)
3✔
1213

3✔
1214
        if from == to {
3✔
1215
                return nil, fmt.Errorf("%v source and destination node must "+
×
1216
                        "differ", pairPrefix)
×
1217
        }
×
1218

1219
        failAmt, failTime, err := getPair(
3✔
1220
                lnwire.MilliSatoshi(pairResult.History.FailAmtMsat),
3✔
1221
                btcutil.Amount(pairResult.History.FailAmtSat),
3✔
1222
                pairResult.History.FailTime,
3✔
1223
                true,
3✔
1224
        )
3✔
1225
        if err != nil {
6✔
1226
                return nil, fmt.Errorf("%v invalid failure: %w", pairPrefix,
3✔
1227
                        err)
3✔
1228
        }
3✔
1229

1230
        successAmt, successTime, err := getPair(
3✔
1231
                lnwire.MilliSatoshi(pairResult.History.SuccessAmtMsat),
3✔
1232
                btcutil.Amount(pairResult.History.SuccessAmtSat),
3✔
1233
                pairResult.History.SuccessTime,
3✔
1234
                false,
3✔
1235
        )
3✔
1236
        if err != nil {
3✔
1237
                return nil, fmt.Errorf("%v invalid success: %w", pairPrefix,
×
1238
                        err)
×
1239
        }
×
1240

1241
        if successAmt == 0 && failAmt == 0 {
3✔
1242
                return nil, fmt.Errorf("%v: either success or failure result "+
×
1243
                        "required", pairPrefix)
×
1244
        }
×
1245

1246
        pair := routing.NewDirectedNodePair(from, to)
3✔
1247

3✔
1248
        result := &routing.TimedPairResult{
3✔
1249
                FailAmt:     failAmt,
3✔
1250
                FailTime:    failTime,
3✔
1251
                SuccessAmt:  successAmt,
3✔
1252
                SuccessTime: successTime,
3✔
1253
        }
3✔
1254

3✔
1255
        return &routing.MissionControlPairSnapshot{
3✔
1256
                Pair:            pair,
3✔
1257
                TimedPairResult: *result,
3✔
1258
        }, nil
3✔
1259
}
1260

1261
// getPair validates the values provided for a mission control result and
1262
// returns the msat amount and timestamp for it. `isFailure` can be used to
1263
// default values to 0 instead of returning an error.
1264
func getPair(amtMsat lnwire.MilliSatoshi, amtSat btcutil.Amount,
1265
        timestamp int64, isFailure bool) (lnwire.MilliSatoshi, time.Time,
1266
        error) {
3✔
1267

3✔
1268
        amt, err := getMsatPairValue(amtMsat, amtSat)
3✔
1269
        if err != nil {
6✔
1270
                return 0, time.Time{}, err
3✔
1271
        }
3✔
1272

1273
        var (
3✔
1274
                timeSet   = timestamp != 0
3✔
1275
                amountSet = amt != 0
3✔
1276
        )
3✔
1277

3✔
1278
        switch {
3✔
1279
        // If a timestamp and amount if provided, return those values.
1280
        case timeSet && amountSet:
3✔
1281
                return amt, time.Unix(timestamp, 0), nil
3✔
1282

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

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

1295
        default:
3✔
1296
                return 0, time.Time{}, nil
3✔
1297
        }
1298
}
1299

1300
// getMsatPairValue checks the msat and sat values set for a pair and ensures
1301
// that the values provided are either the same, or only a single value is set.
1302
func getMsatPairValue(msatValue lnwire.MilliSatoshi,
1303
        satValue btcutil.Amount) (lnwire.MilliSatoshi, error) {
3✔
1304

3✔
1305
        // If our msat value converted to sats equals our sat value, we just
3✔
1306
        // return the msat value, since the values are the same.
3✔
1307
        if msatValue.ToSatoshis() == satValue {
6✔
1308
                return msatValue, nil
3✔
1309
        }
3✔
1310

1311
        // If we have no msatValue, we can just return our state value even if
1312
        // it is zero, because it's impossible that we have mismatched values.
1313
        if msatValue == 0 {
3✔
1314
                return lnwire.MilliSatoshi(satValue * 1000), nil
×
1315
        }
×
1316

1317
        // Likewise, we can just use msat value if we have no sat value set.
1318
        if satValue == 0 {
3✔
1319
                return msatValue, nil
×
1320
        }
×
1321

1322
        // If our values are non-zero but not equal, we have invalid amounts
1323
        // set, so we fail.
1324
        return 0, fmt.Errorf("msat: %v and sat: %v values not equal", msatValue,
3✔
1325
                satValue)
3✔
1326
}
1327

1328
// TrackPaymentV2 returns a stream of payment state updates. The stream is
1329
// closed when the payment completes.
1330
func (s *Server) TrackPaymentV2(request *TrackPaymentRequest,
1331
        stream Router_TrackPaymentV2Server) error {
3✔
1332

3✔
1333
        payHash, err := lntypes.MakeHash(request.PaymentHash)
3✔
1334
        if err != nil {
3✔
1335
                return err
×
1336
        }
×
1337

1338
        log.Debugf("TrackPayment called for payment %v", payHash)
3✔
1339

3✔
1340
        // Make the subscription.
3✔
1341
        sub, err := s.subscribePayment(payHash)
3✔
1342
        if err != nil {
3✔
1343
                return err
×
1344
        }
×
1345

1346
        return s.trackPayment(sub, payHash, stream, request.NoInflightUpdates)
3✔
1347
}
1348

1349
// subscribePayment subscribes to the payment updates for the given payment
1350
// hash.
1351
func (s *Server) subscribePayment(identifier lntypes.Hash) (
1352
        routing.ControlTowerSubscriber, error) {
3✔
1353

3✔
1354
        // Make the subscription.
3✔
1355
        router := s.cfg.RouterBackend
3✔
1356
        sub, err := router.Tower.SubscribePayment(identifier)
3✔
1357

3✔
1358
        switch {
3✔
1359
        case errors.Is(err, channeldb.ErrPaymentNotInitiated):
×
1360
                return nil, status.Error(codes.NotFound, err.Error())
×
1361

1362
        case err != nil:
×
1363
                return nil, err
×
1364
        }
1365

1366
        return sub, nil
3✔
1367
}
1368

1369
// trackPayment writes payment status updates to the provided stream.
1370
func (s *Server) trackPayment(subscription routing.ControlTowerSubscriber,
1371
        identifier lntypes.Hash, stream Router_TrackPaymentV2Server,
1372
        noInflightUpdates bool) error {
3✔
1373

3✔
1374
        err := s.trackPaymentStream(
3✔
1375
                stream.Context(), subscription, noInflightUpdates, stream.Send,
3✔
1376
        )
3✔
1377
        switch {
3✔
1378
        case err == nil:
3✔
1379
                return nil
3✔
1380

1381
        // If the context is canceled, we don't return an error.
1382
        case errors.Is(err, context.Canceled):
3✔
1383
                log.Infof("Payment stream %v canceled", identifier)
3✔
1384

3✔
1385
                return nil
3✔
1386

1387
        default:
×
1388
        }
1389

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

×
1394
        return err
×
1395
}
1396

1397
// TrackPayments returns a stream of payment state updates.
1398
func (s *Server) TrackPayments(request *TrackPaymentsRequest,
1399
        stream Router_TrackPaymentsServer) error {
3✔
1400

3✔
1401
        log.Debug("TrackPayments called")
3✔
1402

3✔
1403
        router := s.cfg.RouterBackend
3✔
1404

3✔
1405
        // Subscribe to payments.
3✔
1406
        subscription, err := router.Tower.SubscribeAllPayments()
3✔
1407
        if err != nil {
3✔
1408
                return err
×
1409
        }
×
1410

1411
        // Stream updates to the client.
1412
        err = s.trackPaymentStream(
3✔
1413
                stream.Context(), subscription, request.NoInflightUpdates,
3✔
1414
                stream.Send,
3✔
1415
        )
3✔
1416

3✔
1417
        if errors.Is(err, context.Canceled) {
6✔
1418
                log.Debugf("TrackPayments payment stream canceled.")
3✔
1419
        }
3✔
1420

1421
        return err
3✔
1422
}
1423

1424
// trackPaymentStream streams payment updates to the client.
1425
func (s *Server) trackPaymentStream(context context.Context,
1426
        subscription routing.ControlTowerSubscriber, noInflightUpdates bool,
1427
        send func(*lnrpc.Payment) error) error {
3✔
1428

3✔
1429
        defer subscription.Close()
3✔
1430

3✔
1431
        // Stream updates back to the client.
3✔
1432
        for {
6✔
1433
                select {
3✔
1434
                case item, ok := <-subscription.Updates():
3✔
1435
                        if !ok {
6✔
1436
                                // No more payment updates.
3✔
1437
                                return nil
3✔
1438
                        }
3✔
1439
                        result := item.(*channeldb.MPPayment)
3✔
1440

3✔
1441
                        log.Tracef("Payment %v updated to state %v",
3✔
1442
                                result.Info.PaymentIdentifier, result.Status)
3✔
1443

3✔
1444
                        // Skip in-flight updates unless requested.
3✔
1445
                        if noInflightUpdates {
3✔
1446
                                if result.Status == channeldb.StatusInitiated {
×
1447
                                        continue
×
1448
                                }
1449
                                if result.Status == channeldb.StatusInFlight {
×
1450
                                        continue
×
1451
                                }
1452
                        }
1453

1454
                        rpcPayment, err := s.cfg.RouterBackend.MarshallPayment(
3✔
1455
                                result,
3✔
1456
                        )
3✔
1457
                        if err != nil {
3✔
1458
                                return err
×
1459
                        }
×
1460

1461
                        // Send event to the client.
1462
                        err = send(rpcPayment)
3✔
1463
                        if err != nil {
3✔
1464
                                return err
×
1465
                        }
×
1466

1467
                case <-s.quit:
×
1468
                        return errServerShuttingDown
×
1469

1470
                case <-context.Done():
3✔
1471
                        return context.Err()
3✔
1472
                }
1473
        }
1474
}
1475

1476
// BuildRoute builds a route from a list of hop addresses.
1477
func (s *Server) BuildRoute(_ context.Context,
1478
        req *BuildRouteRequest) (*BuildRouteResponse, error) {
3✔
1479

3✔
1480
        if len(req.HopPubkeys) == 0 {
3✔
1481
                return nil, errors.New("no hops specified")
×
1482
        }
×
1483

1484
        // Unmarshall hop list.
1485
        hops := make([]route.Vertex, len(req.HopPubkeys))
3✔
1486
        for i, pubkeyBytes := range req.HopPubkeys {
6✔
1487
                pubkey, err := route.NewVertexFromBytes(pubkeyBytes)
3✔
1488
                if err != nil {
3✔
1489
                        return nil, err
×
1490
                }
×
1491
                hops[i] = pubkey
3✔
1492
        }
1493

1494
        // Prepare BuildRoute call parameters from rpc request.
1495
        var amt fn.Option[lnwire.MilliSatoshi]
3✔
1496
        if req.AmtMsat != 0 {
6✔
1497
                rpcAmt := lnwire.MilliSatoshi(req.AmtMsat)
3✔
1498
                amt = fn.Some(rpcAmt)
3✔
1499
        }
3✔
1500

1501
        var outgoingChan *uint64
3✔
1502
        if req.OutgoingChanId != 0 {
3✔
1503
                outgoingChan = &req.OutgoingChanId
×
1504
        }
×
1505

1506
        var payAddr fn.Option[[32]byte]
3✔
1507
        if len(req.PaymentAddr) != 0 {
6✔
1508
                var backingPayAddr [32]byte
3✔
1509
                copy(backingPayAddr[:], req.PaymentAddr)
3✔
1510

3✔
1511
                payAddr = fn.Some(backingPayAddr)
3✔
1512
        }
3✔
1513

1514
        if req.FinalCltvDelta == 0 {
3✔
1515
                req.FinalCltvDelta = int32(
×
1516
                        s.cfg.RouterBackend.DefaultFinalCltvDelta,
×
1517
                )
×
1518
        }
×
1519

1520
        var firstHopBlob fn.Option[[]byte]
3✔
1521
        if len(req.FirstHopCustomRecords) > 0 {
3✔
1522
                firstHopRecords := lnwire.CustomRecords(
×
1523
                        req.FirstHopCustomRecords,
×
1524
                )
×
1525
                if err := firstHopRecords.Validate(); err != nil {
×
1526
                        return nil, err
×
1527
                }
×
1528

1529
                firstHopData, err := firstHopRecords.Serialize()
×
1530
                if err != nil {
×
1531
                        return nil, err
×
1532
                }
×
1533
                firstHopBlob = fn.Some(firstHopData)
×
1534
        }
1535

1536
        // Build the route and return it to the caller.
1537
        route, err := s.cfg.Router.BuildRoute(
3✔
1538
                amt, hops, outgoingChan, req.FinalCltvDelta, payAddr,
3✔
1539
                firstHopBlob,
3✔
1540
        )
3✔
1541
        if err != nil {
3✔
1542
                return nil, err
×
1543
        }
×
1544

1545
        rpcRoute, err := s.cfg.RouterBackend.MarshallRoute(route)
3✔
1546
        if err != nil {
3✔
1547
                return nil, err
×
1548
        }
×
1549

1550
        routeResp := &BuildRouteResponse{
3✔
1551
                Route: rpcRoute,
3✔
1552
        }
3✔
1553

3✔
1554
        return routeResp, nil
3✔
1555
}
1556

1557
// SubscribeHtlcEvents creates a uni-directional stream from the server to
1558
// the client which delivers a stream of htlc events.
1559
func (s *Server) SubscribeHtlcEvents(_ *SubscribeHtlcEventsRequest,
1560
        stream Router_SubscribeHtlcEventsServer) error {
3✔
1561

3✔
1562
        htlcClient, err := s.cfg.RouterBackend.SubscribeHtlcEvents()
3✔
1563
        if err != nil {
3✔
1564
                return err
×
1565
        }
×
1566
        defer htlcClient.Cancel()
3✔
1567

3✔
1568
        // Send out an initial subscribed event so that the caller knows the
3✔
1569
        // point from which new events will be transmitted.
3✔
1570
        if err := stream.Send(&HtlcEvent{
3✔
1571
                Event: &HtlcEvent_SubscribedEvent{
3✔
1572
                        SubscribedEvent: &SubscribedEvent{},
3✔
1573
                },
3✔
1574
        }); err != nil {
3✔
1575
                return err
×
1576
        }
×
1577

1578
        for {
6✔
1579
                select {
3✔
1580
                case event := <-htlcClient.Updates():
3✔
1581
                        rpcEvent, err := rpcHtlcEvent(event)
3✔
1582
                        if err != nil {
3✔
1583
                                return err
×
1584
                        }
×
1585

1586
                        if err := stream.Send(rpcEvent); err != nil {
3✔
1587
                                return err
×
1588
                        }
×
1589

1590
                // If the stream's context is cancelled, return an error.
1591
                case <-stream.Context().Done():
3✔
1592
                        log.Debugf("htlc event stream cancelled")
3✔
1593
                        return stream.Context().Err()
3✔
1594

1595
                // If the subscribe client terminates, exit with an error.
1596
                case <-htlcClient.Quit():
×
1597
                        return errors.New("htlc event subscription terminated")
×
1598

1599
                // If the server has been signalled to shut down, exit.
1600
                case <-s.quit:
×
1601
                        return errServerShuttingDown
×
1602
                }
1603
        }
1604
}
1605

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

3✔
1621
        // Run the forward interceptor.
3✔
1622
        return newForwardInterceptor(
3✔
1623
                s.cfg.RouterBackend.InterceptableForwarder, stream,
3✔
1624
        ).run()
3✔
1625
}
1626

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

3✔
1636
        existingAliases := s.cfg.AliasMgr.ListAliases()
3✔
1637

3✔
1638
        // aliasExists checks if the new alias already exists in the alias map.
3✔
1639
        aliasExists := func(newAlias uint64,
3✔
1640
                baseScid lnwire.ShortChannelID) (bool, error) {
6✔
1641

3✔
1642
                // First check that we actually have a channel for the given
3✔
1643
                // base scid. This should succeed for any channel where the
3✔
1644
                // option-scid-alias feature bit was negotiated.
3✔
1645
                if _, ok := existingAliases[baseScid]; !ok {
3✔
1646
                        return false, fmt.Errorf("base scid %v not found",
×
1647
                                baseScid)
×
1648
                }
×
1649

1650
                for base, aliases := range existingAliases {
6✔
1651
                        for _, alias := range aliases {
6✔
1652
                                exists := alias.ToUint64() == newAlias
3✔
1653

3✔
1654
                                // Trying to add an alias that we already have
3✔
1655
                                // for another channel is wrong.
3✔
1656
                                if exists && base != baseScid {
3✔
1657
                                        return true, fmt.Errorf("%w: alias %v "+
×
1658
                                                "already exists for base scid "+
×
1659
                                                "%v", ErrAliasAlreadyExists,
×
1660
                                                alias, base)
×
1661
                                }
×
1662

1663
                                if exists {
6✔
1664
                                        return true, nil
3✔
1665
                                }
3✔
1666
                        }
1667
                }
1668

1669
                return false, nil
3✔
1670
        }
1671

1672
        for _, v := range in.AliasMaps {
6✔
1673
                baseScid := lnwire.NewShortChanIDFromInt(v.BaseScid)
3✔
1674

3✔
1675
                for _, rpcAlias := range v.Aliases {
6✔
1676
                        // If not, let's add it to the alias manager now.
3✔
1677
                        aliasScid := lnwire.NewShortChanIDFromInt(rpcAlias)
3✔
1678

3✔
1679
                        // But we only add it, if it's a valid alias, as defined
3✔
1680
                        // by the BOLT spec.
3✔
1681
                        if !aliasmgr.IsAlias(aliasScid) {
6✔
1682
                                return nil, fmt.Errorf("%w: SCID alias %v is "+
3✔
1683
                                        "not a valid alias", ErrNoValidAlias,
3✔
1684
                                        aliasScid)
3✔
1685
                        }
3✔
1686

1687
                        exists, err := aliasExists(rpcAlias, baseScid)
3✔
1688
                        if err != nil {
3✔
1689
                                return nil, err
×
1690
                        }
×
1691

1692
                        // If the alias already exists, we see that as an error.
1693
                        // This is to avoid "silent" collisions.
1694
                        if exists {
6✔
1695
                                return nil, fmt.Errorf("%w: SCID alias %v "+
3✔
1696
                                        "already exists", ErrAliasAlreadyExists,
3✔
1697
                                        rpcAlias)
3✔
1698
                        }
3✔
1699

1700
                        err = s.cfg.AliasMgr.AddLocalAlias(
3✔
1701
                                aliasScid, baseScid, false, true,
3✔
1702
                        )
3✔
1703
                        if err != nil {
3✔
1704
                                return nil, fmt.Errorf("error adding scid "+
×
1705
                                        "alias, base_scid=%v, alias_scid=%v: "+
×
1706
                                        "%w", baseScid, aliasScid, err)
×
1707
                        }
×
1708
                }
1709
        }
1710

1711
        return &AddAliasesResponse{
3✔
1712
                AliasMaps: lnrpc.MarshalAliasMap(s.cfg.AliasMgr.ListAliases()),
3✔
1713
        }, nil
3✔
1714
}
1715

1716
// XDeleteLocalChanAliases is an experimental API that deletes a set of alias
1717
// mappings. The final total set of aliases in the manager after the delete
1718
// operation is returned. The deletion will not be communicated to the channel
1719
// peer via any message.
1720
func (s *Server) XDeleteLocalChanAliases(_ context.Context,
1721
        in *DeleteAliasesRequest) (*DeleteAliasesResponse,
1722
        error) {
3✔
1723

3✔
1724
        for _, v := range in.AliasMaps {
6✔
1725
                baseScid := lnwire.NewShortChanIDFromInt(v.BaseScid)
3✔
1726

3✔
1727
                for _, alias := range v.Aliases {
6✔
1728
                        aliasScid := lnwire.NewShortChanIDFromInt(alias)
3✔
1729

3✔
1730
                        err := s.cfg.AliasMgr.DeleteLocalAlias(
3✔
1731
                                aliasScid, baseScid,
3✔
1732
                        )
3✔
1733
                        if err != nil {
3✔
1734
                                return nil, fmt.Errorf("error deleting scid "+
×
1735
                                        "alias, base_scid=%v, alias_scid=%v: "+
×
1736
                                        "%w", baseScid, aliasScid, err)
×
1737
                        }
×
1738
                }
1739
        }
1740

1741
        return &DeleteAliasesResponse{
3✔
1742
                AliasMaps: lnrpc.MarshalAliasMap(s.cfg.AliasMgr.ListAliases()),
3✔
1743
        }, nil
3✔
1744
}
1745

1746
func extractOutPoint(req *UpdateChanStatusRequest) (*wire.OutPoint, error) {
3✔
1747
        chanPoint := req.GetChanPoint()
3✔
1748
        txid, err := lnrpc.GetChanPointFundingTxid(chanPoint)
3✔
1749
        if err != nil {
3✔
1750
                return nil, err
×
1751
        }
×
1752
        index := chanPoint.OutputIndex
3✔
1753
        return wire.NewOutPoint(txid, index), nil
3✔
1754
}
1755

1756
// UpdateChanStatus allows channel state to be set manually.
1757
func (s *Server) UpdateChanStatus(_ context.Context,
1758
        req *UpdateChanStatusRequest) (*UpdateChanStatusResponse, error) {
3✔
1759

3✔
1760
        outPoint, err := extractOutPoint(req)
3✔
1761
        if err != nil {
3✔
1762
                return nil, err
×
1763
        }
×
1764

1765
        action := req.GetAction()
3✔
1766

3✔
1767
        log.Debugf("UpdateChanStatus called for channel(%v) with "+
3✔
1768
                "action %v", outPoint, action)
3✔
1769

3✔
1770
        switch action {
3✔
1771
        case ChanStatusAction_ENABLE:
3✔
1772
                err = s.cfg.RouterBackend.SetChannelEnabled(*outPoint)
3✔
1773
        case ChanStatusAction_DISABLE:
3✔
1774
                err = s.cfg.RouterBackend.SetChannelDisabled(*outPoint)
3✔
1775
        case ChanStatusAction_AUTO:
3✔
1776
                err = s.cfg.RouterBackend.SetChannelAuto(*outPoint)
3✔
1777
        default:
×
1778
                err = fmt.Errorf("unrecognized ChannelStatusAction %v", action)
×
1779
        }
1780

1781
        if err != nil {
3✔
1782
                return nil, err
×
1783
        }
×
1784
        return &UpdateChanStatusResponse{}, nil
3✔
1785
}
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