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

lightningnetwork / lnd / 16918135633

12 Aug 2025 06:56PM UTC coverage: 56.955% (-9.9%) from 66.9%
16918135633

push

github

web-flow
Merge pull request #9871 from GeorgeTsagk/htlc-noop-add

Add `NoopAdd` HTLCs

48 of 147 new or added lines in 3 files covered. (32.65%)

29154 existing lines in 462 files now uncovered.

98265 of 172532 relevant lines covered (56.95%)

1.19 hits per line

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2✔
497
        return &RouteFeeResponse{
2✔
498
                RoutingFeeMsat: int64(route.TotalFees()),
2✔
499
                TimeLockDelay:  int64(timeLockDelay),
2✔
500
                FailureReason:  lnrpc.PaymentFailureReason_FAILURE_REASON_NONE,
2✔
501
        }, nil
2✔
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
//
513
// NOTE: Be aware that because of the special heuristic that is applied to
514
// identify LSPs, the probe payment might use a different node id as the
515
// final destination (the assumed LSP node id).
516
func (s *Server) probePaymentRequest(ctx context.Context, paymentRequest string,
517
        timeout uint32) (*RouteFeeResponse, error) {
2✔
518

2✔
519
        payReq, err := zpay32.Decode(
2✔
520
                paymentRequest, s.cfg.RouterBackend.ActiveNetParams,
2✔
521
        )
2✔
522
        if err != nil {
2✔
523
                return nil, err
×
524
        }
×
525

526
        if payReq.MilliSat == nil || *payReq.MilliSat <= 0 {
2✔
527
                return nil, errors.New("payment request amount must be " +
×
528
                        "greater than 0")
×
529
        }
×
530

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

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

2✔
553
        // If the payment addresses is specified, then we'll also populate that
2✔
554
        // now as well.
2✔
555
        payReq.PaymentAddr.WhenSome(func(addr [32]byte) {
4✔
556
                copy(probeRequest.PaymentAddr, addr[:])
2✔
557
        })
2✔
558

559
        hints := payReq.RouteHints
2✔
560

2✔
561
        // If the hints don't indicate an LSP then chances are that our probe
2✔
562
        // payment won't be blocked along the route to the destination. We send
2✔
563
        // a probe payment with unmodified route hints.
2✔
564
        if !isLSP(hints, s.cfg.RouterBackend.FetchChannelEndpoints) {
4✔
565
                log.Infof("No LSP detected, probing destination %x",
2✔
566
                        probeRequest.Dest)
2✔
567

2✔
568
                probeRequest.RouteHints = invoicesrpc.CreateRPCRouteHints(hints)
2✔
569
                return s.sendProbePayment(ctx, probeRequest)
2✔
570
        }
2✔
571

572
        // If the heuristic indicates an LSP we modify the route hints to allow
573
        // probing the LSP.
574
        lspAdjustedRouteHints, lspHint, err := prepareLspRouteHints(
2✔
575
                hints, *payReq.MilliSat,
2✔
576
        )
2✔
577
        if err != nil {
2✔
578
                return nil, err
×
579
        }
×
580

581
        // Set the destination to the LSP node ID.
582
        lspDest := lspHint.NodeID.SerializeCompressed()
2✔
583
        probeRequest.Dest = lspDest
2✔
584

2✔
585
        log.Infof("LSP detected, probing LSP with destination: %x", lspDest)
2✔
586

2✔
587
        // The adjusted route hints serve the payment probe to find the last
2✔
588
        // public hop to the LSP on the route.
2✔
589
        if len(lspAdjustedRouteHints) > 0 {
2✔
590
                probeRequest.RouteHints = invoicesrpc.CreateRPCRouteHints(
×
591
                        lspAdjustedRouteHints,
×
592
                )
×
593
        }
×
594

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

612
        // Add the last hop's fee to the requested payment amount that we want
613
        // to get an estimate for.
614
        probeRequest.AmtMsat += int64(hopFee)
2✔
615

2✔
616
        // Use the hop hint's cltv delta as the payment request's final cltv
2✔
617
        // delta. The actual final cltv delta of the invoice will be added to
2✔
618
        // the payment probe's cltv delta.
2✔
619
        probeRequest.FinalCltvDelta = int32(lspHint.CLTVExpiryDelta)
2✔
620

2✔
621
        // Dispatch the payment probe with adjusted fee amount.
2✔
622
        resp, err := s.sendProbePayment(ctx, probeRequest)
2✔
623
        if err != nil {
2✔
624
                return nil, fmt.Errorf("failed to send probe payment to "+
×
625
                        "LSP with destination %x: %w", lspDest, err)
×
626
        }
×
627

628
        // If the payment probe failed we only return the failure reason and
629
        // leave the probe result params unaltered.
630
        if resp.FailureReason != lnrpc.PaymentFailureReason_FAILURE_REASON_NONE { //nolint:ll
2✔
631
                return resp, nil
×
632
        }
×
633

634
        // The probe succeeded, so we can add the last hop's fee to fee the
635
        // payment probe returned.
636
        resp.RoutingFeeMsat += int64(hopFee)
2✔
637

2✔
638
        // Add the final cltv delta of the invoice to the payment probe's total
2✔
639
        // cltv delta. This is the cltv delta for the hop behind the LSP.
2✔
640
        resp.TimeLockDelay += int64(payReq.MinFinalCLTVExpiry())
2✔
641

2✔
642
        return resp, nil
2✔
643
}
644

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

2✔
653
        if len(routeHints) == 0 || len(routeHints[0]) == 0 {
4✔
654
                return false
2✔
655
        }
2✔
656

657
        destHopHint := routeHints[0][len(routeHints[0])-1]
2✔
658

2✔
659
        // If the destination hop hint of the first route hint contains a public
2✔
660
        // channel we can send a probe to it directly, hence we don't signal an
2✔
661
        // LSP.
2✔
662
        _, _, err := fetchChannelEndpoints(destHopHint.ChannelID)
2✔
663
        if err == nil {
2✔
UNCOV
664
                return false
×
UNCOV
665
        }
