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

lightningnetwork / lnd / 12628700106

06 Jan 2025 07:54AM UTC coverage: 58.708% (+0.1%) from 58.598%
12628700106

Pull #9150

github

yyforyongyu
x
Pull Request #9150: routing+htlcswitch: fix stuck inflight payments

196 of 237 new or added lines in 6 files covered. (82.7%)

39 existing lines in 13 files now uncovered.

135285 of 230439 relevant lines covered (58.71%)

19155.8 hits per line

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

73.68
/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

45
var (
46
        errServerShuttingDown = errors.New("routerrpc server shutting down")
47

48
        // ErrInterceptorAlreadyExists is an error returned when a new stream is
49
        // opened and there is already one active interceptor. The user must
50
        // disconnect prior to open another stream.
51
        ErrInterceptorAlreadyExists = errors.New("interceptor already exists")
52

53
        errMissingPaymentAttempt = errors.New("missing payment attempt")
54

55
        errMissingRoute = errors.New("missing route")
56

57
        errUnexpectedFailureSource = errors.New("unexpected failure source")
58

59
        // ErrAliasAlreadyExists is returned if a new SCID alias is attempted
60
        // to be added that already exists.
61
        ErrAliasAlreadyExists = errors.New("alias already exists")
62

63
        // ErrNoValidAlias is returned if an alias is not in the valid range for
64
        // allowed SCID aliases.
65
        ErrNoValidAlias = errors.New("not a valid alias")
66

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

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

164
        // DefaultRouterMacFilename is the default name of the router macaroon
165
        // that we expect to find via a file handle within the main
166
        // configuration file in this package.
167
        DefaultRouterMacFilename = "router.macaroon"
168
)
169

170
// ServerShell is a shell struct holding a reference to the actual sub-server.
171
// It is used to register the gRPC sub-server with the root server before we
172
// have the necessary dependencies to populate the actual sub-server.
173
type ServerShell struct {
174
        RouterServer
175
}
176

177
// Server is a stand-alone sub RPC server which exposes functionality that
178
// allows clients to route arbitrary payment through the Lightning Network.
179
type Server struct {
180
        started                  int32 // To be used atomically.
181
        shutdown                 int32 // To be used atomically.
182
        forwardInterceptorActive int32 // To be used atomically.
183

184
        // Required by the grpc-gateway/v2 library for forward compatibility.
185
        // Must be after the atomically used variables to not break struct
186
        // alignment.
187
        UnimplementedRouterServer
188

189
        cfg *Config
190

191
        quit chan struct{}
192
}
193

194
// A compile time check to ensure that Server fully implements the RouterServer
195
// gRPC service.
196
var _ RouterServer = (*Server)(nil)
197

198
// New creates a new instance of the RouterServer given a configuration struct
199
// that contains all external dependencies. If the target macaroon exists, and
200
// we're unable to create it, then an error will be returned. We also return
201
// the set of permissions that we require as a server. At the time of writing
202
// of this documentation, this is the same macaroon as the admin macaroon.
203
func New(cfg *Config) (*Server, lnrpc.MacaroonPerms, error) {
3✔
204
        // If the path of the router macaroon wasn't generated, then we'll
3✔
205
        // assume that it's found at the default network directory.
3✔
206
        if cfg.RouterMacPath == "" {
6✔
207
                cfg.RouterMacPath = filepath.Join(
3✔
208
                        cfg.NetworkDir, DefaultRouterMacFilename,
3✔
209
                )
3✔
210
        }
3✔
211

212
        // Now that we know the full path of the router macaroon, we can check
213
        // to see if we need to create it or not. If stateless_init is set
214
        // then we don't write the macaroons.
215
        macFilePath := cfg.RouterMacPath
3✔
216
        if cfg.MacService != nil && !cfg.MacService.StatelessInit &&
3✔
217
                !lnrpc.FileExists(macFilePath) {
6✔
218

3✔
219
                log.Infof("Making macaroons for Router RPC Server at: %v",
3✔
220
                        macFilePath)
3✔
221

3✔
222
                // At this point, we know that the router macaroon doesn't yet,
3✔
223
                // exist, so we need to create it with the help of the main
3✔
224
                // macaroon service.
3✔
225
                routerMac, err := cfg.MacService.NewMacaroon(
3✔
226
                        context.Background(), macaroons.DefaultRootKeyID,
3✔
227
                        macaroonOps...,
3✔
228
                )
3✔
229
                if err != nil {
3✔
230
                        return nil, nil, err
×
231
                }
×
232
                routerMacBytes, err := routerMac.M().MarshalBinary()
3✔
233
                if err != nil {
3✔
234
                        return nil, nil, err
×
235
                }
×
236
                err = os.WriteFile(macFilePath, routerMacBytes, 0644)
3✔
237
                if err != nil {
3✔
238
                        _ = os.Remove(macFilePath)
×
239
                        return nil, nil, err
×
240
                }
×
241
        }
242

243
        routerServer := &Server{
3✔
244
                cfg:  cfg,
3✔
245
                quit: make(chan struct{}),
3✔
246
        }
3✔
247

3✔
248
        return routerServer, macPermissions, nil
3✔
249
}
250

251
// Start launches any helper goroutines required for the rpcServer to function.
252
//
253
// NOTE: This is part of the lnrpc.SubServer interface.
254
func (s *Server) Start() error {
3✔
255
        if atomic.AddInt32(&s.started, 1) != 1 {
3✔
256
                return nil
×
257
        }
×
258

259
        return nil
3✔
260
}
261

262
// Stop signals any active goroutines for a graceful closure.
263
//
264
// NOTE: This is part of the lnrpc.SubServer interface.
265
func (s *Server) Stop() error {
3✔
266
        if atomic.AddInt32(&s.shutdown, 1) != 1 {
3✔
267
                return nil
×
268
        }
×
269

270
        close(s.quit)
3✔
271
        return nil
3✔
272
}
273

274
// Name returns a unique string representation of the sub-server. This can be
275
// used to identify the sub-server and also de-duplicate them.
276
//
277
// NOTE: This is part of the lnrpc.SubServer interface.
278
func (s *Server) Name() string {
3✔
279
        return subServerName
3✔
280
}
3✔
281

282
// RegisterWithRootServer will be called by the root gRPC server to direct a
283
// sub RPC server to register itself with the main gRPC root server. Until this
284
// is called, each sub-server won't be able to have requests routed towards it.
285
//
286
// NOTE: This is part of the lnrpc.GrpcHandler interface.
287
func (r *ServerShell) RegisterWithRootServer(grpcServer *grpc.Server) error {
3✔
288
        // We make sure that we register it with the main gRPC server to ensure
3✔
289
        // all our methods are routed properly.
3✔
290
        RegisterRouterServer(grpcServer, r)
3✔
291

3✔
292
        log.Debugf("Router RPC server successfully register with root gRPC " +
3✔
293
                "server")
3✔
294

3✔
295
        return nil
3✔
296
}
3✔
297

298
// RegisterWithRestServer will be called by the root REST mux to direct a sub
299
// RPC server to register itself with the main REST mux server. Until this is
300
// called, each sub-server won't be able to have requests routed towards it.
301
//
302
// NOTE: This is part of the lnrpc.GrpcHandler interface.
303
func (r *ServerShell) RegisterWithRestServer(ctx context.Context,
304
        mux *runtime.ServeMux, dest string, opts []grpc.DialOption) error {
3✔
305

3✔
306
        // We make sure that we register it with the main REST server to ensure
3✔
307
        // all our methods are routed properly.
3✔
308
        err := RegisterRouterHandlerFromEndpoint(ctx, mux, dest, opts)
3✔
309
        if err != nil {
3✔
310
                log.Errorf("Could not register Router REST server "+
×
311
                        "with root REST server: %v", err)
×
312
                return err
×
313
        }
×
314

315
        log.Debugf("Router REST server successfully registered with " +
3✔
316
                "root REST server")
3✔
317
        return nil
3✔
318
}
319

320
// CreateSubServer populates the subserver's dependencies using the passed
321
// SubServerConfigDispatcher. This method should fully initialize the
322
// sub-server instance, making it ready for action. It returns the macaroon
323
// permissions that the sub-server wishes to pass on to the root server for all
324
// methods routed towards it.
325
//
326
// NOTE: This is part of the lnrpc.GrpcHandler interface.
327
func (r *ServerShell) CreateSubServer(configRegistry lnrpc.SubServerConfigDispatcher) (
328
        lnrpc.SubServer, lnrpc.MacaroonPerms, error) {
3✔
329

3✔
330
        subServer, macPermissions, err := createNewSubServer(configRegistry)
3✔
331
        if err != nil {
3✔
332
                return nil, nil, err
×
333
        }
×
334

335
        r.RouterServer = subServer
3✔
336
        return subServer, macPermissions, nil
3✔
337
}
338

