github.com/decred/dcrlnd@v0.7.6/lnrpc/routerrpc/router_backend.go (about) 1 package routerrpc 2 3 import ( 4 "context" 5 "crypto/rand" 6 "encoding/hex" 7 "errors" 8 "fmt" 9 math "math" 10 "time" 11 12 "github.com/decred/dcrd/dcrec/secp256k1/v4" 13 "github.com/decred/dcrd/wire" 14 15 "github.com/decred/dcrd/chaincfg/v3" 16 "github.com/decred/dcrd/dcrutil/v4" 17 "github.com/decred/dcrlnd/channeldb" 18 "github.com/decred/dcrlnd/feature" 19 "github.com/decred/dcrlnd/htlcswitch" 20 "github.com/decred/dcrlnd/lnrpc" 21 "github.com/decred/dcrlnd/lntypes" 22 "github.com/decred/dcrlnd/lnwire" 23 "github.com/decred/dcrlnd/record" 24 "github.com/decred/dcrlnd/routing" 25 "github.com/decred/dcrlnd/routing/route" 26 "github.com/decred/dcrlnd/subscribe" 27 "github.com/decred/dcrlnd/zpay32" 28 ) 29 30 const ( 31 // DefaultMaxParts is the default number of splits we'll possibly use 32 // for MPP when the user is attempting to send a payment. 33 // 34 // TODO(roasbeef): make this value dynamic based on expected number of 35 // attempts for given amount 36 DefaultMaxParts = 16 37 ) 38 39 // RouterBackend contains the backend implementation of the router rpc sub 40 // server calls. 41 type RouterBackend struct { 42 // MaxPaymentMAtoms is the largest payment permitted by the backend. 43 MaxPaymentMAtoms lnwire.MilliAtom 44 45 // SelfNode is the vertex of the node sending the payment. 46 SelfNode route.Vertex 47 48 // FetchChannelCapacity is a closure that we'll use the fetch the total 49 // capacity of a channel to populate in responses. 50 FetchChannelCapacity func(chanID uint64) (dcrutil.Amount, error) 51 52 // FetchChannelEndpoints returns the pubkeys of both endpoints of the 53 // given channel id. 54 FetchChannelEndpoints func(chanID uint64) (route.Vertex, 55 route.Vertex, error) 56 57 // FindRoute is a closure that abstracts away how we locate/query for 58 // routes. 59 FindRoute func(source, target route.Vertex, 60 amt lnwire.MilliAtom, restrictions *routing.RestrictParams, 61 destCustomRecords record.CustomSet, 62 routeHints map[route.Vertex][]*channeldb.CachedEdgePolicy, 63 finalExpiry uint16) (*route.Route, error) 64 65 MissionControl MissionControl 66 67 // ActiveNetParams are the network parameters of the primary network 68 // that the route is operating on. This is necessary so we can ensure 69 // that we receive payment requests that send to destinations on our 70 // network. 71 ActiveNetParams *chaincfg.Params 72 73 // Tower is the ControlTower instance that is used to track pending 74 // payments. 75 Tower routing.ControlTower 76 77 // MaxTotalTimelock is the maximum total time lock a route is allowed to 78 // have. 79 MaxTotalTimelock uint32 80 81 // DefaultFinalCltvDelta is the default value used as final cltv delta 82 // when an RPC caller doesn't specify a value. 83 DefaultFinalCltvDelta uint16 84 85 // SubscribeHtlcEvents returns a subscription client for the node's 86 // htlc events. 87 SubscribeHtlcEvents func() (*subscribe.Client, error) 88 89 // InterceptableForwarder exposes the ability to intercept forward events 90 // by letting the router register a ForwardInterceptor. 91 InterceptableForwarder htlcswitch.InterceptableHtlcForwarder 92 93 // SetChannelEnabled exposes the ability to manually enable a channel. 94 SetChannelEnabled func(wire.OutPoint) error 95 96 // SetChannelDisabled exposes the ability to manually disable a channel 97 SetChannelDisabled func(wire.OutPoint) error 98 99 // SetChannelAuto exposes the ability to restore automatic channel state 100 // management after manually setting channel status. 101 SetChannelAuto func(wire.OutPoint) error 102 } 103 104 // MissionControl defines the mission control dependencies of routerrpc. 105 type MissionControl interface { 106 // GetProbability is expected to return the success probability of a 107 // payment from fromNode to toNode. 108 GetProbability(fromNode, toNode route.Vertex, 109 amt lnwire.MilliAtom) float64 110 111 // ResetHistory resets the history of MissionControl returning it to a 112 // state as if no payment attempts have been made. 113 ResetHistory() error 114 115 // GetHistorySnapshot takes a snapshot from the current mission control 116 // state and actual probability estimates. 117 GetHistorySnapshot() *routing.MissionControlSnapshot 118 119 // ImportHistory imports the mission control snapshot to our internal 120 // state. This import will only be applied in-memory, and will not be 121 // persisted across restarts. 122 ImportHistory(snapshot *routing.MissionControlSnapshot, force bool) error 123 124 // GetPairHistorySnapshot returns the stored history for a given node 125 // pair. 126 GetPairHistorySnapshot(fromNode, 127 toNode route.Vertex) routing.TimedPairResult 128 129 // GetConfig gets mission control's current config. 130 GetConfig() *routing.MissionControlConfig 131 132 // SetConfig sets mission control's config to the values provided, if 133 // they are valid. 134 SetConfig(cfg *routing.MissionControlConfig) error 135 } 136 137 // QueryRoutes attempts to query the daemons' Channel Router for a possible 138 // route to a target destination capable of carrying a specific amount of 139 // satoshis within the route's flow. The retuned route contains the full 140 // details required to craft and send an HTLC, also including the necessary 141 // information that should be present within the Sphinx packet encapsulated 142 // within the HTLC. 143 // 144 // TODO(roasbeef): should return a slice of routes in reality * create separate 145 // PR to send based on well formatted route 146 func (r *RouterBackend) QueryRoutes(ctx context.Context, 147 in *lnrpc.QueryRoutesRequest) (*lnrpc.QueryRoutesResponse, error) { 148 149 parsePubKey := func(key string) (route.Vertex, error) { 150 pubKeyBytes, err := hex.DecodeString(key) 151 if err != nil { 152 return route.Vertex{}, err 153 } 154 155 return route.NewVertexFromBytes(pubKeyBytes) 156 } 157 158 // Parse the hex-encoded source and target public keys into full public 159 // key objects we can properly manipulate. 160 targetPubKey, err := parsePubKey(in.PubKey) 161 if err != nil { 162 return nil, err 163 } 164 165 var sourcePubKey route.Vertex 166 if in.SourcePubKey != "" { 167 var err error 168 sourcePubKey, err = parsePubKey(in.SourcePubKey) 169 if err != nil { 170 return nil, err 171 } 172 } else { 173 // If no source is specified, use self. 174 sourcePubKey = r.SelfNode 175 } 176 177 // Currently, within the bootstrap phase of the network, we limit the 178 // largest payment size allotted to (2^32) - 1 mSAT or 4.29 million 179 // satoshis. 180 amt, err := lnrpc.UnmarshallAmt(in.Amt, in.AmtMAtoms) 181 if err != nil { 182 return nil, err 183 } 184 if amt > r.MaxPaymentMAtoms { 185 return nil, fmt.Errorf("payment of %v is too large, max payment "+ 186 "allowed is %v", amt, r.MaxPaymentMAtoms.ToAtoms()) 187 } 188 189 // Unmarshall restrictions from request. 190 feeLimit := lnrpc.CalculateFeeLimit(in.FeeLimit, amt) 191 192 ignoredNodes := make(map[route.Vertex]struct{}) 193 for _, ignorePubKey := range in.IgnoredNodes { 194 ignoreVertex, err := route.NewVertexFromBytes(ignorePubKey) 195 if err != nil { 196 return nil, err 197 } 198 ignoredNodes[ignoreVertex] = struct{}{} 199 } 200 201 ignoredPairs := make(map[routing.DirectedNodePair]struct{}) 202 203 // Convert deprecated ignoredEdges to pairs. 204 for _, ignoredEdge := range in.IgnoredEdges { 205 pair, err := r.rpcEdgeToPair(ignoredEdge) 206 if err != nil { 207 log.Warnf("Ignore channel %v skipped: %v", 208 ignoredEdge.ChannelId, err) 209 210 continue 211 } 212 ignoredPairs[pair] = struct{}{} 213 } 214 215 // Add ignored pairs to set. 216 for _, ignorePair := range in.IgnoredPairs { 217 from, err := route.NewVertexFromBytes(ignorePair.From) 218 if err != nil { 219 return nil, err 220 } 221 222 to, err := route.NewVertexFromBytes(ignorePair.To) 223 if err != nil { 224 return nil, err 225 } 226 227 pair := routing.NewDirectedNodePair(from, to) 228 ignoredPairs[pair] = struct{}{} 229 } 230 231 // Since QueryRoutes allows having a different source other than 232 // ourselves, we'll only apply our max time lock if we are the source. 233 maxTotalTimelock := r.MaxTotalTimelock 234 if sourcePubKey != r.SelfNode { 235 maxTotalTimelock = math.MaxUint32 236 } 237 cltvLimit, err := ValidateCLTVLimit(in.CltvLimit, maxTotalTimelock) 238 if err != nil { 239 return nil, err 240 } 241 242 // We need to subtract the final delta before passing it into path 243 // finding. The optimal path is independent of the final cltv delta and 244 // the path finding algorithm is unaware of this value. 245 finalCLTVDelta := r.DefaultFinalCltvDelta 246 if in.FinalCltvDelta != 0 { 247 finalCLTVDelta = uint16(in.FinalCltvDelta) 248 } 249 250 // Do bounds checking without block padding so we don't give routes 251 // that will leave the router in a zombie payment state. 252 err = routing.ValidateCLTVLimit(cltvLimit, finalCLTVDelta, false) 253 if err != nil { 254 return nil, err 255 } 256 257 cltvLimit -= uint32(finalCLTVDelta) 258 259 // Parse destination feature bits. 260 features, err := UnmarshalFeatures(in.DestFeatures) 261 if err != nil { 262 return nil, err 263 } 264 265 restrictions := &routing.RestrictParams{ 266 FeeLimit: feeLimit, 267 ProbabilitySource: func(fromNode, toNode route.Vertex, 268 amt lnwire.MilliAtom) float64 { 269 270 if _, ok := ignoredNodes[fromNode]; ok { 271 return 0 272 } 273 274 pair := routing.DirectedNodePair{ 275 From: fromNode, 276 To: toNode, 277 } 278 if _, ok := ignoredPairs[pair]; ok { 279 return 0 280 } 281 282 if !in.UseMissionControl { 283 return 1 284 } 285 286 return r.MissionControl.GetProbability( 287 fromNode, toNode, amt, 288 ) 289 }, 290 DestCustomRecords: record.CustomSet(in.DestCustomRecords), 291 CltvLimit: cltvLimit, 292 DestFeatures: features, 293 } 294 295 // Pass along an outgoing channel restriction if specified. 296 if in.OutgoingChanId != 0 { 297 restrictions.OutgoingChannelIDs = []uint64{in.OutgoingChanId} 298 } 299 300 // Pass along a last hop restriction if specified. 301 if len(in.LastHopPubkey) > 0 { 302 lastHop, err := route.NewVertexFromBytes( 303 in.LastHopPubkey, 304 ) 305 if err != nil { 306 return nil, err 307 } 308 restrictions.LastHop = &lastHop 309 } 310 311 // If we have any TLV records destined for the final hop, then we'll 312 // attempt to decode them now into a form that the router can more 313 // easily manipulate. 314 customRecords := record.CustomSet(in.DestCustomRecords) 315 if err := customRecords.Validate(); err != nil { 316 return nil, err 317 } 318 319 // Convert route hints to an edge map. 320 routeHints, err := unmarshallRouteHints(in.RouteHints) 321 if err != nil { 322 return nil, err 323 } 324 routeHintEdges, err := routing.RouteHintsToEdges( 325 routeHints, targetPubKey, 326 ) 327 if err != nil { 328 return nil, err 329 } 330 331 // Query the channel router for a possible path to the destination that 332 // can carry `in.Amt` satoshis _including_ the total fee required on 333 // the route. 334 route, err := r.FindRoute( 335 sourcePubKey, targetPubKey, amt, restrictions, 336 customRecords, routeHintEdges, finalCLTVDelta, 337 ) 338 if err != nil { 339 return nil, err 340 } 341 342 // For each valid route, we'll convert the result into the format 343 // required by the RPC system. 344 rpcRoute, err := r.MarshallRoute(route) 345 if err != nil { 346 return nil, err 347 } 348 349 // Calculate route success probability. Do not rely on a probability 350 // that could have been returned from path finding, because mission 351 // control may have been disabled in the provided ProbabilitySource. 352 successProb := r.getSuccessProbability(route) 353 354 routeResp := &lnrpc.QueryRoutesResponse{ 355 Routes: []*lnrpc.Route{rpcRoute}, 356 SuccessProb: successProb, 357 } 358 359 return routeResp, nil 360 } 361 362 // getSuccessProbability returns the success probability for the given route 363 // based on the current state of mission control. 364 func (r *RouterBackend) getSuccessProbability(rt *route.Route) float64 { 365 fromNode := rt.SourcePubKey 366 amtToFwd := rt.TotalAmount 367 successProb := 1.0 368 for _, hop := range rt.Hops { 369 toNode := hop.PubKeyBytes 370 371 probability := r.MissionControl.GetProbability( 372 fromNode, toNode, amtToFwd, 373 ) 374 375 successProb *= probability 376 377 amtToFwd = hop.AmtToForward 378 fromNode = toNode 379 } 380 381 return successProb 382 } 383 384 // rpcEdgeToPair looks up the provided channel and returns the channel endpoints 385 // as a directed pair. 386 func (r *RouterBackend) rpcEdgeToPair(e *lnrpc.EdgeLocator) ( 387 routing.DirectedNodePair, error) { 388 389 a, b, err := r.FetchChannelEndpoints(e.ChannelId) 390 if err != nil { 391 return routing.DirectedNodePair{}, err 392 } 393 394 var pair routing.DirectedNodePair 395 if e.DirectionReverse { 396 pair.From, pair.To = b, a 397 } else { 398 pair.From, pair.To = a, b 399 } 400 401 return pair, nil 402 } 403 404 // MarshallRoute marshalls an internal route to an rpc route struct. 405 func (r *RouterBackend) MarshallRoute(route *route.Route) (*lnrpc.Route, error) { 406 resp := &lnrpc.Route{ 407 TotalTimeLock: route.TotalTimeLock, 408 TotalFees: int64(route.TotalFees().ToAtoms()), 409 TotalFeesMAtoms: int64(route.TotalFees()), 410 TotalAmt: int64(route.TotalAmount.ToAtoms()), 411 TotalAmtMAtoms: int64(route.TotalAmount), 412 Hops: make([]*lnrpc.Hop, len(route.Hops)), 413 } 414 incomingAmt := route.TotalAmount 415 for i, hop := range route.Hops { 416 fee := route.HopFee(i) 417 418 // Channel capacity is not a defining property of a route. For 419 // backwards RPC compatibility, we retrieve it here from the 420 // graph. 421 chanCapacity, err := r.FetchChannelCapacity(hop.ChannelID) 422 if err != nil { 423 // If capacity cannot be retrieved, this may be a 424 // not-yet-received or private channel. Then report 425 // amount that is sent through the channel as capacity. 426 chanCapacity = incomingAmt.ToAtoms() 427 } 428 429 // Extract the MPP fields if present on this hop. 430 var mpp *lnrpc.MPPRecord 431 if hop.MPP != nil { 432 addr := hop.MPP.PaymentAddr() 433 434 mpp = &lnrpc.MPPRecord{ 435 PaymentAddr: addr[:], 436 TotalAmtMAtoms: int64(hop.MPP.TotalMAtoms()), 437 } 438 } 439 440 resp.Hops[i] = &lnrpc.Hop{ 441 ChanId: hop.ChannelID, 442 ChanCapacity: int64(chanCapacity), 443 AmtToForward: int64(hop.AmtToForward.ToAtoms()), 444 AmtToForwardMAtoms: int64(hop.AmtToForward), 445 Fee: int64(fee.ToAtoms()), 446 FeeMAtoms: int64(fee), 447 Expiry: hop.OutgoingTimeLock, 448 PubKey: hex.EncodeToString( 449 hop.PubKeyBytes[:], 450 ), 451 CustomRecords: hop.CustomRecords, 452 TlvPayload: !hop.LegacyPayload, 453 MppRecord: mpp, 454 } 455 incomingAmt = hop.AmtToForward 456 } 457 458 return resp, nil 459 } 460 461 // UnmarshallHopWithPubkey unmarshalls an rpc hop for which the pubkey has 462 // already been extracted. 463 func UnmarshallHopWithPubkey(rpcHop *lnrpc.Hop, pubkey route.Vertex) (*route.Hop, 464 error) { 465 466 customRecords := record.CustomSet(rpcHop.CustomRecords) 467 if err := customRecords.Validate(); err != nil { 468 return nil, err 469 } 470 471 mpp, err := UnmarshalMPP(rpcHop.MppRecord) 472 if err != nil { 473 return nil, err 474 } 475 476 amp, err := UnmarshalAMP(rpcHop.AmpRecord) 477 if err != nil { 478 return nil, err 479 } 480 481 return &route.Hop{ 482 OutgoingTimeLock: rpcHop.Expiry, 483 AmtToForward: lnwire.MilliAtom(rpcHop.AmtToForwardMAtoms), 484 PubKeyBytes: pubkey, 485 ChannelID: rpcHop.ChanId, 486 CustomRecords: customRecords, 487 LegacyPayload: false, 488 MPP: mpp, 489 AMP: amp, 490 }, nil 491 } 492 493 // UnmarshallHop unmarshalls an rpc hop that may or may not contain a node 494 // pubkey. 495 func (r *RouterBackend) UnmarshallHop(rpcHop *lnrpc.Hop, 496 prevNodePubKey [33]byte) (*route.Hop, error) { 497 498 var pubKeyBytes [33]byte 499 if rpcHop.PubKey != "" { 500 // Unmarshall the provided hop pubkey. 501 pubKey, err := hex.DecodeString(rpcHop.PubKey) 502 if err != nil { 503 return nil, fmt.Errorf("cannot decode pubkey %s", 504 rpcHop.PubKey) 505 } 506 copy(pubKeyBytes[:], pubKey) 507 } else { 508 // If no pub key is given of the hop, the local channel graph 509 // needs to be queried to complete the information necessary for 510 // routing. Discard edge policies, because they may be nil. 511 node1, node2, err := r.FetchChannelEndpoints(rpcHop.ChanId) 512 if err != nil { 513 return nil, err 514 } 515 516 switch { 517 case prevNodePubKey == node1: 518 pubKeyBytes = node2 519 case prevNodePubKey == node2: 520 pubKeyBytes = node1 521 default: 522 return nil, fmt.Errorf("channel edge does not match " + 523 "expected node") 524 } 525 } 526 527 return UnmarshallHopWithPubkey(rpcHop, pubKeyBytes) 528 } 529 530 // UnmarshallRoute unmarshalls an rpc route. For hops that don't specify a 531 // pubkey, the channel graph is queried. 532 func (r *RouterBackend) UnmarshallRoute(rpcroute *lnrpc.Route) ( 533 *route.Route, error) { 534 535 prevNodePubKey := r.SelfNode 536 537 hops := make([]*route.Hop, len(rpcroute.Hops)) 538 for i, hop := range rpcroute.Hops { 539 routeHop, err := r.UnmarshallHop(hop, prevNodePubKey) 540 if err != nil { 541 return nil, err 542 } 543 544 if routeHop.AmtToForward > r.MaxPaymentMAtoms { 545 return nil, fmt.Errorf("payment of %v is too large, "+ 546 "max payment allowed is %v", 547 routeHop.AmtToForward, 548 r.MaxPaymentMAtoms.ToAtoms()) 549 } 550 551 hops[i] = routeHop 552 553 prevNodePubKey = routeHop.PubKeyBytes 554 } 555 556 route, err := route.NewRouteFromHops( 557 lnwire.MilliAtom(rpcroute.TotalAmtMAtoms), 558 rpcroute.TotalTimeLock, 559 r.SelfNode, 560 hops, 561 ) 562 if err != nil { 563 return nil, err 564 } 565 566 return route, nil 567 } 568 569 // extractIntentFromSendRequest attempts to parse the SendRequest details 570 // required to dispatch a client from the information presented by an RPC 571 // client. 572 func (r *RouterBackend) extractIntentFromSendRequest( 573 rpcPayReq *SendPaymentRequest) (*routing.LightningPayment, error) { 574 575 payIntent := &routing.LightningPayment{} 576 577 // Pass along restrictions on the outgoing channels that may be used. 578 payIntent.OutgoingChannelIDs = rpcPayReq.OutgoingChanIds 579 580 // Add the deprecated single outgoing channel restriction if present. 581 if rpcPayReq.OutgoingChanId != 0 { 582 if payIntent.OutgoingChannelIDs != nil { 583 return nil, errors.New("outgoing_chan_id and " + 584 "outgoing_chan_ids are mutually exclusive") 585 } 586 587 payIntent.OutgoingChannelIDs = append( 588 payIntent.OutgoingChannelIDs, rpcPayReq.OutgoingChanId, 589 ) 590 } 591 592 // Pass along a last hop restriction if specified. 593 if len(rpcPayReq.LastHopPubkey) > 0 { 594 lastHop, err := route.NewVertexFromBytes( 595 rpcPayReq.LastHopPubkey, 596 ) 597 if err != nil { 598 return nil, err 599 } 600 payIntent.LastHop = &lastHop 601 } 602 603 // Take the CLTV limit from the request if set, otherwise use the max. 604 cltvLimit, err := ValidateCLTVLimit( 605 uint32(rpcPayReq.CltvLimit), r.MaxTotalTimelock, 606 ) 607 if err != nil { 608 return nil, err 609 } 610 payIntent.CltvLimit = cltvLimit 611 612 // Attempt to parse the max parts value set by the user, if this value 613 // isn't set, then we'll use the current default value for this 614 // setting. 615 maxParts := rpcPayReq.MaxParts 616 if maxParts == 0 { 617 maxParts = DefaultMaxParts 618 } 619 payIntent.MaxParts = maxParts 620 621 // If this payment had a max shard amount specified, then we'll apply 622 // that now, which'll force us to always make payment splits smaller 623 // than this. 624 if rpcPayReq.MaxShardSizeMatoms > 0 { 625 shardAmtMAtoms := lnwire.MilliAtom(rpcPayReq.MaxShardSizeMatoms) 626 payIntent.MaxShardAmt = &shardAmtMAtoms 627 } 628 629 // Take fee limit from request. 630 payIntent.FeeLimit, err = lnrpc.UnmarshallAmt( 631 rpcPayReq.FeeLimitAtoms, rpcPayReq.FeeLimitMAtoms, 632 ) 633 if err != nil { 634 return nil, err 635 } 636 637 // Set payment attempt timeout. 638 if rpcPayReq.TimeoutSeconds == 0 { 639 return nil, errors.New("timeout_seconds must be specified") 640 } 641 642 customRecords := record.CustomSet(rpcPayReq.DestCustomRecords) 643 if err := customRecords.Validate(); err != nil { 644 return nil, err 645 } 646 payIntent.DestCustomRecords = customRecords 647 648 payIntent.PayAttemptTimeout = time.Second * 649 time.Duration(rpcPayReq.TimeoutSeconds) 650 651 // Route hints. 652 routeHints, err := unmarshallRouteHints( 653 rpcPayReq.RouteHints, 654 ) 655 if err != nil { 656 return nil, err 657 } 658 payIntent.RouteHints = routeHints 659 660 // Unmarshall either sat or msat amount from request. 661 reqAmt, err := lnrpc.UnmarshallAmt( 662 rpcPayReq.Amt, rpcPayReq.AmtMAtoms, 663 ) 664 if err != nil { 665 return nil, err 666 } 667 668 // If the payment request field isn't blank, then the details of the 669 // invoice are encoded entirely within the encoded payReq. So we'll 670 // attempt to decode it, populating the payment accordingly. 671 if rpcPayReq.PaymentRequest != "" { 672 switch { 673 674 case len(rpcPayReq.Dest) > 0: 675 return nil, errors.New("dest and payment_request " + 676 "cannot appear together") 677 678 case len(rpcPayReq.PaymentHash) > 0: 679 return nil, errors.New("payment_hash and payment_request " + 680 "cannot appear together") 681 682 case rpcPayReq.FinalCltvDelta != 0: 683 return nil, errors.New("final_cltv_delta and payment_request " + 684 "cannot appear together") 685 } 686 687 payReq, err := zpay32.Decode( 688 rpcPayReq.PaymentRequest, r.ActiveNetParams, 689 ) 690 if err != nil { 691 return nil, err 692 } 693 694 // Next, we'll ensure that this payreq hasn't already expired. 695 err = ValidatePayReqExpiry(payReq) 696 if err != nil { 697 return nil, err 698 } 699 700 // If the amount was not included in the invoice, then we let 701 // the payee specify the amount of satoshis they wish to send. 702 // We override the amount to pay with the amount provided from 703 // the payment request. 704 if payReq.MilliAt == nil { 705 if reqAmt == 0 { 706 return nil, errors.New("amount must be " + 707 "specified when paying a zero amount " + 708 "invoice") 709 } 710 711 payIntent.Amount = reqAmt 712 } else { 713 if reqAmt != 0 { 714 return nil, errors.New("amount must not be " + 715 "specified when paying a non-zero " + 716 " amount invoice") 717 } 718 719 payIntent.Amount = *payReq.MilliAt 720 } 721 722 if !payReq.Features.HasFeature(lnwire.MPPOptional) && 723 !payReq.Features.HasFeature(lnwire.AMPOptional) { 724 725 payIntent.MaxParts = 1 726 } 727 728 payAddr := payReq.PaymentAddr 729 if payReq.Features.HasFeature(lnwire.AMPOptional) { 730 // Generate random SetID and root share. 731 var setID [32]byte 732 _, err = rand.Read(setID[:]) 733 if err != nil { 734 return nil, err 735 } 736 737 var rootShare [32]byte 738 _, err = rand.Read(rootShare[:]) 739 if err != nil { 740 return nil, err 741 } 742 err := payIntent.SetAMP(&routing.AMPOptions{ 743 SetID: setID, 744 RootShare: rootShare, 745 }) 746 if err != nil { 747 return nil, err 748 } 749 750 // For AMP invoices, we'll allow users to override the 751 // included payment addr to allow the invoice to be 752 // pseudo-reusable, e.g. the invoice parameters are 753 // reused (amt, cltv, hop hints, etc) even though the 754 // payments will share different payment hashes. 755 if len(rpcPayReq.PaymentAddr) > 0 { 756 var addr [32]byte 757 copy(addr[:], rpcPayReq.PaymentAddr) 758 payAddr = &addr 759 } 760 } else { 761 err = payIntent.SetPaymentHash(*payReq.PaymentHash) 762 if err != nil { 763 return nil, err 764 } 765 } 766 767 destKey := payReq.Destination.SerializeCompressed() 768 copy(payIntent.Target[:], destKey) 769 770 payIntent.FinalCLTVDelta = uint16(payReq.MinFinalCLTVExpiry()) 771 payIntent.RouteHints = append( 772 payIntent.RouteHints, payReq.RouteHints..., 773 ) 774 payIntent.DestFeatures = payReq.Features 775 payIntent.PaymentAddr = payAddr 776 payIntent.PaymentRequest = []byte(rpcPayReq.PaymentRequest) 777 } else { 778 // Otherwise, If the payment request field was not specified 779 // (and a custom route wasn't specified), construct the payment 780 // from the other fields. 781 782 // Payment destination. 783 target, err := route.NewVertexFromBytes(rpcPayReq.Dest) 784 if err != nil { 785 return nil, err 786 } 787 payIntent.Target = target 788 789 // Final payment CLTV delta. 790 if rpcPayReq.FinalCltvDelta != 0 { 791 payIntent.FinalCLTVDelta = 792 uint16(rpcPayReq.FinalCltvDelta) 793 } else { 794 payIntent.FinalCLTVDelta = r.DefaultFinalCltvDelta 795 } 796 797 // Amount. 798 if reqAmt == 0 { 799 return nil, errors.New("amount must be specified") 800 } 801 802 payIntent.Amount = reqAmt 803 804 // Parse destination feature bits. 805 features, err := UnmarshalFeatures(rpcPayReq.DestFeatures) 806 if err != nil { 807 return nil, err 808 } 809 810 // Validate the features if any was specified. 811 if features != nil { 812 err = feature.ValidateDeps(features) 813 if err != nil { 814 return nil, err 815 } 816 } 817 818 // If this is an AMP payment, we must generate the initial 819 // randomness. 820 if rpcPayReq.Amp { 821 // If no destination features were specified, we set 822 // those necessary for AMP payments. 823 if features == nil { 824 ampFeatures := []lnrpc.FeatureBit{ 825 lnrpc.FeatureBit_TLV_ONION_OPT, 826 lnrpc.FeatureBit_PAYMENT_ADDR_OPT, 827 lnrpc.FeatureBit_AMP_OPT, 828 } 829 830 features, err = UnmarshalFeatures(ampFeatures) 831 if err != nil { 832 return nil, err 833 } 834 } 835 836 // First make sure the destination supports AMP. 837 if !features.HasFeature(lnwire.AMPOptional) { 838 return nil, fmt.Errorf("destination doesn't " + 839 "support AMP payments") 840 } 841 842 // If no payment address is set, generate a random one. 843 var payAddr [32]byte 844 if len(rpcPayReq.PaymentAddr) == 0 { 845 _, err = rand.Read(payAddr[:]) 846 if err != nil { 847 return nil, err 848 } 849 } else { 850 copy(payAddr[:], rpcPayReq.PaymentAddr) 851 } 852 payIntent.PaymentAddr = &payAddr 853 854 // Generate random SetID and root share. 855 var setID [32]byte 856 _, err = rand.Read(setID[:]) 857 if err != nil { 858 return nil, err 859 } 860 861 var rootShare [32]byte 862 _, err = rand.Read(rootShare[:]) 863 if err != nil { 864 return nil, err 865 } 866 err := payIntent.SetAMP(&routing.AMPOptions{ 867 SetID: setID, 868 RootShare: rootShare, 869 }) 870 if err != nil { 871 return nil, err 872 } 873 } else { 874 // Payment hash. 875 paymentHash, err := lntypes.MakeHash(rpcPayReq.PaymentHash) 876 if err != nil { 877 return nil, err 878 } 879 880 err = payIntent.SetPaymentHash(paymentHash) 881 if err != nil { 882 return nil, err 883 } 884 885 // If the payment addresses is specified, then we'll 886 // also populate that now as well. 887 if len(rpcPayReq.PaymentAddr) != 0 { 888 var payAddr [32]byte 889 copy(payAddr[:], rpcPayReq.PaymentAddr) 890 891 payIntent.PaymentAddr = &payAddr 892 } 893 } 894 895 payIntent.DestFeatures = features 896 } 897 898 // Do bounds checking with the block padding so the router isn't 899 // left with a zombie payment in case the user messes up. 900 err = routing.ValidateCLTVLimit( 901 payIntent.CltvLimit, payIntent.FinalCLTVDelta, true, 902 ) 903 if err != nil { 904 return nil, err 905 } 906 907 // Check for disallowed payments to self. 908 if !rpcPayReq.AllowSelfPayment && payIntent.Target == r.SelfNode { 909 return nil, errors.New("self-payments not allowed") 910 } 911 912 return payIntent, nil 913 } 914 915 // unmarshallRouteHints unmarshalls a list of route hints. 916 func unmarshallRouteHints(rpcRouteHints []*lnrpc.RouteHint) ( 917 [][]zpay32.HopHint, error) { 918 919 routeHints := make([][]zpay32.HopHint, 0, len(rpcRouteHints)) 920 for _, rpcRouteHint := range rpcRouteHints { 921 routeHint := make( 922 []zpay32.HopHint, 0, len(rpcRouteHint.HopHints), 923 ) 924 for _, rpcHint := range rpcRouteHint.HopHints { 925 hint, err := unmarshallHopHint(rpcHint) 926 if err != nil { 927 return nil, err 928 } 929 930 routeHint = append(routeHint, hint) 931 } 932 routeHints = append(routeHints, routeHint) 933 } 934 935 return routeHints, nil 936 } 937 938 // unmarshallHopHint unmarshalls a single hop hint. 939 func unmarshallHopHint(rpcHint *lnrpc.HopHint) (zpay32.HopHint, error) { 940 pubBytes, err := hex.DecodeString(rpcHint.NodeId) 941 if err != nil { 942 return zpay32.HopHint{}, err 943 } 944 945 pubkey, err := secp256k1.ParsePubKey(pubBytes) 946 if err != nil { 947 return zpay32.HopHint{}, err 948 } 949 950 return zpay32.HopHint{ 951 NodeID: pubkey, 952 ChannelID: rpcHint.ChanId, 953 FeeBaseMAtoms: rpcHint.FeeBaseMAtoms, 954 FeeProportionalMillionths: rpcHint.FeeProportionalMillionths, 955 CLTVExpiryDelta: uint16(rpcHint.CltvExpiryDelta), 956 }, nil 957 } 958 959 // UnmarshalFeatures converts a list of uint32's into a valid feature vector. 960 // This method checks that feature bit pairs aren't assigned toegether, and 961 // validates transitive dependencies. 962 func UnmarshalFeatures( 963 rpcFeatures []lnrpc.FeatureBit) (*lnwire.FeatureVector, error) { 964 965 // If no destination features are specified we'll return nil to signal 966 // that the router should try to use the graph as a fallback. 967 if rpcFeatures == nil { 968 return nil, nil 969 } 970 971 raw := lnwire.NewRawFeatureVector() 972 for _, bit := range rpcFeatures { 973 err := raw.SafeSet(lnwire.FeatureBit(bit)) 974 if err != nil { 975 return nil, err 976 } 977 } 978 979 return lnwire.NewFeatureVector(raw, lnwire.Features), nil 980 } 981 982 // ValidatePayReqExpiry checks if the passed payment request has expired. In 983 // the case it has expired, an error will be returned. 984 func ValidatePayReqExpiry(payReq *zpay32.Invoice) error { 985 expiry := payReq.Expiry() 986 validUntil := payReq.Timestamp.Add(expiry) 987 if time.Now().After(validUntil) { 988 return fmt.Errorf("invoice expired. Valid until %v", validUntil) 989 } 990 991 return nil 992 } 993 994 // ValidateCLTVLimit returns a valid CLTV limit given a value and a maximum. If 995 // the value exceeds the maximum, then an error is returned. If the value is 0, 996 // then the maximum is used. 997 func ValidateCLTVLimit(val, max uint32) (uint32, error) { 998 switch { 999 case val == 0: 1000 return max, nil 1001 case val > max: 1002 return 0, fmt.Errorf("total time lock of %v exceeds max "+ 1003 "allowed %v", val, max) 1004 default: 1005 return val, nil 1006 } 1007 } 1008 1009 // UnmarshalMPP accepts the mpp_total_amt_m_atoms and mpp_payment_addr fields 1010 // from an RPC request and converts into an record.MPP object. An error is 1011 // returned if the payment address is not 0 or 32 bytes. If the total amount 1012 // and payment address are zero-value, the return value will be nil signaling 1013 // there is no MPP record to attach to this hop. Otherwise, a non-nil reocrd 1014 // will be contained combining the provided values. 1015 func UnmarshalMPP(reqMPP *lnrpc.MPPRecord) (*record.MPP, error) { 1016 // If no MPP record was submitted, assume the user wants to send a 1017 // regular payment. 1018 if reqMPP == nil { 1019 return nil, nil 1020 } 1021 1022 reqTotal := reqMPP.TotalAmtMAtoms 1023 reqAddr := reqMPP.PaymentAddr 1024 1025 switch { 1026 1027 // No MPP fields were provided. 1028 case reqTotal == 0 && len(reqAddr) == 0: 1029 return nil, fmt.Errorf("missing total_msat and payment_addr") 1030 1031 // Total is present, but payment address is missing. 1032 case reqTotal > 0 && len(reqAddr) == 0: 1033 return nil, fmt.Errorf("missing payment_addr") 1034 1035 // Payment address is present, but total is missing. 1036 case reqTotal == 0 && len(reqAddr) > 0: 1037 return nil, fmt.Errorf("missing total_m_atoms") 1038 } 1039 1040 addr, err := lntypes.MakeHash(reqAddr) 1041 if err != nil { 1042 return nil, fmt.Errorf("unable to parse "+ 1043 "payment_addr: %v", err) 1044 } 1045 1046 total := lnwire.MilliAtom(reqTotal) 1047 1048 return record.NewMPP(total, addr), nil 1049 } 1050 1051 func UnmarshalAMP(reqAMP *lnrpc.AMPRecord) (*record.AMP, error) { 1052 if reqAMP == nil { 1053 return nil, nil 1054 } 1055 1056 reqRootShare := reqAMP.RootShare 1057 reqSetID := reqAMP.SetId 1058 1059 switch { 1060 case len(reqRootShare) != 32: 1061 return nil, errors.New("AMP root_share must be 32 bytes") 1062 1063 case len(reqSetID) != 32: 1064 return nil, errors.New("AMP set_id must be 32 bytes") 1065 } 1066 1067 var ( 1068 rootShare [32]byte 1069 setID [32]byte 1070 ) 1071 copy(rootShare[:], reqRootShare) 1072 copy(setID[:], reqSetID) 1073 1074 return record.NewAMP(rootShare, setID, reqAMP.ChildIndex), nil 1075 } 1076 1077 // MarshalHTLCAttempt constructs an RPC HTLCAttempt from the db representation. 1078 func (r *RouterBackend) MarshalHTLCAttempt( 1079 htlc channeldb.HTLCAttempt) (*lnrpc.HTLCAttempt, error) { 1080 1081 route, err := r.MarshallRoute(&htlc.Route) 1082 if err != nil { 1083 return nil, err 1084 } 1085 1086 rpcAttempt := &lnrpc.HTLCAttempt{ 1087 AttemptId: htlc.AttemptID, 1088 AttemptTimeNs: MarshalTimeNano(htlc.AttemptTime), 1089 Route: route, 1090 } 1091 1092 switch { 1093 case htlc.Settle != nil: 1094 rpcAttempt.Status = lnrpc.HTLCAttempt_SUCCEEDED 1095 rpcAttempt.ResolveTimeNs = MarshalTimeNano( 1096 htlc.Settle.SettleTime, 1097 ) 1098 rpcAttempt.Preimage = htlc.Settle.Preimage[:] 1099 1100 case htlc.Failure != nil: 1101 rpcAttempt.Status = lnrpc.HTLCAttempt_FAILED 1102 rpcAttempt.ResolveTimeNs = MarshalTimeNano( 1103 htlc.Failure.FailTime, 1104 ) 1105 1106 var err error 1107 rpcAttempt.Failure, err = marshallHtlcFailure(htlc.Failure) 1108 if err != nil { 1109 return nil, err 1110 } 1111 default: 1112 rpcAttempt.Status = lnrpc.HTLCAttempt_IN_FLIGHT 1113 } 1114 1115 return rpcAttempt, nil 1116 } 1117 1118 // marshallHtlcFailure marshalls htlc fail info from the database to its rpc 1119 // representation. 1120 func marshallHtlcFailure(failure *channeldb.HTLCFailInfo) (*lnrpc.Failure, 1121 error) { 1122 1123 rpcFailure := &lnrpc.Failure{ 1124 FailureSourceIndex: failure.FailureSourceIndex, 1125 } 1126 1127 switch failure.Reason { 1128 1129 case channeldb.HTLCFailUnknown: 1130 rpcFailure.Code = lnrpc.Failure_UNKNOWN_FAILURE 1131 1132 case channeldb.HTLCFailUnreadable: 1133 rpcFailure.Code = lnrpc.Failure_UNREADABLE_FAILURE 1134 1135 case channeldb.HTLCFailInternal: 1136 rpcFailure.Code = lnrpc.Failure_INTERNAL_FAILURE 1137 1138 case channeldb.HTLCFailMessage: 1139 err := marshallWireError(failure.Message, rpcFailure) 1140 if err != nil { 1141 return nil, err 1142 } 1143 1144 default: 1145 return nil, errors.New("unknown htlc failure reason") 1146 } 1147 1148 return rpcFailure, nil 1149 } 1150 1151 // MarshalTimeNano converts a time.Time into its nanosecond representation. If 1152 // the time is zero, this method simply returns 0, since calling UnixNano() on a 1153 // zero-valued time is undefined. 1154 func MarshalTimeNano(t time.Time) int64 { 1155 if t.IsZero() { 1156 return 0 1157 } 1158 return t.UnixNano() 1159 } 1160 1161 // marshallError marshall an error as received from the switch to rpc structs 1162 // suitable for returning to the caller of an rpc method. 1163 // 1164 // Because of difficulties with using protobuf oneof constructs in some 1165 // languages, the decision was made here to use a single message format for all 1166 // failure messages with some fields left empty depending on the failure type. 1167 func marshallError(sendError error) (*lnrpc.Failure, error) { 1168 response := &lnrpc.Failure{} 1169 1170 if sendError == htlcswitch.ErrUnreadableFailureMessage { 1171 response.Code = lnrpc.Failure_UNREADABLE_FAILURE 1172 return response, nil 1173 } 1174 1175 rtErr, ok := sendError.(htlcswitch.ClearTextError) 1176 if !ok { 1177 return nil, sendError 1178 } 1179 1180 err := marshallWireError(rtErr.WireMessage(), response) 1181 if err != nil { 1182 return nil, err 1183 } 1184 1185 // If the ClearTextError received is a ForwardingError, the error 1186 // originated from a node along the route, not locally on our outgoing 1187 // link. We set failureSourceIdx to the index of the node where the 1188 // failure occurred. If the error is not a ForwardingError, the failure 1189 // occurred at our node, so we leave the index as 0 to indicate that 1190 // we failed locally. 1191 fErr, ok := rtErr.(*htlcswitch.ForwardingError) 1192 if ok { 1193 response.FailureSourceIndex = uint32(fErr.FailureSourceIdx) 1194 } 1195 1196 return response, nil 1197 } 1198 1199 // marshallError marshall an error as received from the switch to rpc structs 1200 // suitable for returning to the caller of an rpc method. 1201 // 1202 // Because of difficulties with using protobuf oneof constructs in some 1203 // languages, the decision was made here to use a single message format for all 1204 // failure messages with some fields left empty depending on the failure type. 1205 func marshallWireError(msg lnwire.FailureMessage, 1206 response *lnrpc.Failure) error { 1207 1208 switch onionErr := msg.(type) { 1209 1210 case *lnwire.FailIncorrectDetails: 1211 response.Code = lnrpc.Failure_INCORRECT_OR_UNKNOWN_PAYMENT_DETAILS 1212 response.Height = onionErr.Height() 1213 1214 case *lnwire.FailIncorrectPaymentAmount: 1215 response.Code = lnrpc.Failure_INCORRECT_PAYMENT_AMOUNT 1216 1217 case *lnwire.FailFinalIncorrectCltvExpiry: 1218 response.Code = lnrpc.Failure_FINAL_INCORRECT_CLTV_EXPIRY 1219 response.CltvExpiry = onionErr.CltvExpiry 1220 1221 case *lnwire.FailFinalIncorrectHtlcAmount: 1222 response.Code = lnrpc.Failure_FINAL_INCORRECT_HTLC_AMOUNT 1223 response.HtlcMAtoms = uint64(onionErr.IncomingHTLCAmount) 1224 1225 case *lnwire.FailFinalExpiryTooSoon: 1226 response.Code = lnrpc.Failure_FINAL_EXPIRY_TOO_SOON 1227 1228 case *lnwire.FailInvalidRealm: 1229 response.Code = lnrpc.Failure_INVALID_REALM 1230 1231 case *lnwire.FailExpiryTooSoon: 1232 response.Code = lnrpc.Failure_EXPIRY_TOO_SOON 1233 response.ChannelUpdate = marshallChannelUpdate(&onionErr.Update) 1234 1235 case *lnwire.FailExpiryTooFar: 1236 response.Code = lnrpc.Failure_EXPIRY_TOO_FAR 1237 1238 case *lnwire.FailInvalidOnionVersion: 1239 response.Code = lnrpc.Failure_INVALID_ONION_VERSION 1240 response.OnionSha_256 = onionErr.OnionSHA256[:] 1241 1242 case *lnwire.FailInvalidOnionHmac: 1243 response.Code = lnrpc.Failure_INVALID_ONION_HMAC 1244 response.OnionSha_256 = onionErr.OnionSHA256[:] 1245 1246 case *lnwire.FailInvalidOnionKey: 1247 response.Code = lnrpc.Failure_INVALID_ONION_KEY 1248 response.OnionSha_256 = onionErr.OnionSHA256[:] 1249 1250 case *lnwire.FailAmountBelowMinimum: 1251 response.Code = lnrpc.Failure_AMOUNT_BELOW_MINIMUM 1252 response.ChannelUpdate = marshallChannelUpdate(&onionErr.Update) 1253 response.HtlcMAtoms = uint64(onionErr.HtlcMAtoms) 1254 1255 case *lnwire.FailFeeInsufficient: 1256 response.Code = lnrpc.Failure_FEE_INSUFFICIENT 1257 response.ChannelUpdate = marshallChannelUpdate(&onionErr.Update) 1258 response.HtlcMAtoms = uint64(onionErr.HtlcMAtoms) 1259 1260 case *lnwire.FailIncorrectCltvExpiry: 1261 response.Code = lnrpc.Failure_INCORRECT_CLTV_EXPIRY 1262 response.ChannelUpdate = marshallChannelUpdate(&onionErr.Update) 1263 response.CltvExpiry = onionErr.CltvExpiry 1264 1265 case *lnwire.FailChannelDisabled: 1266 response.Code = lnrpc.Failure_CHANNEL_DISABLED 1267 response.ChannelUpdate = marshallChannelUpdate(&onionErr.Update) 1268 response.Flags = uint32(onionErr.Flags) 1269 1270 case *lnwire.FailTemporaryChannelFailure: 1271 response.Code = lnrpc.Failure_TEMPORARY_CHANNEL_FAILURE 1272 response.ChannelUpdate = marshallChannelUpdate(onionErr.Update) 1273 1274 case *lnwire.FailRequiredNodeFeatureMissing: 1275 response.Code = lnrpc.Failure_REQUIRED_NODE_FEATURE_MISSING 1276 1277 case *lnwire.FailRequiredChannelFeatureMissing: 1278 response.Code = lnrpc.Failure_REQUIRED_CHANNEL_FEATURE_MISSING 1279 1280 case *lnwire.FailUnknownNextPeer: 1281 response.Code = lnrpc.Failure_UNKNOWN_NEXT_PEER 1282 1283 case *lnwire.FailTemporaryNodeFailure: 1284 response.Code = lnrpc.Failure_TEMPORARY_NODE_FAILURE 1285 1286 case *lnwire.FailPermanentNodeFailure: 1287 response.Code = lnrpc.Failure_PERMANENT_NODE_FAILURE 1288 1289 case *lnwire.FailPermanentChannelFailure: 1290 response.Code = lnrpc.Failure_PERMANENT_CHANNEL_FAILURE 1291 1292 case *lnwire.FailMPPTimeout: 1293 response.Code = lnrpc.Failure_MPP_TIMEOUT 1294 1295 case *lnwire.InvalidOnionPayload: 1296 response.Code = lnrpc.Failure_INVALID_ONION_PAYLOAD 1297 1298 case nil: 1299 response.Code = lnrpc.Failure_UNKNOWN_FAILURE 1300 1301 default: 1302 return fmt.Errorf("cannot marshall failure %T", onionErr) 1303 } 1304 1305 return nil 1306 } 1307 1308 // marshallChannelUpdate marshalls a channel update as received over the wire to 1309 // the router rpc format. 1310 func marshallChannelUpdate(update *lnwire.ChannelUpdate) *lnrpc.ChannelUpdate { 1311 if update == nil { 1312 return nil 1313 } 1314 1315 return &lnrpc.ChannelUpdate{ 1316 Signature: update.Signature[:], 1317 ChainHash: update.ChainHash[:], 1318 ChanId: update.ShortChannelID.ToUint64(), 1319 Timestamp: update.Timestamp, 1320 MessageFlags: uint32(update.MessageFlags), 1321 ChannelFlags: uint32(update.ChannelFlags), 1322 TimeLockDelta: uint32(update.TimeLockDelta), 1323 HtlcMinimumMAtoms: uint64(update.HtlcMinimumMAtoms), 1324 BaseFee: update.BaseFee, 1325 FeeRate: update.FeeRate, 1326 HtlcMaximumMAtoms: uint64(update.HtlcMaximumMAtoms), 1327 ExtraOpaqueData: update.ExtraOpaqueData, 1328 } 1329 } 1330 1331 // MarshallPayment marshall a payment to its rpc representation. 1332 func (r *RouterBackend) MarshallPayment(payment *channeldb.MPPayment) ( 1333 *lnrpc.Payment, error) { 1334 1335 // Fetch the payment's preimage and the total paid in fees. 1336 var ( 1337 fee lnwire.MilliAtom 1338 preimage lntypes.Preimage 1339 ) 1340 for _, htlc := range payment.HTLCs { 1341 // If any of the htlcs have settled, extract a valid 1342 // preimage. 1343 if htlc.Settle != nil { 1344 preimage = htlc.Settle.Preimage 1345 fee += htlc.Route.TotalFees() 1346 } 1347 } 1348 1349 matomsValue := int64(payment.Info.Value) 1350 atomsValue := int64(payment.Info.Value.ToAtoms()) 1351 1352 status, err := convertPaymentStatus(payment.Status) 1353 if err != nil { 1354 return nil, err 1355 } 1356 1357 htlcs := make([]*lnrpc.HTLCAttempt, 0, len(payment.HTLCs)) 1358 for _, dbHTLC := range payment.HTLCs { 1359 htlc, err := r.MarshalHTLCAttempt(dbHTLC) 1360 if err != nil { 1361 return nil, err 1362 } 1363 1364 htlcs = append(htlcs, htlc) 1365 } 1366 1367 paymentID := payment.Info.PaymentIdentifier 1368 creationTimeNS := MarshalTimeNano(payment.Info.CreationTime) 1369 1370 failureReason, err := marshallPaymentFailureReason( 1371 payment.FailureReason, 1372 ) 1373 if err != nil { 1374 return nil, err 1375 } 1376 1377 return &lnrpc.Payment{ 1378 // TODO: set this to setID for AMP-payments? 1379 PaymentHash: hex.EncodeToString(paymentID[:]), 1380 Value: atomsValue, 1381 ValueMAtoms: matomsValue, 1382 ValueAtoms: atomsValue, 1383 CreationDate: payment.Info.CreationTime.Unix(), 1384 CreationTimeNs: creationTimeNS, 1385 Fee: int64(fee.ToAtoms()), 1386 FeeAtoms: int64(fee.ToAtoms()), 1387 FeeMAtoms: int64(fee), 1388 PaymentPreimage: hex.EncodeToString(preimage[:]), 1389 PaymentRequest: string(payment.Info.PaymentRequest), 1390 Status: status, 1391 Htlcs: htlcs, 1392 PaymentIndex: payment.SequenceNum, 1393 FailureReason: failureReason, 1394 }, nil 1395 } 1396 1397 // convertPaymentStatus converts a channeldb.PaymentStatus to the type expected 1398 // by the RPC. 1399 func convertPaymentStatus(dbStatus channeldb.PaymentStatus) ( 1400 lnrpc.Payment_PaymentStatus, error) { 1401 1402 switch dbStatus { 1403 case channeldb.StatusUnknown: 1404 return lnrpc.Payment_UNKNOWN, nil 1405 1406 case channeldb.StatusInFlight: 1407 return lnrpc.Payment_IN_FLIGHT, nil 1408 1409 case channeldb.StatusSucceeded: 1410 return lnrpc.Payment_SUCCEEDED, nil 1411 1412 case channeldb.StatusFailed: 1413 return lnrpc.Payment_FAILED, nil 1414 1415 default: 1416 return 0, fmt.Errorf("unhandled payment status %v", dbStatus) 1417 } 1418 } 1419 1420 // marshallPaymentFailureReason marshalls the failure reason to the corresponding rpc 1421 // type. 1422 func marshallPaymentFailureReason(reason *channeldb.FailureReason) ( 1423 lnrpc.PaymentFailureReason, error) { 1424 1425 if reason == nil { 1426 return lnrpc.PaymentFailureReason_FAILURE_REASON_NONE, nil 1427 } 1428 1429 switch *reason { 1430 1431 case channeldb.FailureReasonTimeout: 1432 return lnrpc.PaymentFailureReason_FAILURE_REASON_TIMEOUT, nil 1433 1434 case channeldb.FailureReasonNoRoute: 1435 return lnrpc.PaymentFailureReason_FAILURE_REASON_NO_ROUTE, nil 1436 1437 case channeldb.FailureReasonError: 1438 return lnrpc.PaymentFailureReason_FAILURE_REASON_ERROR, nil 1439 1440 case channeldb.FailureReasonPaymentDetails: 1441 return lnrpc.PaymentFailureReason_FAILURE_REASON_INCORRECT_PAYMENT_DETAILS, nil 1442 1443 case channeldb.FailureReasonInsufficientBalance: 1444 return lnrpc.PaymentFailureReason_FAILURE_REASON_INSUFFICIENT_BALANCE, nil 1445 } 1446 1447 return 0, errors.New("unknown failure reason") 1448 }