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

lightningnetwork / lnd / 12412879685

19 Dec 2024 12:40PM UTC coverage: 58.744% (+0.09%) from 58.653%
12412879685

Pull #8754

github

ViktorTigerstrom
itest: wrap deriveCustomScopeAccounts at 80 chars

This commit fixes that word wrapping for the deriveCustomScopeAccounts
function docs, and ensures that it wraps at 80 characters or less.
Pull Request #8754: Add `Outbound` Remote Signer implementation

1858 of 2816 new or added lines in 47 files covered. (65.98%)

267 existing lines in 51 files now uncovered.

136038 of 231578 relevant lines covered (58.74%)

19020.65 hits per line

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

71.51
/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
        injected                 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() (*Server, lnrpc.MacaroonPerms, error) {
3✔
204
        routerServer := &Server{
3✔
205
                cfg:  &Config{},
3✔
206
                quit: make(chan struct{}),
3✔
207
        }
3✔
208

3✔
209
        return routerServer, macPermissions, nil
3✔
210
}
3✔
211

212
// Stop signals any active goroutines for a graceful closure.
213
//
214
// NOTE: This is part of the lnrpc.SubServer interface.
215
func (s *Server) Stop() error {
3✔
216
        if atomic.AddInt32(&s.shutdown, 1) != 1 {
3✔
NEW
217
                return nil
×
NEW
218
        }
×
219

220
        close(s.quit)
3✔
221

3✔
222
        return nil
3✔
223
}
224

225
// InjectDependencies populates the sub-server's dependencies. If the
226
// finalizeDependencies boolean is true, then the sub-server will finalize its
227
// dependencies and return an error if any required dependencies are missing.
228
//
229
// NOTE: This is part of the lnrpc.SubServer interface.
230
func (s *Server) InjectDependencies(
231
        configRegistry lnrpc.SubServerConfigDispatcher,
232
        finalizeDependencies bool) error {
3✔
233

3✔
234
        if finalizeDependencies && atomic.AddInt32(&s.injected, 1) != 1 {
3✔
NEW
235
                return lnrpc.ErrDependenciesFinalized
×
NEW
236
        }
×
237

238
        cfg, err := getConfig(configRegistry, finalizeDependencies)
3✔
239
        if err != nil {
3✔
NEW
240
                return err
×
NEW
241
        }
×
242

243
        if finalizeDependencies {
6✔
244
                s.cfg = cfg
3✔
245

3✔
246
                return nil
3✔
247
        }
3✔
248

249
        // If the path of the router macaroon wasn't generated, then we'll
250
        // assume that it's found at the default network directory.
UNCOV
251
        if cfg.RouterMacPath == "" {
×
UNCOV
252
                cfg.RouterMacPath = filepath.Join(
×
UNCOV
253
                        cfg.NetworkDir, DefaultRouterMacFilename,
×
UNCOV
254
                )
×
UNCOV
255
        }
×
256

257
        // Now that we know the full path of the router macaroon, we can check
258
        // to see if we need to create it or not. If stateless_init is set
259
        // then we don't write the macaroons.
UNCOV
260
        macFilePath := cfg.RouterMacPath
×
UNCOV
261
        if cfg.MacService != nil && !cfg.MacService.StatelessInit &&
×
UNCOV
262
                !lnrpc.FileExists(macFilePath) {
×
UNCOV
263

×
UNCOV
264
                log.Infof("Making macaroons for Router RPC Server at: %v",
×
UNCOV
265
                        macFilePath)
×
UNCOV
266

×
UNCOV
267
                // At this point, we know that the router macaroon doesn't yet,
×
UNCOV
268
                // exist, so we need to create it with the help of the main
×
UNCOV
269
                // macaroon service.
×
UNCOV
270
                routerMac, err := cfg.MacService.NewMacaroon(
×
UNCOV
271
                        context.Background(), macaroons.DefaultRootKeyID,
×
UNCOV
272
                        macaroonOps...,
×
UNCOV
273
                )
×
UNCOV
274
                if err != nil {
×
NEW
275
                        return err
×
276
                }
×
UNCOV
277
                routerMacBytes, err := routerMac.M().MarshalBinary()
×
UNCOV
278
                if err != nil {
×
NEW
279
                        return err
×
280
                }
×
UNCOV
281
                err = os.WriteFile(macFilePath, routerMacBytes, 0644)
×
UNCOV
282
                if err != nil {
×
283
                        _ = os.Remove(macFilePath)
×
NEW
284
                        return err
×
285
                }
×
286
        }
287

NEW
288
        s.cfg = cfg
×
UNCOV
289

×
UNCOV
290
        return nil
×
291
}
292

293
// Name returns a unique string representation of the sub-server. This can be
294
// used to identify the sub-server and also de-duplicate them.
295
//
296
// NOTE: This is part of the lnrpc.SubServer interface.
297
func (s *Server) Name() string {
3✔
298
        return subServerName
3✔
299
}
3✔
300

301
// RegisterWithRootServer will be called by the root gRPC server to direct a
302
// sub RPC server to register itself with the main gRPC root server. Until this
303
// is called, each sub-server won't be able to have requests routed towards it.
304
//
305
// NOTE: This is part of the lnrpc.GrpcHandler interface.
306
func (r *ServerShell) RegisterWithRootServer(grpcServer *grpc.Server) error {
3✔
307
        // We make sure that we register it with the main gRPC server to ensure
3✔
308
        // all our methods are routed properly.
3✔
309
        RegisterRouterServer(grpcServer, r)
3✔
310

3✔
311
        log.Debugf("Router RPC server successfully register with root gRPC " +
3✔
312
                "server")
3✔
313

3✔
314
        return nil
3✔
315
}
3✔
316

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

3✔
325
        // We make sure that we register it with the main REST server to ensure
3✔
326
        // all our methods are routed properly.
3✔
327
        err := RegisterRouterHandlerFromEndpoint(ctx, mux, dest, opts)
3✔
328
        if err != nil {
3✔
329
                log.Errorf("Could not register Router REST server "+
×
330
                        "with root REST server: %v", err)
×
331
                return err
×
332
        }
×
333

334
        log.Debugf("Router REST server successfully registered with " +
3✔
335
                "root REST server")
3✔
336
        return nil
3✔
337
}
338

339
// CreateSubServer creates an instance of the sub-server, and returns the
340
// macaroon permissions that the sub-server wishes to pass on to the root server
341
// for all methods routed towards it.
342
//
343
// NOTE: This is part of the lnrpc.GrpcHandler interface.
344
func (r *ServerShell) CreateSubServer() (
345
        lnrpc.SubServer, lnrpc.MacaroonPerms, error) {
3✔
346

3✔
347
        subServer, macPermissions, err := New()
3✔
348
        if err != nil {
3✔
349
                return nil, nil, err
×
350
        }
×
351

352
        r.RouterServer = subServer
3✔
353
        return subServer, macPermissions, nil
3✔
354
}
355