×
666

667
        for i := 1; i < len(routeHints); i++ {
4✔
668
                // Skip empty route hints.
2✔
669
                if len(routeHints[i]) == 0 {
2✔
670
                        continue
×
671
                }
672

673
                lastHop := routeHints[i][len(routeHints[i])-1]
2✔
674

2✔
675
                // If the last hop hint of any route hint contains a public
2✔
676
                // channel we can send a probe to it directly, hence we don't
2✔
677
                // signal an LSP.
2✔
678
                _, _, err = fetchChannelEndpoints(lastHop.ChannelID)
2✔
679
                if err == nil {
2✔
UNCOV
680
                        return false
×
UNCOV
681
                }
×
682

683
                matchesDestNode := bytes.Equal(
2✔
684
                        lastHop.NodeID.SerializeCompressed(),
2✔
685
                        destHopHint.NodeID.SerializeCompressed(),
2✔
686
                )
2✔
687
                if !matchesDestNode {
4✔
688
                        return false
2✔
689
                }
2✔
690
        }
691

692
        // We ensured that the destination hop hint doesn't contain a public
693
        // channel, and that all destination hop hints of all route hints match,
694
        // so we signal an LSP.
695
        return true
2✔
696
}
697

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

2✔
705
        if len(routeHints) == 0 {
2✔
706
                return nil, nil, fmt.Errorf("no route hints provided")
×
707
        }
×
708

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

2✔
717
        // We construct a modified list of route hints that allows the caller to
2✔
718
        // probe the LSP.
2✔
719
        adjustedHints := make([][]zpay32.HopHint, 0, len(routeHints))
2✔
720

2✔
721
        // Strip off the LSP hop hint from all route hints.
2✔
722
        for i := 0; i < len(routeHints); i++ {
4✔
723
                hint := routeHints[i]
2✔
724
                if len(hint) > 1 {
2✔
UNCOV
725
                        adjustedHints = append(
×
UNCOV
726
                                adjustedHints, hint[:len(hint)-1],
×
UNCOV
727
                        )
×
UNCOV
728
                }
×
729
        }
730

731
        return adjustedHints, &refHint, nil
2✔
732
}
733

734
// maxLspFee returns base fee and fee rate amongst all LSP route hints that
735
// results in the overall highest fee for the given amount.
736
func maxLspFee(routeHints [][]zpay32.HopHint, amt lnwire.MilliSatoshi) (uint32,
737
        uint32) {
2✔
738

2✔
739
        var maxFeePpm uint32
2✔
740
        var maxBaseFee uint32
2✔
741
        var maxTotalFee lnwire.MilliSatoshi
2✔
742
        for _, rh := range routeHints {
4✔
743
                lastHop := rh[len(rh)-1]
2✔
744
                lastHopFee := lastHop.HopFee(amt)
2✔
745
                if lastHopFee > maxTotalFee {
4✔
746
                        maxTotalFee = lastHopFee
2✔
747
                        maxBaseFee = lastHop.FeeBaseMSat
2✔
748
                        maxFeePpm = lastHop.FeeProportionalMillionths
2✔
749
                }
2✔
750
        }
751

752
        return maxBaseFee, maxFeePpm
2✔
753
}
754

755
// maxLspCltvDelta returns the maximum cltv delta amongst all LSP route hints.
756
func maxLspCltvDelta(routeHints [][]zpay32.HopHint) uint16 {
2✔
757
        var maxCltvDelta uint16
2✔
758
        for _, rh := range routeHints {
4✔
759
                rhLastHop := rh[len(rh)-1]
2✔
760
                if rhLastHop.CLTVExpiryDelta > maxCltvDelta {
4✔
761
                        maxCltvDelta = rhLastHop.CLTVExpiryDelta
2✔
762
                }
2✔
763
        }
764

765
        return maxCltvDelta
2✔
766
}
767

768
// probePaymentStream is a custom implementation of the grpc.ServerStream
769
// interface. It is used to send payment status updates to the caller on the
770
// stream channel.
771
type probePaymentStream struct {
772
        Router_SendPaymentV2Server
773

774
        stream chan *lnrpc.Payment
775
        ctx    context.Context //nolint:containedctx
776
}
777

778
// Send sends a payment status update to a payment stream that the caller can
779
// evaluate.
780
func (p *probePaymentStream) Send(response *lnrpc.Payment) error {
2✔
781
        select {
2✔
782
        case p.stream <- response:
2✔
783

784
        case <-p.ctx.Done():
×
785
                return p.ctx.Err()
×
786
        }
787

788
        return nil
2✔
789
}
790

791
// Context returns the context of the stream.
792
func (p *probePaymentStream) Context() context.Context {
2✔
793
        return p.ctx
2✔
794
}
2✔
795

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

2✔
804
        // We'll launch a goroutine to send the payment probes.
2✔
805
        errChan := make(chan error, 1)
2✔
806
        defer close(errChan)
2✔
807

2✔
808
        paymentStream := &probePaymentStream{
2✔
809
                stream: make(chan *lnrpc.Payment),
2✔
810
                ctx:    ctx,
2✔
811
        }
2✔
812
        go func() {
4✔
813
                err := s.SendPaymentV2(req, paymentStream)
2✔
814
                if err != nil {
2✔
815
                        select {
×
816
                        case errChan <- err:
×
817

818
                        case <-paymentStream.ctx.Done():
×
819
                                return
×
820
                        }
821
                }
822
        }()
823

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

838
                        case lnrpc.Payment_FAILED:
2✔
839
                                // Incorrect payment details point to a
2✔
840
                                // successful probe.
2✔
841
                                //nolint:ll
2✔
842
                                if payment.FailureReason == lnrpc.PaymentFailureReason_FAILURE_REASON_INCORRECT_PAYMENT_DETAILS {
4✔
843
                                        return paymentDetails(payment)
2✔
844
                                }
2✔
845

846
                                return &RouteFeeResponse{
2✔
847
                                        RoutingFeeMsat: 0,
2✔
848
                                        TimeLockDelay:  0,
2✔
849
                                        FailureReason:  payment.FailureReason,
2✔
850
                                }, nil
