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

lightningnetwork / lnd / 16948521526

13 Aug 2025 08:27PM UTC coverage: 54.877% (-12.1%) from 66.929%
16948521526

Pull #10155

github

web-flow
Merge 61c0fecf6 into c6a9116e3
Pull Request #10155: Add missing invoice index for native sql

108941 of 198518 relevant lines covered (54.88%)

22023.66 hits per line

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

11.24
/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
        paymentsdb "github.com/lightningnetwork/lnd/payments/db"
26
        "github.com/lightningnetwork/lnd/routing"
27
        "github.com/lightningnetwork/lnd/routing/route"
28
        "github.com/lightningnetwork/lnd/zpay32"
29
        "google.golang.org/grpc"
30
        "google.golang.org/grpc/codes"
31
        "google.golang.org/grpc/status"
32
        "gopkg.in/macaroon-bakery.v2/bakery"
33
)
34

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

199
        cfg *Config
200

201
        quit chan struct{}
202
}
203

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

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

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

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

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

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

×
258
        return routerServer, macPermissions, nil
×
259
}
260

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

269
        return nil
×
270
}
271

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

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

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

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

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

×
305
        return nil
×
306
}
×
307

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

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

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

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

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

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

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

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

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

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

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

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

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

386
                return err
×
387
        }
388

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

560
        hints := payReq.RouteHints
×
561

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

×
569
                probeRequest.RouteHints = invoicesrpc.CreateRPCRouteHints(hints)
×
570
                return s.sendProbePayment(ctx, probeRequest)
×
571
        }
×
572

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

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

×
586
        log.Infof("LSP detected, probing LSP with destination: %x", lspDest)
×
587

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

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

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

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

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

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

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

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

×
643
        return resp, nil
×
644
}
645

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

9✔
654
        if len(routeHints) == 0 || len(routeHints[0]) == 0 {
10✔
655
                return false
1✔
656
        }
1✔
657

658
        destHopHint := routeHints[0][len(routeHints[0])-1]
8✔
659

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

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

674
                lastHop := routeHints[i][len(routeHints[i])-1]
5✔
675

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

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

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

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

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

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

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

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

732
        return adjustedHints, &refHint, nil
5✔
733
}
734

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

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

753
        return maxBaseFee, maxFeePpm
5✔
754
}
755

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

766
        return maxCltvDelta
5✔
767
}
768

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

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

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

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

789
        return nil
×
790
}
791

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

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

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

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

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

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

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

847
                                return &RouteFeeResponse{
×
848
                                        RoutingFeeMsat: 0,
×
849
                                        TimeLockDelay:  0,
×
850
                                        FailureReason:  payment.FailureReason,
×
851
                                }, nil
×
852

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

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

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

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

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

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

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

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

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

903
        return lastRoute.TotalFeesMsat, int64(lastRoute.TotalTimeLock), nil
×
904
}
905

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

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

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

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

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

930
        var attempt *channeldb.HTLCAttempt
×
931

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

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

962
        case errors.Is(err, paymentsdb.ErrPaymentInFlight):
×
963
                fallthrough
×
964

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

971
        return nil, err
×
972
}
973

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

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

984
        return &ResetMissionControlResponse{}, nil
×
985
}
986

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

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

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

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

×
1021
                resp.Config.EstimatorConfig = &MissionControlConfig_Apriori{
×
1022
                        Apriori: &aCfg,
×
1023
                }
×
1024

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

×
1033
                resp.Config.EstimatorConfig = &MissionControlConfig_Bimodal{
×
1034
                        Bimodal: &bCfg,
×
1035
                }
×
1036

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

1041
        return resp, nil
×
1042
}
1043

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

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

×
1056
        switch req.Config.Model {
×
1057
        case MissionControlConfig_APRIORI:
×
1058
                var aprioriConfig routing.AprioriConfig
×
1059

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

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

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

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

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

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

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

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

1125
        return &SetMissionControlConfigResponse{},
×
1126
                s.cfg.RouterBackend.MissionControl.SetConfig(mcCfg)
×
1127
}
1128

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

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

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

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

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

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