339
// SendPaymentV2 attempts to route a payment described by the passed
340
// PaymentRequest to the final destination. If we are unable to route the
341
// payment, or cannot find a route that satisfies the constraints in the
342
// PaymentRequest, then an error will be returned. Otherwise, the payment
343
// pre-image, along with the final route will be returned.
344
func (s *Server) SendPaymentV2(req *SendPaymentRequest,
345
        stream Router_SendPaymentV2Server) error {
3✔
346

3✔
347
        payment, err := s.cfg.RouterBackend.extractIntentFromSendRequest(req)
3✔
348
        if err != nil {
3✔
349
                return err
×
350
        }
×
351

352
        // Get the payment hash.
353
        payHash := payment.Identifier()
3✔
354

3✔
355
        // Init the payment in db.
3✔
356
        paySession, shardTracker, err := s.cfg.Router.PreparePayment(payment)
3✔
357
        if err != nil {
3✔
358
                log.Errorf("SendPayment async error for payment %x: %v",
×
359
                        payment.Identifier(), err)
×
360

×
361
                // Transform user errors to grpc code.
×
362
                if errors.Is(err, channeldb.ErrPaymentExists) ||
×
363
                        errors.Is(err, channeldb.ErrPaymentInFlight) ||
×
364
                        errors.Is(err, channeldb.ErrAlreadyPaid) {
×
365

×
366
                        return status.Error(
×
367
                                codes.AlreadyExists, err.Error(),
×
368
                        )
×
369
                }
×
370

371
                return err
×
372
        }
373

374
        // Subscribe to the payment before sending it to make sure we won't
375
        // miss events.
376
        sub, err := s.subscribePayment(payHash)
3✔
377
        if err != nil {
3✔
378
                return err
×
379
        }
×
380

381
        // The payment context is influenced by two user-provided parameters,
382
        // the cancelable flag and the payment attempt timeout.
383
        // If the payment is cancelable, we will use the stream context as the
384
        // payment context. That way, if the user ends the stream, the payment
385
        // loop will be canceled.
386
        // The second context parameter is the timeout. If the user provides a
387
        // timeout, we will additionally wrap the context in a deadline. If the
388
        // user provided 'cancelable' and ends the stream before the timeout is
389
        // reached the payment will be canceled.
390
        ctx := context.Background()
3✔
391
        if req.Cancelable {
6✔
392
                ctx = stream.Context()
3✔
393
        }
3✔
394

395
        // Send the payment asynchronously.
396
        s.cfg.Router.SendPaymentAsync(ctx, payment, paySession, shardTracker)
3✔
397

3✔
398
        // Track the payment and return.
3✔
399
        return s.trackPayment(sub, payHash, stream, req.NoInflightUpdates)
3✔
400
}
401

402
// EstimateRouteFee allows callers to obtain an expected value w.r.t how much it
403
// may cost to send an HTLC to the target end destination. This method sends
404
// probe payments to the target node, based on target invoice parameters and a
405
// random payment hash that makes it impossible for the target to settle the
406
// htlc. The probing stops if a user-provided timeout is reached. If provided
407
// with a destination key and amount, this method will perform a local graph
408
// based fee estimation.
409
func (s *Server) EstimateRouteFee(ctx context.Context,
410
        req *RouteFeeRequest) (*RouteFeeResponse, error) {
3✔
411

3✔
412
        isProbeDestination := len(req.Dest) > 0
3✔
413
        isProbeInvoice := len(req.PaymentRequest) > 0
3✔
414

3✔
415
        switch {
3✔
416
        case isProbeDestination == isProbeInvoice:
×
417
                return nil, errors.New("specify either a destination or an " +
×
418
                        "invoice")
×
419

420
        case isProbeDestination:
3✔
421
                switch {
3✔
422
                case len(req.Dest) != 33:
×
423
                        return nil, errors.New("invalid length destination key")
×
424

425
                case req.AmtSat <= 0:
×
426
                        return nil, errors.New("amount must be greater than 0")
×
427

428
                default:
3✔
429
                        return s.probeDestination(req.Dest, req.AmtSat)
3✔
430
                }
431

432
        case isProbeInvoice:
3✔
433
                return s.probePaymentRequest(
3✔
434
                        ctx, req.PaymentRequest, req.Timeout,
3✔
435
                )
3✔
436
        }
437

438
        return &RouteFeeResponse{}, nil
×
439
}
440

441
// probeDestination estimates fees along a route to a destination based on the
442
// contents of the local graph.
443
func (s *Server) probeDestination(dest []byte, amtSat int64) (*RouteFeeResponse,
444
        error) {
3✔
445

3✔
446
        destNode, err := route.NewVertexFromBytes(dest)
3✔
447
        if err != nil {
3✔
448
                return nil, err
×
449
        }
×
450

451
        // Next, we'll convert the amount in satoshis to mSAT, which are the
452
        // native unit of LN.
453
        amtMsat := lnwire.NewMSatFromSatoshis(btcutil.Amount(amtSat))
3✔
454

3✔
455
        // Finally, we'll query for a route to the destination that can carry
3✔
456
        // that target amount, we'll only request a single route. Set a
3✔
457
        // restriction for the default CLTV limit, otherwise we can find a route
3✔
458
        // that exceeds it and is useless to us.
3✔
459
        mc := s.cfg.RouterBackend.MissionControl
3✔
460
        routeReq, err := routing.NewRouteRequest(
3✔
461
                s.cfg.RouterBackend.SelfNode, &destNode, amtMsat, 0,
3✔
462
                &routing.RestrictParams{
3✔
463
                        FeeLimit:          routeFeeLimitSat,
3✔
464
                        CltvLimit:         s.cfg.RouterBackend.MaxTotalTimelock,
3✔
465
                        ProbabilitySource: mc.GetProbability,
3✔
466
                }, nil, nil, nil, s.cfg.RouterBackend.DefaultFinalCltvDelta,
3✔
467
        )
3✔
468
        if err != nil {
3✔
469
                return nil, err
×
470
        }
×
471

472
        route, _, err := s.cfg.Router.FindRoute(routeReq)
3✔
473
        if err != nil {
6✔
474
                return nil, err
3✔
475
        }
3✔
476

477
        // We are adding a block padding to the total time lock to account for
478
        // the safety buffer that the payment session will add to the last hop's
479
        // cltv delta. This is to prevent the htlc from failing if blocks are
480
        // mined while it is in flight.
481
        timeLockDelay := route.TotalTimeLock + uint32(routing.BlockPadding)
3✔
482

3✔
483
        return &RouteFeeResponse{
3✔
484
                RoutingFeeMsat: int64(route.TotalFees()),
3✔
485
                TimeLockDelay:  int64(timeLockDelay),
3✔
486
                FailureReason:  lnrpc.PaymentFailureReason_FAILURE_REASON_NONE,
3✔
487
        }, nil
3✔
488
}
489

