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

lightningnetwork / lnd / 11954082915

21 Nov 2024 01:20PM UTC coverage: 59.327% (+0.6%) from 58.776%
11954082915

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

1940 of 2984 new or added lines in 44 files covered. (65.01%)

226 existing lines in 37 files now uncovered.

135234 of 227947 relevant lines covered (59.33%)

19316.75 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"
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) {
4✔
204
        routerServer := &Server{
4✔
205
                cfg:  &Config{},
4✔
206
                quit: make(chan struct{}),
4✔
207
        }
4✔
208

4✔
209
        return routerServer, macPermissions, nil
4✔
210
}
4✔
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 {
4✔
216
        if atomic.AddInt32(&s.shutdown, 1) != 1 {
4✔
NEW
217
                return nil
×
NEW
218
        }
×
219

220
        close(s.quit)
4✔
221

4✔
222
        return nil
4✔
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 {
4✔
233

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

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

243
        if finalizeDependencies {
8✔
244
                s.cfg = cfg
4✔
245

4✔
246
                return nil
4✔
247
        }
4✔
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 {
4✔
298
        return subServerName
4✔
299
}
4✔
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 {
4✔
307
        // We make sure that we register it with the main gRPC server to ensure
4✔
308
        // all our methods are routed properly.
4✔
309
        RegisterRouterServer(grpcServer, r)
4✔
310

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

4✔
314
        return nil
4✔
315
}
4✔
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 {
4✔
324

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

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

352
        r.RouterServer = subServer
4✔
353
        return subServer, macPermissions, nil
4✔
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 {
4✔
363

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

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

4✔
372
        // Init the payment in db.
4✔
373
        paySession, shardTracker, err := s.cfg.Router.PreparePayment(payment)
4✔
374
        if err != nil {
4✔
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)
4✔
394
        if err != nil {
4✔
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()
4✔
408
        if req.Cancelable {
8✔
409
                ctx = stream.Context()
4✔
410
        }
4✔
411

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

4✔
415
        // Track the payment and return.
4✔
416
        return s.trackPayment(sub, payHash, stream, req.NoInflightUpdates)
4✔
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) {
4✔
428

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

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

437
        case isProbeDestination:
4✔
438
                switch {
4✔
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:
4✔
446
                        return s.probeDestination(req.Dest, req.AmtSat)
4✔
447
                }
448

449
        case isProbeInvoice:
4✔
450
                return s.probePaymentRequest(
4✔
451
                        ctx, req.PaymentRequest, req.Timeout,
4✔
452
                )
4✔
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) {
4✔
462

4✔
463
        destNode, err := route.NewVertexFromBytes(dest)
4✔
464
        if err != nil {
4✔
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))
4✔
471

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

489
        route, _, err := s.cfg.Router.FindRoute(routeReq)
4✔
490
        if err != nil {
8✔
491
                return nil, err
4✔
492
        }
4✔
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)
4✔
499

4✔
500
        return &RouteFeeResponse{
4✔
501
                RoutingFeeMsat: int64(route.TotalFees()),
4✔
502
                TimeLockDelay:  int64(timeLockDelay),
4✔
503
                FailureReason:  lnrpc.PaymentFailureReason_FAILURE_REASON_NONE,
4✔
504
        }, nil
4✔
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) {
4✔
517

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

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

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

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

558
        hints := payReq.RouteHints
4✔
559

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

568
        // If the heuristic indicates an LSP we modify the route hints to allow
569
        // probing the LSP.
570
        lspAdjustedRouteHints, lspHint, err := prepareLspRouteHints(
4✔
571
                hints, *payReq.MilliSat,
4✔
572
        )
4✔
573
        if err != nil {
4✔
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()
4✔
580
        if len(lspAdjustedRouteHints) > 0 {
4✔
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)
4✔
599
        if err != nil {
4✔
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)
4✔
606

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

4✔
612
        // Dispatch the payment probe with adjusted fee amount.
4✔
613
        resp, err := s.sendProbePayment(ctx, probeRequest)
4✔
614
        if err != nil {
4✔
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:lll
4✔
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)
4✔
627

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

4✔
632
        return resp, nil
4✔
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 {
4✔
639
        if len(routeHints) == 0 || len(routeHints[0]) == 0 {
8✔
640
                return false
4✔
641
        }
4✔
642

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

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

660
        return true
4✔
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) {
4✔
669

4✔
670
        if len(routeHints) == 0 {
4✔
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]
4✔
677
        refHint.CLTVExpiryDelta = maxLspCltvDelta(routeHints)
4✔
678
        refHint.FeeBaseMSat, refHint.FeeProportionalMillionths = maxLspFee(
4✔
679
                routeHints, amt,
4✔
680
        )
4✔
681

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

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

696
        return adjustedHints, &refHint, nil
4✔
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) {
4✔
703

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

717
        return maxBaseFee, maxFeePpm
4✔
718
}
719

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

730
        return maxCltvDelta
4✔
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 {
4✔
746
        select {
4✔
747
        case p.stream <- response:
4✔
748

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

753
        return nil
4✔
754
}
755

756
// Context returns the context of the stream.
757
func (p *probePaymentStream) Context() context.Context {
4✔
758
        return p.ctx
4✔
759
}
4✔
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) {
4✔
768

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

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

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

789
        for {
8✔
790
                select {
4✔
791
                case payment := <-paymentStream.stream:
4✔
792
                        switch payment.Status {
4✔
793
                        case lnrpc.Payment_INITIATED:
×
794
                        case lnrpc.Payment_IN_FLIGHT:
4✔
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:
4✔
804
                                // Incorrect payment details point to a
4✔
805
                                // successful probe.
4✔
806
                                //nolint:lll
4✔
807
                                if payment.FailureReason == lnrpc.PaymentFailureReason_FAILURE_REASON_INCORRECT_PAYMENT_DETAILS {
8✔
808
                                        return paymentDetails(payment)
4✔
809
                                }
4✔
810

811
                                return &RouteFeeResponse{
4✔
812
                                        RoutingFeeMsat: 0,
4✔
813
                                        TimeLockDelay:  0,
4✔
814
                                        FailureReason:  payment.FailureReason,
4✔
815
                                }, nil
4✔
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) {
4✔
832
        fee, timeLock, err := timelockAndFee(payment)
4✔
833
        if errors.Is(err, errUnexpectedFailureSource) {
4✔
834
                return nil, err
×
835
        }
×
836

837
        return &RouteFeeResponse{
4✔
838
                RoutingFeeMsat: fee,
4✔
839
                TimeLockDelay:  timeLock,
4✔
840
                FailureReason:  lnrpc.PaymentFailureReason_FAILURE_REASON_NONE,
4✔
841
        }, nil
4✔
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) {
4✔
847
        if len(p.Htlcs) == 0 {
4✔
848
                return 0, 0, nil
×
849
        }
×
850

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

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

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

867
        return lastRoute.TotalFeesMsat, int64(lastRoute.TotalTimeLock), nil
4✔
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) {
4✔
874

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

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

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

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

894
        var attempt *channeldb.HTLCAttempt
4✔
895

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

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

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

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

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

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

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

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

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

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

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

1005
        return resp, nil
4✔
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) {
4✔
1012

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

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

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

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

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

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

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

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

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

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

1089
        return &SetMissionControlConfigResponse{},
4✔
1090
                s.cfg.RouterBackend.MissionControl.SetConfig(mcCfg)
4✔
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 {
4✔
1123
        rpcData := PairData{
4✔
1124
                FailAmtSat:     int64(data.FailAmt.ToSatoshis()),
4✔
1125
                FailAmtMsat:    int64(data.FailAmt),
4✔
1126
                SuccessAmtSat:  int64(data.SuccessAmt.ToSatoshis()),
4✔
1127
                SuccessAmtMsat: int64(data.SuccessAmt),
4✔
1128
        }
4✔
1129

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

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

1138
        return &rpcData
4✔
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) {
4✔
1146

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

4✔
1232
        return &routing.MissionControlPairSnapshot{
4✔
1233
                Pair:            pair,
4✔
1234
                TimedPairResult: *result,
4✔
1235
        }, nil
4✔
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) {
4✔
1244

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

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

4✔
1255
        switch {
4✔
1256
        // If a timestamp and amount if provided, return those values.
1257
        case timeSet && amountSet:
4✔
1258
                return amt, time.Unix(timestamp, 0), nil
4✔
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:
4✔
1273
                return 0, time.Time{}, nil
4✔
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) {
4✔
1281

4✔
1282
        // If our msat value converted to sats equals our sat value, we just
4✔
1283
        // return the msat value, since the values are the same.
4✔
1284
        if msatValue.ToSatoshis() == satValue {
8✔
1285
                return msatValue, nil
4✔
1286
        }
4✔
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 {
4✔
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 {
4✔
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,
4✔
1302
                satValue)
4✔
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 {
4✔
1309

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

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

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

1323
        return s.trackPayment(sub, payHash, stream, request.NoInflightUpdates)
4✔
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) {
4✔
1330

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

4✔
1335
        switch {
4✔
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
4✔
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 {
4✔
1350

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

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

4✔
1359
                return nil
4✔
1360
        }
4✔
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)
4✔
1365

4✔
1366
        return err
4✔
1367
}
1368

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

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

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

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

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

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

1393
        return err
4✔
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 {
4✔
1400

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

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

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

4✔
1416
                        // Skip in-flight updates unless requested.
4✔
1417
                        if noInflightUpdates {
4✔
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(
4✔
1427
                                result,
4✔
1428
                        )
4✔
1429
                        if err != nil {
4✔
1430
                                return err
×
1431
                        }
×
1432

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

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

1442
                case <-context.Done():
4✔
1443
                        return context.Err()
4✔
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) {
4✔
1451

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

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

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

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

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

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

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

1492
        var firstHopBlob fn.Option[[]byte]
4✔
1493
        if len(req.FirstHopCustomRecords) > 0 {
4✔
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(
4✔
1510
                amt, hops, outgoingChan, req.FinalCltvDelta, payAddr,
4✔
1511
                firstHopBlob,
4✔
1512
        )
4✔
1513
        if err != nil {
4✔
1514
                return nil, err
×
1515
        }
×
1516

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

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

4✔
1526
        return routeResp, nil
4✔
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 {
4✔
1533

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

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

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

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

1562
                // If the stream's context is cancelled, return an error.
1563
                case <-stream.Context().Done():
4✔
1564
                        log.Debugf("htlc event stream cancelled")
4✔
1565
                        return stream.Context().Err()
4✔
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 {
4✔
1587
        // We ensure there is only one interceptor at a time.
4✔
1588
        if !atomic.CompareAndSwapInt32(&s.forwardInterceptorActive, 0, 1) {
4✔
1589
                return ErrInterceptorAlreadyExists
×
1590
        }
×
1591
        defer atomic.CompareAndSwapInt32(&s.forwardInterceptorActive, 1, 0)
4✔
1592

4✔
1593
        // Run the forward interceptor.
4✔
1594
        return newForwardInterceptor(
4✔
1595
                s.cfg.RouterBackend.InterceptableForwarder, stream,
4✔
1596
        ).run()
4✔
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) {
4✔
1607

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

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

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

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

4✔
1626
                                // Trying to add an alias that we already have
4✔
1627
                                // for another channel is wrong.
4✔
1628
                                if exists && base != baseScid {
4✔
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 {
8✔
1636
                                        return true, nil
4✔
1637
                                }
4✔
1638
                        }
1639
                }
1640

1641
                return false, nil
4✔
1642
        }
1643

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

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

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

1659
                        exists, err := aliasExists(rpcAlias, baseScid)
4✔
1660
                        if err != nil {
4✔
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 {
8✔
1667
                                return nil, fmt.Errorf("%w: SCID alias %v "+
4✔
1668
                                        "already exists", ErrAliasAlreadyExists,
4✔
1669
                                        rpcAlias)
4✔
1670
                        }
4✔
1671

1672
                        err = s.cfg.AliasMgr.AddLocalAlias(
4✔
1673
                                aliasScid, baseScid, false, true,
4✔
1674
                        )
4✔
1675
                        if err != nil {
4✔
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{
4✔
1684
                AliasMaps: lnrpc.MarshalAliasMap(s.cfg.AliasMgr.ListAliases()),
4✔
1685
        }, nil
4✔
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) {
4✔
1695

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

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

4✔
1702
                        err := s.cfg.AliasMgr.DeleteLocalAlias(
4✔
1703
                                aliasScid, baseScid,
4✔
1704
                        )
4✔
1705
                        if err != nil {
4✔
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{
4✔
1714
                AliasMaps: lnrpc.MarshalAliasMap(s.cfg.AliasMgr.ListAliases()),
4✔
1715
        }, nil
4✔
1716
}
1717

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

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

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

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

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

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

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