356
// SendPaymentV2 attempts to route a payment described by the passed
357
// PaymentRequest to the final destination. If we are unable to route the
358
// payment, or cannot find a route that satisfies the constraints in the
359
// PaymentRequest, then an error will be returned. Otherwise, the payment
360
// pre-image, along with the final route will be returned.
361
func (s *Server) SendPaymentV2(req *SendPaymentRequest,
362
        stream Router_SendPaymentV2Server) error {
3✔
363

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

369
        // Get the payment hash.
370
        payHash := payment.Identifier()
3✔
371

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

×
378
                // Transform user errors to grpc code.
×
379
                if errors.Is(err, channeldb.ErrPaymentExists) ||
×
380
                        errors.Is(err, channeldb.ErrPaymentInFlight) ||
×
381
                        errors.Is(err, channeldb.ErrAlreadyPaid) {
×
382

×
383
                        return status.Error(
×
384
                                codes.AlreadyExists, err.Error(),
×
385
                        )
×
386
                }
×
387

388
                return err
×
389
        }
390

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

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

412
        // Send the payment asynchronously.
413
        s.cfg.Router.SendPaymentAsync(ctx, payment, paySession, shardTracker)
3✔
414

3✔
415
        // Track the payment and return.
3✔
416
        return s.trackPayment(sub, payHash, stream, req.NoInflightUpdates)
3✔
417
}
418

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

3✔
429
        isProbeDestination := len(req.Dest) > 0
3✔
430
        isProbeInvoice := len(req.PaymentRequest) > 0
3✔
431

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

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

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

445
                default:
3✔
446
                        return s.probeDestination(req.Dest, req.AmtSat)
3✔
447
                }
448

449
        case isProbeInvoice:
3✔
450
                return s.probePaymentRequest(
3✔
451
                        ctx, req.PaymentRequest, req.Timeout,
3✔
452
                )
3✔
453
        }
454

455
        return &RouteFeeResponse{}, nil
×
456
}
457

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

3✔
463
        destNode, err := route.NewVertexFromBytes(dest)
3✔
464
        if err != nil {
3✔
465
                return nil, err
×
466
        }
×
467

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

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

489
        route, _, err := s.cfg.Router.FindRoute(routeReq)
3✔
490
        if err != nil {
6✔
491
                return nil, err
3✔
492
        }
3✔
493

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

3✔
500
        return &RouteFeeResponse{
3✔
501
                RoutingFeeMsat: int64(route.TotalFees()),
3✔
502
                TimeLockDelay:  int64(timeLockDelay),
3✔
503
                FailureReason:  lnrpc.PaymentFailureReason_FAILURE_REASON_NONE,
3✔
504
        }, nil
3✔
505
}
506

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

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

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

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

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

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

558
        hints := payReq.RouteHints
3✔
559

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

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

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

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

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

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

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

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

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

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

3✔
632
        return resp, nil
3✔
633
}
634

635
// isLSP checks if the route hints indicate an LSP. An LSP is indicated with
636
// true if the last node in each route hint has the same node id, false
637
// otherwise.
638
func isLSP(routeHints [][]zpay32.HopHint) bool {
3✔
639
        if len(routeHints) == 0 || len(routeHints[0]) == 0 {
6✔
640
                return false
3✔
641
        }
3✔
642

643
        refNodeID := routeHints[0][len(routeHints[0])-1].NodeID
3✔
644
        for i := 1; i < len(routeHints); i++ {
6✔
645
                // Skip empty route hints.
3✔
646
                if len(routeHints[i]) == 0 {
3✔
647
                        continue
×
648
                }
649

650
                lastHop := routeHints[i][len(routeHints[i])-1]
3✔
651
                idMatchesRefNode := bytes.Equal(
3✔
652
                        lastHop.NodeID.SerializeCompressed(),
3✔
653
                        refNodeID.SerializeCompressed(),
3✔
654
                )
3✔
655
                if !idMatchesRefNode {
6✔
656
                        return false
3✔
657
                }
3✔
658
        }
659

660
        return true
3✔
661
}
662

663
// prepareLspRouteHints assumes that the isLsp heuristic returned true for the
664
// route hints passed in here. It constructs a modified list of route hints that
665
// allows the caller to probe the LSP, which itself is returned as a separate
666
// hop hint.
667
func prepareLspRouteHints(routeHints [][]zpay32.HopHint,
668
        amt lnwire.MilliSatoshi) ([][]zpay32.HopHint, *zpay32.HopHint, error) {
3✔
669

3✔
670
        if len(routeHints) == 0 {
3✔
671
                return nil, nil, fmt.Errorf("no route hints provided")
×
672
        }
×
673

674
        // Create the LSP hop hint. We are probing for the worst case fee and
675
        // cltv delta. So we look for the max values amongst all LSP hop hints.
676
        refHint := routeHints[0][len(routeHints[0])-1]
3✔
677
        refHint.CLTVExpiryDelta = maxLspCltvDelta(routeHints)
3✔
678
        refHint.FeeBaseMSat, refHint.FeeProportionalMillionths = maxLspFee(
3✔
679
                routeHints, amt,
3✔
680
        )
3✔
681

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

3✔
686
        // Strip off the LSP hop hint from all route hints.
3✔
687
        for i := 0; i < len(routeHints); i++ {
6✔
688
                hint := routeHints[i]
3✔
689
                if len(hint) > 1 {
3✔
690
                        adjustedHints = append(
×
691
                                adjustedHints, hint[:len(hint)-1],
×
692
                        )
×
693
                }
×
694
        }
695

696
        return adjustedHints, &refHint, nil
3✔
697
}
698

699
// maxLspFee returns base fee and fee rate amongst all LSP route hints that
700
// results in the overall highest fee for the given amount.
701
func maxLspFee(routeHints [][]zpay32.HopHint, amt lnwire.MilliSatoshi) (uint32,
702
        uint32) {
3✔
703

3✔
704
        var maxFeePpm uint32
3✔
705
        var maxBaseFee uint32
3✔
706
        var maxTotalFee lnwire.MilliSatoshi
3✔
707
        for _, rh := range routeHints {
6✔
708
                lastHop := rh[len(rh)-1]
3✔
709
                lastHopFee := lastHop.HopFee(amt)
3✔
710
                if lastHopFee > maxTotalFee {
6✔
711
                        maxTotalFee = lastHopFee
3✔
712
                        maxBaseFee = lastHop.FeeBaseMSat
3✔
713
                        maxFeePpm = lastHop.FeeProportionalMillionths
3✔
714
                }
3✔
715
        }
716

717
        return maxBaseFee, maxFeePpm
3✔
718
}
719

720
// maxLspCltvDelta returns the maximum cltv delta amongst all LSP route hints.
721
func maxLspCltvDelta(routeHints [][]zpay32.HopHint) uint16 {
3✔
722
        var maxCltvDelta uint16
3✔
723
        for _, rh := range routeHints {
6✔
724
                rhLastHop := rh[len(rh)-1]
3✔
725
                if rhLastHop.CLTVExpiryDelta > maxCltvDelta {
6✔
726
                        maxCltvDelta = rhLastHop.CLTVExpiryDelta
3✔
727
                }
3✔
728
        }
729

730
        return maxCltvDelta
3✔
731
}
732