490
// probePaymentRequest estimates fees along a route to a destination that is
491
// specified in an invoice. The estimation duration is limited by a timeout. In
492
// case that route hints are provided, this method applies a heuristic to
493
// identify LSPs which might block probe payments. In that case, fees are
494
// manually calculated and added to the probed fee estimation up until the LSP
495
// node. If the route hints don't indicate an LSP, they are passed as arguments
496
// to the SendPayment_V2 method, which enable it to send probe payments to the
497
// payment request destination.
498
func (s *Server) probePaymentRequest(ctx context.Context, paymentRequest string,
499
        timeout uint32) (*RouteFeeResponse, error) {
3✔
500

3✔
501
        payReq, err := zpay32.Decode(
3✔
502
                paymentRequest, s.cfg.RouterBackend.ActiveNetParams,
3✔
503
        )
3✔
504
        if err != nil {
3✔
505
                return nil, err
×
506
        }
×
507

508
        if *payReq.MilliSat <= 0 {
3✔
509
                return nil, errors.New("payment request amount must be " +
×
510
                        "greater than 0")
×
511
        }
×
512

513
        // Generate random payment hash, so we can be sure that the target of
514
        // the probe payment doesn't have the preimage to settle the htlc.
515
        var paymentHash lntypes.Hash
3✔
516
        _, err = crand.Read(paymentHash[:])
3✔
517
        if err != nil {
3✔
518
                return nil, fmt.Errorf("cannot generate random probe "+
×
519
                        "preimage: %w", err)
×
520
        }
×
521

522
        amtMsat := int64(*payReq.MilliSat)
3✔
523
        probeRequest := &SendPaymentRequest{
3✔
524
                TimeoutSeconds:   int32(timeout),
3✔
525
                Dest:             payReq.Destination.SerializeCompressed(),
3✔
526
                MaxParts:         1,
3✔
527
                AllowSelfPayment: false,
3✔
528
                AmtMsat:          amtMsat,
3✔
529
                PaymentHash:      paymentHash[:],
3✔
530
                FeeLimitSat:      routeFeeLimitSat,
3✔
531
                FinalCltvDelta:   int32(payReq.MinFinalCLTVExpiry()),
3✔
532
                DestFeatures:     MarshalFeatures(payReq.Features),
3✔
533
        }
3✔
534

3✔
535
        // If the payment addresses is specified, then we'll also populate that
3✔
536
        // now as well.
3✔
537
        payReq.PaymentAddr.WhenSome(func(addr [32]byte) {
6✔
538
                copy(probeRequest.PaymentAddr, addr[:])
3✔
539
        })
3✔
540

541
        hints := payReq.RouteHints
3✔
542

3✔
543
        // If the hints don't indicate an LSP then chances are that our probe
3✔
544
        // payment won't be blocked along the route to the destination. We send
3✔
545
        // a probe payment with unmodified route hints.
3✔
546
        if !isLSP(hints) {
6✔
547
                probeRequest.RouteHints = invoicesrpc.CreateRPCRouteHints(hints)
3✔
548
                return s.sendProbePayment(ctx, probeRequest)
3✔
549
        }
3✔
550

551
        // If the heuristic indicates an LSP we modify the route hints to allow
552
        // probing the LSP.
553
        lspAdjustedRouteHints, lspHint, err := prepareLspRouteHints(
3✔
554
                hints, *payReq.MilliSat,
3✔
555
        )
3✔
556
        if err != nil {
3✔
557
                return nil, err
×
558
        }
×
559

560
        // The adjusted route hints serve the payment probe to find the last
561
        // public hop to the LSP on the route.
562
        probeRequest.Dest = lspHint.NodeID.SerializeCompressed()
3✔
563
        if len(lspAdjustedRouteHints) > 0 {
3✔
564
                probeRequest.RouteHints = invoicesrpc.CreateRPCRouteHints(
×
565
                        lspAdjustedRouteHints,
×
566
                )
×
567
        }
×
568

569
        // The payment probe will be able to calculate the fee up until the LSP
570
        // node. The fee of the last hop has to be calculated manually. Since
571
        // the last hop's fee amount has to be sent across the payment path we
572
        // have to add it to the original payment amount. Only then will the
573
        // payment probe be able to determine the correct fee to the last hop
574
        // prior to the private destination. For example, if the user wants to
575
        // send 1000 sats to a private destination and the last hop's fee is 10
576
        // sats, then 1010 sats will have to arrive at the last hop. This means
577
        // that the probe has to be dispatched with 1010 sats to correctly
578
        // calculate the routing fee.
579
        //
580
        // Calculate the hop fee for the last hop manually.
581
        hopFee := lspHint.HopFee(*payReq.MilliSat)
3✔
582
        if err != nil {
3✔
583
                return nil, err
×
584
        }
×
585

586
        // Add the last hop's fee to the requested payment amount that we want
587
        // to get an estimate for.
588
        probeRequest.AmtMsat += int64(hopFee)
3✔
589

3✔
590
        // Use the hop hint's cltv delta as the payment request's final cltv
3✔
591
        // delta. The actual final cltv delta of the invoice will be added to
3✔
592
        // the payment probe's cltv delta.
3✔
593
        probeRequest.FinalCltvDelta = int32(lspHint.CLTVExpiryDelta)
3✔
594

3✔
595
        // Dispatch the payment probe with adjusted fee amount.
3✔
596
        resp, err := s.sendProbePayment(ctx, probeRequest)
3✔
597
        if err != nil {
3✔
598
                return nil, err
×
599
        }
×
600

601
        // If the payment probe failed we only return the failure reason and
602
        // leave the probe result params unaltered.
603
        if resp.FailureReason != lnrpc.PaymentFailureReason_FAILURE_REASON_NONE { //nolint:ll
3✔
604
                return resp, nil
×
605
        }
×
606

607
        // The probe succeeded, so we can add the last hop's fee to fee the
608
        // payment probe returned.
609
        resp.RoutingFeeMsat += int64(hopFee)
3✔
610

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

3✔
615
        return resp, nil
3✔
616
}
617

618
// isLSP checks if the route hints indicate an LSP. An LSP is indicated with
619
// true if the last node in each route hint has the same node id, false
620
// otherwise.
621
func isLSP(routeHints [][]zpay32.HopHint) bool {
3✔
622
        if len(routeHints) == 0 || len(routeHints[0]) == 0 {
6✔
623
                return false
3✔
624
        }
3✔
625

626
        refNodeID := routeHints[0][len(routeHints[0])-1].NodeID
3✔
627
        for i := 1; i < len(routeHints); i++ {
6✔
628
                // Skip empty route hints.
3✔
629
                if len(routeHints[i]) == 0 {
3✔
630
                        continue
×
631
                }
632

633
                lastHop := routeHints[i][len(routeHints[i])-1]
3✔
634
                idMatchesRefNode := bytes.Equal(
3✔
635
                        lastHop.NodeID.SerializeCompressed(),
3✔
636
                        refNodeID.SerializeCompressed(),
3✔
637
                )
3✔
638
                if !idMatchesRefNode {
6✔
639
                        return false
3✔
640
                }
3✔
641
        }
642

643
        return true
3✔
644
}
645

646
// prepareLspRouteHints assumes that the isLsp heuristic returned true for the
647
// route hints passed in here. It constructs a modified list of route hints that
648
// allows the caller to probe the LSP, which itself is returned as a separate
649
// hop hint.
650
func prepareLspRouteHints(routeHints [][]zpay32.HopHint,
651
        amt lnwire.MilliSatoshi) ([][]zpay32.HopHint, *zpay32.HopHint, error) {
3✔
652

3✔
653
        if len(routeHints) == 0 {
3✔
654
                return nil, nil, fmt.Errorf("no route hints provided")
×
655
        }
×
656

657
        // Create the LSP hop hint. We are probing for the worst case fee and
658
        // cltv delta. So we look for the max values amongst all LSP hop hints.
659
        refHint := routeHints[0][len(routeHints[0])-1]
3✔
660
        refHint.CLTVExpiryDelta = maxLspCltvDelta(routeHints)
3✔
661
        refHint.FeeBaseMSat, refHint.FeeProportionalMillionths = maxLspFee(
3✔
662
                routeHints, amt,
3✔
663
        )
3✔
664

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

3✔
669
        // Strip off the LSP hop hint from all route hints.
3✔
670
        for i := 0; i < len(routeHints); i++ {
6✔
671
                hint := routeHints[i]
3✔
672
                if len(hint) > 1 {
3✔
673
                        adjustedHints = append(
×
674
                                adjustedHints, hint[:len(hint)-1],
×
675
                        )
×
676
                }
×
677
        }
678

679
        return adjustedHints, &refHint, nil
3✔
680
}
681

682
// maxLspFee returns base fee and fee rate amongst all LSP route hints that
683
// results in the overall highest fee for the given amount.
684
func maxLspFee(routeHints [][]zpay32.HopHint, amt lnwire.MilliSatoshi) (uint32,
685
        uint32) {
3✔
686

3✔
687
        var maxFeePpm uint32
3✔
688
        var maxBaseFee uint32
3✔
689
        var maxTotalFee lnwire.MilliSatoshi
3✔
690
        for _, rh := range routeHints {
6✔
691
                lastHop := rh[len(rh)-1]
3✔
692
                lastHopFee := lastHop.HopFee(amt)
3✔
693
                if lastHopFee > maxTotalFee {
6✔
694
                        maxTotalFee = lastHopFee
3✔
695
                        maxBaseFee = lastHop.FeeBaseMSat
3✔
696
                        maxFeePpm = lastHop.FeeProportionalMillionths
3✔
697
                }
3✔
698
        }
699

700
        return maxBaseFee, maxFeePpm
3✔
701
}
702

703
// maxLspCltvDelta returns the maximum cltv delta amongst all LSP route hints.
704
func maxLspCltvDelta(routeHints [][]zpay32.HopHint) uint16 {
3✔
705
        var maxCltvDelta uint16
3✔
706
        for _, rh := range routeHints {
6✔
707
                rhLastHop := rh[len(rh)-1]
3✔
708
                if rhLastHop.CLTVExpiryDelta > maxCltvDelta {
6✔
709
                        maxCltvDelta = rhLastHop.CLTVExpiryDelta
3✔
710
                }
3✔
711
        }
712

713
        return maxCltvDelta
3✔
714
}
715

716
// probePaymentStream is a custom implementation of the grpc.ServerStream
717
// interface. It is used to send payment status updates to the caller on the
718
// stream channel.
719
type probePaymentStream struct {
720
        Router_SendPaymentV2Server
721

722
        stream chan *lnrpc.Payment
723
        ctx    context.Context //nolint:containedctx
724
}
725