2✔
851

852
                        default:
×
853
                                return nil, errors.New("unexpected payment " +
×
854
                                        "status")
×
855
                        }
856

857
                case err := <-errChan:
×
858
                        return nil, err
×
859

860
                case <-s.quit:
×
861
                        return nil, errServerShuttingDown
×
862
                }
863
        }
864
}
865

866
func paymentDetails(payment *lnrpc.Payment) (*RouteFeeResponse, error) {
2✔
867
        fee, timeLock, err := timelockAndFee(payment)
2✔
868
        if errors.Is(err, errUnexpectedFailureSource) {
2✔
869
                return nil, err
×
870
        }
×
871

872
        return &RouteFeeResponse{
2✔
873
                RoutingFeeMsat: fee,
2✔
874
                TimeLockDelay:  timeLock,
2✔
875
                FailureReason:  lnrpc.PaymentFailureReason_FAILURE_REASON_NONE,
2✔
876
        }, nil
2✔
877
}
878

879
// timelockAndFee returns the fee and total time lock of the last payment
880
// attempt.
881
func timelockAndFee(p *lnrpc.Payment) (int64, int64, error) {
2✔
882
        if len(p.Htlcs) == 0 {
2✔
883
                return 0, 0, nil
×
884
        }
×
885

886
        lastAttempt := p.Htlcs[len(p.Htlcs)-1]
2✔
887
        if lastAttempt == nil {
2✔
888
                return 0, 0, errMissingPaymentAttempt
×
889
        }
×
890

891
        lastRoute := lastAttempt.Route
2✔
892
        if lastRoute == nil {
2✔
893
                return 0, 0, errMissingRoute
×
894
        }
×
895

896
        hopFailureIndex := lastAttempt.Failure.FailureSourceIndex
2✔
897
        finalHopIndex := uint32(len(lastRoute.Hops))
2✔
898
        if hopFailureIndex != finalHopIndex {
2✔
899
                return 0, 0, errUnexpectedFailureSource
×
900
        }
×
901

902
        return lastRoute.TotalFeesMsat, int64(lastRoute.TotalTimeLock), nil
2✔
903
}
904

905
// SendToRouteV2 sends a payment through a predefined route. The response of
906
// this call contains structured error information.
907
func (s *Server) SendToRouteV2(ctx context.Context,
908
        req *SendToRouteRequest) (*lnrpc.HTLCAttempt, error) {
2✔
909

2✔
910
        if req.Route == nil {
2✔
911
                return nil, fmt.Errorf("unable to send, no routes provided")
×
912
        }
×
913

914
        route, err := s.cfg.RouterBackend.UnmarshallRoute(req.Route)
2✔
915
        if err != nil {
2✔
916
                return nil, err
×
917
        }
×
918

919
        hash, err := lntypes.MakeHash(req.PaymentHash)
2✔
920
        if err != nil {
2✔
921
                return nil, err
×
922
        }
×
923

924
        firstHopRecords := lnwire.CustomRecords(req.FirstHopCustomRecords)
2✔
925
        if err := firstHopRecords.Validate(); err != nil {
2✔
926
                return nil, err
×
927
        }
×
928

929
        var attempt *channeldb.HTLCAttempt
2✔
930

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

956
        // Transform user errors to grpc code.
957
        switch {
×
958
        case errors.Is(err, channeldb.ErrPaymentExists):
×
959
                fallthrough
×
960

961
        case errors.Is(err, channeldb.ErrPaymentInFlight):
×
962
                fallthrough
×
963

964
        case errors.Is(err, channeldb.ErrAlreadyPaid):
×
965
                return nil, status.Error(
×
966
                        codes.AlreadyExists, err.Error(),
×
967
                )
×
968
        }
969

970
        return nil, err
×
971
}
972

973
// ResetMissionControl clears all mission control state and starts with a clean
974
// slate.
975
func (s *Server) ResetMissionControl(ctx context.Context,
976
        req *ResetMissionControlRequest) (*ResetMissionControlResponse, error) {
2✔
977

2✔
978
        err := s.cfg.RouterBackend.MissionControl.ResetHistory()
2✔
979
        if err != nil {
2✔
980
                return nil, err
×
981
        }
×
982

983
        return &ResetMissionControlResponse{}, nil
2✔
984
}
985

986
// GetMissionControlConfig returns our current mission control config.
987
func (s *Server) GetMissionControlConfig(ctx context.Context,
988
        req *GetMissionControlConfigRequest) (*GetMissionControlConfigResponse,
989
        error) {
2✔
990

2✔
991
        // Query the current mission control config.
2✔
992
        cfg := s.cfg.RouterBackend.MissionControl.GetConfig()
2✔
993
        resp := &GetMissionControlConfigResponse{
2✔
994
                Config: &MissionControlConfig{
2✔
995
                        MaximumPaymentResults: uint32(cfg.MaxMcHistory),
2✔
996
                        MinimumFailureRelaxInterval: uint64(
2✔
997
                                cfg.MinFailureRelaxInterval.Seconds(),
2✔
998
                        ),
2✔
999
                },
2✔
1000
        }
2✔
1001

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

2✔
1013
                // Populate deprecated fields.
2✔
1014
                resp.Config.HalfLifeSeconds = uint64(
2✔
1015
                        v.PenaltyHalfLife.Seconds(),
2✔
1016
                )
2✔
1017
                resp.Config.HopProbability = float32(v.AprioriHopProbability)
2✔
1018
                resp.Config.Weight = float32(v.AprioriWeight)
2✔
1019

2✔
1020
                resp.Config.EstimatorConfig = &MissionControlConfig_Apriori{
2✔
1021
                        Apriori: &aCfg,
2✔
1022
                }
2✔
1023

1024
        case routing.BimodalConfig:
2✔
1025
                resp.Config.Model = MissionControlConfig_BIMODAL
2✔
1026
                bCfg := BimodalParameters{
2✔
1027
                        NodeWeight: v.BimodalNodeWeight,
2✔
1028
                        ScaleMsat:  uint64(v.BimodalScaleMsat),
2✔
1029
                        DecayTime:  uint64(v.BimodalDecayTime.Seconds()),
2✔
1030
                }
2✔
1031

2✔
1032
                resp.Config.EstimatorConfig = &MissionControlConfig_Bimodal{
2✔
1033
                        Bimodal: &bCfg,
2✔
1034
                }
2✔
1035

1036
        default:
×
1037
                return nil, fmt.Errorf("unknown estimator config type %T", v)
×
1038
        }