733
// probePaymentStream is a custom implementation of the grpc.ServerStream
734
// interface. It is used to send payment status updates to the caller on the
735
// stream channel.
736
type probePaymentStream struct {
737
        Router_SendPaymentV2Server
738

739
        stream chan *lnrpc.Payment
740
        ctx    context.Context //nolint:containedctx
741
}
742

743
// Send sends a payment status update to a payment stream that the caller can
744
// evaluate.
745
func (p *probePaymentStream) Send(response *lnrpc.Payment) error {
3✔
746
        select {
3✔
747
        case p.stream <- response:
3✔
748

749
        case <-p.ctx.Done():
×
750
                return p.ctx.Err()
×
751
        }
752

753
        return nil
3✔
754
}
755

756
// Context returns the context of the stream.
757
func (p *probePaymentStream) Context() context.Context {
3✔
758
        return p.ctx
3✔
759
}
3✔
760

761
// sendProbePayment sends a payment to a target node in order to obtain
762
// potential routing fees for it. The payment request has to contain a payment
763
// hash that is guaranteed to be unknown to the target node, so it cannot settle
764
// the payment. This method invokes a payment request loop in a goroutine and
765
// awaits payment status updates.
766
func (s *Server) sendProbePayment(ctx context.Context,
767
        req *SendPaymentRequest) (*RouteFeeResponse, error) {
3✔
768

3✔
769
        // We'll launch a goroutine to send the payment probes.
3✔
770
        errChan := make(chan error, 1)
3✔
771
        defer close(errChan)
3✔
772

3✔
773
        paymentStream := &probePaymentStream{
3✔
774
                stream: make(chan *lnrpc.Payment),
3✔
775
                ctx:    ctx,
3✔
776
        }
3✔
777
        go func() {
6✔
778
                err := s.SendPaymentV2(req, paymentStream)
3✔
779
                if err != nil {
3✔
780
                        select {
×
781
                        case errChan <- err:
×
782

783
                        case <-paymentStream.ctx.Done():
×
784
                                return
×
785
                        }
786
                }
787
        }()
788

789
        for {
6✔
790
                select {
3✔
791
                case payment := <-paymentStream.stream:
3✔
792
                        switch payment.Status {
3✔
793
                        case lnrpc.Payment_INITIATED:
×
794
                        case lnrpc.Payment_IN_FLIGHT:
3✔
795
                        case lnrpc.Payment_SUCCEEDED:
×
796
                                return nil, errors.New("warning, the fee " +
×
797
                                        "estimation payment probe " +
×
798
                                        "unexpectedly succeeded. Please reach" +
×
799
                                        "out to the probe destination to " +
×
800
                                        "negotiate a refund. Otherwise the " +
×
801
                                        "payment probe amount is lost forever")
×
802

803
                        case lnrpc.Payment_FAILED:
3✔
804
                                // Incorrect payment details point to a
3✔
805
                                // successful probe.
3✔
806
                                //nolint:ll
3✔
807
                                if payment.FailureReason == lnrpc.PaymentFailureReason_FAILURE_REASON_INCORRECT_PAYMENT_DETAILS {
6✔
808
                                        return paymentDetails(payment)
3✔
809
                                }
3✔
810

811
                                return &RouteFeeResponse{
3✔
812
                                        RoutingFeeMsat: 0,
3✔
813
                                        TimeLockDelay:  0,
3✔
814
                                        FailureReason:  payment.FailureReason,
3✔
815
                                }, nil
3✔
816

817
                        default:
×
818
                                return nil, errors.New("unexpected payment " +
×
819
                                        "status")
×
820
                        }
821

822
                case err := <-errChan:
×
823
                        return nil, err
×
824

825
                case <-s.quit:
×
826
                        return nil, errServerShuttingDown
×
827
                }
828
        }
829
}
830

831
func paymentDetails(payment *lnrpc.Payment) (*RouteFeeResponse, error) {
3✔
832
        fee, timeLock, err := timelockAndFee(payment)
3✔
833
        if errors.Is(err, errUnexpectedFailureSource) {
3✔
834
                return nil, err
×
835
        }
×
836

837
        return &RouteFeeResponse{
3✔
838
                RoutingFeeMsat: fee,
3✔
839
                TimeLockDelay:  timeLock,
3✔
840
                FailureReason:  lnrpc.PaymentFailureReason_FAILURE_REASON_NONE,
3✔
841
        }, nil
3✔
842
}
843

844
// timelockAndFee returns the fee and total time lock of the last payment
845
// attempt.
846
func timelockAndFee(p *lnrpc.Payment) (int64, int64, error) {
3✔
847
        if len(p.Htlcs) == 0 {
3✔
848
                return 0, 0, nil
×
849
        }
×
850

851
        lastAttempt := p.Htlcs[len(p.Htlcs)-1]
3✔
852
        if lastAttempt == nil {
3✔
853
                return 0, 0, errMissingPaymentAttempt
×
854
        }
×
855

856
        lastRoute := lastAttempt.Route
3✔
857
        if lastRoute == nil {
3✔
858
                return 0, 0, errMissingRoute
×
859
        }
×
860

861
        hopFailureIndex := lastAttempt.Failure.FailureSourceIndex
3✔
862
        finalHopIndex := uint32(len(lastRoute.Hops))
3✔
863
        if hopFailureIndex != finalHopIndex {
3✔
864
                return 0, 0, errUnexpectedFailureSource
×
865
        }
×
866

867
        return lastRoute.TotalFeesMsat, int64(lastRoute.TotalTimeLock), nil
3✔
868
}
869

870
// SendToRouteV2 sends a payment through a predefined route. The response of
871
// this call contains structured error information.
872
func (s *Server) SendToRouteV2(ctx context.Context,
873
        req *SendToRouteRequest) (*lnrpc.HTLCAttempt, error) {
3✔
874

3✔
875
        if req.Route == nil {
3✔
876
                return nil, fmt.Errorf("unable to send, no routes provided")
×
877
        }
×
878

879
        route, err := s.cfg.RouterBackend.UnmarshallRoute(req.Route)
3✔
880
        if err != nil {
3✔
881
                return nil, err
×
882
        }
×
883

884
        hash, err := lntypes.MakeHash(req.PaymentHash)
3✔
885
        if err != nil {
3✔
886
                return nil, err
×
887
        }
×
888

889
        firstHopRecords := lnwire.CustomRecords(req.FirstHopCustomRecords)
3✔
890
        if err := firstHopRecords.Validate(); err != nil {
3✔
891
                return nil, err
×
892
        }
×
893

894
        var attempt *channeldb.HTLCAttempt
3✔
895

3✔
896
        // Pass route to the router. This call returns the full htlc attempt
3✔
897
        // information as it is stored in the database. It is possible that both
3✔
898
        // the attempt return value and err are non-nil. This can happen when
3✔
899
        // the attempt was already initiated before the error happened. In that
3✔
900
        // case, we give precedence to the attempt information as stored in the
3✔
901
        // db.
3✔
902
        if req.SkipTempErr {
3✔
903
                attempt, err = s.cfg.Router.SendToRouteSkipTempErr(
×
904
                        hash, route, firstHopRecords,
×
905
                )
×
906
        } else {
3✔
907
                attempt, err = s.cfg.Router.SendToRoute(
3✔
908
                        hash, route, firstHopRecords,
3✔
909
                )
3✔
910
        }
3✔
911
        if attempt != nil {
6✔
912
                rpcAttempt, err := s.cfg.RouterBackend.MarshalHTLCAttempt(
3✔
913
                        *attempt,
3✔
914
                )
3✔
915
                if err != nil {
3✔
916
                        return nil, err
×
917
                }
×
918
                return rpcAttempt, nil
3✔
919
        }
920

921
        // Transform user errors to grpc code.
922
        switch {
×
923
        case errors.Is(err, channeldb.ErrPaymentExists):
×
924
                fallthrough
×
925

926
        case errors.Is(err, channeldb.ErrPaymentInFlight):
×
927
                fallthrough
×
928

929
        case errors.Is(err, channeldb.ErrAlreadyPaid):
×
930
                return nil, status.Error(
×
931
                        codes.AlreadyExists, err.Error(),
×
932
                )
×
933
        }
934

935
        return nil, err
×
936
}
937

