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

lightningnetwork / lnd / 15205630088

23 May 2025 08:14AM UTC coverage: 57.45% (-11.5%) from 68.996%
15205630088

Pull #9784

github

web-flow
Merge f8b9f36a3 into c52a6ddeb
Pull Request #9784: [wip] lnwallet+walletrpc: add SubmitPackage and related RPC call

47 of 96 new or added lines in 5 files covered. (48.96%)

30087 existing lines in 459 files now uncovered.

95586 of 166380 relevant lines covered (57.45%)

0.61 hits per line

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

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

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

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

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

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

268
        return nil
1✔
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 {
1✔
275
        if atomic.AddInt32(&s.shutdown, 1) != 1 {
1✔
276
                return nil
×
277
        }
×
278

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

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

1✔
304
        return nil
1✔
305
}
1✔
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 {
1✔
314

1✔
315
        // We make sure that we register it with the main REST server to ensure
1✔
316
        // all our methods are routed properly.
1✔
317
        err := RegisterRouterHandlerFromEndpoint(ctx, mux, dest, opts)
1✔
318
        if err != nil {
1✔
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 " +
1✔
325
                "root REST server")
1✔
326
        return nil
1✔
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) {
1✔
338

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

344
        r.RouterServer = subServer
1✔
345
        return subServer, macPermissions, nil
1✔
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 {
1✔
355

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

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

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

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

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

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

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

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

434
        case isProbeDestination:
1✔
435
                switch {
1✔
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:
1✔
443
                        return s.probeDestination(req.Dest, req.AmtSat)
1✔
444
                }
445

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

1✔
460
        destNode, err := route.NewVertexFromBytes(dest)
1✔
461
        if err != nil {
1✔
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))
1✔
468

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

486
        route, _, err := s.cfg.Router.FindRoute(routeReq)
1✔
487
        if err != nil {
2✔
488
                return nil, err
1✔
489
        }
1✔
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)
1✔
496

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

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

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

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

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

555
        hints := payReq.RouteHints
1✔
556

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

565
        // If the heuristic indicates an LSP we modify the route hints to allow
566
        // probing the LSP.
567
        lspAdjustedRouteHints, lspHint, err := prepareLspRouteHints(
1✔
568
                hints, *payReq.MilliSat,
1✔
569
        )
1✔
570
        if err != nil {
1✔
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()
1✔
577
        if len(lspAdjustedRouteHints) > 0 {
1✔
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)
1✔
596
        if err != nil {
1✔
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)
1✔
603

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

1✔
609
        // Dispatch the payment probe with adjusted fee amount.
1✔
610
        resp, err := s.sendProbePayment(ctx, probeRequest)
1✔
611
        if err != nil {
1✔
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
1✔
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)
1✔
624

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

1✔
629
        return resp, nil
1✔
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 {
1✔
639

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

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

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

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

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

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

670
                idMatchesRefNode := bytes.Equal(
1✔
671
                        lastHop.NodeID.SerializeCompressed(),
1✔
672
                        destHopHint.NodeID.SerializeCompressed(),
1✔
673
                )
1✔
674
                if !idMatchesRefNode {
2✔
675
                        return false
1✔
676
                }
1✔
677
        }
678

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

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

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

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

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

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

718
        return adjustedHints, &refHint, nil
1✔
719
}
720

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

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

739
        return maxBaseFee, maxFeePpm
1✔
740
}
741

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

752
        return maxCltvDelta
1✔
753
}
754

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

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

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

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

775
        return nil
1✔
776
}
777

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

889
        return lastRoute.TotalFeesMsat, int64(lastRoute.TotalTimeLock), nil
1✔
890
}
891

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

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

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

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

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

916
        var attempt *channeldb.HTLCAttempt
1✔
917

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

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

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

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

957
        return nil, err
×
958
}
959

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

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

970
        return &ResetMissionControlResponse{}, nil
1✔
971
}
972

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

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

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

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

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

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

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

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

1027
        return resp, nil
1✔
1028
}
1029

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
1140
        return &response, nil
×
1141
}
1142

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

1✔
1152
        if !data.FailTime.IsZero() {
2✔
1153
                rpcData.FailTime = data.FailTime.Unix()
1✔
1154
        }
1✔
1155

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

1160
        return &rpcData
1✔
1161
}
1162

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

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

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

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

1185
                snapshot.Pairs[i] = *pairSnapshot
1✔
1186
        }
1187

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

1195
        return &XImportMissionControlResponse{}, nil
1✔
1196
}
1197

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

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

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

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

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

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

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

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

1245
        pair := routing.NewDirectedNodePair(from, to)
1✔
1246

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

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

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

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

1272
        var (
1✔
1273
                timeSet   = timestamp != 0
1✔
1274
                amountSet = amt != 0
1✔
1275
        )
1✔
1276

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1365
        return sub, nil
1✔
1366
}
1367

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

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

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

1✔
1384
                return nil
1✔
1385

1386
        default:
×
1387
        }
1388

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

×
1393
        return err
×
1394
}
1395

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

1✔
1400
        log.Debug("TrackPayments called")
1✔
1401

1✔
1402
        router := s.cfg.RouterBackend
1✔
1403

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

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

1✔
1416
        if errors.Is(err, context.Canceled) {
2✔
1417
                log.Debugf("TrackPayments payment stream canceled.")
1✔
1418
        }
1✔
1419

1420
        return err
1✔
1421
}
1422

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

1✔
1428
        defer subscription.Close()
1✔
1429

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

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

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

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

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

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

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

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

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

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

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

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

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

1✔
1510
                payAddr = fn.Some(backingPayAddr)
1✔
1511
        }
1✔
1512

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

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

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

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

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

1549
        routeResp := &BuildRouteResponse{
1✔
1550
                Route: rpcRoute,
1✔
1551
        }
1✔
1552

1✔
1553
        return routeResp, nil
1✔
1554
}
1555

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

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

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

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

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

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

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

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

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

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

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

1✔
1635
        existingAliases := s.cfg.AliasMgr.ListAliases()
1✔
1636

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

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

1649
                for base, aliases := range existingAliases {
2✔
1650
                        for _, alias := range aliases {
2✔
1651
                                exists := alias.ToUint64() == newAlias
1✔
1652

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

1662
                                if exists {
2✔
1663
                                        return true, nil
1✔
1664
                                }
1✔
1665
                        }
1666
                }
1667

1668
                return false, nil
1✔
1669
        }
1670

1671
        for _, v := range in.AliasMaps {
2✔
1672
                baseScid := lnwire.NewShortChanIDFromInt(v.BaseScid)
1✔
1673

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

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

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

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

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

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

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

1✔
1723
        for _, v := range in.AliasMaps {
2✔
1724
                baseScid := lnwire.NewShortChanIDFromInt(v.BaseScid)
1✔
1725

1✔
1726
                for _, alias := range v.Aliases {
2✔
1727
                        aliasScid := lnwire.NewShortChanIDFromInt(alias)
1✔
1728

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

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

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

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

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

1764
        action := req.GetAction()
1✔
1765

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

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

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