1039

1040
        return resp, nil
2✔
1041
}
1042

1043
// SetMissionControlConfig sets parameters in the mission control config.
1044
func (s *Server) SetMissionControlConfig(ctx context.Context,
1045
        req *SetMissionControlConfigRequest) (*SetMissionControlConfigResponse,
1046
        error) {
2✔
1047

2✔
1048
        mcCfg := &routing.MissionControlConfig{
2✔
1049
                MaxMcHistory: int(req.Config.MaximumPaymentResults),
2✔
1050
                MinFailureRelaxInterval: time.Duration(
2✔
1051
                        req.Config.MinimumFailureRelaxInterval,
2✔
1052
                ) * time.Second,
2✔
1053
        }
2✔
1054

2✔
1055
        switch req.Config.Model {
2✔
1056
        case MissionControlConfig_APRIORI:
2✔
1057
                var aprioriConfig routing.AprioriConfig
2✔
1058

2✔
1059
                // Determine the apriori config with backward compatibility
2✔
1060
                // should the api use deprecated fields.
2✔
1061
                switch v := req.Config.EstimatorConfig.(type) {
2✔
1062
                case *MissionControlConfig_Bimodal:
2✔
1063
                        return nil, fmt.Errorf("bimodal config " +
2✔
1064
                                "provided, but apriori model requested")
2✔
1065

1066
                case *MissionControlConfig_Apriori:
2✔
1067
                        aprioriConfig = routing.AprioriConfig{
2✔
1068
                                PenaltyHalfLife: time.Duration(
2✔
1069
                                        v.Apriori.HalfLifeSeconds,
2✔
1070
                                ) * time.Second,
2✔
1071
                                AprioriHopProbability: v.Apriori.HopProbability,
2✔
1072
                                AprioriWeight:         v.Apriori.Weight,
2✔
1073
                                CapacityFraction: v.Apriori.
2✔
1074
                                        CapacityFraction,
2✔
1075
                        }
2✔
1076

1077
                default:
2✔
1078
                        aprioriConfig = routing.AprioriConfig{
2✔
1079
                                PenaltyHalfLife: time.Duration(
2✔
1080
                                        int64(req.Config.HalfLifeSeconds),
2✔
1081
                                ) * time.Second,
2✔
1082
                                AprioriHopProbability: float64(
2✔
1083
                                        req.Config.HopProbability,
2✔
1084
                                ),
2✔
1085
                                AprioriWeight:    float64(req.Config.Weight),
2✔
1086
                                CapacityFraction: routing.DefaultCapacityFraction, //nolint:ll
2✔
1087
                        }
2✔
1088
                }
1089

1090
                estimator, err := routing.NewAprioriEstimator(aprioriConfig)
2✔
1091
                if err != nil {
2✔
1092
                        return nil, err
×
1093
                }
×
1094
                mcCfg.Estimator = estimator
2✔
1095

1096
        case MissionControlConfig_BIMODAL:
2✔
1097
                cfg, ok := req.Config.
2✔
1098
                        EstimatorConfig.(*MissionControlConfig_Bimodal)
2✔
1099
                if !ok {
2✔
1100
                        return nil, fmt.Errorf("bimodal estimator requested " +
×
1101
                                "but corresponding config not set")
×
1102
                }
×
1103
                bCfg := cfg.Bimodal
2✔
1104

2✔
1105
                bimodalConfig := routing.BimodalConfig{
2✔
1106
                        BimodalDecayTime: time.Duration(
2✔
1107
                                bCfg.DecayTime,
2✔
1108
                        ) * time.Second,
2✔
1109
                        BimodalScaleMsat:  lnwire.MilliSatoshi(bCfg.ScaleMsat),
2✔
1110
                        BimodalNodeWeight: bCfg.NodeWeight,
2✔
1111
                }
2✔
1112

2✔
1113
                estimator, err := routing.NewBimodalEstimator(bimodalConfig)
2✔
1114
                if err != nil {
2✔
1115
                        return nil, err
×
1116
                }
×
1117
                mcCfg.Estimator = estimator
2✔
1118

1119
        default:
×
1120
                return nil, fmt.Errorf("unknown estimator type %v",
×
1121
                        req.Config.Model)
×
1122
        }
1123

1124
        return &SetMissionControlConfigResponse{},
2✔
1125
                s.cfg.RouterBackend.MissionControl.SetConfig(mcCfg)
2✔
1126
}
1127

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

×
1133
        snapshot := s.cfg.RouterBackend.MissionControl.GetHistorySnapshot()
×
1134

×
1135
        rpcPairs := make([]*PairHistory, 0, len(snapshot.Pairs))
×
1136
        for _, p := range snapshot.Pairs {
×
1137
                // Prevent binding to loop variable.
×
1138
                pair := p
×
1139

×
1140
                rpcPair := PairHistory{
×
1141
                        NodeFrom: pair.Pair.From[:],
×
1142
                        NodeTo:   pair.Pair.To[:],
×
1143
                        History:  toRPCPairData(&pair.TimedPairResult),
×
1144
                }
×
1145

×
1146
                rpcPairs = append(rpcPairs, &rpcPair)
×
1147
        }
×
1148

1149
        response := QueryMissionControlResponse{
×
1150
                Pairs: rpcPairs,
×
1151
        }
×
1152

×
1153
        return &response, nil
×
1154
}
1155