938
// ResetMissionControl clears all mission control state and starts with a clean
939
// slate.
940
func (s *Server) ResetMissionControl(ctx context.Context,
941
        req *ResetMissionControlRequest) (*ResetMissionControlResponse, error) {
3✔
942

3✔
943
        err := s.cfg.RouterBackend.MissionControl.ResetHistory()
3✔
944
        if err != nil {
3✔
945
                return nil, err
×
946
        }
×
947

948
        return &ResetMissionControlResponse{}, nil
3✔
949
}
950

951
// GetMissionControlConfig returns our current mission control config.
952
func (s *Server) GetMissionControlConfig(ctx context.Context,
953
        req *GetMissionControlConfigRequest) (*GetMissionControlConfigResponse,
954
        error) {
3✔
955

3✔
956
        // Query the current mission control config.
3✔
957
        cfg := s.cfg.RouterBackend.MissionControl.GetConfig()
3✔
958
        resp := &GetMissionControlConfigResponse{
3✔
959
                Config: &MissionControlConfig{
3✔
960
                        MaximumPaymentResults: uint32(cfg.MaxMcHistory),
3✔
961
                        MinimumFailureRelaxInterval: uint64(
3✔
962
                                cfg.MinFailureRelaxInterval.Seconds(),
3✔
963
                        ),
3✔
964
                },
3✔
965
        }
3✔
966

3✔
967
        // We only populate fields based on the current estimator.
3✔
968
        switch v := cfg.Estimator.Config().(type) {
3✔
969
        case routing.AprioriConfig:
3✔
970
                resp.Config.Model = MissionControlConfig_APRIORI
3✔
971
                aCfg := AprioriParameters{
3✔
972
                        HalfLifeSeconds:  uint64(v.PenaltyHalfLife.Seconds()),
3✔
973
                        HopProbability:   v.AprioriHopProbability,
3✔
974
                        Weight:           v.AprioriWeight,
3✔
975
                        CapacityFraction: v.CapacityFraction,
3✔
976
                }
3✔
977

3✔
978
                // Populate deprecated fields.
3✔
979
                resp.Config.HalfLifeSeconds = uint64(
3✔
980
                        v.PenaltyHalfLife.Seconds(),
3✔
981
                )
3✔
982
                resp.Config.HopProbability = float32(v.AprioriHopProbability)
3✔
983
                resp.Config.Weight = float32(v.AprioriWeight)
3✔
984

3✔
985
                resp.Config.EstimatorConfig = &MissionControlConfig_Apriori{
3✔
986
                        Apriori: &aCfg,
3✔
987
                }
3✔
988

989
        case routing.BimodalConfig:
3✔
990
                resp.Config.Model = MissionControlConfig_BIMODAL
3✔
991
                bCfg := BimodalParameters{
3✔
992
                        NodeWeight: v.BimodalNodeWeight,
3✔
993
                        ScaleMsat:  uint64(v.BimodalScaleMsat),
3✔
994
                        DecayTime:  uint64(v.BimodalDecayTime.Seconds()),
3✔
995
                }
3✔
996

3✔
997
                resp.Config.EstimatorConfig = &MissionControlConfig_Bimodal{
3✔
998
                        Bimodal: &bCfg,
3✔
999
                }
3✔
1000

1001
        default:
×
1002
                return nil, fmt.Errorf("unknown estimator config type %T", v)
×
1003
        }
1004

1005
        return resp, nil
3✔
1006
}
1007

1008
// SetMissionControlConfig sets parameters in the mission control config.
1009
func (s *Server) SetMissionControlConfig(ctx context.Context,
1010
        req *SetMissionControlConfigRequest) (*SetMissionControlConfigResponse,
1011
        error) {
3✔
1012

3✔
1013
        mcCfg := &routing.MissionControlConfig{
3✔
1014
                MaxMcHistory: int(req.Config.MaximumPaymentResults),
3✔
1015
                MinFailureRelaxInterval: time.Duration(
3✔
1016
                        req.Config.MinimumFailureRelaxInterval,
3✔
1017
                ) * time.Second,
3✔
1018
        }
3✔
1019

3✔
1020
        switch req.Config.Model {
3✔
1021
        case MissionControlConfig_APRIORI:
3✔
1022
                var aprioriConfig routing.AprioriConfig
3✔
1023

3✔
1024
                // Determine the apriori config with backward compatibility
3✔
1025
                // should the api use deprecated fields.
3✔
1026
                switch v := req.Config.EstimatorConfig.(type) {
3✔
1027
                case *MissionControlConfig_Bimodal:
3✔
1028
                        return nil, fmt.Errorf("bimodal config " +
3✔
1029
                                "provided, but apriori model requested")
3✔
1030

1031
                case *MissionControlConfig_Apriori:
3✔
1032
                        aprioriConfig = routing.AprioriConfig{
3✔
1033
                                PenaltyHalfLife: time.Duration(
3✔
1034
                                        v.Apriori.HalfLifeSeconds,
3✔
1035
                                ) * time.Second,
3✔
1036
                                AprioriHopProbability: v.Apriori.HopProbability,
3✔
1037
                                AprioriWeight:         v.Apriori.Weight,
3✔
1038
                                CapacityFraction: v.Apriori.
3✔
1039
                                        CapacityFraction,
3✔
1040
                        }
3✔
1041

1042
                default:
3✔
1043
                        aprioriConfig = routing.AprioriConfig{
3✔
1044
                                PenaltyHalfLife: time.Duration(
3✔
1045
                                        int64(req.Config.HalfLifeSeconds),
3✔
1046
                                ) * time.Second,
3✔
1047
                                AprioriHopProbability: float64(
3✔
1048
                                        req.Config.HopProbability,
3✔
1049
                                ),
3✔
1050
                                AprioriWeight:    float64(req.Config.Weight),
3✔
1051
                                CapacityFraction: routing.DefaultCapacityFraction, //nolint:ll
3✔
1052
                        }
3✔
1053
                }
1054

1055
                estimator, err := routing.NewAprioriEstimator(aprioriConfig)
3✔
1056
                if err != nil {
3✔
1057
                        return nil, err
×
1058
                }
×
1059
                mcCfg.Estimator = estimator
3✔
1060

1061
        case MissionControlConfig_BIMODAL:
3✔
1062
                cfg, ok := req.Config.
3✔
1063
                        EstimatorConfig.(*MissionControlConfig_Bimodal)
3✔
1064
                if !ok {
3✔
1065
                        return nil, fmt.Errorf("bimodal estimator requested " +
×
1066
                                "but corresponding config not set")
×
1067
                }
×
1068
                bCfg := cfg.Bimodal
3✔
1069

3✔
1070
                bimodalConfig := routing.BimodalConfig{
3✔
1071
                        BimodalDecayTime: time.Duration(
3✔
1072
                                bCfg.DecayTime,
3✔
1073
                        ) * time.Second,
3✔
1074
                        BimodalScaleMsat:  lnwire.MilliSatoshi(bCfg.ScaleMsat),
3✔
1075
                        BimodalNodeWeight: bCfg.NodeWeight,
3✔
1076
                }
3✔
1077

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

1084
        default:
×
1085
                return nil, fmt.Errorf("unknown estimator type %v",
×
1086
                        req.Config.Model)
×
1087
        }
1088

1089
        return &SetMissionControlConfigResponse{},
3✔
1090
                s.cfg.RouterBackend.MissionControl.SetConfig(mcCfg)
3✔
1091
}
1092