726
// Send sends a payment status update to a payment stream that the caller can
727
// evaluate.
728
func (p *probePaymentStream) Send(response *lnrpc.Payment) error {
3✔
729
        select {
3✔
730
        case p.stream <- response:
3✔
731

732
        case <-p.ctx.Done():
×
733
                return p.ctx.Err()
×
734
        }
735

736
        return nil
3✔
737
}
738

739
// Context returns the context of the stream.
740
func (p *probePaymentStream) Context() context.Context {
3✔
741
        return p.ctx
3✔
742
}
3✔
743

744
// sendProbePayment sends a payment to a target node in order to obtain
745
// potential routing fees for it. The payment request has to contain a payment
746
// hash that is guaranteed to be unknown to the target node, so it cannot settle
747
// the payment. This method invokes a payment request loop in a goroutine and
748
// awaits payment status updates.
749
func (s *Server) sendProbePayment(ctx context.Context,
750
        req *SendPaymentRequest) (*RouteFeeResponse, error) {
3✔
751

3✔
752
        // We'll launch a goroutine to send the payment probes.
3✔
753
        errChan := make(chan error, 1)
3✔
754
        defer close(errChan)
3✔
755

3✔
756
        paymentStream := &probePaymentStream{
3✔
757
                stream: make(chan *lnrpc.Payment),
3✔
758
                ctx:    ctx,
3✔
759
        }
3✔
760
        go func() {
6✔
761
                err := s.SendPaymentV2(req, paymentStream)
3✔
762
                if err != nil {
3✔
763
                        select {
×
764
                        case errChan <- err:
×
765

766
                        case <-paymentStream.ctx.Done():
×
767
                                return
×
768
                        }
769
                }
770
        }()
771

772
        for {
6✔
773
                select {
3✔
774
                case payment := <-paymentStream.stream:
3✔
775
                        switch payment.Status {
3✔
776
                        case lnrpc.Payment_INITIATED:
×
777
                        case lnrpc.Payment_IN_FLIGHT:
3✔
778
                        case lnrpc.Payment_SUCCEEDED:
×
779
                                return nil, errors.New("warning, the fee " +
×
780
                                        "estimation payment probe " +
×
781
                                        "unexpectedly succeeded. Please reach" +
×
782
                                        "out to the probe destination to " +
×
783
                                        "negotiate a refund. Otherwise the " +
×
784
                                        "payment probe amount is lost forever")
×
785

786
                        case lnrpc.Payment_FAILED:
3✔
787
                                // Incorrect payment details point to a
3✔
788
                                // successful probe.
3✔
789
                                //nolint:ll
3✔
790
                                if payment.FailureReason == lnrpc.PaymentFailureReason_FAILURE_REASON_INCORRECT_PAYMENT_DETAILS {
6✔
791
                                        return paymentDetails(payment)
3✔
792
                                }
3✔
793

794
                                return &RouteFeeResponse{
3✔
795
                                        RoutingFeeMsat: 0,
3✔
796
                                        TimeLockDelay:  0,
3✔
797
                                        FailureReason:  payment.FailureReason,
3✔
798
                                }, nil
3✔
799

800
                        default:
×
801
                                return nil, errors.New("unexpected payment " +
×
802
                                        "status")
×
803
                        }
804

805
                case err := <-errChan:
×
806
                        return nil, err
×
807

808
                case <-s.quit:
×
809
                        return nil, errServerShuttingDown
×
810
                }
811
        }
812
}
813

814
func paymentDetails(payment *lnrpc.Payment) (*RouteFeeResponse, error) {
3✔
815
        fee, timeLock, err := timelockAndFee(payment)
3✔
816
        if errors.Is(err, errUnexpectedFailureSource) {
3✔
817
                return nil, err
×
818
        }
×
819

820
        return &RouteFeeResponse{
3✔
821
                RoutingFeeMsat: fee,
3✔
822
                TimeLockDelay:  timeLock,
3✔
823
                FailureReason:  lnrpc.PaymentFailureReason_FAILURE_REASON_NONE,
3✔
824
        }, nil
3✔
825
}
826

827
// timelockAndFee returns the fee and total time lock of the last payment
828
// attempt.
829
func timelockAndFee(p *lnrpc.Payment) (int64, int64, error) {
3✔
830
        if len(p.Htlcs) == 0 {
3✔
831
                return 0, 0, nil
×
832
        }
×
833

834
        lastAttempt := p.Htlcs[len(p.Htlcs)-1]
3✔
835
        if lastAttempt == nil {
3✔
836
                return 0, 0, errMissingPaymentAttempt
×
837
        }
×
838

839
        lastRoute := lastAttempt.Route
3✔
840
        if lastRoute == nil {
3✔
841
                return 0, 0, errMissingRoute
×
842
        }
×
843

844
        hopFailureIndex := lastAttempt.Failure.FailureSourceIndex
3✔
845
        finalHopIndex := uint32(len(lastRoute.Hops))
3✔
846
        if hopFailureIndex != finalHopIndex {
3✔
847
                return 0, 0, errUnexpectedFailureSource
×
848
        }
×
849

850
        return lastRoute.TotalFeesMsat, int64(lastRoute.TotalTimeLock), nil
3✔
851
}
852

853
// SendToRouteV2 sends a payment through a predefined route. The response of
854
// this call contains structured error information.
855
func (s *Server) SendToRouteV2(ctx context.Context,
856
        req *SendToRouteRequest) (*lnrpc.HTLCAttempt, error) {
3✔
857

3✔
858
        if req.Route == nil {
3✔
859
                return nil, fmt.Errorf("unable to send, no routes provided")
×
860
        }
×
861

862
        route, err := s.cfg.RouterBackend.UnmarshallRoute(req.Route)
3✔
863
        if err != nil {
3✔
864
                return nil, err
×
865
        }
×
866

867
        hash, err := lntypes.MakeHash(req.PaymentHash)
3✔
868
        if err != nil {
3✔
869
                return nil, err
×
870
        }
×
871

872
        firstHopRecords := lnwire.CustomRecords(req.FirstHopCustomRecords)
3✔
873
        if err := firstHopRecords.Validate(); err != nil {
3✔
874
                return nil, err
×
875
        }
×
876

877
        var attempt *channeldb.HTLCAttempt
3✔
878

3✔
879
        // Pass route to the router. This call returns the full htlc attempt
3✔
880
        // information as it is stored in the database. It is possible that both
3✔
881
        // the attempt return value and err are non-nil. This can happen when
3✔
882
        // the attempt was already initiated before the error happened. In that
3✔
883
        // case, we give precedence to the attempt information as stored in the
3✔
884
        // db.
3✔
885
        if req.SkipTempErr {
3✔
886
                attempt, err = s.cfg.Router.SendToRouteSkipTempErr(
×
887
                        hash, route, firstHopRecords,
×
888
                )
×
889
        } else {
3✔
890
                attempt, err = s.cfg.Router.SendToRoute(
3✔
891
                        hash, route, firstHopRecords,
3✔
892
                )
3✔
893
        }
3✔
894
        if attempt != nil {
6✔
895
                rpcAttempt, err := s.cfg.RouterBackend.MarshalHTLCAttempt(
3✔
896
                        *attempt,
3✔
897
                )
3✔
898
                if err != nil {
3✔
899
                        return nil, err
×
900
                }
×
901
                return rpcAttempt, nil
3✔
902
        }
903

904
        // Transform user errors to grpc code.
905
        switch {
×
906
        case errors.Is(err, channeldb.ErrPaymentExists):
×
907
                fallthrough
×
908

909
        case errors.Is(err, channeldb.ErrPaymentInFlight):
×
910
                fallthrough
×
911

912
        case errors.Is(err, channeldb.ErrAlreadyPaid):
×
913
                return nil, status.Error(
×
914
                        codes.AlreadyExists, err.Error(),
×
915
                )
×
916
        }
917

918
        return nil, err
×
919
}
920

921
// ResetMissionControl clears all mission control state and starts with a clean
922
// slate.
923
func (s *Server) ResetMissionControl(ctx context.Context,
924
        req *ResetMissionControlRequest) (*ResetMissionControlResponse, error) {
3✔
925

3✔
926
        err := s.cfg.RouterBackend.MissionControl.ResetHistory()
3✔
927
        if err != nil {
3✔
928
                return nil, err
×
929
        }
×
930

931
        return &ResetMissionControlResponse{}, nil
3✔
932
}
933