1156
// toRPCPairData marshalls mission control pair data to the rpc struct.
1157
func toRPCPairData(data *routing.TimedPairResult) *PairData {
2✔
1158
        rpcData := PairData{
2✔
1159
                FailAmtSat:     int64(data.FailAmt.ToSatoshis()),
2✔
1160
                FailAmtMsat:    int64(data.FailAmt),
2✔
1161
                SuccessAmtSat:  int64(data.SuccessAmt.ToSatoshis()),
2✔
1162
                SuccessAmtMsat: int64(data.SuccessAmt),
2✔
1163
        }
2✔
1164

2✔
1165
        if !data.FailTime.IsZero() {
4✔
1166
                rpcData.FailTime = data.FailTime.Unix()
2✔
1167
        }
2✔
1168

1169
        if !data.SuccessTime.IsZero() {
2✔
1170
                rpcData.SuccessTime = data.SuccessTime.Unix()
×
1171
        }
×
1172

1173
        return &rpcData
2✔
1174
}
1175

1176
// XImportMissionControl imports the state provided to our internal mission
1177
// control. Only entries that are fresher than our existing state will be used.
1178
func (s *Server) XImportMissionControl(_ context.Context,
1179
        req *XImportMissionControlRequest) (*XImportMissionControlResponse,
1180
        error) {
2✔
1181

2✔
1182
        if len(req.Pairs) == 0 {
2✔
1183
                return nil, errors.New("at least one pair required for import")
×
1184
        }
×
1185

1186
        snapshot := &routing.MissionControlSnapshot{
2✔
1187
                Pairs: make(
2✔
1188
                        []routing.MissionControlPairSnapshot, len(req.Pairs),
2✔
1189
                ),
2✔
1190
        }
2✔
1191

2✔
1192
        for i, pairResult := range req.Pairs {
4✔
1193
                pairSnapshot, err := toPairSnapshot(pairResult)
2✔
1194
                if err != nil {
4✔
1195
                        return nil, err
2✔
1196
                }
2✔
1197

1198
                snapshot.Pairs[i] = *pairSnapshot
2✔
1199
        }
1200

1201
        err := s.cfg.RouterBackend.MissionControl.ImportHistory(
2✔
1202
                snapshot, req.Force,
2✔
1203
        )
2✔
1204
        if err != nil {
2✔
1205
                return nil, err
×
1206
        }
×
1207

1208
        return &XImportMissionControlResponse{}, nil
2✔
1209
}
1210

1211
func toPairSnapshot(pairResult *PairHistory) (*routing.MissionControlPairSnapshot,
1212
        error) {
2✔
1213

2✔
1214
        from, err := route.NewVertexFromBytes(pairResult.NodeFrom)
2✔
1215
        if err != nil {
2✔
1216
                return nil, err
×
1217
        }
×
1218

1219
        to, err := route.NewVertexFromBytes(pairResult.NodeTo)
2✔
1220
        if err != nil {
2✔
1221
                return nil, err
×
1222
        }
×
1223

1224
        pairPrefix := fmt.Sprintf("pair: %v -> %v:", from, to)
2✔
1225

2✔
1226
        if from == to {
2✔
1227
                return nil, fmt.Errorf("%v source and destination node must "+
×
1228
                        "differ", pairPrefix)
×
1229
        }
×
1230

1231
        failAmt, failTime, err := getPair(
2✔
1232
                lnwire.MilliSatoshi(pairResult.History.FailAmtMsat),
2✔
1233
                btcutil.Amount(pairResult.History.FailAmtSat),
2✔
1234
                pairResult.History.FailTime,
2✔
1235
                true,
2✔
1236
        )
2✔
1237
        if err != nil {
4✔
1238
                return nil, fmt.Errorf("%v invalid failure: %w", pairPrefix,
2✔
1239
                        err)
2✔
1240
        }
2✔
1241

1242
        successAmt, successTime, err := getPair(
2✔
1243
                lnwire.MilliSatoshi(pairResult.History.SuccessAmtMsat),
2✔
1244
                btcutil.Amount(pairResult.History.SuccessAmtSat),
2✔
1245
                pairResult.History.SuccessTime,
2✔
1246
                false,
2✔
1247
        )
2✔
1248
        if err != nil {
2✔
1249
                return nil, fmt.Errorf("%v invalid success: %w", pairPrefix,
×
1250
                        err)
×
1251
        }
×
1252

1253
        if successAmt == 0 && failAmt == 0 {
2✔
1254
                return nil, fmt.Errorf("%v: either success or failure result "+
×
1255
                        "required", pairPrefix)
×
1256
        }
×
1257

1258
        pair := routing.NewDirectedNodePair(from, to)
2✔
1259

2✔
1260
        result := &routing.TimedPairResult{
2✔
1261
                FailAmt:     failAmt,
2✔
1262
                FailTime:    failTime,
2✔
1263
                SuccessAmt:  successAmt,
2✔
1264
                SuccessTime: successTime,
2✔
1265
        }
2✔
1266

2✔
1267
        return &routing.MissionControlPairSnapshot{
2✔
1268
                Pair:            pair,
2✔
1269
                TimedPairResult: *result,
2✔
1270
        }, nil
2✔
1271
}
1272

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

2✔
1280
        amt, err := getMsatPairValue(amtMsat, amtSat)
2✔
1281
        if err != nil {
4✔
1282
                return 0, time.Time{}, err
2✔
1283
        }
2✔
1284

1285
        var (
2✔
1286
                timeSet   = timestamp != 0
2✔
1287
                amountSet = amt != 0
2✔
1288
        )
2✔
1289

2✔
1290
        switch {
2✔
1291
        // If a timestamp and amount if provided, return those values.
1292
        case timeSet && amountSet:
2✔
1293
                return amt, time.Unix(timestamp, 0), nil
2✔
1294

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

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

1307
        default:
2✔
1308
                return 0, time.Time{}, nil
2✔
1309
        }
1310
}
1311