1093
// QueryMissionControl exposes the internal mission control state to callers. It
1094
// is a development feature.
1095
func (s *Server) QueryMissionControl(_ context.Context,
1096
        _ *QueryMissionControlRequest) (*QueryMissionControlResponse, error) {
×
1097

×
1098
        snapshot := s.cfg.RouterBackend.MissionControl.GetHistorySnapshot()
×
1099

×
1100
        rpcPairs := make([]*PairHistory, 0, len(snapshot.Pairs))
×
1101
        for _, p := range snapshot.Pairs {
×
1102
                // Prevent binding to loop variable.
×
1103
                pair := p
×
1104

×
1105
                rpcPair := PairHistory{
×
1106
                        NodeFrom: pair.Pair.From[:],
×
1107
                        NodeTo:   pair.Pair.To[:],
×
1108
                        History:  toRPCPairData(&pair.TimedPairResult),
×
1109
                }
×
1110

×
1111
                rpcPairs = append(rpcPairs, &rpcPair)
×
1112
        }
×
1113

1114
        response := QueryMissionControlResponse{
×
1115
                Pairs: rpcPairs,
×
1116
        }
×
1117

×
1118
        return &response, nil
×
1119
}
1120

1121
// toRPCPairData marshalls mission control pair data to the rpc struct.
1122
func toRPCPairData(data *routing.TimedPairResult) *PairData {
3✔
1123
        rpcData := PairData{
3✔
1124
                FailAmtSat:     int64(data.FailAmt.ToSatoshis()),
3✔
1125
                FailAmtMsat:    int64(data.FailAmt),
3✔
1126
                SuccessAmtSat:  int64(data.SuccessAmt.ToSatoshis()),
3✔
1127
                SuccessAmtMsat: int64(data.SuccessAmt),
3✔
1128
        }
3✔
1129

3✔
1130
        if !data.FailTime.IsZero() {
6✔
1131
                rpcData.FailTime = data.FailTime.Unix()
3✔
1132
        }
3✔
1133

1134
        if !data.SuccessTime.IsZero() {
3✔
1135
                rpcData.SuccessTime = data.SuccessTime.Unix()
×
1136
        }
×
1137

1138
        return &rpcData
3✔
1139
}
1140

1141
// XImportMissionControl imports the state provided to our internal mission
1142
// control. Only entries that are fresher than our existing state will be used.
1143
func (s *Server) XImportMissionControl(_ context.Context,
1144
        req *XImportMissionControlRequest) (*XImportMissionControlResponse,
1145
        error) {
3✔
1146

3✔
1147
        if len(req.Pairs) == 0 {
3✔
1148
                return nil, errors.New("at least one pair required for import")
×
1149
        }
×
1150

1151
        snapshot := &routing.MissionControlSnapshot{
3✔
1152
                Pairs: make(
3✔
1153
                        []routing.MissionControlPairSnapshot, len(req.Pairs),
3✔
1154
                ),
3✔
1155
        }
3✔
1156

3✔
1157
        for i, pairResult := range req.Pairs {
6✔
1158
                pairSnapshot, err := toPairSnapshot(pairResult)
3✔
1159
                if err != nil {
6✔
1160
                        return nil, err
3✔
1161
                }
3✔
1162

1163
                snapshot.Pairs[i] = *pairSnapshot
3✔
1164
        }
1165

1166
        err := s.cfg.RouterBackend.MissionControl.ImportHistory(
3✔
1167
                snapshot, req.Force,
3✔
1168
        )
3✔
1169
        if err != nil {
3✔
1170
                return nil, err
×
1171
        }
×
1172

1173
        return &XImportMissionControlResponse{}, nil
3✔
1174
}
1175

1176
func toPairSnapshot(pairResult *PairHistory) (*routing.MissionControlPairSnapshot,
1177
        error) {
3✔
1178

3✔
1179
        from, err := route.NewVertexFromBytes(pairResult.NodeFrom)
3✔
1180
        if err != nil {
3✔
1181
                return nil, err
×
1182
        }
×
1183

1184
        to, err := route.NewVertexFromBytes(pairResult.NodeTo)
3✔
1185
        if err != nil {
3✔
1186
                return nil, err
×
1187
        }
×
1188

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

3✔
1191
        if from == to {
3✔
1192
                return nil, fmt.Errorf("%v source and destination node must "+
×
1193
                        "differ", pairPrefix)
×
1194
        }
×
1195

1196
        failAmt, failTime, err := getPair(
3✔
1197
                lnwire.MilliSatoshi(pairResult.History.FailAmtMsat),
3✔
1198
                btcutil.Amount(pairResult.History.FailAmtSat),
3✔
1199
                pairResult.History.FailTime,
3✔
1200
                true,
3✔
1201
        )
3✔
1202
        if err != nil {
6✔
1203
                return nil, fmt.Errorf("%v invalid failure: %w", pairPrefix,
3✔
1204
                        err)
3✔
1205
        }
3✔
1206

1207
        successAmt, successTime, err := getPair(
3✔
1208
                lnwire.MilliSatoshi(pairResult.History.SuccessAmtMsat),
3✔
1209
                btcutil.Amount(pairResult.History.SuccessAmtSat),
3✔
1210
                pairResult.History.SuccessTime,
3✔
1211
                false,
3✔
1212
        )
3✔
1213
        if err != nil {
3✔
1214
                return nil, fmt.Errorf("%v invalid success: %w", pairPrefix,
×
1215
                        err)
×
1216
        }
×
1217

1218
        if successAmt == 0 && failAmt == 0 {
3✔
1219
                return nil, fmt.Errorf("%v: either success or failure result "+
×
1220
                        "required", pairPrefix)
×
1221
        }
×
1222

1223
        pair := routing.NewDirectedNodePair(from, to)
3✔
1224

3✔
1225
        result := &routing.TimedPairResult{
3✔
1226
                FailAmt:     failAmt,
3✔
1227
                FailTime:    failTime,
3✔
1228
                SuccessAmt:  successAmt,
3✔
1229
                SuccessTime: successTime,
3✔
1230
        }
3✔
1231

3✔
1232
        return &routing.MissionControlPairSnapshot{
3✔
1233
                Pair:            pair,
3✔
1234
                TimedPairResult: *result,
3✔
1235
        }, nil
3✔
1236
}
1237