934
// GetMissionControlConfig returns our current mission control config.
935
func (s *Server) GetMissionControlConfig(ctx context.Context,
936
        req *GetMissionControlConfigRequest) (*GetMissionControlConfigResponse,
937
        error) {
3✔
938

3✔
939
        // Query the current mission control config.
3✔
940
        cfg := s.cfg.RouterBackend.MissionControl.GetConfig()
3✔
941
        resp := &GetMissionControlConfigResponse{
3✔
942
                Config: &MissionControlConfig{
3✔
943
                        MaximumPaymentResults: uint32(cfg.MaxMcHistory),
3✔
944
                        MinimumFailureRelaxInterval: uint64(
3✔
945
                                cfg.MinFailureRelaxInterval.Seconds(),
3✔
946
                        ),
3✔
947
                },
3✔
948
        }
3✔
949

3✔
950
        // We only populate fields based on the current estimator.
3✔
951
        switch v := cfg.Estimator.Config().(type) {
3✔
952
        case routing.AprioriConfig:
3✔
953
                resp.Config.Model = MissionControlConfig_APRIORI
3✔
954
                aCfg := AprioriParameters{
3✔
955
                        HalfLifeSeconds:  uint64(v.PenaltyHalfLife.Seconds()),
3✔
956
                        HopProbability:   v.AprioriHopProbability,
3✔
957
                        Weight:           v.AprioriWeight,
3✔
958
                        CapacityFraction: v.CapacityFraction,
3✔
959
                }
3✔
960

3✔
961
                // Populate deprecated fields.
3✔
962
                resp.Config.HalfLifeSeconds = uint64(
3✔
963
                        v.PenaltyHalfLife.Seconds(),
3✔
964
                )
3✔
965
                resp.Config.HopProbability = float32(v.AprioriHopProbability)
3✔
966
                resp.Config.Weight = float32(v.AprioriWeight)
3✔
967

3✔
968
                resp.Config.EstimatorConfig = &MissionControlConfig_Apriori{
3✔
969
                        Apriori: &aCfg,
3✔
970
                }
3✔
971

972
        case routing.BimodalConfig:
3✔
973
                resp.Config.Model = MissionControlConfig_BIMODAL
3✔
974
                bCfg := BimodalParameters{
3✔
975
                        NodeWeight: v.BimodalNodeWeight,
3✔
976
                        ScaleMsat:  uint64(v.BimodalScaleMsat),
3✔
977
                        DecayTime:  uint64(v.BimodalDecayTime.Seconds()),
3✔
978
                }
3✔
979

3✔
980
                resp.Config.EstimatorConfig = &MissionControlConfig_Bimodal{
3✔
981
                        Bimodal: &bCfg,
3✔
982
                }
3✔
983

984
        default:
×
985
                return nil, fmt.Errorf("unknown estimator config type %T", v)
×
986
        }
987

988
        return resp, nil
3✔
989
}
990

991
// SetMissionControlConfig sets parameters in the mission control config.
992
func (s *Server) SetMissionControlConfig(ctx context.Context,
993
        req *SetMissionControlConfigRequest) (*SetMissionControlConfigResponse,
994
        error) {
3✔
995

3✔
996
        mcCfg := &routing.MissionControlConfig{
3✔
997
                MaxMcHistory: int(req.Config.MaximumPaymentResults),
3✔
998
                MinFailureRelaxInterval: time.Duration(
3✔
999
                        req.Config.MinimumFailureRelaxInterval,
3✔
1000
                ) * time.Second,
3✔
1001
        }
3✔
1002

3✔
1003
        switch req.Config.Model {
3✔
1004
        case MissionControlConfig_APRIORI:
3✔
1005
                var aprioriConfig routing.AprioriConfig
3✔
1006

3✔
1007
                // Determine the apriori config with backward compatibility
3✔
1008
                // should the api use deprecated fields.
3✔
1009
                switch v := req.Config.EstimatorConfig.(type) {
3✔
1010
                case *MissionControlConfig_Bimodal:
3✔
1011
                        return nil, fmt.Errorf("bimodal config " +
3✔
1012
                                "provided, but apriori model requested")
3✔
1013

1014
                case *MissionControlConfig_Apriori:
3✔
1015
                        aprioriConfig = routing.AprioriConfig{
3✔
1016
                                PenaltyHalfLife: time.Duration(
3✔
1017
                                        v.Apriori.HalfLifeSeconds,
3✔
1018
                                ) * time.Second,
3✔
1019
                                AprioriHopProbability: v.Apriori.HopProbability,
3✔
1020
                                AprioriWeight:         v.Apriori.Weight,
3✔
1021
                                CapacityFraction: v.Apriori.
3✔
1022
                                        CapacityFraction,
3✔
1023
                        }
3✔
1024

1025
                default:
3✔
1026
                        aprioriConfig = routing.AprioriConfig{
3✔
1027
                                PenaltyHalfLife: time.Duration(
3✔
1028
                                        int64(req.Config.HalfLifeSeconds),
3✔
1029
                                ) * time.Second,
3✔
1030
                                AprioriHopProbability: float64(
3✔
1031
                                        req.Config.HopProbability,
3✔
1032
                                ),
3✔
1033
                                AprioriWeight:    float64(req.Config.Weight),
3✔
1034
                                CapacityFraction: routing.DefaultCapacityFraction, //nolint:ll
3✔
1035
                        }
3✔
1036
                }
1037

1038
                estimator, err := routing.NewAprioriEstimator(aprioriConfig)
3✔
1039
                if err != nil {
3✔
1040
                        return nil, err
×
1041
                }
×
1042
                mcCfg.Estimator = estimator
3✔
1043

1044
        case MissionControlConfig_BIMODAL:
3✔
1045
                cfg, ok := req.Config.
3✔
1046
                        EstimatorConfig.(*MissionControlConfig_Bimodal)
3✔
1047
                if !ok {
3✔
1048
                        return nil, fmt.Errorf("bimodal estimator requested " +
×
1049
                                "but corresponding config not set")
×
1050
                }
×
1051
                bCfg := cfg.Bimodal
3✔
1052

3✔
1053
                bimodalConfig := routing.BimodalConfig{
3✔
1054
                        BimodalDecayTime: time.Duration(
3✔
1055
                                bCfg.DecayTime,
3✔
1056
                        ) * time.Second,
3✔
1057
                        BimodalScaleMsat:  lnwire.MilliSatoshi(bCfg.ScaleMsat),
3✔
1058
                        BimodalNodeWeight: bCfg.NodeWeight,
3✔
1059
                }
3✔
1060

3✔
1061
                estimator, err := routing.NewBimodalEstimator(bimodalConfig)
3✔
1062
                if err != nil {
3✔
1063
                        return nil, err
×
1064
                }
×
1065
                mcCfg.Estimator = estimator
3✔
1066

1067
        default:
×
1068
                return nil, fmt.Errorf("unknown estimator type %v",
×
1069
                        req.Config.Model)
×
1070
        }
1071

1072
        return &SetMissionControlConfigResponse{},
3✔
1073
                s.cfg.RouterBackend.MissionControl.SetConfig(mcCfg)
3✔
1074
}
1075

1076
// QueryMissionControl exposes the internal mission control state to callers. It
1077
// is a development feature.
1078
func (s *Server) QueryMissionControl(_ context.Context,
1079
        _ *QueryMissionControlRequest) (*QueryMissionControlResponse, error) {
×
1080

×
1081
        snapshot := s.cfg.RouterBackend.MissionControl.GetHistorySnapshot()
×
1082

×
1083
        rpcPairs := make([]*PairHistory, 0, len(snapshot.Pairs))
×
1084
        for _, p := range snapshot.Pairs {
×
1085
                // Prevent binding to loop variable.
×
1086
                pair := p
×
1087

×
1088
                rpcPair := PairHistory{
×
1089
                        NodeFrom: pair.Pair.From[:],
×
1090
                        NodeTo:   pair.Pair.To[:],
×
1091
                        History:  toRPCPairData(&pair.TimedPairResult),
×
1092
                }
×
1093

×
1094
                rpcPairs = append(rpcPairs, &rpcPair)
×
1095
        }
×
1096

1097
        response := QueryMissionControlResponse{
×
1098
                Pairs: rpcPairs,
×
1099
        }
×
1100

×
1101
        return &response, nil
×
1102
}
1103

1104
// toRPCPairData marshalls mission control pair data to the rpc struct.
1105
func toRPCPairData(data *routing.TimedPairResult) *PairData {
3✔
1106
        rpcData := PairData{
3✔
1107
                FailAmtSat:     int64(data.FailAmt.ToSatoshis()),
3✔
1108
                FailAmtMsat:    int64(data.FailAmt),
3✔
1109
                SuccessAmtSat:  int64(data.SuccessAmt.ToSatoshis()),
3✔
1110
                SuccessAmtMsat: int64(data.SuccessAmt),
3✔
1111
        }
3✔
1112

3✔
1113
        if !data.FailTime.IsZero() {
6✔
1114
                rpcData.FailTime = data.FailTime.Unix()
3✔
1115
        }
3✔
1116

1117
        if !data.SuccessTime.IsZero() {
3✔
1118
                rpcData.SuccessTime = data.SuccessTime.Unix()
×
1119
        }
×
1120

1121
        return &rpcData
3✔
1122
}
1123