1312
// getMsatPairValue checks the msat and sat values set for a pair and ensures
1313
// that the values provided are either the same, or only a single value is set.
1314
func getMsatPairValue(msatValue lnwire.MilliSatoshi,
1315
        satValue btcutil.Amount) (lnwire.MilliSatoshi, error) {
2✔
1316

2✔
1317
        // If our msat value converted to sats equals our sat value, we just
2✔
1318
        // return the msat value, since the values are the same.
2✔
1319
        if msatValue.ToSatoshis() == satValue {
4✔
1320
                return msatValue, nil
2✔
1321
        }
2✔
1322

1323
        // If we have no msatValue, we can just return our state value even if
1324
        // it is zero, because it's impossible that we have mismatched values.
1325
        if msatValue == 0 {
2✔
1326
                return lnwire.MilliSatoshi(satValue * 1000), nil
×
1327
        }
×
1328

1329
        // Likewise, we can just use msat value if we have no sat value set.
1330
        if satValue == 0 {
2✔
1331
                return msatValue, nil
×
1332
        }
×
1333

1334
        // If our values are non-zero but not equal, we have invalid amounts
1335
        // set, so we fail.
1336
        return 0, fmt.Errorf("msat: %v and sat: %v values not equal", msatValue,
2✔
1337
                satValue)
2✔
1338
}
1339

1340
// TrackPaymentV2 returns a stream of payment state updates. The stream is
1341
// closed when the payment completes.
1342
func (s *Server) TrackPaymentV2(request *TrackPaymentRequest,
1343
        stream Router_TrackPaymentV2Server) error {
2✔
1344

2✔
1345
        payHash, err := lntypes.MakeHash(request.PaymentHash)
2✔
1346
        if err != nil {
2✔
1347
                return err
×
1348
        }
×
1349

1350
        log.Debugf("TrackPayment called for payment %v", payHash)
2✔
1351

2✔
1352
        // Make the subscription.
2✔
1353
        sub, err := s.subscribePayment(payHash)
2✔
1354
        if err != nil {
2✔
1355
                return err
×
1356
        }
×
1357

1358
        return s.trackPayment(sub, payHash, stream, request.NoInflightUpdates)
2✔
1359
}
1360

1361
// subscribePayment subscribes to the payment updates for the given payment
1362
// hash.
1363
func (s *Server) subscribePayment(identifier lntypes.Hash) (
1364
        routing.ControlTowerSubscriber, error) {
2✔
1365

2✔
1366
        // Make the subscription.
2✔
1367
        router := s.cfg.RouterBackend
2✔
1368
        sub, err := router.Tower.SubscribePayment(identifier)
2✔
1369

2✔
1370
        switch {
2✔
1371
        case errors.Is(err, channeldb.ErrPaymentNotInitiated):
×
1372
                return nil, status.Error(codes.NotFound, err.Error())
×
1373

1374
        case err != nil:
×
1375
                return nil, err
×
1376
        }
1377

1378
        return sub, nil
2✔
1379
}
1380

1381
// trackPayment writes payment status updates to the provided stream.
1382
func (s *Server) trackPayment(subscription routing.ControlTowerSubscriber,
1383
        identifier lntypes.Hash, stream Router_TrackPaymentV2Server,
1384
        noInflightUpdates bool) error {
2✔
1385

2✔
1386
        err := s.trackPaymentStream(
2✔
1387
                stream.Context(), subscription, noInflightUpdates, stream.Send,
2✔
1388
        )
2✔
1389
        switch {
2✔
1390
        case err == nil:
2✔
1391
                return nil
2✔
1392

1393
        // If the context is canceled, we don't return an error.
1394
        case errors.Is(err, context.Canceled):
2✔
1395
                log.Infof("Payment stream %v canceled", identifier)
2✔
1396

2✔
1397
                return nil
2✔
1398

1399
        default:
×
1400
        }
1401

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

×
1406
        return err
×
1407
}
1408

1409
// TrackPayments returns a stream of payment state updates.
1410
func (s *Server) TrackPayments(request *TrackPaymentsRequest,
1411
        stream Router_TrackPaymentsServer) error {
2✔
1412

2✔
1413
        log.Debug("TrackPayments called")
2✔
1414

2✔
1415
        router := s.cfg.RouterBackend
2✔
1416

2✔
1417
        // Subscribe to payments.
2✔
1418
        subscription, err := router.Tower.SubscribeAllPayments()
2✔
1419
        if err != nil {
2✔
1420
                return err
×
1421
        }
×
1422

1423
        // Stream updates to the client.
1424
        err = s.trackPaymentStream(
2✔
1425
                stream.Context(), subscription, request.NoInflightUpdates,
2✔
1426
                stream.Send,
2✔
1427
        )
2✔
1428

2✔
1429
        if errors.Is(err, context.Canceled) {
4✔
1430
                log.Debugf("TrackPayments payment stream canceled.")
2✔
1431
        }
2✔
1432

1433
        return err
2✔
1434
}
1435

1436
// trackPaymentStream streams payment updates to the client.
1437
func (s *Server) trackPaymentStream(context context.Context,
1438
        subscription routing.ControlTowerSubscriber, noInflightUpdates bool,
1439
        send func(*lnrpc.Payment) error) error {
2✔
1440

2✔
1441
        defer subscription.Close()
2✔
1442

2✔
1443
        // Stream updates back to the client.
2✔
1444
        for {
4✔
1445
                select {
2✔
1446
                case item, ok := <-subscription.Updates():
2✔
1447
                        if !ok {
4✔
1448
                                // No more payment updates.
2✔
1449
                                return nil
2✔
1450
                        }
2✔
1451
                        result := item.(*channeldb.MPPayment)
2✔
1452

2✔
1453
                        log.Tracef("Payment %v updated to state %v",
2✔
1454
                                result.Info.PaymentIdentifier, result.Status)
2✔
1455

2✔
1456
                        // Skip in-flight updates unless requested.
2✔
1457
                        if noInflightUpdates {
4✔
1458
                                if result.Status == channeldb.StatusInitiated {
4✔
1459
                                        continue
2✔
1460
                                }
1461
                                if result.Status == channeldb.StatusInFlight {
4✔
1462
                                        continue
2✔
1463
                                }
1464
                        }
1465

1466
                        rpcPayment, err := s.cfg.RouterBackend.MarshallPayment(
2✔
1467
                                result,
2✔
1468
                        )
2✔
1469
                        if err != nil {
2✔
1470
                                return err
×
1471
                        }
×
1472

1473
                        // Send event to the client.
1474
                        err = send(rpcPayment)
2✔
1475
                        if err != nil {
2✔
1476
                                return err
×
1477
                        }
×
1478

1479
                case <-s.quit:
×
1480
                        return errServerShuttingDown
×
1481

1482
                case <-context.Done():
2✔
1483
                        return context.Err()
2✔
1484
                }
1485
        }
1486
}
1487