×
1154
        return &response, nil
×
1155
}
1156

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

×
1166
        if !data.FailTime.IsZero() {
×
1167
                rpcData.FailTime = data.FailTime.Unix()
×
1168
        }
×
1169

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

1174
        return &rpcData
×
1175
}
1176

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

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

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

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

1199
                snapshot.Pairs[i] = *pairSnapshot
×
1200
        }
1201

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

1209
        return &XImportMissionControlResponse{}, nil
×
1210
}
1211

1212
func toPairSnapshot(pairResult *PairHistory) (*routing.MissionControlPairSnapshot,
1213
        error) {
×
1214

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

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

1225
        pairPrefix := fmt.Sprintf("pair: %v -> %v:", from, to)
×
1226

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

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

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

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

1259
        pair := routing.NewDirectedNodePair(from, to)
×
1260

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

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

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

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

1286
        var (
×
1287
                timeSet   = timestamp != 0
×
1288
                amountSet = amt != 0
×
1289
        )
×
1290

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

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

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

1308
        default:
×
1309
                return 0, time.Time{}, nil
×
1310
        }
1311
}
1312

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

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

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

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

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

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

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

1351
        log.Debugf("TrackPayment called for payment %v", payHash)
×
1352

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

1359
        return s.trackPayment(sub, payHash, stream, request.NoInflightUpdates)
×
1360
}
1361

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

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

×
1371
        switch {
×
1372
        case errors.Is(err, paymentsdb.ErrPaymentNotInitiated):
×
1373
                return nil, status.Error(codes.NotFound, err.Error())
×
1374

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

1379
        return sub, nil
×
1380
}
1381

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

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

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

×
1398
                return nil
×
1399

1400
        default:
×
1401
        }
1402

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

×
1407
        return err
×
1408
}
1409

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

3✔
1414
        log.Debug("TrackPayments called")
3✔
1415

3✔
1416
        router := s.cfg.RouterBackend
3✔
1417

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

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

3✔
1430
        if errors.Is(err, context.Canceled) {
6✔
1431
                log.Debugf("TrackPayments payment stream canceled.")
3✔
1432
        }
3✔
1433

1434
        return err
3✔
1435
}
1436

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

3✔
1442
        defer subscription.Close()
3✔
1443

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

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

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

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

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

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

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

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

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

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

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

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

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

×
1524
                payAddr = fn.Some(backingPayAddr)
×
1525
        }
×
1526

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

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

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

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

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

1563
        routeResp := &BuildRouteResponse{
×
1564
                Route: rpcRoute,
×
1565
        }
×
1566

×
1567
        return routeResp, nil
×
1568
}
1569

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

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

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

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

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

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

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

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

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

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

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

×
1649
        existingAliases := s.cfg.AliasMgr.ListAliases()
×
1650

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

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

1663
                for base, aliases := range existingAliases {
×
1664
                        for _, alias := range aliases {
×
1665
                                exists := alias.ToUint64() == newAlias
×
1666

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

1676
                                if exists {
×
1677
                                        return true, nil
×
1678
                                }
×
1679
                        }
1680
                }
1681

1682
                return false, nil
×
1683
        }
1684

1685
        for _, v := range in.AliasMaps {
×
1686
                baseScid := lnwire.NewShortChanIDFromInt(v.BaseScid)
×
1687

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

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

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

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

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

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

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

×
1737
        for _, v := range in.AliasMaps {
×
1738
                baseScid := lnwire.NewShortChanIDFromInt(v.BaseScid)
×
1739

×
1740
                for _, alias := range v.Aliases {
×
1741
                        aliasScid := lnwire.NewShortChanIDFromInt(alias)
×
1742

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

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

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

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

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

1778
        action := req.GetAction()
×
1779

×
1780
        log.Debugf("UpdateChanStatus called for channel(%v) with "+
×
1781
                "action %v", outPoint, action)
×
1782

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

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