1124
// XImportMissionControl imports the state provided to our internal mission
1125
// control. Only entries that are fresher than our existing state will be used.
1126
func (s *Server) XImportMissionControl(_ context.Context,
1127
        req *XImportMissionControlRequest) (*XImportMissionControlResponse,
1128
        error) {
3✔
1129

3✔
1130
        if len(req.Pairs) == 0 {
3✔
1131
                return nil, errors.New("at least one pair required for import")
×
1132
        }
×
1133

1134
        snapshot := &routing.MissionControlSnapshot{
3✔
1135
                Pairs: make(
3✔
1136
                        []routing.MissionControlPairSnapshot, len(req.Pairs),
3✔
1137
                ),
3✔
1138
        }
3✔
1139

3✔
1140
        for i, pairResult := range req.Pairs {
6✔
1141
                pairSnapshot, err := toPairSnapshot(pairResult)
3✔
1142
                if err != nil {
6✔
1143
                        return nil, err
3✔
1144
                }
3✔
1145

1146
                snapshot.Pairs[i] = *pairSnapshot
3✔
1147
        }
1148

1149
        err := s.cfg.RouterBackend.MissionControl.ImportHistory(
3✔
1150
                snapshot, req.Force,
3✔
1151
        )
3✔
1152
        if err != nil {
3✔
1153
                return nil, err
×
1154
        }
×
1155

1156
        return &XImportMissionControlResponse{}, nil
3✔
1157
}
1158

1159
func toPairSnapshot(pairResult *PairHistory) (*routing.MissionControlPairSnapshot,
1160
        error) {
3✔
1161

3✔
1162
        from, err := route.NewVertexFromBytes(pairResult.NodeFrom)
3✔
1163
        if err != nil {
3✔
1164
                return nil, err
×
1165
        }
×
1166

1167
        to, err := route.NewVertexFromBytes(pairResult.NodeTo)
3✔
1168
        if err != nil {
3✔
1169
                return nil, err
×
1170
        }
×
1171

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

3✔
1174
        if from == to {
3✔
1175
                return nil, fmt.Errorf("%v source and destination node must "+
×
1176
                        "differ", pairPrefix)
×
1177
        }
×
1178

1179
        failAmt, failTime, err := getPair(
3✔
1180
                lnwire.MilliSatoshi(pairResult.History.FailAmtMsat),
3✔
1181
                btcutil.Amount(pairResult.History.FailAmtSat),
3✔
1182
                pairResult.History.FailTime,
3✔
1183
                true,
3✔
1184
        )
3✔
1185
        if err != nil {
6✔
1186
                return nil, fmt.Errorf("%v invalid failure: %w", pairPrefix,
3✔
1187
                        err)
3✔
1188
        }
3✔
1189

1190
        successAmt, successTime, err := getPair(
3✔
1191
                lnwire.MilliSatoshi(pairResult.History.SuccessAmtMsat),
3✔
1192
                btcutil.Amount(pairResult.History.SuccessAmtSat),
3✔
1193
                pairResult.History.SuccessTime,
3✔
1194
                false,
3✔
1195
        )
3✔
1196
        if err != nil {
3✔
1197
                return nil, fmt.Errorf("%v invalid success: %w", pairPrefix,
×
1198
                        err)
×
1199
        }
×
1200

1201
        if successAmt == 0 && failAmt == 0 {
3✔
1202
                return nil, fmt.Errorf("%v: either success or failure result "+
×
1203
                        "required", pairPrefix)
×
1204
        }
×
1205

1206
        pair := routing.NewDirectedNodePair(from, to)
3✔
1207

3✔
1208
        result := &routing.TimedPairResult{
3✔
1209
                FailAmt:     failAmt,
3✔
1210
                FailTime:    failTime,
3✔
1211
                SuccessAmt:  successAmt,
3✔
1212
                SuccessTime: successTime,
3✔
1213
        }
3✔
1214

3✔
1215
        return &routing.MissionControlPairSnapshot{
3✔
1216
                Pair:            pair,
3✔
1217
                TimedPairResult: *result,
3✔
1218
        }, nil
3✔
1219
}
1220

1221
// getPair validates the values provided for a mission control result and
1222
// returns the msat amount and timestamp for it. `isFailure` can be used to
1223
// default values to 0 instead of returning an error.
1224
func getPair(amtMsat lnwire.MilliSatoshi, amtSat btcutil.Amount,
1225
        timestamp int64, isFailure bool) (lnwire.MilliSatoshi, time.Time,
1226
        error) {
3✔
1227

3✔
1228
        amt, err := getMsatPairValue(amtMsat, amtSat)
3✔
1229
        if err != nil {
6✔
1230
                return 0, time.Time{}, err
3✔
1231
        }
3✔
1232

1233
        var (
3✔
1234
                timeSet   = timestamp != 0
3✔
1235
                amountSet = amt != 0
3✔
1236
        )
3✔
1237

3✔
1238
        switch {
3✔
1239
        // If a timestamp and amount if provided, return those values.
1240
        case timeSet && amountSet:
3✔
1241
                return amt, time.Unix(timestamp, 0), nil
3✔
1242

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

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

1255
        default:
3✔
1256
                return 0, time.Time{}, nil
3✔
1257
        }
1258
}
1259

1260
// getMsatPairValue checks the msat and sat values set for a pair and ensures
1261
// that the values provided are either the same, or only a single value is set.
1262
func getMsatPairValue(msatValue lnwire.MilliSatoshi,
1263
        satValue btcutil.Amount) (lnwire.MilliSatoshi, error) {
3✔
1264

3✔
1265
        // If our msat value converted to sats equals our sat value, we just
3✔
1266
        // return the msat value, since the values are the same.
3✔
1267
        if msatValue.ToSatoshis() == satValue {
6✔
1268
                return msatValue, nil
3✔
1269
        }
3✔
1270

1271
        // If we have no msatValue, we can just return our state value even if
1272
        // it is zero, because it's impossible that we have mismatched values.
1273
        if msatValue == 0 {
3✔
1274
                return lnwire.MilliSatoshi(satValue * 1000), nil
×
1275
        }
×
1276

1277
        // Likewise, we can just use msat value if we have no sat value set.
1278
        if satValue == 0 {
3✔
1279
                return msatValue, nil
×
1280
        }
×
1281

1282
        // If our values are non-zero but not equal, we have invalid amounts
1283
        // set, so we fail.
1284
        return 0, fmt.Errorf("msat: %v and sat: %v values not equal", msatValue,
3✔
1285
                satValue)
3✔
1286
}
1287

1288
// TrackPaymentV2 returns a stream of payment state updates. The stream is
1289
// closed when the payment completes.
1290
func (s *Server) TrackPaymentV2(request *TrackPaymentRequest,
1291
        stream Router_TrackPaymentV2Server) error {
3✔
1292

3✔
1293
        payHash, err := lntypes.MakeHash(request.PaymentHash)
3✔
1294
        if err != nil {
3✔
1295
                return err
×
1296
        }
×
1297

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

3✔
1300
        // Make the subscription.
3✔
1301
        sub, err := s.subscribePayment(payHash)
3✔
1302
        if err != nil {
3✔
1303
                return err
×
1304
        }
×
1305

1306
        return s.trackPayment(sub, payHash, stream, request.NoInflightUpdates)
3✔
1307
}
1308

1309
// subscribePayment subscribes to the payment updates for the given payment
1310
// hash.
1311
func (s *Server) subscribePayment(identifier lntypes.Hash) (
1312
        routing.ControlTowerSubscriber, error) {
3✔
1313

3✔
1314
        // Make the subscription.
3✔
1315
        router := s.cfg.RouterBackend
3✔
1316
        sub, err := router.Tower.SubscribePayment(identifier)
3✔
1317

3✔
1318
        switch {
3✔
1319
        case errors.Is(err, channeldb.ErrPaymentNotInitiated):
×
1320
                return nil, status.Error(codes.NotFound, err.Error())
×
1321

1322
        case err != nil:
×
1323
                return nil, err
×
1324
        }
1325

1326
        return sub, nil
3✔
1327
}
1328