1488
// BuildRoute builds a route from a list of hop addresses.
1489
func (s *Server) BuildRoute(_ context.Context,
1490
        req *BuildRouteRequest) (*BuildRouteResponse, error) {
2✔
1491

2✔
1492
        if len(req.HopPubkeys) == 0 {
2✔
1493
                return nil, errors.New("no hops specified")
×
1494
        }
×
1495

1496
        // Unmarshall hop list.
1497
        hops := make([]route.Vertex, len(req.HopPubkeys))
2✔
1498
        for i, pubkeyBytes := range req.HopPubkeys {
4✔
1499
                pubkey, err := route.NewVertexFromBytes(pubkeyBytes)
2✔
1500
                if err != nil {
2✔
1501
                        return nil, err
×
1502
                }
×
1503
                hops[i] = pubkey
2✔
1504
        }
1505

1506
        // Prepare BuildRoute call parameters from rpc request.
1507
        var amt fn.Option[lnwire.MilliSatoshi]
2✔
1508
        if req.AmtMsat != 0 {
4✔
1509
                rpcAmt := lnwire.MilliSatoshi(req.AmtMsat)
2✔
1510
                amt = fn.Some(rpcAmt)
2✔
1511
        }
2✔
1512

1513
        var outgoingChan *uint64
2✔
1514
        if req.OutgoingChanId != 0 {
2✔
1515
                outgoingChan = &req.OutgoingChanId
×
1516
        }
×
1517

1518
        var payAddr fn.Option[[32]byte]
2✔
1519
        if len(req.PaymentAddr) != 0 {
4✔
1520
                var backingPayAddr [32]byte
2✔
1521
                copy(backingPayAddr[:], req.PaymentAddr)
2✔
1522

2✔
1523
                payAddr = fn.Some(backingPayAddr)
2✔
1524
        }
2✔
1525

1526
        if req.FinalCltvDelta == 0 {
2✔
1527
                req.FinalCltvDelta = int32(
×
1528
                        s.cfg.RouterBackend.DefaultFinalCltvDelta,
×
1529
                )
×
1530
        }
×
1531

1532
        var firstHopBlob fn.Option[[]byte]
2✔
1533
        if len(req.FirstHopCustomRecords) > 0 {
2✔
1534
                firstHopRecords := lnwire.CustomRecords(
×
1535
                        req.FirstHopCustomRecords,
×
1536
                )
×
1537
                if err := firstHopRecords.Validate(); err != nil {
×
1538
                        return nil, err
×
1539
                }
×
1540

1541
                firstHopData, err := firstHopRecords.Serialize()
×
1542
                if err != nil {
×
1543
                        return nil, err
×
1544
                }
×
1545
                firstHopBlob = fn.Some(firstHopData)
×
1546
        }
1547

1548
        // Build the route and return it to the caller.
1549
        route, err := s.cfg.Router.BuildRoute(
2✔
1550
                amt, hops, outgoingChan, req.FinalCltvDelta, payAddr,
2✔
1551
                firstHopBlob,
2✔
1552
        )
2✔
1553
        if err != nil {
2✔
1554
                return nil, err
×
1555
        }
×
1556

1557
        rpcRoute, err := s.cfg.RouterBackend.MarshallRoute(route)
2✔
1558
        if err != nil {
2✔
1559
                return nil, err
×
1560
        }
×
1561

1562
        routeResp := &BuildRouteResponse{
2✔
1563
                Route: rpcRoute,
2✔
1564
        }
2✔
1565

2✔
1566
        return routeResp, nil
2✔
1567
}
1568

1569
// SubscribeHtlcEvents creates a uni-directional stream from the server to
1570
// the client which delivers a stream of htlc events.
1571
func (s *Server) SubscribeHtlcEvents(_ *SubscribeHtlcEventsRequest,
1572
        stream Router_SubscribeHtlcEventsServer) error {
2✔
1573

2✔
1574
        htlcClient, err := s.cfg.RouterBackend.SubscribeHtlcEvents()
2✔
1575
        if err != nil {
2✔
1576
                return err
×
1577
        }
×
1578
        defer htlcClient.Cancel()
2✔
1579

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

1590
        for {
4✔
1591
                select {
2✔
1592
                case event := <-htlcClient.Updates():
2✔
1593
                        rpcEvent, err := rpcHtlcEvent(event)
2✔
1594
                        if err != nil {
2✔
1595
                                return err
×
1596
                        }
×
1597

1598
                        if err := stream.Send(rpcEvent); err != nil {
2✔
1599
                                return err
×
1600
                        }
×
1601

1602
                // If the stream's context is cancelled, return an error.
1603
                case <-stream.Context().Done():
2✔
1604
                        log.Debugf("htlc event stream cancelled")
2✔
1605
                        return stream.Context().Err()
2✔
1606

1607
                // If the subscribe client terminates, exit with an error.
1608
                case <-htlcClient.Quit():
×
1609
                        return errors.New("htlc event subscription terminated")
×
1610

1611
                // If the server has been signalled to shut down, exit.
1612
                case <-s.quit:
×
1613
                        return errServerShuttingDown
×
1614
                }
1615
        }
1616
}
1617

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

2✔
1633
        // Run the forward interceptor.
2✔
1634
        return newForwardInterceptor(
2✔
1635
                s.cfg.RouterBackend.InterceptableForwarder, stream,
2✔
1636
        ).run()