1238
// getPair validates the values provided for a mission control result and
1239
// returns the msat amount and timestamp for it. `isFailure` can be used to
1240
// default values to 0 instead of returning an error.
1241
func getPair(amtMsat lnwire.MilliSatoshi, amtSat btcutil.Amount,
1242
        timestamp int64, isFailure bool) (lnwire.MilliSatoshi, time.Time,
1243
        error) {
3✔
1244

3✔
1245
        amt, err := getMsatPairValue(amtMsat, amtSat)
3✔
1246
        if err != nil {
6✔
1247
                return 0, time.Time{}, err
3✔
1248
        }
3✔
1249

1250
        var (
3✔
1251
                timeSet   = timestamp != 0
3✔
1252
                amountSet = amt != 0
3✔
1253
        )
3✔
1254

3✔
1255
        switch {
3✔
1256
        // If a timestamp and amount if provided, return those values.
1257
        case timeSet && amountSet:
3✔
1258
                return amt, time.Unix(timestamp, 0), nil
3✔
1259

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

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

1272
        default:
3✔
1273
                return 0, time.Time{}, nil
3✔
1274
        }
1275
}
1276

1277
// getMsatPairValue checks the msat and sat values set for a pair and ensures
1278
// that the values provided are either the same, or only a single value is set.
1279
func getMsatPairValue(msatValue lnwire.MilliSatoshi,
1280
        satValue btcutil.Amount) (lnwire.MilliSatoshi, error) {
3✔
1281

3✔
1282
        // If our msat value converted to sats equals our sat value, we just
3✔
1283
        // return the msat value, since the values are the same.
3✔
1284
        if msatValue.ToSatoshis() == satValue {
6✔
1285
                return msatValue, nil
3✔
1286
        }
3✔
1287

1288
        // If we have no msatValue, we can just return our state value even if
1289
        // it is zero, because it's impossible that we have mismatched values.
1290
        if msatValue == 0 {
3✔
1291
                return lnwire.MilliSatoshi(satValue * 1000), nil
×
1292
        }
×
1293

1294
        // Likewise, we can just use msat value if we have no sat value set.
1295
        if satValue == 0 {
3✔
1296
                return msatValue, nil
×
1297
        }
×
1298

1299
        // If our values are non-zero but not equal, we have invalid amounts
1300
        // set, so we fail.
1301
        return 0, fmt.Errorf("msat: %v and sat: %v values not equal", msatValue,
3✔
1302
                satValue)
3✔
1303
}
1304

1305
// TrackPaymentV2 returns a stream of payment state updates. The stream is
1306
// closed when the payment completes.
1307
func (s *Server) TrackPaymentV2(request *TrackPaymentRequest,
1308
        stream Router_TrackPaymentV2Server) error {
3✔
1309

3✔
1310
        payHash, err := lntypes.MakeHash(request.PaymentHash)
3✔
1311
        if err != nil {
3✔
1312
                return err
×
1313
        }
×
1314

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

3✔
1317
        // Make the subscription.
3✔
1318
        sub, err := s.subscribePayment(payHash)
3✔
1319
        if err != nil {
3✔
1320
                return err
×
1321
        }
×
1322

1323
        return s.trackPayment(sub, payHash, stream, request.NoInflightUpdates)
3✔
1324
}
1325

1326
// subscribePayment subscribes to the payment updates for the given payment
1327
// hash.
1328
func (s *Server) subscribePayment(identifier lntypes.Hash) (
1329
        routing.ControlTowerSubscriber, error) {
3✔
1330

3✔
1331
        // Make the subscription.
3✔
1332
        router := s.cfg.RouterBackend
3✔
1333
        sub, err := router.Tower.SubscribePayment(identifier)
3✔
1334

3✔
1335
        switch {
3✔
1336
        case errors.Is(err, channeldb.ErrPaymentNotInitiated):
×
1337
                return nil, status.Error(codes.NotFound, err.Error())
×
1338

1339
        case err != nil:
×
1340
                return nil, err
×
1341
        }
1342

1343
        return sub, nil
3✔
1344
}
1345

1346
// trackPayment writes payment status updates to the provided stream.
1347
func (s *Server) trackPayment(subscription routing.ControlTowerSubscriber,
1348
        identifier lntypes.Hash, stream Router_TrackPaymentV2Server,
1349
        noInflightUpdates bool) error {
3✔
1350

3✔
1351
        err := s.trackPaymentStream(
3✔
1352
                stream.Context(), subscription, noInflightUpdates, stream.Send,
3✔
1353
        )
3✔
1354

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

3✔
1359
                return nil
3✔
1360
        }
3✔
1361

1362
        // Otherwise, we will log and return the error as the stream has
1363
        // received an error from the payment lifecycle.
1364
        log.Errorf("TrackPayment got error for payment %v: %v", identifier, err)
3✔
1365

3✔
1366
        return err
3✔
1367
}
1368

1369
// TrackPayments returns a stream of payment state updates.
1370
func (s *Server) TrackPayments(request *TrackPaymentsRequest,
1371
        stream Router_TrackPaymentsServer) error {
3✔
1372

3✔
1373
        log.Debug("TrackPayments called")
3✔
1374

3✔
1375
        router := s.cfg.RouterBackend
3✔
1376

3✔
1377
        // Subscribe to payments.
3✔
1378
        subscription, err := router.Tower.SubscribeAllPayments()
3✔
1379
        if err != nil {
3✔
1380
                return err
×
1381
        }
×
1382

1383
        // Stream updates to the client.
1384
        err = s.trackPaymentStream(
3✔
1385
                stream.Context(), subscription, request.NoInflightUpdates,
3✔
1386
                stream.Send,
3✔
1387
        )
3✔
1388

3✔
1389
        if errors.Is(err, context.Canceled) {
6✔
1390
                log.Debugf("TrackPayments payment stream canceled.")
3✔
1391
        }
3✔
1392

1393
        return err
3✔
1394
}
1395