1329
// trackPayment writes payment status updates to the provided stream.
1330
func (s *Server) trackPayment(subscription routing.ControlTowerSubscriber,
1331
        identifier lntypes.Hash, stream Router_TrackPaymentV2Server,
1332
        noInflightUpdates bool) error {
3✔
1333

3✔
1334
        err := s.trackPaymentStream(
3✔
1335
                stream.Context(), subscription, noInflightUpdates, stream.Send,
3✔
1336
        )
3✔
1337

3✔
1338
        // If the context is canceled, we don't return an error.
3✔
1339
        if errors.Is(err, context.Canceled) {
6✔
1340
                log.Infof("Payment stream %v canceled", identifier)
3✔
1341

3✔
1342
                return nil
3✔
1343
        }
3✔
1344

1345
        // Otherwise, we will log and return the error as the stream has
1346
        // received an error from the payment lifecycle.
1347
        if err != nil {
3✔
NEW
1348
                log.Errorf("TrackPayment got error for payment %v: %v",
×
NEW
1349
                        identifier, err)
×
NEW
1350
        }
×
1351

1352
        return err
3✔
1353
}
1354

1355
// TrackPayments returns a stream of payment state updates.
1356
func (s *Server) TrackPayments(request *TrackPaymentsRequest,
1357
        stream Router_TrackPaymentsServer) error {
3✔
1358

3✔
1359
        log.Debug("TrackPayments called")
3✔
1360

3✔
1361
        router := s.cfg.RouterBackend
3✔
1362

3✔
1363
        // Subscribe to payments.
3✔
1364
        subscription, err := router.Tower.SubscribeAllPayments()
3✔
1365
        if err != nil {
3✔
1366
                return err
×
1367
        }
×
1368

1369
        // Stream updates to the client.
1370
        err = s.trackPaymentStream(
3✔
1371
                stream.Context(), subscription, request.NoInflightUpdates,
3✔
1372
                stream.Send,
3✔
1373
        )
3✔
1374

3✔
1375
        if errors.Is(err, context.Canceled) {
6✔
1376
                log.Debugf("TrackPayments payment stream canceled.")
3✔
1377
        }
3✔
1378

1379
        return err
3✔
1380
}
1381

1382
// trackPaymentStream streams payment updates to the client.
1383
func (s *Server) trackPaymentStream(context context.Context,
1384
        subscription routing.ControlTowerSubscriber, noInflightUpdates bool,
1385
        send func(*lnrpc.Payment) error) error {
3✔
1386

3✔
1387
        defer subscription.Close()
3✔
1388

3✔
1389
        // Stream updates back to the client.
3✔
1390
        for {
6✔
1391
                select {
3✔
1392
                case item, ok := <-subscription.Updates():
3✔
1393
                        if !ok {
6✔
1394
                                // No more payment updates.
3✔
1395
                                return nil
3✔
1396
                        }
3✔
1397
                        result := item.(*channeldb.MPPayment)
3✔
1398

3✔
1399
                        log.Tracef("Payment %v updated to state %v",
3✔
1400
                                result.Info.PaymentIdentifier, result.Status)
3✔
1401

3✔
1402
                        // Skip in-flight updates unless requested.
3✔
1403
                        if noInflightUpdates {
3✔
1404
                                if result.Status == channeldb.StatusInitiated {
×
1405
                                        continue
×
1406
                                }
1407
                                if result.Status == channeldb.StatusInFlight {
×
1408
                                        continue
×
1409
                                }
1410
                        }
1411

1412
                        rpcPayment, err := s.cfg.RouterBackend.MarshallPayment(
3✔
1413
                                result,
3✔
1414
                        )
3✔
1415
                        if err != nil {
3✔
1416
                                return err
×
1417
                        }
×
1418

1419
                        // Send event to the client.
1420
                        err = send(rpcPayment)
3✔
1421
                        if err != nil {
3✔
1422
                                return err
×
1423
                        }
×
1424

1425
                case <-s.quit:
×
1426
                        return errServerShuttingDown
×
1427

1428
                case <-context.Done():
3✔
1429
                        return context.Err()
3✔
1430
                }
1431
        }
1432
}
1433

1434
// BuildRoute builds a route from a list of hop addresses.
1435
func (s *Server) BuildRoute(_ context.Context,
1436
        req *BuildRouteRequest) (*BuildRouteResponse, error) {
3✔
1437

3✔
1438
        if len(req.HopPubkeys) == 0 {
3✔
1439
                return nil, errors.New("no hops specified")
×
1440
        }
×
1441

1442
        // Unmarshall hop list.
1443
        hops := make([]route.Vertex, len(req.HopPubkeys))
3✔
1444
        for i, pubkeyBytes := range req.HopPubkeys {
6✔
1445
                pubkey, err := route.NewVertexFromBytes(pubkeyBytes)
3✔
1446
                if err != nil {
3✔
1447
                        return nil, err
×
1448
                }
×
1449
                hops[i] = pubkey
3✔
1450
        }
1451

1452
        // Prepare BuildRoute call parameters from rpc request.
1453
        var amt fn.Option[lnwire.MilliSatoshi]
3✔
1454
        if req.AmtMsat != 0 {
6✔
1455
                rpcAmt := lnwire.MilliSatoshi(req.AmtMsat)
3✔
1456
                amt = fn.Some(rpcAmt)
3✔
1457
        }
3✔
1458

1459
        var outgoingChan *uint64
3✔
1460
        if req.OutgoingChanId != 0 {
3✔
1461
                outgoingChan = &req.OutgoingChanId
×
1462
        }
×
1463

1464
        var payAddr fn.Option[[32]byte]
3✔
1465
        if len(req.PaymentAddr) != 0 {
6✔
1466
                var backingPayAddr [32]byte
3✔
1467
                copy(backingPayAddr[:], req.PaymentAddr)
3✔
1468

3✔
1469
                payAddr = fn.Some(backingPayAddr)
3✔
1470
        }
3✔
1471

1472
        if req.FinalCltvDelta == 0 {
3✔
1473
                req.FinalCltvDelta = int32(
×
1474
                        s.cfg.RouterBackend.DefaultFinalCltvDelta,
×
1475
                )
×
1476
        }
×
1477

1478
        var firstHopBlob fn.Option[[]byte]
3✔
1479
        if len(req.FirstHopCustomRecords) > 0 {
3✔
1480
                firstHopRecords := lnwire.CustomRecords(
×
1481
                        req.FirstHopCustomRecords,
×
1482
                )
×
1483
                if err := firstHopRecords.Validate(); err != nil {
×
1484
                        return nil, err
×
1485
                }
×
1486

1487
                firstHopData, err := firstHopRecords.Serialize()
×
1488
                if err != nil {
×
1489
                        return nil, err
×
1490
                }
×
1491
                firstHopBlob = fn.Some(firstHopData)
×
1492
        }
1493

1494
        // Build the route and return it to the caller.
1495
        route, err := s.cfg.Router.BuildRoute(
3✔
1496
                amt, hops, outgoingChan, req.FinalCltvDelta, payAddr,
3✔
1497
                firstHopBlob,
3✔
1498
        )
3✔
1499
        if err != nil {
3✔
1500
                return nil, err
×
1501
        }
×
1502

1503
        rpcRoute, err := s.cfg.RouterBackend.MarshallRoute(route)
3✔
1504
        if err != nil {
3✔
1505
                return nil, err
×
1506
        }
×
1507

1508
        routeResp := &BuildRouteResponse{
3✔
1509
                Route: rpcRoute,
3✔
1510
        }
3✔
1511

3✔
1512
        return routeResp, nil
3✔
1513
}
1514

1515
// SubscribeHtlcEvents creates a uni-directional stream from the server to
1516
// the client which delivers a stream of htlc events.
1517
func (s *Server) SubscribeHtlcEvents(_ *SubscribeHtlcEventsRequest,
1518
        stream Router_SubscribeHtlcEventsServer) error {
3✔
1519

3✔
1520
        htlcClient, err := s.cfg.RouterBackend.SubscribeHtlcEvents()
3✔
1521
        if err != nil {
3✔
1522
                return err
×
1523
        }
×
1524
        defer htlcClient.Cancel()
3✔
1525

3✔
1526
        // Send out an initial subscribed event so that the caller knows the
3✔
1527
        // point from which new events will be transmitted.
3✔
1528
        if err := stream.Send(&HtlcEvent{
3✔
1529
                Event: &HtlcEvent_SubscribedEvent{
3✔
1530
                        SubscribedEvent: &SubscribedEvent{},
3✔
1531
                },
3✔
1532
        }); err != nil {
3✔
1533
                return err
×
1534
        }
×
1535

1536
        for {
6✔
1537
                select {
3✔
1538
                case event := <-htlcClient.Updates():
3✔
1539
                        rpcEvent, err := rpcHtlcEvent(event)
3✔
1540
                        if err != nil {
3✔
1541
                                return err
×
1542
                        }
×
1543

1544
                        if err := stream.Send(rpcEvent); err != nil {
3✔
1545
                                return err
×
1546
                        }
×
1547

1548
                // If the stream's context is cancelled, return an error.
1549
                case <-stream.Context().Done():
3✔
1550
                        log.Debugf("htlc event stream cancelled")
3✔
1551
                        return stream.Context().Err()
3✔
1552

1553
                // If the subscribe client terminates, exit with an error.
1554
                case <-htlcClient.Quit():
×
1555
                        return errors.New("htlc event subscription terminated")
×
1556

1557
                // If the server has been signalled to shut down, exit.
1558
                case <-s.quit:
×
1559
                        return errServerShuttingDown
×
1560
                }
1561
        }
1562
}
1563