2✔
1637
}
1638

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

2✔
1648
        existingAliases := s.cfg.AliasMgr.ListAliases()
2✔
1649

2✔
1650
        // aliasExists checks if the new alias already exists in the alias map.
2✔
1651
        aliasExists := func(newAlias uint64,
2✔
1652
                baseScid lnwire.ShortChannelID) (bool, error) {
4✔
1653

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

1662
                for base, aliases := range existingAliases {
4✔
1663
                        for _, alias := range aliases {
4✔
1664
                                exists := alias.ToUint64() == newAlias
2✔
1665

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

1675
                                if exists {
4✔
1676
                                        return true, nil
2✔
1677
                                }
2✔
1678
                        }
1679
                }
1680

1681
                return false, nil
2✔
1682
        }
1683

1684
        for _, v := range in.AliasMaps {
4✔
1685
                baseScid := lnwire.NewShortChanIDFromInt(v.BaseScid)
2✔
1686

2✔
1687
                for _, rpcAlias := range v.Aliases {
4✔
1688
                        // If not, let's add it to the alias manager now.
2✔
1689
                        aliasScid := lnwire.NewShortChanIDFromInt(rpcAlias)
2✔
1690

2✔
1691
                        // But we only add it, if it's a valid alias, as defined
2✔
1692
                        // by the BOLT spec.
2✔
1693
                        if !aliasmgr.IsAlias(aliasScid) {
4✔
1694
                                return nil, fmt.Errorf("%w: SCID alias %v is "+
2✔
1695
                                        "not a valid alias", ErrNoValidAlias,
2✔
1696
                                        aliasScid)
2✔
1697
                        }
2✔
1698

1699
                        exists, err := aliasExists(rpcAlias, baseScid)
2✔
1700
                        if err != nil {
2✔
1701
                                return nil, err
×
1702
                        }
×
1703

1704
                        // If the alias already exists, we see that as an error.
1705
                        // This is to avoid "silent" collisions.
1706
                        if exists {
4✔
1707
                                return nil, fmt.Errorf("%w: SCID alias %v "+
2✔
1708
                                        "already exists", ErrAliasAlreadyExists,
2✔
1709
                                        rpcAlias)
2✔
1710
                        }
2✔
1711

1712
                        err = s.cfg.AliasMgr.AddLocalAlias(
2✔
1713
                                aliasScid, baseScid, false, true,
2✔
1714
                        )
2✔
1715
                        if err != nil {
2✔
1716
                                return nil, fmt.Errorf("error adding scid "+
×
1717
                                        "alias, base_scid=%v, alias_scid=%v: "+
×
1718
                                        "%w", baseScid, aliasScid, err)
×
1719
                        }
×
1720
                }
1721
        }
1722

1723
        return &AddAliasesResponse{
2✔
1724
                AliasMaps: lnrpc.MarshalAliasMap(s.cfg.AliasMgr.ListAliases()),
2✔
1725
        }, nil
2✔
1726
}
1727

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

2✔
1736
        for _, v := range in.AliasMaps {
4✔
1737
                baseScid := lnwire.NewShortChanIDFromInt(v.BaseScid)
2✔
1738

2✔
1739
                for _, alias := range v.Aliases {
4✔
1740
                        aliasScid := lnwire.NewShortChanIDFromInt(alias)
2✔
1741

2✔
1742
                        err := s.cfg.AliasMgr.DeleteLocalAlias(
2✔
1743
                                aliasScid, baseScid,
2✔
1744
                        )
2✔
1745
                        if err != nil {
2✔
1746
                                return nil, fmt.Errorf("error deleting scid "+
×
1747
                                        "alias, base_scid=%v, alias_scid=%v: "+
×
1748
                                        "%w", baseScid, aliasScid, err)
×
1749
                        }
×
1750
                }
1751
        }
1752

1753
        return &DeleteAliasesResponse{
2✔
1754
                AliasMaps: lnrpc.MarshalAliasMap(s.cfg.AliasMgr.ListAliases()),
2✔
1755
        }, nil
2✔
1756
}
1757

1758
func extractOutPoint(req *UpdateChanStatusRequest) (*wire.OutPoint, error) {
2✔
1759
        chanPoint := req.GetChanPoint()
2✔
1760
        txid, err := lnrpc.GetChanPointFundingTxid(chanPoint)
2✔
1761
        if err != nil {
2✔
1762
                return nil, err
×
1763
        }
×
1764
        index := chanPoint.OutputIndex
2✔
1765
        return wire.NewOutPoint(txid, index), nil
2✔
1766
}
1767

1768
// UpdateChanStatus allows channel state to be set manually.
1769
func (s *Server) UpdateChanStatus(_ context.Context,
1770
        req *UpdateChanStatusRequest) (*UpdateChanStatusResponse, error) {
2✔
1771

2✔
1772
        outPoint, err := extractOutPoint(req)
2✔
1773
        if err != nil {
2✔
1774
                return nil, err
×
1775
        }
×
1776

1777
        action := req.GetAction()
2✔
1778

2✔
1779
        log.Debugf("UpdateChanStatus called for channel(%v) with "+
2✔
1780
                "action %v", outPoint, action)
2✔
1781

2✔
1782
        switch action {
2✔
1783
        case ChanStatusAction_ENABLE:
2✔
1784
                err = s.cfg.RouterBackend.SetChannelEnabled(*outPoint)
2✔
1785
        case ChanStatusAction_DISABLE:
2✔
1786
                err = s.cfg.RouterBackend.SetChannelDisabled(*outPoint)
2✔
1787
        case ChanStatusAction_AUTO:
2✔
1788
                err = s.cfg.RouterBackend.SetChannelAuto(*outPoint)
2✔
1789
        default:
×
1790
                err = fmt.Errorf("unrecognized ChannelStatusAction %v", action)
×
1791
        }
1792

1793
        if err != nil {
2✔
1794
                return nil, err
×
1795
        }
×
1796
        return &UpdateChanStatusResponse{}, nil
2✔
1797
}
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