1396
// trackPaymentStream streams payment updates to the client.
1397
func (s *Server) trackPaymentStream(context context.Context,
1398
        subscription routing.ControlTowerSubscriber, noInflightUpdates bool,
1399
        send func(*lnrpc.Payment) error) error {
3✔
1400

3✔
1401
        defer subscription.Close()
3✔
1402

3✔
1403
        // Stream updates back to the client.
3✔
1404
        for {
6✔
1405
                select {
3✔
1406
                case item, ok := <-subscription.Updates():
3✔
1407
                        if !ok {
6✔
1408
                                // No more payment updates.
3✔
1409
                                return nil
3✔
1410
                        }
3✔
1411
                        result := item.(*channeldb.MPPayment)
3✔
1412

3✔
1413
                        log.Tracef("Payment %v updated to state %v",
3✔
1414
                                result.Info.PaymentIdentifier, result.Status)
3✔
1415

3✔
1416
                        // Skip in-flight updates unless requested.
3✔
1417
                        if noInflightUpdates {
3✔
1418
                                if result.Status == channeldb.StatusInitiated {
×
1419
                                        continue
×
1420
                                }
1421
                                if result.Status == channeldb.StatusInFlight {
×
1422
                                        continue
×
1423
                                }
1424
                        }
1425

1426
                        rpcPayment, err := s.cfg.RouterBackend.MarshallPayment(
3✔
1427
                                result,
3✔
1428
                        )
3✔
1429
                        if err != nil {
3✔
1430
                                return err
×
1431
                        }
×
1432

1433
                        // Send event to the client.
1434
                        err = send(rpcPayment)
3✔
1435
                        if err != nil {
3✔
1436
                                return err
×
1437
                        }
×
1438

1439
                case <-s.quit:
×
1440
                        return errServerShuttingDown
×
1441

1442
                case <-context.Done():
3✔
1443
                        return context.Err()
3✔
1444
                }
1445
        }
1446
}
1447

1448
// BuildRoute builds a route from a list of hop addresses.
1449
func (s *Server) BuildRoute(_ context.Context,
1450
        req *BuildRouteRequest) (*BuildRouteResponse, error) {
3✔
1451

3✔
1452
        if len(req.HopPubkeys) == 0 {
3✔
1453
                return nil, errors.New("no hops specified")
×
1454
        }
×
1455

1456
        // Unmarshall hop list.
1457
        hops := make([]route.Vertex, len(req.HopPubkeys))
3✔
1458
        for i, pubkeyBytes := range req.HopPubkeys {
6✔
1459
                pubkey, err := route.NewVertexFromBytes(pubkeyBytes)
3✔
1460
                if err != nil {
3✔
1461
                        return nil, err
×
1462
                }
×
1463
                hops[i] = pubkey
3✔
1464
        }
1465

1466
        // Prepare BuildRoute call parameters from rpc request.
1467
        var amt fn.Option[lnwire.MilliSatoshi]
3✔
1468
        if req.AmtMsat != 0 {
6✔
1469
                rpcAmt := lnwire.MilliSatoshi(req.AmtMsat)
3✔
1470
                amt = fn.Some(rpcAmt)
3✔
1471
        }
3✔
1472

1473
        var outgoingChan *uint64
3✔
1474
        if req.OutgoingChanId != 0 {
3✔
1475
                outgoingChan = &req.OutgoingChanId
×
1476
        }
×
1477

1478
        var payAddr fn.Option[[32]byte]
3✔
1479
        if len(req.PaymentAddr) != 0 {
6✔
1480
                var backingPayAddr [32]byte
3✔
1481
                copy(backingPayAddr[:], req.PaymentAddr)
3✔
1482

3✔
1483
                payAddr = fn.Some(backingPayAddr)
3✔
1484
        }
3✔
1485

1486
        if req.FinalCltvDelta == 0 {
3✔
1487
                req.FinalCltvDelta = int32(
×
1488
                        s.cfg.RouterBackend.DefaultFinalCltvDelta,
×
1489
                )
×
1490
        }
×
1491

1492
        var firstHopBlob fn.Option[[]byte]
3✔
1493
        if len(req.FirstHopCustomRecords) > 0 {
3✔
1494
                firstHopRecords := lnwire.CustomRecords(
×
1495
                        req.FirstHopCustomRecords,
×
1496
                )
×
1497
                if err := firstHopRecords.Validate(); err != nil {
×
1498
                        return nil, err
×
1499
                }
×
1500

1501
                firstHopData, err := firstHopRecords.Serialize()
×
1502
                if err != nil {
×
1503
                        return nil, err
×
1504
                }
×
1505
                firstHopBlob = fn.Some(firstHopData)
×
1506
        }
1507

1508
        // Build the route and return it to the caller.
1509
        route, err := s.cfg.Router.BuildRoute(
3✔
1510
                amt, hops, outgoingChan, req.FinalCltvDelta, payAddr,
3✔
1511
                firstHopBlob,
3✔
1512
        )
3✔
1513
        if err != nil {
3✔
1514
                return nil, err
×
1515
        }
×
1516

1517
        rpcRoute, err := s.cfg.RouterBackend.MarshallRoute(route)
3✔
1518
        if err != nil {
3✔
1519
                return nil, err
×
1520
        }
×
1521

1522
        routeResp := &BuildRouteResponse{
3✔
1523
                Route: rpcRoute,
3✔
1524
        }
3✔
1525

3✔
1526
        return routeResp, nil
3✔
1527
}
1528

1529
// SubscribeHtlcEvents creates a uni-directional stream from the server to
1530
// the client which delivers a stream of htlc events.
1531
func (s *Server) SubscribeHtlcEvents(_ *SubscribeHtlcEventsRequest,
1532
        stream Router_SubscribeHtlcEventsServer) error {
3✔
1533

3✔
1534
        htlcClient, err := s.cfg.RouterBackend.SubscribeHtlcEvents()
3✔
1535
        if err != nil {
3✔
1536
                return err
×
1537
        }
×
1538
        defer htlcClient.Cancel()
3✔
1539

3✔
1540
        // Send out an initial subscribed event so that the caller knows the
3✔
1541
        // point from which new events will be transmitted.
3✔
1542
        if err := stream.Send(&HtlcEvent{
3✔
1543
                Event: &HtlcEvent_SubscribedEvent{
3✔
1544
                        SubscribedEvent: &SubscribedEvent{},
3✔
1545
                },
3✔
1546
        }); err != nil {
3✔
1547
                return err
×
1548
        }
×
1549

1550
        for {
6✔
1551
                select {
3✔
1552
                case event := <-htlcClient.Updates():
3✔
1553
                        rpcEvent, err := rpcHtlcEvent(event)
3✔
1554
                        if err != nil {
3✔
1555
                                return err
×
1556
                        }
×
1557

1558
                        if err := stream.Send(rpcEvent); err != nil {
3✔
1559
                                return err
×
1560
                        }
×
1561

1562
                // If the stream's context is cancelled, return an error.
1563
                case <-stream.Context().Done():
3✔
1564
                        log.Debugf("htlc event stream cancelled")
3✔
1565
                        return stream.Context().Err()
3✔
1566

1567
                // If the subscribe client terminates, exit with an error.
1568
                case <-htlcClient.Quit():
×
1569
                        return errors.New("htlc event subscription terminated")
×
1570

1571
                // If the server has been signalled to shut down, exit.
1572
                case <-s.quit:
×
1573
                        return errServerShuttingDown
×
1574
                }
1575
        }
1576
}
1577