1564
// HtlcInterceptor is a bidirectional stream for streaming interception
1565
// requests to the caller.
1566
// Upon connection, it does the following:
1567
// 1. Check if there is already a live stream, if yes it rejects the request.
1568
// 2. Registered a ForwardInterceptor
1569
// 3. Delivers to the caller every √√ and detect his answer.
1570
// It uses a local implementation of holdForwardsStore to keep all the hold
1571
// forwards and find them when manual resolution is later needed.
1572
func (s *Server) HtlcInterceptor(stream Router_HtlcInterceptorServer) error {
3✔
1573
        // We ensure there is only one interceptor at a time.
3✔
1574
        if !atomic.CompareAndSwapInt32(&s.forwardInterceptorActive, 0, 1) {
3✔
1575
                return ErrInterceptorAlreadyExists
×
1576
        }
×
1577
        defer atomic.CompareAndSwapInt32(&s.forwardInterceptorActive, 1, 0)
3✔
1578

3✔
1579
        // Run the forward interceptor.
3✔
1580
        return newForwardInterceptor(
3✔
1581
                s.cfg.RouterBackend.InterceptableForwarder, stream,
3✔
1582
        ).run()
3✔
1583
}
1584

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

3✔
1594
        existingAliases := s.cfg.AliasMgr.ListAliases()
3✔
1595

3✔
1596
        // aliasExists checks if the new alias already exists in the alias map.
3✔
1597
        aliasExists := func(newAlias uint64,
3✔
1598
                baseScid lnwire.ShortChannelID) (bool, error) {
6✔
1599

3✔
1600
                // First check that we actually have a channel for the given
3✔
1601
                // base scid. This should succeed for any channel where the
3✔
1602
                // option-scid-alias feature bit was negotiated.
3✔
1603
                if _, ok := existingAliases[baseScid]; !ok {
3✔
1604
                        return false, fmt.Errorf("base scid %v not found",
×
1605
                                baseScid)
×
1606
                }
×
1607

1608
                for base, aliases := range existingAliases {
6✔
1609
                        for _, alias := range aliases {
6✔
1610
                                exists := alias.ToUint64() == newAlias
3✔
1611

3✔
1612
                                // Trying to add an alias that we already have
3✔
1613
                                // for another channel is wrong.
3✔
1614
                                if exists && base != baseScid {
3✔
1615
                                        return true, fmt.Errorf("%w: alias %v "+
×
1616
                                                "already exists for base scid "+
×
1617
                                                "%v", ErrAliasAlreadyExists,
×
1618
                                                alias, base)
×
1619
                                }
×
1620

1621
                                if exists {
6✔
1622
                                        return true, nil
3✔
1623
                                }
3✔
1624
                        }
1625
                }
1626

1627
                return false, nil
3✔
1628
        }
1629

1630
        for _, v := range in.AliasMaps {
6✔
1631
                baseScid := lnwire.NewShortChanIDFromInt(v.BaseScid)
3✔
1632

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

3✔
1637
                        // But we only add it, if it's a valid alias, as defined
3✔
1638
                        // by the BOLT spec.
3✔
1639
                        if !aliasmgr.IsAlias(aliasScid) {
6✔
1640
                                return nil, fmt.Errorf("%w: SCID alias %v is "+
3✔
1641
                                        "not a valid alias", ErrNoValidAlias,
3✔
1642
                                        aliasScid)
3✔
1643
                        }
3✔
1644

1645
                        exists, err := aliasExists(rpcAlias, baseScid)
3✔
1646
                        if err != nil {
3✔
1647
                                return nil, err
×
1648
                        }
×
1649

1650
                        // If the alias already exists, we see that as an error.
1651
                        // This is to avoid "silent" collisions.
1652
                        if exists {
6✔
1653
                                return nil, fmt.Errorf("%w: SCID alias %v "+
3✔
1654
                                        "already exists", ErrAliasAlreadyExists,
3✔
1655
                                        rpcAlias)
3✔
1656
                        }
3✔
1657

1658
                        err = s.cfg.AliasMgr.AddLocalAlias(
3✔
1659
                                aliasScid, baseScid, false, true,
3✔
1660
                        )
3✔
1661
                        if err != nil {
3✔
1662
                                return nil, fmt.Errorf("error adding scid "+
×
1663
                                        "alias, base_scid=%v, alias_scid=%v: "+
×
1664
                                        "%w", baseScid, aliasScid, err)
×
1665
                        }
×
1666
                }
1667
        }
1668

1669
        return &AddAliasesResponse{
3✔
1670
                AliasMaps: lnrpc.MarshalAliasMap(s.cfg.AliasMgr.ListAliases()),
3✔
1671
        }, nil
3✔
1672
}
1673

1674
// XDeleteLocalChanAliases is an experimental API that deletes a set of alias
1675
// mappings. The final total set of aliases in the manager after the delete
1676
// operation is returned. The deletion will not be communicated to the channel
1677
// peer via any message.
1678
func (s *Server) XDeleteLocalChanAliases(_ context.Context,
1679
        in *DeleteAliasesRequest) (*DeleteAliasesResponse,
1680
        error) {
3✔
1681

3✔
1682
        for _, v := range in.AliasMaps {
6✔
1683
                baseScid := lnwire.NewShortChanIDFromInt(v.BaseScid)
3✔
1684

3✔
1685
                for _, alias := range v.Aliases {
6✔
1686
                        aliasScid := lnwire.NewShortChanIDFromInt(alias)
3✔
1687

3✔
1688
                        err := s.cfg.AliasMgr.DeleteLocalAlias(
3✔
1689
                                aliasScid, baseScid,
3✔
1690
                        )
3✔
1691
                        if err != nil {
3✔
1692
                                return nil, fmt.Errorf("error deleting scid "+
×
1693
                                        "alias, base_scid=%v, alias_scid=%v: "+
×
1694
                                        "%w", baseScid, aliasScid, err)
×
1695
                        }
×
1696
                }
1697
        }
1698

1699
        return &DeleteAliasesResponse{
3✔
1700
                AliasMaps: lnrpc.MarshalAliasMap(s.cfg.AliasMgr.ListAliases()),
3✔
1701
        }, nil
3✔
1702
}
1703

1704
func extractOutPoint(req *UpdateChanStatusRequest) (*wire.OutPoint, error) {
3✔
1705
        chanPoint := req.GetChanPoint()
3✔
1706
        txid, err := lnrpc.GetChanPointFundingTxid(chanPoint)
3✔
1707
        if err != nil {
3✔
1708
                return nil, err
×
1709
        }
×
1710
        index := chanPoint.OutputIndex
3✔
1711
        return wire.NewOutPoint(txid, index), nil
3✔
1712
}
1713

1714
// UpdateChanStatus allows channel state to be set manually.
1715
func (s *Server) UpdateChanStatus(_ context.Context,
1716
        req *UpdateChanStatusRequest) (*UpdateChanStatusResponse, error) {
3✔
1717

3✔
1718
        outPoint, err := extractOutPoint(req)
3✔
1719
        if err != nil {
3✔
1720
                return nil, err
×
1721
        }
×
1722

1723
        action := req.GetAction()
3✔
1724

3✔
1725
        log.Debugf("UpdateChanStatus called for channel(%v) with "+
3✔
1726
                "action %v", outPoint, action)
3✔
1727

3✔
1728
        switch action {
3✔
1729
        case ChanStatusAction_ENABLE:
3✔
1730
                err = s.cfg.RouterBackend.SetChannelEnabled(*outPoint)
3✔
1731
        case ChanStatusAction_DISABLE:
3✔
1732
                err = s.cfg.RouterBackend.SetChannelDisabled(*outPoint)
3✔
1733
        case ChanStatusAction_AUTO:
3✔
1734
                err = s.cfg.RouterBackend.SetChannelAuto(*outPoint)
3✔
1735
        default:
×
1736
                err = fmt.Errorf("unrecognized ChannelStatusAction %v", action)
×
1737
        }
1738

1739
        if err != nil {
3✔
1740
                return nil, err
×
1741
        }
×
1742
        return &UpdateChanStatusResponse{}, nil
3✔
1743
}
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