1578
// HtlcInterceptor is a bidirectional stream for streaming interception
1579
// requests to the caller.
1580
// Upon connection, it does the following:
1581
// 1. Check if there is already a live stream, if yes it rejects the request.
1582
// 2. Registered a ForwardInterceptor
1583
// 3. Delivers to the caller every √√ and detect his answer.
1584
// It uses a local implementation of holdForwardsStore to keep all the hold
1585
// forwards and find them when manual resolution is later needed.
1586
func (s *Server) HtlcInterceptor(stream Router_HtlcInterceptorServer) error {
3✔
1587
        // We ensure there is only one interceptor at a time.
3✔
1588
        if !atomic.CompareAndSwapInt32(&s.forwardInterceptorActive, 0, 1) {
3✔
1589
                return ErrInterceptorAlreadyExists
×
1590
        }
×
1591
        defer atomic.CompareAndSwapInt32(&s.forwardInterceptorActive, 1, 0)
3✔
1592

3✔
1593
        // Run the forward interceptor.
3✔
1594
        return newForwardInterceptor(
3✔
1595
                s.cfg.RouterBackend.InterceptableForwarder, stream,
3✔
1596
        ).run()
3✔
1597
}
1598

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

3✔
1608
        existingAliases := s.cfg.AliasMgr.ListAliases()
3✔
1609

3✔
1610
        // aliasExists checks if the new alias already exists in the alias map.
3✔
1611
        aliasExists := func(newAlias uint64,
3✔
1612
                baseScid lnwire.ShortChannelID) (bool, error) {
6✔
1613

3✔
1614
                // First check that we actually have a channel for the given
3✔
1615
                // base scid. This should succeed for any channel where the
3✔
1616
                // option-scid-alias feature bit was negotiated.
3✔
1617
                if _, ok := existingAliases[baseScid]; !ok {
3✔
1618
                        return false, fmt.Errorf("base scid %v not found",
×
1619
                                baseScid)
×
1620
                }
×
1621

1622
                for base, aliases := range existingAliases {
6✔
1623
                        for _, alias := range aliases {
6✔
1624
                                exists := alias.ToUint64() == newAlias
3✔
1625

3✔
1626
                                // Trying to add an alias that we already have
3✔
1627
                                // for another channel is wrong.
3✔
1628
                                if exists && base != baseScid {
3✔
1629
                                        return true, fmt.Errorf("%w: alias %v "+
×
1630
                                                "already exists for base scid "+
×
1631
                                                "%v", ErrAliasAlreadyExists,
×
1632
                                                alias, base)
×
1633
                                }
×
1634

1635
                                if exists {
6✔
1636
                                        return true, nil
3✔
1637
                                }
3✔
1638
                        }
1639
                }
1640

1641
                return false, nil
3✔
1642
        }
1643

1644
        for _, v := range in.AliasMaps {
6✔
1645
                baseScid := lnwire.NewShortChanIDFromInt(v.BaseScid)
3✔
1646

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

3✔
1651
                        // But we only add it, if it's a valid alias, as defined
3✔
1652
                        // by the BOLT spec.
3✔
1653
                        if !aliasmgr.IsAlias(aliasScid) {
6✔
1654
                                return nil, fmt.Errorf("%w: SCID alias %v is "+
3✔
1655
                                        "not a valid alias", ErrNoValidAlias,
3✔
1656
                                        aliasScid)
3✔
1657
                        }
3✔
1658

1659
                        exists, err := aliasExists(rpcAlias, baseScid)
3✔
1660
                        if err != nil {
3✔
1661
                                return nil, err
×
1662
                        }
×
1663

1664
                        // If the alias already exists, we see that as an error.
1665
                        // This is to avoid "silent" collisions.
1666
                        if exists {
6✔
1667
                                return nil, fmt.Errorf("%w: SCID alias %v "+
3✔
1668
                                        "already exists", ErrAliasAlreadyExists,
3✔
1669
                                        rpcAlias)
3✔
1670
                        }
3✔
1671

1672
                        err = s.cfg.AliasMgr.AddLocalAlias(
3✔
1673
                                aliasScid, baseScid, false, true,
3✔
1674
                        )
3✔
1675
                        if err != nil {
3✔
1676
                                return nil, fmt.Errorf("error adding scid "+
×
1677
                                        "alias, base_scid=%v, alias_scid=%v: "+
×
1678
                                        "%w", baseScid, aliasScid, err)
×
1679
                        }
×
1680
                }
1681
        }
1682

1683
        return &AddAliasesResponse{
3✔
1684
                AliasMaps: lnrpc.MarshalAliasMap(s.cfg.AliasMgr.ListAliases()),
3✔
1685
        }, nil
3✔
1686
}
1687

1688
// XDeleteLocalChanAliases is an experimental API that deletes a set of alias
1689
// mappings. The final total set of aliases in the manager after the delete
1690
// operation is returned. The deletion will not be communicated to the channel
1691
// peer via any message.
1692
func (s *Server) XDeleteLocalChanAliases(_ context.Context,
1693
        in *DeleteAliasesRequest) (*DeleteAliasesResponse,
1694
        error) {
3✔
1695

3✔
1696
        for _, v := range in.AliasMaps {
6✔
1697
                baseScid := lnwire.NewShortChanIDFromInt(v.BaseScid)
3✔
1698

3✔
1699
                for _, alias := range v.Aliases {
6✔
1700
                        aliasScid := lnwire.NewShortChanIDFromInt(alias)
3✔
1701

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

1713
        return &DeleteAliasesResponse{
3✔
1714
                AliasMaps: lnrpc.MarshalAliasMap(s.cfg.AliasMgr.ListAliases()),
3✔
1715
        }, nil
3✔
1716
}
1717

1718
func extractOutPoint(req *UpdateChanStatusRequest) (*wire.OutPoint, error) {
3✔
1719
        chanPoint := req.GetChanPoint()
3✔
1720
        txid, err := lnrpc.GetChanPointFundingTxid(chanPoint)
3✔
1721
        if err != nil {
3✔
1722
                return nil, err
×
1723
        }
×
1724
        index := chanPoint.OutputIndex
3✔
1725
        return wire.NewOutPoint(txid, index), nil
3✔
1726
}
1727

1728
// UpdateChanStatus allows channel state to be set manually.
1729
func (s *Server) UpdateChanStatus(_ context.Context,
1730
        req *UpdateChanStatusRequest) (*UpdateChanStatusResponse, error) {
3✔
1731

3✔
1732
        outPoint, err := extractOutPoint(req)
3✔
1733
        if err != nil {
3✔
1734
                return nil, err
×
1735
        }
×
1736

1737
        action := req.GetAction()
3✔
1738

3✔
1739
        log.Debugf("UpdateChanStatus called for channel(%v) with "+
3✔
1740
                "action %v", outPoint, action)
3✔
1741

3✔
1742
        switch action {
3✔
1743
        case ChanStatusAction_ENABLE:
3✔
1744
                err = s.cfg.RouterBackend.SetChannelEnabled(*outPoint)
3✔
1745
        case ChanStatusAction_DISABLE:
3✔
1746
                err = s.cfg.RouterBackend.SetChannelDisabled(*outPoint)
3✔
1747
        case ChanStatusAction_AUTO:
3✔
1748
                err = s.cfg.RouterBackend.SetChannelAuto(*outPoint)
3✔
1749
        default:
×
1750
                err = fmt.Errorf("unrecognized ChannelStatusAction %v", action)
×
1751
        }
1752

1753
        if err != nil {
3✔
1754
                return nil, err
×
1755
        }
×
1756
        return &UpdateChanStatusResponse{}, nil
3✔
1757
}
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