1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! The top-level routing/network map tracking logic lives here.
12 //! You probably want to create a NetGraphMsgHandler and use that as your RoutingMessageHandler and then
13 //! interrogate it to get routes for your own payments.
15 use bitcoin::secp256k1::key::PublicKey;
17 use ln::channelmanager::ChannelDetails;
18 use ln::features::{ChannelFeatures, InvoiceFeatures, NodeFeatures};
19 use ln::msgs::{DecodeError, ErrorAction, LightningError, MAX_VALUE_MSAT};
20 use routing::scoring::Score;
21 use routing::network_graph::{DirectedChannelInfoWithUpdate, EffectiveCapacity, NetworkGraph, NodeId, RoutingFees};
22 use util::ser::{Writeable, Readable};
23 use util::logger::{Level, Logger};
27 use alloc::collections::BinaryHeap;
32 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
34 /// The node_id of the node at this hop.
35 pub pubkey: PublicKey,
36 /// The node_announcement features of the node at this hop. For the last hop, these may be
37 /// amended to match the features present in the invoice this node generated.
38 pub node_features: NodeFeatures,
39 /// The channel that should be used from the previous hop to reach this node.
40 pub short_channel_id: u64,
41 /// The channel_announcement features of the channel that should be used from the previous hop
42 /// to reach this node.
43 pub channel_features: ChannelFeatures,
44 /// The fee taken on this hop (for paying for the use of the *next* channel in the path).
45 /// For the last hop, this should be the full value of the payment (might be more than
46 /// requested if we had to match htlc_minimum_msat).
48 /// The CLTV delta added for this hop. For the last hop, this should be the full CLTV value
49 /// expected at the destination, in excess of the current block height.
50 pub cltv_expiry_delta: u32,
53 impl_writeable_tlv_based!(RouteHop, {
54 (0, pubkey, required),
55 (2, node_features, required),
56 (4, short_channel_id, required),
57 (6, channel_features, required),
58 (8, fee_msat, required),
59 (10, cltv_expiry_delta, required),
62 /// A route directs a payment from the sender (us) to the recipient. If the recipient supports MPP,
63 /// it can take multiple paths. Each path is composed of one or more hops through the network.
64 #[derive(Clone, Hash, PartialEq, Eq)]
66 /// The list of routes taken for a single (potentially-)multi-part payment. The pubkey of the
67 /// last RouteHop in each path must be the same.
68 /// Each entry represents a list of hops, NOT INCLUDING our own, where the last hop is the
69 /// destination. Thus, this must always be at least length one. While the maximum length of any
70 /// given path is variable, keeping the length of any path to less than 20 should currently
71 /// ensure it is viable.
72 pub paths: Vec<Vec<RouteHop>>,
73 /// The `payment_params` parameter passed to [`find_route`].
74 /// This is used by `ChannelManager` to track information which may be required for retries,
75 /// provided back to you via [`Event::PaymentPathFailed`].
77 /// [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed
78 pub payment_params: Option<PaymentParameters>,
81 pub(crate) trait RoutePath {
82 /// Gets the fees for a given path, excluding any excess paid to the recipient.
83 fn get_path_fees(&self) -> u64;
85 impl RoutePath for Vec<RouteHop> {
86 fn get_path_fees(&self) -> u64 {
87 // Do not count last hop of each path since that's the full value of the payment
88 self.split_last().map(|(_, path_prefix)| path_prefix).unwrap_or(&[])
89 .iter().map(|hop| &hop.fee_msat)
95 /// Returns the total amount of fees paid on this [`Route`].
97 /// This doesn't include any extra payment made to the recipient, which can happen in excess of
98 /// the amount passed to [`find_route`]'s `params.final_value_msat`.
99 pub fn get_total_fees(&self) -> u64 {
100 self.paths.iter().map(|path| path.get_path_fees()).sum()
103 /// Returns the total amount paid on this [`Route`], excluding the fees.
104 pub fn get_total_amount(&self) -> u64 {
105 return self.paths.iter()
106 .map(|path| path.split_last().map(|(hop, _)| hop.fee_msat).unwrap_or(0))
111 const SERIALIZATION_VERSION: u8 = 1;
112 const MIN_SERIALIZATION_VERSION: u8 = 1;
114 impl Writeable for Route {
115 fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
116 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
117 (self.paths.len() as u64).write(writer)?;
118 for hops in self.paths.iter() {
119 (hops.len() as u8).write(writer)?;
120 for hop in hops.iter() {
124 write_tlv_fields!(writer, {
125 (1, self.payment_params, option),
131 impl Readable for Route {
132 fn read<R: io::Read>(reader: &mut R) -> Result<Route, DecodeError> {
133 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
134 let path_count: u64 = Readable::read(reader)?;
135 let mut paths = Vec::with_capacity(cmp::min(path_count, 128) as usize);
136 for _ in 0..path_count {
137 let hop_count: u8 = Readable::read(reader)?;
138 let mut hops = Vec::with_capacity(hop_count as usize);
139 for _ in 0..hop_count {
140 hops.push(Readable::read(reader)?);
144 let mut payment_params = None;
145 read_tlv_fields!(reader, {
146 (1, payment_params, option),
148 Ok(Route { paths, payment_params })
152 /// Parameters needed to find a [`Route`].
154 /// Passed to [`find_route`] and also provided in [`Event::PaymentPathFailed`] for retrying a failed
157 /// [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed
158 #[derive(Clone, Debug)]
159 pub struct RouteParameters {
160 /// The parameters of the failed payment path.
161 pub payment_params: PaymentParameters,
163 /// The amount in msats sent on the failed payment path.
164 pub final_value_msat: u64,
166 /// The CLTV on the final hop of the failed payment path.
167 pub final_cltv_expiry_delta: u32,
170 impl_writeable_tlv_based!(RouteParameters, {
171 (0, payment_params, required),
172 (2, final_value_msat, required),
173 (4, final_cltv_expiry_delta, required),
176 /// Maximum total CTLV difference we allow for a full payment path.
177 pub const DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA: u32 = 1008;
179 /// The recipient of a payment.
180 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
181 pub struct PaymentParameters {
182 /// The node id of the payee.
183 pub payee_pubkey: PublicKey,
185 /// Features supported by the payee.
187 /// May be set from the payee's invoice or via [`for_keysend`]. May be `None` if the invoice
188 /// does not contain any features.
190 /// [`for_keysend`]: Self::for_keysend
191 pub features: Option<InvoiceFeatures>,
193 /// Hints for routing to the payee, containing channels connecting the payee to public nodes.
194 pub route_hints: Vec<RouteHint>,
196 /// Expiration of a payment to the payee, in seconds relative to the UNIX epoch.
197 pub expiry_time: Option<u64>,
199 /// The maximum total CLTV delta we accept for the route.
200 pub max_total_cltv_expiry_delta: u32,
203 impl_writeable_tlv_based!(PaymentParameters, {
204 (0, payee_pubkey, required),
205 (1, max_total_cltv_expiry_delta, (default_value, DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA)),
206 (2, features, option),
207 (4, route_hints, vec_type),
208 (6, expiry_time, option),
211 impl PaymentParameters {
212 /// Creates a payee with the node id of the given `pubkey`.
213 pub fn from_node_id(payee_pubkey: PublicKey) -> Self {
219 max_total_cltv_expiry_delta: DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA,
223 /// Creates a payee with the node id of the given `pubkey` to use for keysend payments.
224 pub fn for_keysend(payee_pubkey: PublicKey) -> Self {
225 Self::from_node_id(payee_pubkey).with_features(InvoiceFeatures::for_keysend())
228 /// Includes the payee's features.
230 /// (C-not exported) since bindings don't support move semantics
231 pub fn with_features(self, features: InvoiceFeatures) -> Self {
232 Self { features: Some(features), ..self }
235 /// Includes hints for routing to the payee.
237 /// (C-not exported) since bindings don't support move semantics
238 pub fn with_route_hints(self, route_hints: Vec<RouteHint>) -> Self {
239 Self { route_hints, ..self }
242 /// Includes a payment expiration in seconds relative to the UNIX epoch.
244 /// (C-not exported) since bindings don't support move semantics
245 pub fn with_expiry_time(self, expiry_time: u64) -> Self {
246 Self { expiry_time: Some(expiry_time), ..self }
249 /// Includes a limit for the total CLTV expiry delta which is considered during routing
251 /// (C-not exported) since bindings don't support move semantics
252 pub fn with_max_total_cltv_expiry_delta(self, max_total_cltv_expiry_delta: u32) -> Self {
253 Self { max_total_cltv_expiry_delta, ..self }
257 /// A list of hops along a payment path terminating with a channel to the recipient.
258 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
259 pub struct RouteHint(pub Vec<RouteHintHop>);
262 impl Writeable for RouteHint {
263 fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
264 (self.0.len() as u64).write(writer)?;
265 for hop in self.0.iter() {
272 impl Readable for RouteHint {
273 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
274 let hop_count: u64 = Readable::read(reader)?;
275 let mut hops = Vec::with_capacity(cmp::min(hop_count, 16) as usize);
276 for _ in 0..hop_count {
277 hops.push(Readable::read(reader)?);
283 /// A channel descriptor for a hop along a payment path.
284 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
285 pub struct RouteHintHop {
286 /// The node_id of the non-target end of the route
287 pub src_node_id: PublicKey,
288 /// The short_channel_id of this channel
289 pub short_channel_id: u64,
290 /// The fees which must be paid to use this channel
291 pub fees: RoutingFees,
292 /// The difference in CLTV values between this node and the next node.
293 pub cltv_expiry_delta: u16,
294 /// The minimum value, in msat, which must be relayed to the next hop.
295 pub htlc_minimum_msat: Option<u64>,
296 /// The maximum value in msat available for routing with a single HTLC.
297 pub htlc_maximum_msat: Option<u64>,
300 impl_writeable_tlv_based!(RouteHintHop, {
301 (0, src_node_id, required),
302 (1, htlc_minimum_msat, option),
303 (2, short_channel_id, required),
304 (3, htlc_maximum_msat, option),
306 (6, cltv_expiry_delta, required),
309 #[derive(Eq, PartialEq)]
310 struct RouteGraphNode {
312 lowest_fee_to_peer_through_node: u64,
313 lowest_fee_to_node: u64,
314 total_cltv_delta: u32,
315 // The maximum value a yet-to-be-constructed payment path might flow through this node.
316 // This value is upper-bounded by us by:
317 // - how much is needed for a path being constructed
318 // - how much value can channels following this node (up to the destination) can contribute,
319 // considering their capacity and fees
320 value_contribution_msat: u64,
321 /// The effective htlc_minimum_msat at this hop. If a later hop on the path had a higher HTLC
322 /// minimum, we use it, plus the fees required at each earlier hop to meet it.
323 path_htlc_minimum_msat: u64,
324 /// All penalties incurred from this hop on the way to the destination, as calculated using
326 path_penalty_msat: u64,
329 impl cmp::Ord for RouteGraphNode {
330 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
331 let other_score = cmp::max(other.lowest_fee_to_peer_through_node, other.path_htlc_minimum_msat)
332 .checked_add(other.path_penalty_msat)
333 .unwrap_or_else(|| u64::max_value());
334 let self_score = cmp::max(self.lowest_fee_to_peer_through_node, self.path_htlc_minimum_msat)
335 .checked_add(self.path_penalty_msat)
336 .unwrap_or_else(|| u64::max_value());
337 other_score.cmp(&self_score).then_with(|| other.node_id.cmp(&self.node_id))
341 impl cmp::PartialOrd for RouteGraphNode {
342 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
343 Some(self.cmp(other))
347 /// A wrapper around the various hop representations.
349 /// Used to construct a [`PathBuildingHop`] and to estimate [`EffectiveCapacity`].
350 #[derive(Clone, Debug)]
351 enum CandidateRouteHop<'a> {
352 /// A hop from the payer, where the outbound liquidity is known.
354 details: &'a ChannelDetails,
356 /// A hop found in the [`NetworkGraph`], where the channel capacity may or may not be known.
358 info: DirectedChannelInfoWithUpdate<'a>,
359 short_channel_id: u64,
361 /// A hop to the payee found in the payment invoice, though not necessarily a direct channel.
363 hint: &'a RouteHintHop,
367 impl<'a> CandidateRouteHop<'a> {
368 fn short_channel_id(&self) -> u64 {
370 CandidateRouteHop::FirstHop { details } => details.short_channel_id.unwrap(),
371 CandidateRouteHop::PublicHop { short_channel_id, .. } => *short_channel_id,
372 CandidateRouteHop::PrivateHop { hint } => hint.short_channel_id,
376 // NOTE: This may alloc memory so avoid calling it in a hot code path.
377 fn features(&self) -> ChannelFeatures {
379 CandidateRouteHop::FirstHop { details } => details.counterparty.features.to_context(),
380 CandidateRouteHop::PublicHop { info, .. } => info.channel().features.clone(),
381 CandidateRouteHop::PrivateHop { .. } => ChannelFeatures::empty(),
385 fn cltv_expiry_delta(&self) -> u32 {
387 CandidateRouteHop::FirstHop { .. } => 0,
388 CandidateRouteHop::PublicHop { info, .. } => info.direction().cltv_expiry_delta as u32,
389 CandidateRouteHop::PrivateHop { hint } => hint.cltv_expiry_delta as u32,
393 fn htlc_minimum_msat(&self) -> u64 {
395 CandidateRouteHop::FirstHop { .. } => 0,
396 CandidateRouteHop::PublicHop { info, .. } => info.direction().htlc_minimum_msat,
397 CandidateRouteHop::PrivateHop { hint } => hint.htlc_minimum_msat.unwrap_or(0),
401 fn fees(&self) -> RoutingFees {
403 CandidateRouteHop::FirstHop { .. } => RoutingFees {
404 base_msat: 0, proportional_millionths: 0,
406 CandidateRouteHop::PublicHop { info, .. } => info.direction().fees,
407 CandidateRouteHop::PrivateHop { hint } => hint.fees,
411 fn effective_capacity(&self) -> EffectiveCapacity {
413 CandidateRouteHop::FirstHop { details } => EffectiveCapacity::ExactLiquidity {
414 liquidity_msat: details.outbound_capacity_msat,
416 CandidateRouteHop::PublicHop { info, .. } => info.effective_capacity(),
417 CandidateRouteHop::PrivateHop { .. } => EffectiveCapacity::Infinite,
422 /// It's useful to keep track of the hops associated with the fees required to use them,
423 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
424 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
425 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
426 #[derive(Clone, Debug)]
427 struct PathBuildingHop<'a> {
428 // Note that this should be dropped in favor of loading it from CandidateRouteHop, but doing so
429 // is a larger refactor and will require careful performance analysis.
431 candidate: CandidateRouteHop<'a>,
434 /// Minimal fees required to route to the source node of the current hop via any of its inbound channels.
435 src_lowest_inbound_fees: RoutingFees,
436 /// All the fees paid *after* this channel on the way to the destination
437 next_hops_fee_msat: u64,
438 /// Fee paid for the use of the current channel (see candidate.fees()).
439 /// The value will be actually deducted from the counterparty balance on the previous link.
440 hop_use_fee_msat: u64,
441 /// Used to compare channels when choosing the for routing.
442 /// Includes paying for the use of a hop and the following hops, as well as
443 /// an estimated cost of reaching this hop.
444 /// Might get stale when fees are recomputed. Primarily for internal use.
446 /// A mirror of the same field in RouteGraphNode. Note that this is only used during the graph
447 /// walk and may be invalid thereafter.
448 path_htlc_minimum_msat: u64,
449 /// All penalties incurred from this channel on the way to the destination, as calculated using
451 path_penalty_msat: u64,
452 /// If we've already processed a node as the best node, we shouldn't process it again. Normally
453 /// we'd just ignore it if we did as all channels would have a higher new fee, but because we
454 /// may decrease the amounts in use as we walk the graph, the actual calculated fee may
455 /// decrease as well. Thus, we have to explicitly track which nodes have been processed and
456 /// avoid processing them again.
458 #[cfg(any(test, feature = "fuzztarget"))]
459 // In tests, we apply further sanity checks on cases where we skip nodes we already processed
460 // to ensure it is specifically in cases where the fee has gone down because of a decrease in
461 // value_contribution_msat, which requires tracking it here. See comments below where it is
462 // used for more info.
463 value_contribution_msat: u64,
466 // Instantiated with a list of hops with correct data in them collected during path finding,
467 // an instance of this struct should be further modified only via given methods.
469 struct PaymentPath<'a> {
470 hops: Vec<(PathBuildingHop<'a>, NodeFeatures)>,
473 impl<'a> PaymentPath<'a> {
474 // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
475 fn get_value_msat(&self) -> u64 {
476 self.hops.last().unwrap().0.fee_msat
479 fn get_total_fee_paid_msat(&self) -> u64 {
480 if self.hops.len() < 1 {
484 // Can't use next_hops_fee_msat because it gets outdated.
485 for (i, (hop, _)) in self.hops.iter().enumerate() {
486 if i != self.hops.len() - 1 {
487 result += hop.fee_msat;
493 // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
494 // to change fees may result in an inconsistency.
496 // Sometimes we call this function right after constructing a path which is inconsistent in
497 // that it the value being transferred has decreased while we were doing path finding, leading
498 // to the fees being paid not lining up with the actual limits.
500 // Note that this function is not aware of the available_liquidity limit, and thus does not
501 // support increasing the value being transferred.
502 fn update_value_and_recompute_fees(&mut self, value_msat: u64) {
503 assert!(value_msat <= self.hops.last().unwrap().0.fee_msat);
505 let mut total_fee_paid_msat = 0 as u64;
506 for i in (0..self.hops.len()).rev() {
507 let last_hop = i == self.hops.len() - 1;
509 // For non-last-hop, this value will represent the fees paid on the current hop. It
510 // will consist of the fees for the use of the next hop, and extra fees to match
511 // htlc_minimum_msat of the current channel. Last hop is handled separately.
512 let mut cur_hop_fees_msat = 0;
514 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().0.hop_use_fee_msat;
517 let mut cur_hop = &mut self.hops.get_mut(i).unwrap().0;
518 cur_hop.next_hops_fee_msat = total_fee_paid_msat;
519 // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
520 // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
521 // set it too high just to maliciously take more fees by exploiting this
522 // match htlc_minimum_msat logic.
523 let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
524 if let Some(extra_fees_msat) = cur_hop.candidate.htlc_minimum_msat().checked_sub(cur_hop_transferred_amount_msat) {
525 // Note that there is a risk that *previous hops* (those closer to us, as we go
526 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
528 // This might make us end up with a broken route, although this should be super-rare
529 // in practice, both because of how healthy channels look like, and how we pick
530 // channels in add_entry.
531 // Also, this can't be exploited more heavily than *announce a free path and fail
533 cur_hop_transferred_amount_msat += extra_fees_msat;
534 total_fee_paid_msat += extra_fees_msat;
535 cur_hop_fees_msat += extra_fees_msat;
539 // Final hop is a special case: it usually has just value_msat (by design), but also
540 // it still could overpay for the htlc_minimum_msat.
541 cur_hop.fee_msat = cur_hop_transferred_amount_msat;
543 // Propagate updated fees for the use of the channels to one hop back, where they
544 // will be actually paid (fee_msat). The last hop is handled above separately.
545 cur_hop.fee_msat = cur_hop_fees_msat;
548 // Fee for the use of the current hop which will be deducted on the previous hop.
549 // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
550 // this channel is free for us.
552 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.candidate.fees()) {
553 cur_hop.hop_use_fee_msat = new_fee;
554 total_fee_paid_msat += new_fee;
556 // It should not be possible because this function is called only to reduce the
557 // value. In that case, compute_fee was already called with the same fees for
558 // larger amount and there was no overflow.
566 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
567 let proportional_fee_millions =
568 amount_msat.checked_mul(channel_fees.proportional_millionths as u64);
569 if let Some(new_fee) = proportional_fee_millions.and_then(|part| {
570 (channel_fees.base_msat as u64).checked_add(part / 1_000_000) }) {
574 // This function may be (indirectly) called without any verification,
575 // with channel_fees provided by a caller. We should handle it gracefully.
580 /// Finds a route from us (payer) to the given target node (payee).
582 /// If the payee provided features in their invoice, they should be provided via `params.payee`.
583 /// Without this, MPP will only be used if the payee's features are available in the network graph.
585 /// Private routing paths between a public node and the target may be included in `params.payee`.
587 /// If some channels aren't announced, it may be useful to fill in `first_hops` with the results
588 /// from [`ChannelManager::list_usable_channels`]. If it is filled in, the view of our local
589 /// channels from [`NetworkGraph`] will be ignored, and only those in `first_hops` will be used.
591 /// The fees on channels from us to the next hop are ignored as they are assumed to all be equal.
592 /// However, the enabled/disabled bit on such channels as well as the `htlc_minimum_msat` /
593 /// `htlc_maximum_msat` *are* checked as they may change based on the receiving node.
597 /// May be used to re-compute a [`Route`] when handling a [`Event::PaymentPathFailed`]. Any
598 /// adjustments to the [`NetworkGraph`] and channel scores should be made prior to calling this
603 /// Panics if first_hops contains channels without short_channel_ids;
604 /// [`ChannelManager::list_usable_channels`] will never include such channels.
606 /// [`ChannelManager::list_usable_channels`]: crate::ln::channelmanager::ChannelManager::list_usable_channels
607 /// [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed
608 pub fn find_route<L: Deref, S: Score>(
609 our_node_pubkey: &PublicKey, route_params: &RouteParameters, network: &NetworkGraph,
610 first_hops: Option<&[&ChannelDetails]>, logger: L, scorer: &S
611 ) -> Result<Route, LightningError>
612 where L::Target: Logger {
614 our_node_pubkey, &route_params.payment_params, network, first_hops, route_params.final_value_msat,
615 route_params.final_cltv_expiry_delta, logger, scorer
619 pub(crate) fn get_route<L: Deref, S: Score>(
620 our_node_pubkey: &PublicKey, payment_params: &PaymentParameters, network: &NetworkGraph,
621 first_hops: Option<&[&ChannelDetails]>, final_value_msat: u64, final_cltv_expiry_delta: u32,
622 logger: L, scorer: &S
623 ) -> Result<Route, LightningError>
624 where L::Target: Logger {
625 let payee_node_id = NodeId::from_pubkey(&payment_params.payee_pubkey);
626 let our_node_id = NodeId::from_pubkey(&our_node_pubkey);
628 if payee_node_id == our_node_id {
629 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
632 if final_value_msat > MAX_VALUE_MSAT {
633 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
636 if final_value_msat == 0 {
637 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
640 for route in payment_params.route_hints.iter() {
641 for hop in &route.0 {
642 if hop.src_node_id == payment_params.payee_pubkey {
643 return Err(LightningError{err: "Route hint cannot have the payee as the source.".to_owned(), action: ErrorAction::IgnoreError});
648 // The general routing idea is the following:
649 // 1. Fill first/last hops communicated by the caller.
650 // 2. Attempt to construct a path from payer to payee for transferring
651 // any ~sufficient (described later) value.
652 // If succeed, remember which channels were used and how much liquidity they have available,
653 // so that future paths don't rely on the same liquidity.
654 // 3. Proceed to the next step if:
655 // - we hit the recommended target value;
656 // - OR if we could not construct a new path. Any next attempt will fail too.
657 // Otherwise, repeat step 2.
658 // 4. See if we managed to collect paths which aggregately are able to transfer target value
659 // (not recommended value). If yes, proceed. If not, fail routing.
660 // 5. Randomly combine paths into routes having enough to fulfill the payment. (TODO: knapsack)
661 // 6. Of all the found paths, select only those with the lowest total fee.
662 // 7. The last path in every selected route is likely to be more than we need.
663 // Reduce its value-to-transfer and recompute fees.
664 // 8. Choose the best route by the lowest total fee.
666 // As for the actual search algorithm,
667 // we do a payee-to-payer pseudo-Dijkstra's sorting by each node's distance from the payee
668 // plus the minimum per-HTLC fee to get from it to another node (aka "shitty pseudo-A*").
670 // We are not a faithful Dijkstra's implementation because we can change values which impact
671 // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
672 // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) than
673 // the value we are currently attempting to send over a path, we simply reduce the value being
674 // sent along the path for any hops after that channel. This may imply that later fees (which
675 // we've already tabulated) are lower because a smaller value is passing through the channels
676 // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
677 // channels which were selected earlier (and which may still be used for other paths without a
678 // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
681 // One potentially problematic case for this algorithm would be if there are many
682 // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
683 // graph walking), we may never find a path which is not liquidity-limited and has lower
684 // proportional fee (and only lower absolute fee when considering the ultimate value sent).
685 // Because we only consider paths with at least 5% of the total value being sent, the damage
686 // from such a case should be limited, however this could be further reduced in the future by
687 // calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
688 // limits for the purposes of fee calculation.
690 // Alternatively, we could store more detailed path information in the heap (targets, below)
691 // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
692 // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
693 // and practically (as we would need to store dynamically-allocated path information in heap
694 // objects, increasing malloc traffic and indirect memory access significantly). Further, the
695 // results of such an algorithm would likely be biased towards lower-value paths.
697 // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
698 // outside of our current search value, running a path search more times to gather candidate
699 // paths at different values. While this may be acceptable, further path searches may increase
700 // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
701 // graph for candidate paths, calculating the maximum value which can realistically be sent at
702 // the same time, remaining generic across different payment values.
704 // TODO: There are a few tweaks we could do, including possibly pre-calculating more stuff
705 // to use as the A* heuristic beyond just the cost to get one node further than the current
708 let network_graph = network.read_only();
709 let network_channels = network_graph.channels();
710 let network_nodes = network_graph.nodes();
712 // Allow MPP only if we have a features set from somewhere that indicates the payee supports
713 // it. If the payee supports it they're supposed to include it in the invoice, so that should
715 let allow_mpp = if let Some(features) = &payment_params.features {
716 features.supports_basic_mpp()
717 } else if let Some(node) = network_nodes.get(&payee_node_id) {
718 if let Some(node_info) = node.announcement_info.as_ref() {
719 node_info.features.supports_basic_mpp()
722 log_trace!(logger, "Searching for a route from payer {} to payee {} {} MPP", our_node_pubkey,
723 payment_params.payee_pubkey, if allow_mpp { "with" } else { "without" });
726 // Prepare the data we'll use for payee-to-payer search by
727 // inserting first hops suggested by the caller as targets.
728 // Our search will then attempt to reach them while traversing from the payee node.
729 let mut first_hop_targets: HashMap<_, Vec<&ChannelDetails>> =
730 HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
731 if let Some(hops) = first_hops {
733 if chan.short_channel_id.is_none() {
734 panic!("first_hops should be filled in with usable channels, not pending ones");
736 if chan.counterparty.node_id == *our_node_pubkey {
737 return Err(LightningError{err: "First hop cannot have our_node_pubkey as a destination.".to_owned(), action: ErrorAction::IgnoreError});
740 .entry(NodeId::from_pubkey(&chan.counterparty.node_id))
741 .or_insert(Vec::new())
744 if first_hop_targets.is_empty() {
745 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
749 // The main heap containing all candidate next-hops sorted by their score (max(A* fee,
750 // htlc_minimum)). Ideally this would be a heap which allowed cheap score reduction instead of
751 // adding duplicate entries when we find a better path to a given node.
752 let mut targets = BinaryHeap::new();
754 // Map from node_id to information about the best current path to that node, including feerate
756 let mut dist = HashMap::with_capacity(network_nodes.len());
758 // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
759 // indicating that we may wish to try again with a higher value, potentially paying to meet an
760 // htlc_minimum with extra fees while still finding a cheaper path.
761 let mut hit_minimum_limit;
763 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
764 // We start with a path_value of the exact amount we want, and if that generates a route we may
765 // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
766 // amount we want in total across paths, selecting the best subset at the end.
767 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
768 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
769 let mut path_value_msat = final_value_msat;
771 // We don't want multiple paths (as per MPP) share liquidity of the same channels.
772 // This map allows paths to be aware of the channel use by other paths in the same call.
773 // This would help to make a better path finding decisions and not "overbook" channels.
774 // It is unaware of the directions (except for `outbound_capacity_msat` in `first_hops`).
775 let mut bookkept_channels_liquidity_available_msat = HashMap::with_capacity(network_nodes.len());
777 // Keeping track of how much value we already collected across other paths. Helps to decide:
778 // - how much a new path should be transferring (upper bound);
779 // - whether a channel should be disregarded because
780 // it's available liquidity is too small comparing to how much more we need to collect;
781 // - when we want to stop looking for new paths.
782 let mut already_collected_value_msat = 0;
784 log_trace!(logger, "Building path from {} (payee) to {} (us/payer) for value {} msat.", payment_params.payee_pubkey, our_node_pubkey, final_value_msat);
786 macro_rules! add_entry {
787 // Adds entry which goes from $src_node_id to $dest_node_id over the $candidate hop.
788 // $next_hops_fee_msat represents the fees paid for using all the channels *after* this one,
789 // since that value has to be transferred over this channel.
790 // Returns whether this channel caused an update to `targets`.
791 ( $candidate: expr, $src_node_id: expr, $dest_node_id: expr, $next_hops_fee_msat: expr,
792 $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr,
793 $next_hops_path_penalty_msat: expr, $next_hops_cltv_delta: expr ) => { {
794 // We "return" whether we updated the path at the end, via this:
795 let mut did_add_update_path_to_src_node = false;
796 // Channels to self should not be used. This is more of belt-and-suspenders, because in
797 // practice these cases should be caught earlier:
798 // - for regular channels at channel announcement (TODO)
799 // - for first and last hops early in get_route
800 if $src_node_id != $dest_node_id {
801 let short_channel_id = $candidate.short_channel_id();
802 let available_liquidity_msat = bookkept_channels_liquidity_available_msat
803 .entry(short_channel_id)
804 .or_insert_with(|| $candidate.effective_capacity().as_msat());
806 // It is tricky to substract $next_hops_fee_msat from available liquidity here.
807 // It may be misleading because we might later choose to reduce the value transferred
808 // over these channels, and the channel which was insufficient might become sufficient.
809 // Worst case: we drop a good channel here because it can't cover the high following
810 // fees caused by one expensive channel, but then this channel could have been used
811 // if the amount being transferred over this path is lower.
812 // We do this for now, but this is a subject for removal.
813 if let Some(available_value_contribution_msat) = available_liquidity_msat.checked_sub($next_hops_fee_msat) {
815 // Routing Fragmentation Mitigation heuristic:
817 // Routing fragmentation across many payment paths increases the overall routing
818 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
819 // Taking too many smaller paths also increases the chance of payment failure.
820 // Thus to avoid this effect, we require from our collected links to provide
821 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
823 // This requirement is currently 5% of the remaining-to-be-collected value.
824 // This means as we successfully advance in our collection,
825 // the absolute liquidity contribution is lowered,
826 // thus increasing the number of potential channels to be selected.
828 // Derive the minimal liquidity contribution with a ratio of 20 (5%, rounded up)
829 // or 100% if we're not allowed to do multipath payments.
830 let minimal_value_contribution_msat: u64 = if allow_mpp {
831 (recommended_value_msat - already_collected_value_msat + 19) / 20
835 // Verify the liquidity offered by this channel complies to the minimal contribution.
836 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
838 // Do not consider candidates that exceed the maximum total cltv expiry limit.
839 let max_total_cltv_expiry_delta = payment_params.max_total_cltv_expiry_delta;
840 let hop_total_cltv_delta = ($next_hops_cltv_delta as u32)
841 .checked_add($candidate.cltv_expiry_delta())
842 .unwrap_or(u32::max_value());
843 let doesnt_exceed_cltv_delta_limit = hop_total_cltv_delta <= max_total_cltv_expiry_delta;
845 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
846 // Includes paying fees for the use of the following channels.
847 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
848 Some(result) => result,
849 // Can't overflow due to how the values were computed right above.
850 None => unreachable!(),
852 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
853 let over_path_minimum_msat = amount_to_transfer_over_msat >= $candidate.htlc_minimum_msat() &&
854 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
856 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
857 // bother considering this channel.
858 // Since we're choosing amount_to_transfer_over_msat as maximum possible, it can
859 // be only reduced later (not increased), so this channel should just be skipped
860 // as not sufficient.
861 if !over_path_minimum_msat && doesnt_exceed_cltv_delta_limit {
862 hit_minimum_limit = true;
863 } else if contributes_sufficient_value && doesnt_exceed_cltv_delta_limit {
864 // Note that low contribution here (limited by available_liquidity_msat)
865 // might violate htlc_minimum_msat on the hops which are next along the
866 // payment path (upstream to the payee). To avoid that, we recompute
867 // path fees knowing the final path contribution after constructing it.
868 let path_htlc_minimum_msat = compute_fees($next_hops_path_htlc_minimum_msat, $candidate.fees())
869 .and_then(|fee_msat| fee_msat.checked_add($next_hops_path_htlc_minimum_msat))
870 .map(|fee_msat| cmp::max(fee_msat, $candidate.htlc_minimum_msat()))
871 .unwrap_or_else(|| u64::max_value());
872 let hm_entry = dist.entry($src_node_id);
873 let old_entry = hm_entry.or_insert_with(|| {
874 // If there was previously no known way to access the source node
875 // (recall it goes payee-to-payer) of short_channel_id, first add a
876 // semi-dummy record just to compute the fees to reach the source node.
877 // This will affect our decision on selecting short_channel_id
878 // as a way to reach the $dest_node_id.
879 let mut fee_base_msat = 0;
880 let mut fee_proportional_millionths = 0;
881 if let Some(Some(fees)) = network_nodes.get(&$src_node_id).map(|node| node.lowest_inbound_channel_fees) {
882 fee_base_msat = fees.base_msat;
883 fee_proportional_millionths = fees.proportional_millionths;
886 node_id: $dest_node_id.clone(),
887 candidate: $candidate.clone(),
889 src_lowest_inbound_fees: RoutingFees {
890 base_msat: fee_base_msat,
891 proportional_millionths: fee_proportional_millionths,
893 next_hops_fee_msat: u64::max_value(),
894 hop_use_fee_msat: u64::max_value(),
895 total_fee_msat: u64::max_value(),
896 path_htlc_minimum_msat,
897 path_penalty_msat: u64::max_value(),
898 was_processed: false,
899 #[cfg(any(test, feature = "fuzztarget"))]
900 value_contribution_msat,
904 #[allow(unused_mut)] // We only use the mut in cfg(test)
905 let mut should_process = !old_entry.was_processed;
906 #[cfg(any(test, feature = "fuzztarget"))]
908 // In test/fuzzing builds, we do extra checks to make sure the skipping
909 // of already-seen nodes only happens in cases we expect (see below).
910 if !should_process { should_process = true; }
914 let mut hop_use_fee_msat = 0;
915 let mut total_fee_msat = $next_hops_fee_msat;
917 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
918 // will have the same effective-fee
919 if $src_node_id != our_node_id {
920 match compute_fees(amount_to_transfer_over_msat, $candidate.fees()) {
921 // max_value means we'll always fail
922 // the old_entry.total_fee_msat > total_fee_msat check
923 None => total_fee_msat = u64::max_value(),
925 hop_use_fee_msat = fee_msat;
926 total_fee_msat += hop_use_fee_msat;
927 // When calculating the lowest inbound fees to a node, we
928 // calculate fees here not based on the actual value we think
929 // will flow over this channel, but on the minimum value that
930 // we'll accept flowing over it. The minimum accepted value
931 // is a constant through each path collection run, ensuring
932 // consistent basis. Otherwise we may later find a
933 // different path to the source node that is more expensive,
934 // but which we consider to be cheaper because we are capacity
935 // constrained and the relative fee becomes lower.
936 match compute_fees(minimal_value_contribution_msat, old_entry.src_lowest_inbound_fees)
937 .map(|a| a.checked_add(total_fee_msat)) {
942 total_fee_msat = u64::max_value();
949 let path_penalty_msat = $next_hops_path_penalty_msat.checked_add(
950 scorer.channel_penalty_msat(short_channel_id, amount_to_transfer_over_msat, *available_liquidity_msat,
951 &$src_node_id, &$dest_node_id)).unwrap_or_else(|| u64::max_value());
952 let new_graph_node = RouteGraphNode {
953 node_id: $src_node_id,
954 lowest_fee_to_peer_through_node: total_fee_msat,
955 lowest_fee_to_node: $next_hops_fee_msat as u64 + hop_use_fee_msat,
956 total_cltv_delta: hop_total_cltv_delta,
957 value_contribution_msat: value_contribution_msat,
958 path_htlc_minimum_msat,
962 // Update the way of reaching $src_node_id with the given short_channel_id (from $dest_node_id),
963 // if this way is cheaper than the already known
964 // (considering the cost to "reach" this channel from the route destination,
965 // the cost of using this channel,
966 // and the cost of routing to the source node of this channel).
967 // Also, consider that htlc_minimum_msat_difference, because we might end up
968 // paying it. Consider the following exploit:
969 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
970 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
971 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
972 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
974 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
975 // but it may require additional tracking - we don't want to double-count
976 // the fees included in $next_hops_path_htlc_minimum_msat, but also
977 // can't use something that may decrease on future hops.
978 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat)
979 .checked_add(old_entry.path_penalty_msat)
980 .unwrap_or_else(|| u64::max_value());
981 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat)
982 .checked_add(path_penalty_msat)
983 .unwrap_or_else(|| u64::max_value());
985 if !old_entry.was_processed && new_cost < old_cost {
986 targets.push(new_graph_node);
987 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
988 old_entry.hop_use_fee_msat = hop_use_fee_msat;
989 old_entry.total_fee_msat = total_fee_msat;
990 old_entry.node_id = $dest_node_id.clone();
991 old_entry.candidate = $candidate.clone();
992 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
993 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
994 old_entry.path_penalty_msat = path_penalty_msat;
995 #[cfg(any(test, feature = "fuzztarget"))]
997 old_entry.value_contribution_msat = value_contribution_msat;
999 did_add_update_path_to_src_node = true;
1000 } else if old_entry.was_processed && new_cost < old_cost {
1001 #[cfg(any(test, feature = "fuzztarget"))]
1003 // If we're skipping processing a node which was previously
1004 // processed even though we found another path to it with a
1005 // cheaper fee, check that it was because the second path we
1006 // found (which we are processing now) has a lower value
1007 // contribution due to an HTLC minimum limit.
1009 // e.g. take a graph with two paths from node 1 to node 2, one
1010 // through channel A, and one through channel B. Channel A and
1011 // B are both in the to-process heap, with their scores set by
1012 // a higher htlc_minimum than fee.
1013 // Channel A is processed first, and the channels onwards from
1014 // node 1 are added to the to-process heap. Thereafter, we pop
1015 // Channel B off of the heap, note that it has a much more
1016 // restrictive htlc_maximum_msat, and recalculate the fees for
1017 // all of node 1's channels using the new, reduced, amount.
1019 // This would be bogus - we'd be selecting a higher-fee path
1020 // with a lower htlc_maximum_msat instead of the one we'd
1021 // already decided to use.
1022 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
1024 value_contribution_msat + path_penalty_msat <
1025 old_entry.value_contribution_msat + old_entry.path_penalty_msat
1033 did_add_update_path_to_src_node
1037 let empty_node_features = NodeFeatures::empty();
1038 // Find ways (channels with destination) to reach a given node and store them
1039 // in the corresponding data structures (routing graph etc).
1040 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
1041 // meaning how much will be paid in fees after this node (to the best of our knowledge).
1042 // This data can later be helpful to optimize routing (pay lower fees).
1043 macro_rules! add_entries_to_cheapest_to_target_node {
1044 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr, $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr, $next_hops_path_penalty_msat: expr, $next_hops_cltv_delta: expr ) => {
1045 let skip_node = if let Some(elem) = dist.get_mut(&$node_id) {
1046 let was_processed = elem.was_processed;
1047 elem.was_processed = true;
1050 // Entries are added to dist in add_entry!() when there is a channel from a node.
1051 // Because there are no channels from payee, it will not have a dist entry at this point.
1052 // If we're processing any other node, it is always be the result of a channel from it.
1053 assert_eq!($node_id, payee_node_id);
1058 if let Some(first_channels) = first_hop_targets.get(&$node_id) {
1059 for details in first_channels {
1060 let candidate = CandidateRouteHop::FirstHop { details };
1061 add_entry!(candidate, our_node_id, $node_id, $fee_to_target_msat, $next_hops_value_contribution, $next_hops_path_htlc_minimum_msat, $next_hops_path_penalty_msat, $next_hops_cltv_delta);
1065 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
1068 &empty_node_features
1071 if !features.requires_unknown_bits() {
1072 for chan_id in $node.channels.iter() {
1073 let chan = network_channels.get(chan_id).unwrap();
1074 if !chan.features.requires_unknown_bits() {
1075 let (directed_channel, source) =
1076 chan.as_directed_to(&$node_id).expect("inconsistent NetworkGraph");
1077 if first_hops.is_none() || *source != our_node_id {
1078 if let Some(direction) = directed_channel.direction() {
1079 if direction.enabled {
1080 let candidate = CandidateRouteHop::PublicHop {
1081 info: directed_channel.with_update().unwrap(),
1082 short_channel_id: *chan_id,
1084 add_entry!(candidate, *source, $node_id, $fee_to_target_msat, $next_hops_value_contribution, $next_hops_path_htlc_minimum_msat, $next_hops_path_penalty_msat, $next_hops_cltv_delta);
1095 let mut payment_paths = Vec::<PaymentPath>::new();
1097 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
1098 'paths_collection: loop {
1099 // For every new path, start from scratch, except
1100 // bookkept_channels_liquidity_available_msat, which will improve
1101 // the further iterations of path finding. Also don't erase first_hop_targets.
1104 hit_minimum_limit = false;
1106 // If first hop is a private channel and the only way to reach the payee, this is the only
1107 // place where it could be added.
1108 if let Some(first_channels) = first_hop_targets.get(&payee_node_id) {
1109 for details in first_channels {
1110 let candidate = CandidateRouteHop::FirstHop { details };
1111 let added = add_entry!(candidate, our_node_id, payee_node_id, 0, path_value_msat, 0, 0u64, 0);
1112 log_trace!(logger, "{} direct route to payee via SCID {}", if added { "Added" } else { "Skipped" }, candidate.short_channel_id());
1116 // Add the payee as a target, so that the payee-to-payer
1117 // search algorithm knows what to start with.
1118 match network_nodes.get(&payee_node_id) {
1119 // The payee is not in our network graph, so nothing to add here.
1120 // There is still a chance of reaching them via last_hops though,
1121 // so don't yet fail the payment here.
1122 // If not, targets.pop() will not even let us enter the loop in step 2.
1125 add_entries_to_cheapest_to_target_node!(node, payee_node_id, 0, path_value_msat, 0, 0u64, 0);
1130 // If a caller provided us with last hops, add them to routing targets. Since this happens
1131 // earlier than general path finding, they will be somewhat prioritized, although currently
1132 // it matters only if the fees are exactly the same.
1133 for route in payment_params.route_hints.iter().filter(|route| !route.0.is_empty()) {
1134 let first_hop_in_route = &(route.0)[0];
1135 let have_hop_src_in_graph =
1136 // Only add the hops in this route to our candidate set if either
1137 // we have a direct channel to the first hop or the first hop is
1138 // in the regular network graph.
1139 first_hop_targets.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some() ||
1140 network_nodes.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some();
1141 if have_hop_src_in_graph {
1142 // We start building the path from reverse, i.e., from payee
1143 // to the first RouteHintHop in the path.
1144 let hop_iter = route.0.iter().rev();
1145 let prev_hop_iter = core::iter::once(&payment_params.payee_pubkey).chain(
1146 route.0.iter().skip(1).rev().map(|hop| &hop.src_node_id));
1147 let mut hop_used = true;
1148 let mut aggregate_next_hops_fee_msat: u64 = 0;
1149 let mut aggregate_next_hops_path_htlc_minimum_msat: u64 = 0;
1150 let mut aggregate_next_hops_path_penalty_msat: u64 = 0;
1151 let mut aggregate_next_hops_cltv_delta: u32 = 0;
1153 for (idx, (hop, prev_hop_id)) in hop_iter.zip(prev_hop_iter).enumerate() {
1154 let source = NodeId::from_pubkey(&hop.src_node_id);
1155 let target = NodeId::from_pubkey(&prev_hop_id);
1156 let candidate = network_channels
1157 .get(&hop.short_channel_id)
1158 .and_then(|channel| channel.as_directed_to(&target))
1159 .and_then(|(channel, _)| channel.with_update())
1160 .map(|info| CandidateRouteHop::PublicHop {
1162 short_channel_id: hop.short_channel_id,
1164 .unwrap_or_else(|| CandidateRouteHop::PrivateHop { hint: hop });
1165 let capacity_msat = candidate.effective_capacity().as_msat();
1166 aggregate_next_hops_path_penalty_msat = aggregate_next_hops_path_penalty_msat
1167 .checked_add(scorer.channel_penalty_msat(hop.short_channel_id, final_value_msat, capacity_msat, &source, &target))
1168 .unwrap_or_else(|| u64::max_value());
1170 aggregate_next_hops_cltv_delta = aggregate_next_hops_cltv_delta
1171 .checked_add(hop.cltv_expiry_delta as u32)
1172 .unwrap_or_else(|| u32::max_value());
1174 if !add_entry!(candidate, source, target, aggregate_next_hops_fee_msat, path_value_msat, aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat, aggregate_next_hops_cltv_delta) {
1175 // If this hop was not used then there is no use checking the preceding hops
1176 // in the RouteHint. We can break by just searching for a direct channel between
1177 // last checked hop and first_hop_targets
1181 // Searching for a direct channel between last checked hop and first_hop_targets
1182 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&prev_hop_id)) {
1183 for details in first_channels {
1184 let candidate = CandidateRouteHop::FirstHop { details };
1185 add_entry!(candidate, our_node_id, NodeId::from_pubkey(&prev_hop_id), aggregate_next_hops_fee_msat, path_value_msat, aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat, aggregate_next_hops_cltv_delta);
1193 // In the next values of the iterator, the aggregate fees already reflects
1194 // the sum of value sent from payer (final_value_msat) and routing fees
1195 // for the last node in the RouteHint. We need to just add the fees to
1196 // route through the current node so that the preceeding node (next iteration)
1198 let hops_fee = compute_fees(aggregate_next_hops_fee_msat + final_value_msat, hop.fees)
1199 .map_or(None, |inc| inc.checked_add(aggregate_next_hops_fee_msat));
1200 aggregate_next_hops_fee_msat = if let Some(val) = hops_fee { val } else { break; };
1202 let hop_htlc_minimum_msat = candidate.htlc_minimum_msat();
1203 let hop_htlc_minimum_msat_inc = if let Some(val) = compute_fees(aggregate_next_hops_path_htlc_minimum_msat, hop.fees) { val } else { break; };
1204 let hops_path_htlc_minimum = aggregate_next_hops_path_htlc_minimum_msat
1205 .checked_add(hop_htlc_minimum_msat_inc);
1206 aggregate_next_hops_path_htlc_minimum_msat = if let Some(val) = hops_path_htlc_minimum { cmp::max(hop_htlc_minimum_msat, val) } else { break; };
1208 if idx == route.0.len() - 1 {
1209 // The last hop in this iterator is the first hop in
1210 // overall RouteHint.
1211 // If this hop connects to a node with which we have a direct channel,
1212 // ignore the network graph and, if the last hop was added, add our
1213 // direct channel to the candidate set.
1215 // Note that we *must* check if the last hop was added as `add_entry`
1216 // always assumes that the third argument is a node to which we have a
1218 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&hop.src_node_id)) {
1219 for details in first_channels {
1220 let candidate = CandidateRouteHop::FirstHop { details };
1221 add_entry!(candidate, our_node_id, NodeId::from_pubkey(&hop.src_node_id), aggregate_next_hops_fee_msat, path_value_msat, aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat, aggregate_next_hops_cltv_delta);
1229 log_trace!(logger, "Starting main path collection loop with {} nodes pre-filled from first/last hops.", targets.len());
1231 // At this point, targets are filled with the data from first and
1232 // last hops communicated by the caller, and the payment receiver.
1233 let mut found_new_path = false;
1236 // If this loop terminates due the exhaustion of targets, two situations are possible:
1237 // - not enough outgoing liquidity:
1238 // 0 < already_collected_value_msat < final_value_msat
1239 // - enough outgoing liquidity:
1240 // final_value_msat <= already_collected_value_msat < recommended_value_msat
1241 // Both these cases (and other cases except reaching recommended_value_msat) mean that
1242 // paths_collection will be stopped because found_new_path==false.
1243 // This is not necessarily a routing failure.
1244 'path_construction: while let Some(RouteGraphNode { node_id, lowest_fee_to_node, total_cltv_delta, value_contribution_msat, path_htlc_minimum_msat, path_penalty_msat, .. }) = targets.pop() {
1246 // Since we're going payee-to-payer, hitting our node as a target means we should stop
1247 // traversing the graph and arrange the path out of what we found.
1248 if node_id == our_node_id {
1249 let mut new_entry = dist.remove(&our_node_id).unwrap();
1250 let mut ordered_hops = vec!((new_entry.clone(), NodeFeatures::empty()));
1253 let mut features_set = false;
1254 if let Some(first_channels) = first_hop_targets.get(&ordered_hops.last().unwrap().0.node_id) {
1255 for details in first_channels {
1256 if details.short_channel_id.unwrap() == ordered_hops.last().unwrap().0.candidate.short_channel_id() {
1257 ordered_hops.last_mut().unwrap().1 = details.counterparty.features.to_context();
1258 features_set = true;
1264 if let Some(node) = network_nodes.get(&ordered_hops.last().unwrap().0.node_id) {
1265 if let Some(node_info) = node.announcement_info.as_ref() {
1266 ordered_hops.last_mut().unwrap().1 = node_info.features.clone();
1268 ordered_hops.last_mut().unwrap().1 = NodeFeatures::empty();
1271 // We can fill in features for everything except hops which were
1272 // provided via the invoice we're paying. We could guess based on the
1273 // recipient's features but for now we simply avoid guessing at all.
1277 // Means we succesfully traversed from the payer to the payee, now
1278 // save this path for the payment route. Also, update the liquidity
1279 // remaining on the used hops, so that we take them into account
1280 // while looking for more paths.
1281 if ordered_hops.last().unwrap().0.node_id == payee_node_id {
1285 new_entry = match dist.remove(&ordered_hops.last().unwrap().0.node_id) {
1286 Some(payment_hop) => payment_hop,
1287 // We can't arrive at None because, if we ever add an entry to targets,
1288 // we also fill in the entry in dist (see add_entry!).
1289 None => unreachable!(),
1291 // We "propagate" the fees one hop backward (topologically) here,
1292 // so that fees paid for a HTLC forwarding on the current channel are
1293 // associated with the previous channel (where they will be subtracted).
1294 ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
1295 ordered_hops.push((new_entry.clone(), NodeFeatures::empty()));
1297 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
1298 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
1300 log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: {:?}",
1301 ordered_hops.len(), value_contribution_msat, ordered_hops);
1303 let mut payment_path = PaymentPath {hops: ordered_hops};
1305 // We could have possibly constructed a slightly inconsistent path: since we reduce
1306 // value being transferred along the way, we could have violated htlc_minimum_msat
1307 // on some channels we already passed (assuming dest->source direction). Here, we
1308 // recompute the fees again, so that if that's the case, we match the currently
1309 // underpaid htlc_minimum_msat with fees.
1310 payment_path.update_value_and_recompute_fees(cmp::min(value_contribution_msat, final_value_msat));
1312 // Since a path allows to transfer as much value as
1313 // the smallest channel it has ("bottleneck"), we should recompute
1314 // the fees so sender HTLC don't overpay fees when traversing
1315 // larger channels than the bottleneck. This may happen because
1316 // when we were selecting those channels we were not aware how much value
1317 // this path will transfer, and the relative fee for them
1318 // might have been computed considering a larger value.
1319 // Remember that we used these channels so that we don't rely
1320 // on the same liquidity in future paths.
1321 let mut prevented_redundant_path_selection = false;
1322 for (payment_hop, _) in payment_path.hops.iter() {
1323 let channel_liquidity_available_msat = bookkept_channels_liquidity_available_msat.get_mut(&payment_hop.candidate.short_channel_id()).unwrap();
1324 let mut spent_on_hop_msat = value_contribution_msat;
1325 let next_hops_fee_msat = payment_hop.next_hops_fee_msat;
1326 spent_on_hop_msat += next_hops_fee_msat;
1327 if spent_on_hop_msat == *channel_liquidity_available_msat {
1328 // If this path used all of this channel's available liquidity, we know
1329 // this path will not be selected again in the next loop iteration.
1330 prevented_redundant_path_selection = true;
1332 *channel_liquidity_available_msat -= spent_on_hop_msat;
1334 if !prevented_redundant_path_selection {
1335 // If we weren't capped by hitting a liquidity limit on a channel in the path,
1336 // we'll probably end up picking the same path again on the next iteration.
1337 // Decrease the available liquidity of a hop in the middle of the path.
1338 let victim_scid = payment_path.hops[(payment_path.hops.len() - 1) / 2].0.candidate.short_channel_id();
1339 log_trace!(logger, "Disabling channel {} for future path building iterations to avoid duplicates.", victim_scid);
1340 let victim_liquidity = bookkept_channels_liquidity_available_msat.get_mut(&victim_scid).unwrap();
1341 *victim_liquidity = 0;
1344 // Track the total amount all our collected paths allow to send so that we:
1345 // - know when to stop looking for more paths
1346 // - know which of the hops are useless considering how much more sats we need
1347 // (contributes_sufficient_value)
1348 already_collected_value_msat += value_contribution_msat;
1350 payment_paths.push(payment_path);
1351 found_new_path = true;
1352 break 'path_construction;
1355 // If we found a path back to the payee, we shouldn't try to process it again. This is
1356 // the equivalent of the `elem.was_processed` check in
1357 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
1358 if node_id == payee_node_id { continue 'path_construction; }
1360 // Otherwise, since the current target node is not us,
1361 // keep "unrolling" the payment graph from payee to payer by
1362 // finding a way to reach the current target from the payer side.
1363 match network_nodes.get(&node_id) {
1366 add_entries_to_cheapest_to_target_node!(node, node_id, lowest_fee_to_node, value_contribution_msat, path_htlc_minimum_msat, path_penalty_msat, total_cltv_delta);
1372 // If we don't support MPP, no use trying to gather more value ever.
1373 break 'paths_collection;
1377 // Stop either when the recommended value is reached or if no new path was found in this
1379 // In the latter case, making another path finding attempt won't help,
1380 // because we deterministically terminated the search due to low liquidity.
1381 if already_collected_value_msat >= recommended_value_msat || !found_new_path {
1382 log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
1383 already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
1384 break 'paths_collection;
1385 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
1386 // Further, if this was our first walk of the graph, and we weren't limited by an
1387 // htlc_minimum_msat, return immediately because this path should suffice. If we were
1388 // limited by an htlc_minimum_msat value, find another path with a higher value,
1389 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
1390 // still keeping a lower total fee than this path.
1391 if !hit_minimum_limit {
1392 log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
1393 break 'paths_collection;
1395 log_trace!(logger, "Collected our payment amount on the first pass, but running again to collect extra paths with a potentially higher limit.");
1396 path_value_msat = recommended_value_msat;
1401 if payment_paths.len() == 0 {
1402 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1405 if already_collected_value_msat < final_value_msat {
1406 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1409 // Sort by total fees and take the best paths.
1410 payment_paths.sort_by_key(|path| path.get_total_fee_paid_msat());
1411 if payment_paths.len() > 50 {
1412 payment_paths.truncate(50);
1415 // Draw multiple sufficient routes by randomly combining the selected paths.
1416 let mut drawn_routes = Vec::new();
1417 for i in 0..payment_paths.len() {
1418 let mut cur_route = Vec::<PaymentPath>::new();
1419 let mut aggregate_route_value_msat = 0;
1422 // TODO: real random shuffle
1423 // Currently just starts with i_th and goes up to i-1_th in a looped way.
1424 let cur_payment_paths = [&payment_paths[i..], &payment_paths[..i]].concat();
1427 for payment_path in cur_payment_paths {
1428 cur_route.push(payment_path.clone());
1429 aggregate_route_value_msat += payment_path.get_value_msat();
1430 if aggregate_route_value_msat > final_value_msat {
1431 // Last path likely overpaid. Substract it from the most expensive
1432 // (in terms of proportional fee) path in this route and recompute fees.
1433 // This might be not the most economically efficient way, but fewer paths
1434 // also makes routing more reliable.
1435 let mut overpaid_value_msat = aggregate_route_value_msat - final_value_msat;
1437 // First, drop some expensive low-value paths entirely if possible.
1438 // Sort by value so that we drop many really-low values first, since
1439 // fewer paths is better: the payment is less likely to fail.
1440 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1441 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1442 cur_route.sort_by_key(|path| path.get_value_msat());
1443 // We should make sure that at least 1 path left.
1444 let mut paths_left = cur_route.len();
1445 cur_route.retain(|path| {
1446 if paths_left == 1 {
1449 let mut keep = true;
1450 let path_value_msat = path.get_value_msat();
1451 if path_value_msat <= overpaid_value_msat {
1453 overpaid_value_msat -= path_value_msat;
1459 if overpaid_value_msat == 0 {
1463 assert!(cur_route.len() > 0);
1466 // Now, substract the overpaid value from the most-expensive path.
1467 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1468 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1469 cur_route.sort_by_key(|path| { path.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>() });
1470 let expensive_payment_path = cur_route.first_mut().unwrap();
1471 // We already dropped all the small channels above, meaning all the
1472 // remaining channels are larger than remaining overpaid_value_msat.
1473 // Thus, this can't be negative.
1474 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
1475 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
1479 drawn_routes.push(cur_route);
1483 // Select the best route by lowest total fee.
1484 drawn_routes.sort_by_key(|paths| paths.iter().map(|path| path.get_total_fee_paid_msat()).sum::<u64>());
1485 let mut selected_paths = Vec::<Vec<Result<RouteHop, LightningError>>>::new();
1486 for payment_path in drawn_routes.first().unwrap() {
1487 let mut path = payment_path.hops.iter().map(|(payment_hop, node_features)| {
1489 pubkey: PublicKey::from_slice(payment_hop.node_id.as_slice()).map_err(|_| LightningError{err: format!("Public key {:?} is invalid", &payment_hop.node_id), action: ErrorAction::IgnoreAndLog(Level::Trace)})?,
1490 node_features: node_features.clone(),
1491 short_channel_id: payment_hop.candidate.short_channel_id(),
1492 channel_features: payment_hop.candidate.features(),
1493 fee_msat: payment_hop.fee_msat,
1494 cltv_expiry_delta: payment_hop.candidate.cltv_expiry_delta(),
1496 }).collect::<Vec<_>>();
1497 // Propagate the cltv_expiry_delta one hop backwards since the delta from the current hop is
1498 // applicable for the previous hop.
1499 path.iter_mut().rev().fold(final_cltv_expiry_delta, |prev_cltv_expiry_delta, hop| {
1500 core::mem::replace(&mut hop.as_mut().unwrap().cltv_expiry_delta, prev_cltv_expiry_delta)
1502 selected_paths.push(path);
1505 if let Some(features) = &payment_params.features {
1506 for path in selected_paths.iter_mut() {
1507 if let Ok(route_hop) = path.last_mut().unwrap() {
1508 route_hop.node_features = features.to_context();
1514 paths: selected_paths.into_iter().map(|path| path.into_iter().collect()).collect::<Result<Vec<_>, _>>()?,
1515 payment_params: Some(payment_params.clone()),
1517 log_info!(logger, "Got route to {}: {}", payment_params.payee_pubkey, log_route!(route));
1523 use routing::scoring::{ProbabilisticScorer, ProbabilisticScoringParameters, Score};
1524 use routing::network_graph::{NetworkGraph, NetGraphMsgHandler, NodeId};
1525 use routing::router::{get_route, PaymentParameters, Route, RouteHint, RouteHintHop, RouteHop, RoutingFees};
1526 use chain::transaction::OutPoint;
1527 use ln::features::{ChannelFeatures, InitFeatures, InvoiceFeatures, NodeFeatures};
1528 use ln::msgs::{ErrorAction, LightningError, OptionalField, UnsignedChannelAnnouncement, ChannelAnnouncement, RoutingMessageHandler,
1529 NodeAnnouncement, UnsignedNodeAnnouncement, ChannelUpdate, UnsignedChannelUpdate};
1530 use ln::channelmanager;
1531 use util::test_utils;
1532 use util::ser::Writeable;
1534 use util::ser::Writer;
1536 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
1537 use bitcoin::hashes::Hash;
1538 use bitcoin::network::constants::Network;
1539 use bitcoin::blockdata::constants::genesis_block;
1540 use bitcoin::blockdata::script::Builder;
1541 use bitcoin::blockdata::opcodes;
1542 use bitcoin::blockdata::transaction::TxOut;
1546 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
1547 use bitcoin::secp256k1::{Secp256k1, All};
1550 use sync::{self, Arc};
1552 fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
1553 features: InitFeatures, outbound_capacity_msat: u64) -> channelmanager::ChannelDetails {
1554 channelmanager::ChannelDetails {
1555 channel_id: [0; 32],
1556 counterparty: channelmanager::ChannelCounterparty {
1559 unspendable_punishment_reserve: 0,
1560 forwarding_info: None,
1562 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
1564 channel_value_satoshis: 0,
1567 outbound_capacity_msat,
1568 inbound_capacity_msat: 42,
1569 unspendable_punishment_reserve: None,
1570 confirmations_required: None,
1571 force_close_spend_delay: None,
1572 is_outbound: true, is_funding_locked: true,
1573 is_usable: true, is_public: true,
1577 // Using the same keys for LN and BTC ids
1579 net_graph_msg_handler: &NetGraphMsgHandler<Arc<NetworkGraph>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1580 secp_ctx: &Secp256k1<All>, node_1_privkey: &SecretKey, node_2_privkey: &SecretKey, features: ChannelFeatures, short_channel_id: u64
1582 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1583 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1585 let unsigned_announcement = UnsignedChannelAnnouncement {
1587 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1591 bitcoin_key_1: node_id_1,
1592 bitcoin_key_2: node_id_2,
1593 excess_data: Vec::new(),
1596 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1597 let valid_announcement = ChannelAnnouncement {
1598 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1599 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1600 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1601 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1602 contents: unsigned_announcement.clone(),
1604 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1605 Ok(res) => assert!(res),
1611 net_graph_msg_handler: &NetGraphMsgHandler<Arc<NetworkGraph>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1612 secp_ctx: &Secp256k1<All>, node_privkey: &SecretKey, update: UnsignedChannelUpdate
1614 let msghash = hash_to_message!(&Sha256dHash::hash(&update.encode()[..])[..]);
1615 let valid_channel_update = ChannelUpdate {
1616 signature: secp_ctx.sign(&msghash, node_privkey),
1617 contents: update.clone()
1620 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1621 Ok(res) => assert!(res),
1626 fn add_or_update_node(
1627 net_graph_msg_handler: &NetGraphMsgHandler<Arc<NetworkGraph>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1628 secp_ctx: &Secp256k1<All>, node_privkey: &SecretKey, features: NodeFeatures, timestamp: u32
1630 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
1631 let unsigned_announcement = UnsignedNodeAnnouncement {
1637 addresses: Vec::new(),
1638 excess_address_data: Vec::new(),
1639 excess_data: Vec::new(),
1641 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1642 let valid_announcement = NodeAnnouncement {
1643 signature: secp_ctx.sign(&msghash, node_privkey),
1644 contents: unsigned_announcement.clone()
1647 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1653 fn get_nodes(secp_ctx: &Secp256k1<All>) -> (SecretKey, PublicKey, Vec<SecretKey>, Vec<PublicKey>) {
1654 let privkeys: Vec<SecretKey> = (2..10).map(|i| {
1655 SecretKey::from_slice(&hex::decode(format!("{:02x}", i).repeat(32)).unwrap()[..]).unwrap()
1658 let pubkeys = privkeys.iter().map(|secret| PublicKey::from_secret_key(&secp_ctx, secret)).collect();
1660 let our_privkey = SecretKey::from_slice(&hex::decode("01".repeat(32)).unwrap()[..]).unwrap();
1661 let our_id = PublicKey::from_secret_key(&secp_ctx, &our_privkey);
1663 (our_privkey, our_id, privkeys, pubkeys)
1666 fn id_to_feature_flags(id: u8) -> Vec<u8> {
1667 // Set the feature flags to the id'th odd (ie non-required) feature bit so that we can
1668 // test for it later.
1669 let idx = (id - 1) * 2 + 1;
1671 vec![1 << (idx - 8*3), 0, 0, 0]
1672 } else if idx > 8*2 {
1673 vec![1 << (idx - 8*2), 0, 0]
1674 } else if idx > 8*1 {
1675 vec![1 << (idx - 8*1), 0]
1681 fn build_graph() -> (
1683 sync::Arc<NetworkGraph>,
1684 NetGraphMsgHandler<sync::Arc<NetworkGraph>, sync::Arc<test_utils::TestChainSource>, sync::Arc<crate::util::test_utils::TestLogger>>,
1685 sync::Arc<test_utils::TestChainSource>,
1686 sync::Arc<test_utils::TestLogger>,
1688 let secp_ctx = Secp256k1::new();
1689 let logger = Arc::new(test_utils::TestLogger::new());
1690 let chain_monitor = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1691 let network_graph = Arc::new(NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash()));
1692 let net_graph_msg_handler = NetGraphMsgHandler::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
1693 // Build network from our_id to node6:
1695 // -1(1)2- node0 -1(3)2-
1697 // our_id -1(12)2- node7 -1(13)2--- node2
1699 // -1(2)2- node1 -1(4)2-
1702 // chan1 1-to-2: disabled
1703 // chan1 2-to-1: enabled, 0 fee
1705 // chan2 1-to-2: enabled, ignored fee
1706 // chan2 2-to-1: enabled, 0 fee
1708 // chan3 1-to-2: enabled, 0 fee
1709 // chan3 2-to-1: enabled, 100 msat fee
1711 // chan4 1-to-2: enabled, 100% fee
1712 // chan4 2-to-1: enabled, 0 fee
1714 // chan12 1-to-2: enabled, ignored fee
1715 // chan12 2-to-1: enabled, 0 fee
1717 // chan13 1-to-2: enabled, 200% fee
1718 // chan13 2-to-1: enabled, 0 fee
1721 // -1(5)2- node3 -1(8)2--
1725 // node2--1(6)2- node4 -1(9)2--- node6 (not in global route map)
1727 // -1(7)2- node5 -1(10)2-
1729 // Channels 5, 8, 9 and 10 are private channels.
1731 // chan5 1-to-2: enabled, 100 msat fee
1732 // chan5 2-to-1: enabled, 0 fee
1734 // chan6 1-to-2: enabled, 0 fee
1735 // chan6 2-to-1: enabled, 0 fee
1737 // chan7 1-to-2: enabled, 100% fee
1738 // chan7 2-to-1: enabled, 0 fee
1740 // chan8 1-to-2: enabled, variable fee (0 then 1000 msat)
1741 // chan8 2-to-1: enabled, 0 fee
1743 // chan9 1-to-2: enabled, 1001 msat fee
1744 // chan9 2-to-1: enabled, 0 fee
1746 // chan10 1-to-2: enabled, 0 fee
1747 // chan10 2-to-1: enabled, 0 fee
1749 // chan11 1-to-2: enabled, 0 fee
1750 // chan11 2-to-1: enabled, 0 fee
1752 let (our_privkey, _, privkeys, _) = get_nodes(&secp_ctx);
1754 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[0], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
1755 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1756 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1757 short_channel_id: 1,
1760 cltv_expiry_delta: 0,
1761 htlc_minimum_msat: 0,
1762 htlc_maximum_msat: OptionalField::Absent,
1764 fee_proportional_millionths: 0,
1765 excess_data: Vec::new()
1768 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
1770 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
1771 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1772 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1773 short_channel_id: 2,
1776 cltv_expiry_delta: (5 << 4) | 3,
1777 htlc_minimum_msat: 0,
1778 htlc_maximum_msat: OptionalField::Absent,
1779 fee_base_msat: u32::max_value(),
1780 fee_proportional_millionths: u32::max_value(),
1781 excess_data: Vec::new()
1783 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1784 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1785 short_channel_id: 2,
1788 cltv_expiry_delta: 0,
1789 htlc_minimum_msat: 0,
1790 htlc_maximum_msat: OptionalField::Absent,
1792 fee_proportional_millionths: 0,
1793 excess_data: Vec::new()
1796 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
1798 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[7], ChannelFeatures::from_le_bytes(id_to_feature_flags(12)), 12);
1799 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1800 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1801 short_channel_id: 12,
1804 cltv_expiry_delta: (5 << 4) | 3,
1805 htlc_minimum_msat: 0,
1806 htlc_maximum_msat: OptionalField::Absent,
1807 fee_base_msat: u32::max_value(),
1808 fee_proportional_millionths: u32::max_value(),
1809 excess_data: Vec::new()
1811 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1812 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1813 short_channel_id: 12,
1816 cltv_expiry_delta: 0,
1817 htlc_minimum_msat: 0,
1818 htlc_maximum_msat: OptionalField::Absent,
1820 fee_proportional_millionths: 0,
1821 excess_data: Vec::new()
1824 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], NodeFeatures::from_le_bytes(id_to_feature_flags(8)), 0);
1826 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
1827 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1828 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1829 short_channel_id: 3,
1832 cltv_expiry_delta: (3 << 4) | 1,
1833 htlc_minimum_msat: 0,
1834 htlc_maximum_msat: OptionalField::Absent,
1836 fee_proportional_millionths: 0,
1837 excess_data: Vec::new()
1839 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1840 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1841 short_channel_id: 3,
1844 cltv_expiry_delta: (3 << 4) | 2,
1845 htlc_minimum_msat: 0,
1846 htlc_maximum_msat: OptionalField::Absent,
1848 fee_proportional_millionths: 0,
1849 excess_data: Vec::new()
1852 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
1853 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1854 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1855 short_channel_id: 4,
1858 cltv_expiry_delta: (4 << 4) | 1,
1859 htlc_minimum_msat: 0,
1860 htlc_maximum_msat: OptionalField::Absent,
1862 fee_proportional_millionths: 1000000,
1863 excess_data: Vec::new()
1865 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1866 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1867 short_channel_id: 4,
1870 cltv_expiry_delta: (4 << 4) | 2,
1871 htlc_minimum_msat: 0,
1872 htlc_maximum_msat: OptionalField::Absent,
1874 fee_proportional_millionths: 0,
1875 excess_data: Vec::new()
1878 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(13)), 13);
1879 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1880 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1881 short_channel_id: 13,
1884 cltv_expiry_delta: (13 << 4) | 1,
1885 htlc_minimum_msat: 0,
1886 htlc_maximum_msat: OptionalField::Absent,
1888 fee_proportional_millionths: 2000000,
1889 excess_data: Vec::new()
1891 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1892 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1893 short_channel_id: 13,
1896 cltv_expiry_delta: (13 << 4) | 2,
1897 htlc_minimum_msat: 0,
1898 htlc_maximum_msat: OptionalField::Absent,
1900 fee_proportional_millionths: 0,
1901 excess_data: Vec::new()
1904 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
1906 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
1907 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1908 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1909 short_channel_id: 6,
1912 cltv_expiry_delta: (6 << 4) | 1,
1913 htlc_minimum_msat: 0,
1914 htlc_maximum_msat: OptionalField::Absent,
1916 fee_proportional_millionths: 0,
1917 excess_data: Vec::new()
1919 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1920 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1921 short_channel_id: 6,
1924 cltv_expiry_delta: (6 << 4) | 2,
1925 htlc_minimum_msat: 0,
1926 htlc_maximum_msat: OptionalField::Absent,
1928 fee_proportional_millionths: 0,
1929 excess_data: Vec::new(),
1932 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(11)), 11);
1933 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1934 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1935 short_channel_id: 11,
1938 cltv_expiry_delta: (11 << 4) | 1,
1939 htlc_minimum_msat: 0,
1940 htlc_maximum_msat: OptionalField::Absent,
1942 fee_proportional_millionths: 0,
1943 excess_data: Vec::new()
1945 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
1946 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1947 short_channel_id: 11,
1950 cltv_expiry_delta: (11 << 4) | 2,
1951 htlc_minimum_msat: 0,
1952 htlc_maximum_msat: OptionalField::Absent,
1954 fee_proportional_millionths: 0,
1955 excess_data: Vec::new()
1958 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(5)), 0);
1960 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
1962 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[5], ChannelFeatures::from_le_bytes(id_to_feature_flags(7)), 7);
1963 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1964 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1965 short_channel_id: 7,
1968 cltv_expiry_delta: (7 << 4) | 1,
1969 htlc_minimum_msat: 0,
1970 htlc_maximum_msat: OptionalField::Absent,
1972 fee_proportional_millionths: 1000000,
1973 excess_data: Vec::new()
1975 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[5], UnsignedChannelUpdate {
1976 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1977 short_channel_id: 7,
1980 cltv_expiry_delta: (7 << 4) | 2,
1981 htlc_minimum_msat: 0,
1982 htlc_maximum_msat: OptionalField::Absent,
1984 fee_proportional_millionths: 0,
1985 excess_data: Vec::new()
1988 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[5], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
1990 (secp_ctx, network_graph, net_graph_msg_handler, chain_monitor, logger)
1994 fn simple_route_test() {
1995 let (secp_ctx, network_graph, _, _, logger) = build_graph();
1996 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1997 let payment_params = PaymentParameters::from_node_id(nodes[2]);
1998 let scorer = test_utils::TestScorer::with_penalty(0);
2000 // Simple route to 2 via 1
2002 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payment_params, &network_graph, None, 0, 42, Arc::clone(&logger), &scorer) {
2003 assert_eq!(err, "Cannot send a payment of 0 msat");
2004 } else { panic!(); }
2006 let route = get_route(&our_id, &payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2007 assert_eq!(route.paths[0].len(), 2);
2009 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2010 assert_eq!(route.paths[0][0].short_channel_id, 2);
2011 assert_eq!(route.paths[0][0].fee_msat, 100);
2012 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2013 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2014 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2016 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2017 assert_eq!(route.paths[0][1].short_channel_id, 4);
2018 assert_eq!(route.paths[0][1].fee_msat, 100);
2019 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2020 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2021 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2025 fn invalid_first_hop_test() {
2026 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2027 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2028 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2029 let scorer = test_utils::TestScorer::with_penalty(0);
2031 // Simple route to 2 via 1
2033 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
2035 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payment_params, &network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 100, 42, Arc::clone(&logger), &scorer) {
2036 assert_eq!(err, "First hop cannot have our_node_pubkey as a destination.");
2037 } else { panic!(); }
2039 let route = get_route(&our_id, &payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2040 assert_eq!(route.paths[0].len(), 2);
2044 fn htlc_minimum_test() {
2045 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2046 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2047 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2048 let scorer = test_utils::TestScorer::with_penalty(0);
2050 // Simple route to 2 via 1
2052 // Disable other paths
2053 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2054 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2055 short_channel_id: 12,
2057 flags: 2, // to disable
2058 cltv_expiry_delta: 0,
2059 htlc_minimum_msat: 0,
2060 htlc_maximum_msat: OptionalField::Absent,
2062 fee_proportional_millionths: 0,
2063 excess_data: Vec::new()
2065 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2066 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2067 short_channel_id: 3,
2069 flags: 2, // to disable
2070 cltv_expiry_delta: 0,
2071 htlc_minimum_msat: 0,
2072 htlc_maximum_msat: OptionalField::Absent,
2074 fee_proportional_millionths: 0,
2075 excess_data: Vec::new()
2077 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2078 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2079 short_channel_id: 13,
2081 flags: 2, // to disable
2082 cltv_expiry_delta: 0,
2083 htlc_minimum_msat: 0,
2084 htlc_maximum_msat: OptionalField::Absent,
2086 fee_proportional_millionths: 0,
2087 excess_data: Vec::new()
2089 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2090 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2091 short_channel_id: 6,
2093 flags: 2, // to disable
2094 cltv_expiry_delta: 0,
2095 htlc_minimum_msat: 0,
2096 htlc_maximum_msat: OptionalField::Absent,
2098 fee_proportional_millionths: 0,
2099 excess_data: Vec::new()
2101 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2102 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2103 short_channel_id: 7,
2105 flags: 2, // to disable
2106 cltv_expiry_delta: 0,
2107 htlc_minimum_msat: 0,
2108 htlc_maximum_msat: OptionalField::Absent,
2110 fee_proportional_millionths: 0,
2111 excess_data: Vec::new()
2114 // Check against amount_to_transfer_over_msat.
2115 // Set minimal HTLC of 200_000_000 msat.
2116 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2117 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2118 short_channel_id: 2,
2121 cltv_expiry_delta: 0,
2122 htlc_minimum_msat: 200_000_000,
2123 htlc_maximum_msat: OptionalField::Absent,
2125 fee_proportional_millionths: 0,
2126 excess_data: Vec::new()
2129 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
2131 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2132 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2133 short_channel_id: 4,
2136 cltv_expiry_delta: 0,
2137 htlc_minimum_msat: 0,
2138 htlc_maximum_msat: OptionalField::Present(199_999_999),
2140 fee_proportional_millionths: 0,
2141 excess_data: Vec::new()
2144 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
2145 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payment_params, &network_graph, None, 199_999_999, 42, Arc::clone(&logger), &scorer) {
2146 assert_eq!(err, "Failed to find a path to the given destination");
2147 } else { panic!(); }
2149 // Lift the restriction on the first hop.
2150 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2151 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2152 short_channel_id: 2,
2155 cltv_expiry_delta: 0,
2156 htlc_minimum_msat: 0,
2157 htlc_maximum_msat: OptionalField::Absent,
2159 fee_proportional_millionths: 0,
2160 excess_data: Vec::new()
2163 // A payment above the minimum should pass
2164 let route = get_route(&our_id, &payment_params, &network_graph, None, 199_999_999, 42, Arc::clone(&logger), &scorer).unwrap();
2165 assert_eq!(route.paths[0].len(), 2);
2169 fn htlc_minimum_overpay_test() {
2170 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2171 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2172 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
2173 let scorer = test_utils::TestScorer::with_penalty(0);
2175 // A route to node#2 via two paths.
2176 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
2177 // Thus, they can't send 60 without overpaying.
2178 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2179 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2180 short_channel_id: 2,
2183 cltv_expiry_delta: 0,
2184 htlc_minimum_msat: 35_000,
2185 htlc_maximum_msat: OptionalField::Present(40_000),
2187 fee_proportional_millionths: 0,
2188 excess_data: Vec::new()
2190 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2191 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2192 short_channel_id: 12,
2195 cltv_expiry_delta: 0,
2196 htlc_minimum_msat: 35_000,
2197 htlc_maximum_msat: OptionalField::Present(40_000),
2199 fee_proportional_millionths: 0,
2200 excess_data: Vec::new()
2204 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2205 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2206 short_channel_id: 13,
2209 cltv_expiry_delta: 0,
2210 htlc_minimum_msat: 0,
2211 htlc_maximum_msat: OptionalField::Absent,
2213 fee_proportional_millionths: 0,
2214 excess_data: Vec::new()
2216 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2217 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2218 short_channel_id: 4,
2221 cltv_expiry_delta: 0,
2222 htlc_minimum_msat: 0,
2223 htlc_maximum_msat: OptionalField::Absent,
2225 fee_proportional_millionths: 0,
2226 excess_data: Vec::new()
2229 // Disable other paths
2230 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2231 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2232 short_channel_id: 1,
2234 flags: 2, // to disable
2235 cltv_expiry_delta: 0,
2236 htlc_minimum_msat: 0,
2237 htlc_maximum_msat: OptionalField::Absent,
2239 fee_proportional_millionths: 0,
2240 excess_data: Vec::new()
2243 let route = get_route(&our_id, &payment_params, &network_graph, None, 60_000, 42, Arc::clone(&logger), &scorer).unwrap();
2244 // Overpay fees to hit htlc_minimum_msat.
2245 let overpaid_fees = route.paths[0][0].fee_msat + route.paths[1][0].fee_msat;
2246 // TODO: this could be better balanced to overpay 10k and not 15k.
2247 assert_eq!(overpaid_fees, 15_000);
2249 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
2250 // while taking even more fee to match htlc_minimum_msat.
2251 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2252 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2253 short_channel_id: 12,
2256 cltv_expiry_delta: 0,
2257 htlc_minimum_msat: 65_000,
2258 htlc_maximum_msat: OptionalField::Present(80_000),
2260 fee_proportional_millionths: 0,
2261 excess_data: Vec::new()
2263 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2264 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2265 short_channel_id: 2,
2268 cltv_expiry_delta: 0,
2269 htlc_minimum_msat: 0,
2270 htlc_maximum_msat: OptionalField::Absent,
2272 fee_proportional_millionths: 0,
2273 excess_data: Vec::new()
2275 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2276 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2277 short_channel_id: 4,
2280 cltv_expiry_delta: 0,
2281 htlc_minimum_msat: 0,
2282 htlc_maximum_msat: OptionalField::Absent,
2284 fee_proportional_millionths: 100_000,
2285 excess_data: Vec::new()
2288 let route = get_route(&our_id, &payment_params, &network_graph, None, 60_000, 42, Arc::clone(&logger), &scorer).unwrap();
2289 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
2290 assert_eq!(route.paths.len(), 1);
2291 assert_eq!(route.paths[0][0].short_channel_id, 12);
2292 let fees = route.paths[0][0].fee_msat;
2293 assert_eq!(fees, 5_000);
2295 let route = get_route(&our_id, &payment_params, &network_graph, None, 50_000, 42, Arc::clone(&logger), &scorer).unwrap();
2296 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
2297 // the other channel.
2298 assert_eq!(route.paths.len(), 1);
2299 assert_eq!(route.paths[0][0].short_channel_id, 2);
2300 let fees = route.paths[0][0].fee_msat;
2301 assert_eq!(fees, 5_000);
2305 fn disable_channels_test() {
2306 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2307 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2308 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2309 let scorer = test_utils::TestScorer::with_penalty(0);
2311 // // Disable channels 4 and 12 by flags=2
2312 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2313 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2314 short_channel_id: 4,
2316 flags: 2, // to disable
2317 cltv_expiry_delta: 0,
2318 htlc_minimum_msat: 0,
2319 htlc_maximum_msat: OptionalField::Absent,
2321 fee_proportional_millionths: 0,
2322 excess_data: Vec::new()
2324 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2325 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2326 short_channel_id: 12,
2328 flags: 2, // to disable
2329 cltv_expiry_delta: 0,
2330 htlc_minimum_msat: 0,
2331 htlc_maximum_msat: OptionalField::Absent,
2333 fee_proportional_millionths: 0,
2334 excess_data: Vec::new()
2337 // If all the channels require some features we don't understand, route should fail
2338 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer) {
2339 assert_eq!(err, "Failed to find a path to the given destination");
2340 } else { panic!(); }
2342 // If we specify a channel to node7, that overrides our local channel view and that gets used
2343 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2344 let route = get_route(&our_id, &payment_params, &network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 100, 42, Arc::clone(&logger), &scorer).unwrap();
2345 assert_eq!(route.paths[0].len(), 2);
2347 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2348 assert_eq!(route.paths[0][0].short_channel_id, 42);
2349 assert_eq!(route.paths[0][0].fee_msat, 200);
2350 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2351 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2352 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2354 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2355 assert_eq!(route.paths[0][1].short_channel_id, 13);
2356 assert_eq!(route.paths[0][1].fee_msat, 100);
2357 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2358 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2359 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2363 fn disable_node_test() {
2364 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2365 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2366 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2367 let scorer = test_utils::TestScorer::with_penalty(0);
2369 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
2370 let unknown_features = NodeFeatures::known().set_unknown_feature_required();
2371 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
2372 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
2373 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
2375 // If all nodes require some features we don't understand, route should fail
2376 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer) {
2377 assert_eq!(err, "Failed to find a path to the given destination");
2378 } else { panic!(); }
2380 // If we specify a channel to node7, that overrides our local channel view and that gets used
2381 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2382 let route = get_route(&our_id, &payment_params, &network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 100, 42, Arc::clone(&logger), &scorer).unwrap();
2383 assert_eq!(route.paths[0].len(), 2);
2385 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2386 assert_eq!(route.paths[0][0].short_channel_id, 42);
2387 assert_eq!(route.paths[0][0].fee_msat, 200);
2388 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2389 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2390 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2392 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2393 assert_eq!(route.paths[0][1].short_channel_id, 13);
2394 assert_eq!(route.paths[0][1].fee_msat, 100);
2395 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2396 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2397 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2399 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
2400 // naively) assume that the user checked the feature bits on the invoice, which override
2401 // the node_announcement.
2405 fn our_chans_test() {
2406 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2407 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2408 let scorer = test_utils::TestScorer::with_penalty(0);
2410 // Route to 1 via 2 and 3 because our channel to 1 is disabled
2411 let payment_params = PaymentParameters::from_node_id(nodes[0]);
2412 let route = get_route(&our_id, &payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2413 assert_eq!(route.paths[0].len(), 3);
2415 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2416 assert_eq!(route.paths[0][0].short_channel_id, 2);
2417 assert_eq!(route.paths[0][0].fee_msat, 200);
2418 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2419 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2420 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2422 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2423 assert_eq!(route.paths[0][1].short_channel_id, 4);
2424 assert_eq!(route.paths[0][1].fee_msat, 100);
2425 assert_eq!(route.paths[0][1].cltv_expiry_delta, (3 << 4) | 2);
2426 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2427 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2429 assert_eq!(route.paths[0][2].pubkey, nodes[0]);
2430 assert_eq!(route.paths[0][2].short_channel_id, 3);
2431 assert_eq!(route.paths[0][2].fee_msat, 100);
2432 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
2433 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(1));
2434 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(3));
2436 // If we specify a channel to node7, that overrides our local channel view and that gets used
2437 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2438 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2439 let route = get_route(&our_id, &payment_params, &network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 100, 42, Arc::clone(&logger), &scorer).unwrap();
2440 assert_eq!(route.paths[0].len(), 2);
2442 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2443 assert_eq!(route.paths[0][0].short_channel_id, 42);
2444 assert_eq!(route.paths[0][0].fee_msat, 200);
2445 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2446 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2447 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2449 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2450 assert_eq!(route.paths[0][1].short_channel_id, 13);
2451 assert_eq!(route.paths[0][1].fee_msat, 100);
2452 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2453 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2454 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2457 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2458 let zero_fees = RoutingFees {
2460 proportional_millionths: 0,
2462 vec![RouteHint(vec![RouteHintHop {
2463 src_node_id: nodes[3],
2464 short_channel_id: 8,
2466 cltv_expiry_delta: (8 << 4) | 1,
2467 htlc_minimum_msat: None,
2468 htlc_maximum_msat: None,
2470 ]), RouteHint(vec![RouteHintHop {
2471 src_node_id: nodes[4],
2472 short_channel_id: 9,
2475 proportional_millionths: 0,
2477 cltv_expiry_delta: (9 << 4) | 1,
2478 htlc_minimum_msat: None,
2479 htlc_maximum_msat: None,
2480 }]), RouteHint(vec![RouteHintHop {
2481 src_node_id: nodes[5],
2482 short_channel_id: 10,
2484 cltv_expiry_delta: (10 << 4) | 1,
2485 htlc_minimum_msat: None,
2486 htlc_maximum_msat: None,
2490 fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2491 let zero_fees = RoutingFees {
2493 proportional_millionths: 0,
2495 vec![RouteHint(vec![RouteHintHop {
2496 src_node_id: nodes[2],
2497 short_channel_id: 5,
2500 proportional_millionths: 0,
2502 cltv_expiry_delta: (5 << 4) | 1,
2503 htlc_minimum_msat: None,
2504 htlc_maximum_msat: None,
2506 src_node_id: nodes[3],
2507 short_channel_id: 8,
2509 cltv_expiry_delta: (8 << 4) | 1,
2510 htlc_minimum_msat: None,
2511 htlc_maximum_msat: None,
2513 ]), RouteHint(vec![RouteHintHop {
2514 src_node_id: nodes[4],
2515 short_channel_id: 9,
2518 proportional_millionths: 0,
2520 cltv_expiry_delta: (9 << 4) | 1,
2521 htlc_minimum_msat: None,
2522 htlc_maximum_msat: None,
2523 }]), RouteHint(vec![RouteHintHop {
2524 src_node_id: nodes[5],
2525 short_channel_id: 10,
2527 cltv_expiry_delta: (10 << 4) | 1,
2528 htlc_minimum_msat: None,
2529 htlc_maximum_msat: None,
2534 fn partial_route_hint_test() {
2535 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2536 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2537 let scorer = test_utils::TestScorer::with_penalty(0);
2539 // Simple test across 2, 3, 5, and 4 via a last_hop channel
2540 // Tests the behaviour when the RouteHint contains a suboptimal hop.
2541 // RouteHint may be partially used by the algo to build the best path.
2543 // First check that last hop can't have its source as the payee.
2544 let invalid_last_hop = RouteHint(vec![RouteHintHop {
2545 src_node_id: nodes[6],
2546 short_channel_id: 8,
2549 proportional_millionths: 0,
2551 cltv_expiry_delta: (8 << 4) | 1,
2552 htlc_minimum_msat: None,
2553 htlc_maximum_msat: None,
2556 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
2557 invalid_last_hops.push(invalid_last_hop);
2559 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(invalid_last_hops);
2560 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer) {
2561 assert_eq!(err, "Route hint cannot have the payee as the source.");
2562 } else { panic!(); }
2565 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops_multi_private_channels(&nodes));
2566 let route = get_route(&our_id, &payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2567 assert_eq!(route.paths[0].len(), 5);
2569 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2570 assert_eq!(route.paths[0][0].short_channel_id, 2);
2571 assert_eq!(route.paths[0][0].fee_msat, 100);
2572 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2573 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2574 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2576 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2577 assert_eq!(route.paths[0][1].short_channel_id, 4);
2578 assert_eq!(route.paths[0][1].fee_msat, 0);
2579 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
2580 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2581 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2583 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2584 assert_eq!(route.paths[0][2].short_channel_id, 6);
2585 assert_eq!(route.paths[0][2].fee_msat, 0);
2586 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
2587 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2588 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2590 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2591 assert_eq!(route.paths[0][3].short_channel_id, 11);
2592 assert_eq!(route.paths[0][3].fee_msat, 0);
2593 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
2594 // If we have a peer in the node map, we'll use their features here since we don't have
2595 // a way of figuring out their features from the invoice:
2596 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2597 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2599 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2600 assert_eq!(route.paths[0][4].short_channel_id, 8);
2601 assert_eq!(route.paths[0][4].fee_msat, 100);
2602 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2603 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2604 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2607 fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2608 let zero_fees = RoutingFees {
2610 proportional_millionths: 0,
2612 vec![RouteHint(vec![RouteHintHop {
2613 src_node_id: nodes[3],
2614 short_channel_id: 8,
2616 cltv_expiry_delta: (8 << 4) | 1,
2617 htlc_minimum_msat: None,
2618 htlc_maximum_msat: None,
2619 }]), RouteHint(vec![
2621 ]), RouteHint(vec![RouteHintHop {
2622 src_node_id: nodes[5],
2623 short_channel_id: 10,
2625 cltv_expiry_delta: (10 << 4) | 1,
2626 htlc_minimum_msat: None,
2627 htlc_maximum_msat: None,
2632 fn ignores_empty_last_hops_test() {
2633 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2634 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2635 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(empty_last_hop(&nodes));
2636 let scorer = test_utils::TestScorer::with_penalty(0);
2638 // Test handling of an empty RouteHint passed in Invoice.
2640 let route = get_route(&our_id, &payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2641 assert_eq!(route.paths[0].len(), 5);
2643 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2644 assert_eq!(route.paths[0][0].short_channel_id, 2);
2645 assert_eq!(route.paths[0][0].fee_msat, 100);
2646 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2647 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2648 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2650 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2651 assert_eq!(route.paths[0][1].short_channel_id, 4);
2652 assert_eq!(route.paths[0][1].fee_msat, 0);
2653 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
2654 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2655 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2657 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2658 assert_eq!(route.paths[0][2].short_channel_id, 6);
2659 assert_eq!(route.paths[0][2].fee_msat, 0);
2660 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
2661 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2662 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2664 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2665 assert_eq!(route.paths[0][3].short_channel_id, 11);
2666 assert_eq!(route.paths[0][3].fee_msat, 0);
2667 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
2668 // If we have a peer in the node map, we'll use their features here since we don't have
2669 // a way of figuring out their features from the invoice:
2670 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2671 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2673 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2674 assert_eq!(route.paths[0][4].short_channel_id, 8);
2675 assert_eq!(route.paths[0][4].fee_msat, 100);
2676 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2677 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2678 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2681 /// Builds a trivial last-hop hint that passes through the two nodes given, with channel 0xff00
2683 fn multi_hop_last_hops_hint(hint_hops: [PublicKey; 2]) -> Vec<RouteHint> {
2684 let zero_fees = RoutingFees {
2686 proportional_millionths: 0,
2688 vec![RouteHint(vec![RouteHintHop {
2689 src_node_id: hint_hops[0],
2690 short_channel_id: 0xff00,
2693 proportional_millionths: 0,
2695 cltv_expiry_delta: (5 << 4) | 1,
2696 htlc_minimum_msat: None,
2697 htlc_maximum_msat: None,
2699 src_node_id: hint_hops[1],
2700 short_channel_id: 0xff01,
2702 cltv_expiry_delta: (8 << 4) | 1,
2703 htlc_minimum_msat: None,
2704 htlc_maximum_msat: None,
2709 fn multi_hint_last_hops_test() {
2710 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2711 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2712 let last_hops = multi_hop_last_hops_hint([nodes[2], nodes[3]]);
2713 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops.clone());
2714 let scorer = test_utils::TestScorer::with_penalty(0);
2715 // Test through channels 2, 3, 0xff00, 0xff01.
2716 // Test shows that multiple hop hints are considered.
2718 // Disabling channels 6 & 7 by flags=2
2719 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2720 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2721 short_channel_id: 6,
2723 flags: 2, // to disable
2724 cltv_expiry_delta: 0,
2725 htlc_minimum_msat: 0,
2726 htlc_maximum_msat: OptionalField::Absent,
2728 fee_proportional_millionths: 0,
2729 excess_data: Vec::new()
2731 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2732 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2733 short_channel_id: 7,
2735 flags: 2, // to disable
2736 cltv_expiry_delta: 0,
2737 htlc_minimum_msat: 0,
2738 htlc_maximum_msat: OptionalField::Absent,
2740 fee_proportional_millionths: 0,
2741 excess_data: Vec::new()
2744 let route = get_route(&our_id, &payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2745 assert_eq!(route.paths[0].len(), 4);
2747 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2748 assert_eq!(route.paths[0][0].short_channel_id, 2);
2749 assert_eq!(route.paths[0][0].fee_msat, 200);
2750 assert_eq!(route.paths[0][0].cltv_expiry_delta, 65);
2751 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2752 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2754 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2755 assert_eq!(route.paths[0][1].short_channel_id, 4);
2756 assert_eq!(route.paths[0][1].fee_msat, 100);
2757 assert_eq!(route.paths[0][1].cltv_expiry_delta, 81);
2758 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2759 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2761 assert_eq!(route.paths[0][2].pubkey, nodes[3]);
2762 assert_eq!(route.paths[0][2].short_channel_id, last_hops[0].0[0].short_channel_id);
2763 assert_eq!(route.paths[0][2].fee_msat, 0);
2764 assert_eq!(route.paths[0][2].cltv_expiry_delta, 129);
2765 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(4));
2766 assert_eq!(route.paths[0][2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2768 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2769 assert_eq!(route.paths[0][3].short_channel_id, last_hops[0].0[1].short_channel_id);
2770 assert_eq!(route.paths[0][3].fee_msat, 100);
2771 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2772 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2773 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2777 fn private_multi_hint_last_hops_test() {
2778 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2779 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2781 let non_announced_privkey = SecretKey::from_slice(&hex::decode(format!("{:02x}", 0xf0).repeat(32)).unwrap()[..]).unwrap();
2782 let non_announced_pubkey = PublicKey::from_secret_key(&secp_ctx, &non_announced_privkey);
2784 let last_hops = multi_hop_last_hops_hint([nodes[2], non_announced_pubkey]);
2785 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops.clone());
2786 let scorer = test_utils::TestScorer::with_penalty(0);
2787 // Test through channels 2, 3, 0xff00, 0xff01.
2788 // Test shows that multiple hop hints are considered.
2790 // Disabling channels 6 & 7 by flags=2
2791 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2792 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2793 short_channel_id: 6,
2795 flags: 2, // to disable
2796 cltv_expiry_delta: 0,
2797 htlc_minimum_msat: 0,
2798 htlc_maximum_msat: OptionalField::Absent,
2800 fee_proportional_millionths: 0,
2801 excess_data: Vec::new()
2803 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2804 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2805 short_channel_id: 7,
2807 flags: 2, // to disable
2808 cltv_expiry_delta: 0,
2809 htlc_minimum_msat: 0,
2810 htlc_maximum_msat: OptionalField::Absent,
2812 fee_proportional_millionths: 0,
2813 excess_data: Vec::new()
2816 let route = get_route(&our_id, &payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2817 assert_eq!(route.paths[0].len(), 4);
2819 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2820 assert_eq!(route.paths[0][0].short_channel_id, 2);
2821 assert_eq!(route.paths[0][0].fee_msat, 200);
2822 assert_eq!(route.paths[0][0].cltv_expiry_delta, 65);
2823 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2824 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2826 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2827 assert_eq!(route.paths[0][1].short_channel_id, 4);
2828 assert_eq!(route.paths[0][1].fee_msat, 100);
2829 assert_eq!(route.paths[0][1].cltv_expiry_delta, 81);
2830 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2831 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2833 assert_eq!(route.paths[0][2].pubkey, non_announced_pubkey);
2834 assert_eq!(route.paths[0][2].short_channel_id, last_hops[0].0[0].short_channel_id);
2835 assert_eq!(route.paths[0][2].fee_msat, 0);
2836 assert_eq!(route.paths[0][2].cltv_expiry_delta, 129);
2837 assert_eq!(route.paths[0][2].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2838 assert_eq!(route.paths[0][2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2840 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2841 assert_eq!(route.paths[0][3].short_channel_id, last_hops[0].0[1].short_channel_id);
2842 assert_eq!(route.paths[0][3].fee_msat, 100);
2843 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2844 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2845 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2848 fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2849 let zero_fees = RoutingFees {
2851 proportional_millionths: 0,
2853 vec![RouteHint(vec![RouteHintHop {
2854 src_node_id: nodes[4],
2855 short_channel_id: 11,
2857 cltv_expiry_delta: (11 << 4) | 1,
2858 htlc_minimum_msat: None,
2859 htlc_maximum_msat: None,
2861 src_node_id: nodes[3],
2862 short_channel_id: 8,
2864 cltv_expiry_delta: (8 << 4) | 1,
2865 htlc_minimum_msat: None,
2866 htlc_maximum_msat: None,
2867 }]), RouteHint(vec![RouteHintHop {
2868 src_node_id: nodes[4],
2869 short_channel_id: 9,
2872 proportional_millionths: 0,
2874 cltv_expiry_delta: (9 << 4) | 1,
2875 htlc_minimum_msat: None,
2876 htlc_maximum_msat: None,
2877 }]), RouteHint(vec![RouteHintHop {
2878 src_node_id: nodes[5],
2879 short_channel_id: 10,
2881 cltv_expiry_delta: (10 << 4) | 1,
2882 htlc_minimum_msat: None,
2883 htlc_maximum_msat: None,
2888 fn last_hops_with_public_channel_test() {
2889 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2890 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2891 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops_with_public_channel(&nodes));
2892 let scorer = test_utils::TestScorer::with_penalty(0);
2893 // This test shows that public routes can be present in the invoice
2894 // which would be handled in the same manner.
2896 let route = get_route(&our_id, &payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2897 assert_eq!(route.paths[0].len(), 5);
2899 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2900 assert_eq!(route.paths[0][0].short_channel_id, 2);
2901 assert_eq!(route.paths[0][0].fee_msat, 100);
2902 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2903 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2904 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2906 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2907 assert_eq!(route.paths[0][1].short_channel_id, 4);
2908 assert_eq!(route.paths[0][1].fee_msat, 0);
2909 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
2910 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2911 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2913 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2914 assert_eq!(route.paths[0][2].short_channel_id, 6);
2915 assert_eq!(route.paths[0][2].fee_msat, 0);
2916 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
2917 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2918 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2920 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2921 assert_eq!(route.paths[0][3].short_channel_id, 11);
2922 assert_eq!(route.paths[0][3].fee_msat, 0);
2923 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
2924 // If we have a peer in the node map, we'll use their features here since we don't have
2925 // a way of figuring out their features from the invoice:
2926 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2927 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2929 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2930 assert_eq!(route.paths[0][4].short_channel_id, 8);
2931 assert_eq!(route.paths[0][4].fee_msat, 100);
2932 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2933 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2934 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2938 fn our_chans_last_hop_connect_test() {
2939 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2940 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2941 let scorer = test_utils::TestScorer::with_penalty(0);
2943 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
2944 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2945 let mut last_hops = last_hops(&nodes);
2946 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops.clone());
2947 let route = get_route(&our_id, &payment_params, &network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 100, 42, Arc::clone(&logger), &scorer).unwrap();
2948 assert_eq!(route.paths[0].len(), 2);
2950 assert_eq!(route.paths[0][0].pubkey, nodes[3]);
2951 assert_eq!(route.paths[0][0].short_channel_id, 42);
2952 assert_eq!(route.paths[0][0].fee_msat, 0);
2953 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 4) | 1);
2954 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2955 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2957 assert_eq!(route.paths[0][1].pubkey, nodes[6]);
2958 assert_eq!(route.paths[0][1].short_channel_id, 8);
2959 assert_eq!(route.paths[0][1].fee_msat, 100);
2960 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2961 assert_eq!(route.paths[0][1].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2962 assert_eq!(route.paths[0][1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2964 last_hops[0].0[0].fees.base_msat = 1000;
2966 // Revert to via 6 as the fee on 8 goes up
2967 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops);
2968 let route = get_route(&our_id, &payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2969 assert_eq!(route.paths[0].len(), 4);
2971 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2972 assert_eq!(route.paths[0][0].short_channel_id, 2);
2973 assert_eq!(route.paths[0][0].fee_msat, 200); // fee increased as its % of value transferred across node
2974 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2975 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2976 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2978 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2979 assert_eq!(route.paths[0][1].short_channel_id, 4);
2980 assert_eq!(route.paths[0][1].fee_msat, 100);
2981 assert_eq!(route.paths[0][1].cltv_expiry_delta, (7 << 4) | 1);
2982 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2983 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2985 assert_eq!(route.paths[0][2].pubkey, nodes[5]);
2986 assert_eq!(route.paths[0][2].short_channel_id, 7);
2987 assert_eq!(route.paths[0][2].fee_msat, 0);
2988 assert_eq!(route.paths[0][2].cltv_expiry_delta, (10 << 4) | 1);
2989 // If we have a peer in the node map, we'll use their features here since we don't have
2990 // a way of figuring out their features from the invoice:
2991 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
2992 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(7));
2994 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2995 assert_eq!(route.paths[0][3].short_channel_id, 10);
2996 assert_eq!(route.paths[0][3].fee_msat, 100);
2997 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2998 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2999 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3001 // ...but still use 8 for larger payments as 6 has a variable feerate
3002 let route = get_route(&our_id, &payment_params, &network_graph, None, 2000, 42, Arc::clone(&logger), &scorer).unwrap();
3003 assert_eq!(route.paths[0].len(), 5);
3005 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3006 assert_eq!(route.paths[0][0].short_channel_id, 2);
3007 assert_eq!(route.paths[0][0].fee_msat, 3000);
3008 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
3009 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3010 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3012 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3013 assert_eq!(route.paths[0][1].short_channel_id, 4);
3014 assert_eq!(route.paths[0][1].fee_msat, 0);
3015 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
3016 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3017 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3019 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
3020 assert_eq!(route.paths[0][2].short_channel_id, 6);
3021 assert_eq!(route.paths[0][2].fee_msat, 0);
3022 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
3023 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
3024 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
3026 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
3027 assert_eq!(route.paths[0][3].short_channel_id, 11);
3028 assert_eq!(route.paths[0][3].fee_msat, 1000);
3029 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
3030 // If we have a peer in the node map, we'll use their features here since we don't have
3031 // a way of figuring out their features from the invoice:
3032 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
3033 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
3035 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
3036 assert_eq!(route.paths[0][4].short_channel_id, 8);
3037 assert_eq!(route.paths[0][4].fee_msat, 2000);
3038 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
3039 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
3040 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3043 fn do_unannounced_path_test(last_hop_htlc_max: Option<u64>, last_hop_fee_prop: u32, outbound_capacity_msat: u64, route_val: u64) -> Result<Route, LightningError> {
3044 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
3045 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3046 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3048 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
3049 let last_hops = RouteHint(vec![RouteHintHop {
3050 src_node_id: middle_node_id,
3051 short_channel_id: 8,
3054 proportional_millionths: last_hop_fee_prop,
3056 cltv_expiry_delta: (8 << 4) | 1,
3057 htlc_minimum_msat: None,
3058 htlc_maximum_msat: last_hop_htlc_max,
3060 let payment_params = PaymentParameters::from_node_id(target_node_id).with_route_hints(vec![last_hops]);
3061 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
3062 let scorer = test_utils::TestScorer::with_penalty(0);
3063 get_route(&source_node_id, &payment_params, &NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash()), Some(&our_chans.iter().collect::<Vec<_>>()), route_val, 42, &test_utils::TestLogger::new(), &scorer)
3067 fn unannounced_path_test() {
3068 // We should be able to send a payment to a destination without any help of a routing graph
3069 // if we have a channel with a common counterparty that appears in the first and last hop
3071 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
3073 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3074 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3075 assert_eq!(route.paths[0].len(), 2);
3077 assert_eq!(route.paths[0][0].pubkey, middle_node_id);
3078 assert_eq!(route.paths[0][0].short_channel_id, 42);
3079 assert_eq!(route.paths[0][0].fee_msat, 1001);
3080 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 4) | 1);
3081 assert_eq!(route.paths[0][0].node_features.le_flags(), &[0b11]);
3082 assert_eq!(route.paths[0][0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3084 assert_eq!(route.paths[0][1].pubkey, target_node_id);
3085 assert_eq!(route.paths[0][1].short_channel_id, 8);
3086 assert_eq!(route.paths[0][1].fee_msat, 1000000);
3087 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
3088 assert_eq!(route.paths[0][1].node_features.le_flags(), &[0; 0]); // We dont pass flags in from invoices yet
3089 assert_eq!(route.paths[0][1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3093 fn overflow_unannounced_path_test_liquidity_underflow() {
3094 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
3095 // the last-hop had a fee which overflowed a u64, we'd panic.
3096 // This was due to us adding the first-hop from us unconditionally, causing us to think
3097 // we'd built a path (as our node is in the "best candidate" set), when we had not.
3098 // In this test, we previously hit a subtraction underflow due to having less available
3099 // liquidity at the last hop than 0.
3100 assert!(do_unannounced_path_test(Some(21_000_000_0000_0000_000), 0, 21_000_000_0000_0000_000, 21_000_000_0000_0000_000).is_err());
3104 fn overflow_unannounced_path_test_feerate_overflow() {
3105 // This tests for the same case as above, except instead of hitting a subtraction
3106 // underflow, we hit a case where the fee charged at a hop overflowed.
3107 assert!(do_unannounced_path_test(Some(21_000_000_0000_0000_000), 50000, 21_000_000_0000_0000_000, 21_000_000_0000_0000_000).is_err());
3111 fn available_amount_while_routing_test() {
3112 // Tests whether we choose the correct available channel amount while routing.
3114 let (secp_ctx, network_graph, mut net_graph_msg_handler, chain_monitor, logger) = build_graph();
3115 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3116 let scorer = test_utils::TestScorer::with_penalty(0);
3117 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
3119 // We will use a simple single-path route from
3120 // our node to node2 via node0: channels {1, 3}.
3122 // First disable all other paths.
3123 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3124 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3125 short_channel_id: 2,
3128 cltv_expiry_delta: 0,
3129 htlc_minimum_msat: 0,
3130 htlc_maximum_msat: OptionalField::Present(100_000),
3132 fee_proportional_millionths: 0,
3133 excess_data: Vec::new()
3135 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3136 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3137 short_channel_id: 12,
3140 cltv_expiry_delta: 0,
3141 htlc_minimum_msat: 0,
3142 htlc_maximum_msat: OptionalField::Present(100_000),
3144 fee_proportional_millionths: 0,
3145 excess_data: Vec::new()
3148 // Make the first channel (#1) very permissive,
3149 // and we will be testing all limits on the second channel.
3150 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3151 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3152 short_channel_id: 1,
3155 cltv_expiry_delta: 0,
3156 htlc_minimum_msat: 0,
3157 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3159 fee_proportional_millionths: 0,
3160 excess_data: Vec::new()
3163 // First, let's see if routing works if we have absolutely no idea about the available amount.
3164 // In this case, it should be set to 250_000 sats.
3165 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3166 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3167 short_channel_id: 3,
3170 cltv_expiry_delta: 0,
3171 htlc_minimum_msat: 0,
3172 htlc_maximum_msat: OptionalField::Absent,
3174 fee_proportional_millionths: 0,
3175 excess_data: Vec::new()
3179 // Attempt to route more than available results in a failure.
3180 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3181 &our_id, &payment_params, &network_graph, None, 250_000_001, 42, Arc::clone(&logger), &scorer) {
3182 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3183 } else { panic!(); }
3187 // Now, attempt to route an exact amount we have should be fine.
3188 let route = get_route(&our_id, &payment_params, &network_graph, None, 250_000_000, 42, Arc::clone(&logger), &scorer).unwrap();
3189 assert_eq!(route.paths.len(), 1);
3190 let path = route.paths.last().unwrap();
3191 assert_eq!(path.len(), 2);
3192 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3193 assert_eq!(path.last().unwrap().fee_msat, 250_000_000);
3196 // Check that setting outbound_capacity_msat in first_hops limits the channels.
3197 // Disable channel #1 and use another first hop.
3198 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3199 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3200 short_channel_id: 1,
3203 cltv_expiry_delta: 0,
3204 htlc_minimum_msat: 0,
3205 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3207 fee_proportional_millionths: 0,
3208 excess_data: Vec::new()
3211 // Now, limit the first_hop by the outbound_capacity_msat of 200_000 sats.
3212 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
3215 // Attempt to route more than available results in a failure.
3216 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3217 &our_id, &payment_params, &network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 200_000_001, 42, Arc::clone(&logger), &scorer) {
3218 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3219 } else { panic!(); }
3223 // Now, attempt to route an exact amount we have should be fine.
3224 let route = get_route(&our_id, &payment_params, &network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 200_000_000, 42, Arc::clone(&logger), &scorer).unwrap();
3225 assert_eq!(route.paths.len(), 1);
3226 let path = route.paths.last().unwrap();
3227 assert_eq!(path.len(), 2);
3228 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3229 assert_eq!(path.last().unwrap().fee_msat, 200_000_000);
3232 // Enable channel #1 back.
3233 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3234 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3235 short_channel_id: 1,
3238 cltv_expiry_delta: 0,
3239 htlc_minimum_msat: 0,
3240 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3242 fee_proportional_millionths: 0,
3243 excess_data: Vec::new()
3247 // Now let's see if routing works if we know only htlc_maximum_msat.
3248 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3249 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3250 short_channel_id: 3,
3253 cltv_expiry_delta: 0,
3254 htlc_minimum_msat: 0,
3255 htlc_maximum_msat: OptionalField::Present(15_000),
3257 fee_proportional_millionths: 0,
3258 excess_data: Vec::new()
3262 // Attempt to route more than available results in a failure.
3263 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3264 &our_id, &payment_params, &network_graph, None, 15_001, 42, Arc::clone(&logger), &scorer) {
3265 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3266 } else { panic!(); }
3270 // Now, attempt to route an exact amount we have should be fine.
3271 let route = get_route(&our_id, &payment_params, &network_graph, None, 15_000, 42, Arc::clone(&logger), &scorer).unwrap();
3272 assert_eq!(route.paths.len(), 1);
3273 let path = route.paths.last().unwrap();
3274 assert_eq!(path.len(), 2);
3275 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3276 assert_eq!(path.last().unwrap().fee_msat, 15_000);
3279 // Now let's see if routing works if we know only capacity from the UTXO.
3281 // We can't change UTXO capacity on the fly, so we'll disable
3282 // the existing channel and add another one with the capacity we need.
3283 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3284 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3285 short_channel_id: 3,
3288 cltv_expiry_delta: 0,
3289 htlc_minimum_msat: 0,
3290 htlc_maximum_msat: OptionalField::Absent,
3292 fee_proportional_millionths: 0,
3293 excess_data: Vec::new()
3296 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
3297 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
3298 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
3299 .push_opcode(opcodes::all::OP_PUSHNUM_2)
3300 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
3302 *chain_monitor.utxo_ret.lock().unwrap() = Ok(TxOut { value: 15, script_pubkey: good_script.clone() });
3303 net_graph_msg_handler.add_chain_access(Some(chain_monitor));
3305 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
3306 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3307 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3308 short_channel_id: 333,
3311 cltv_expiry_delta: (3 << 4) | 1,
3312 htlc_minimum_msat: 0,
3313 htlc_maximum_msat: OptionalField::Absent,
3315 fee_proportional_millionths: 0,
3316 excess_data: Vec::new()
3318 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3319 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3320 short_channel_id: 333,
3323 cltv_expiry_delta: (3 << 4) | 2,
3324 htlc_minimum_msat: 0,
3325 htlc_maximum_msat: OptionalField::Absent,
3327 fee_proportional_millionths: 0,
3328 excess_data: Vec::new()
3332 // Attempt to route more than available results in a failure.
3333 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3334 &our_id, &payment_params, &network_graph, None, 15_001, 42, Arc::clone(&logger), &scorer) {
3335 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3336 } else { panic!(); }
3340 // Now, attempt to route an exact amount we have should be fine.
3341 let route = get_route(&our_id, &payment_params, &network_graph, None, 15_000, 42, Arc::clone(&logger), &scorer).unwrap();
3342 assert_eq!(route.paths.len(), 1);
3343 let path = route.paths.last().unwrap();
3344 assert_eq!(path.len(), 2);
3345 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3346 assert_eq!(path.last().unwrap().fee_msat, 15_000);
3349 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
3350 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3351 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3352 short_channel_id: 333,
3355 cltv_expiry_delta: 0,
3356 htlc_minimum_msat: 0,
3357 htlc_maximum_msat: OptionalField::Present(10_000),
3359 fee_proportional_millionths: 0,
3360 excess_data: Vec::new()
3364 // Attempt to route more than available results in a failure.
3365 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3366 &our_id, &payment_params, &network_graph, None, 10_001, 42, Arc::clone(&logger), &scorer) {
3367 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3368 } else { panic!(); }
3372 // Now, attempt to route an exact amount we have should be fine.
3373 let route = get_route(&our_id, &payment_params, &network_graph, None, 10_000, 42, Arc::clone(&logger), &scorer).unwrap();
3374 assert_eq!(route.paths.len(), 1);
3375 let path = route.paths.last().unwrap();
3376 assert_eq!(path.len(), 2);
3377 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3378 assert_eq!(path.last().unwrap().fee_msat, 10_000);
3383 fn available_liquidity_last_hop_test() {
3384 // Check that available liquidity properly limits the path even when only
3385 // one of the latter hops is limited.
3386 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3387 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3388 let scorer = test_utils::TestScorer::with_penalty(0);
3389 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
3391 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3392 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
3393 // Total capacity: 50 sats.
3395 // Disable other potential paths.
3396 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3397 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3398 short_channel_id: 2,
3401 cltv_expiry_delta: 0,
3402 htlc_minimum_msat: 0,
3403 htlc_maximum_msat: OptionalField::Present(100_000),
3405 fee_proportional_millionths: 0,
3406 excess_data: Vec::new()
3408 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3409 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3410 short_channel_id: 7,
3413 cltv_expiry_delta: 0,
3414 htlc_minimum_msat: 0,
3415 htlc_maximum_msat: OptionalField::Present(100_000),
3417 fee_proportional_millionths: 0,
3418 excess_data: Vec::new()
3423 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3424 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3425 short_channel_id: 12,
3428 cltv_expiry_delta: 0,
3429 htlc_minimum_msat: 0,
3430 htlc_maximum_msat: OptionalField::Present(100_000),
3432 fee_proportional_millionths: 0,
3433 excess_data: Vec::new()
3435 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3436 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3437 short_channel_id: 13,
3440 cltv_expiry_delta: 0,
3441 htlc_minimum_msat: 0,
3442 htlc_maximum_msat: OptionalField::Present(100_000),
3444 fee_proportional_millionths: 0,
3445 excess_data: Vec::new()
3448 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3449 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3450 short_channel_id: 6,
3453 cltv_expiry_delta: 0,
3454 htlc_minimum_msat: 0,
3455 htlc_maximum_msat: OptionalField::Present(50_000),
3457 fee_proportional_millionths: 0,
3458 excess_data: Vec::new()
3460 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3461 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3462 short_channel_id: 11,
3465 cltv_expiry_delta: 0,
3466 htlc_minimum_msat: 0,
3467 htlc_maximum_msat: OptionalField::Present(100_000),
3469 fee_proportional_millionths: 0,
3470 excess_data: Vec::new()
3473 // Attempt to route more than available results in a failure.
3474 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3475 &our_id, &payment_params, &network_graph, None, 60_000, 42, Arc::clone(&logger), &scorer) {
3476 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3477 } else { panic!(); }
3481 // Now, attempt to route 49 sats (just a bit below the capacity).
3482 let route = get_route(&our_id, &payment_params, &network_graph, None, 49_000, 42, Arc::clone(&logger), &scorer).unwrap();
3483 assert_eq!(route.paths.len(), 1);
3484 let mut total_amount_paid_msat = 0;
3485 for path in &route.paths {
3486 assert_eq!(path.len(), 4);
3487 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3488 total_amount_paid_msat += path.last().unwrap().fee_msat;
3490 assert_eq!(total_amount_paid_msat, 49_000);
3494 // Attempt to route an exact amount is also fine
3495 let route = get_route(&our_id, &payment_params, &network_graph, None, 50_000, 42, Arc::clone(&logger), &scorer).unwrap();
3496 assert_eq!(route.paths.len(), 1);
3497 let mut total_amount_paid_msat = 0;
3498 for path in &route.paths {
3499 assert_eq!(path.len(), 4);
3500 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3501 total_amount_paid_msat += path.last().unwrap().fee_msat;
3503 assert_eq!(total_amount_paid_msat, 50_000);
3508 fn ignore_fee_first_hop_test() {
3509 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3510 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3511 let scorer = test_utils::TestScorer::with_penalty(0);
3512 let payment_params = PaymentParameters::from_node_id(nodes[2]);
3514 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3515 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3516 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3517 short_channel_id: 1,
3520 cltv_expiry_delta: 0,
3521 htlc_minimum_msat: 0,
3522 htlc_maximum_msat: OptionalField::Present(100_000),
3523 fee_base_msat: 1_000_000,
3524 fee_proportional_millionths: 0,
3525 excess_data: Vec::new()
3527 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3528 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3529 short_channel_id: 3,
3532 cltv_expiry_delta: 0,
3533 htlc_minimum_msat: 0,
3534 htlc_maximum_msat: OptionalField::Present(50_000),
3536 fee_proportional_millionths: 0,
3537 excess_data: Vec::new()
3541 let route = get_route(&our_id, &payment_params, &network_graph, None, 50_000, 42, Arc::clone(&logger), &scorer).unwrap();
3542 assert_eq!(route.paths.len(), 1);
3543 let mut total_amount_paid_msat = 0;
3544 for path in &route.paths {
3545 assert_eq!(path.len(), 2);
3546 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3547 total_amount_paid_msat += path.last().unwrap().fee_msat;
3549 assert_eq!(total_amount_paid_msat, 50_000);
3554 fn simple_mpp_route_test() {
3555 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3556 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3557 let scorer = test_utils::TestScorer::with_penalty(0);
3558 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
3560 // We need a route consisting of 3 paths:
3561 // From our node to node2 via node0, node7, node1 (three paths one hop each).
3562 // To achieve this, the amount being transferred should be around
3563 // the total capacity of these 3 paths.
3565 // First, we set limits on these (previously unlimited) channels.
3566 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
3568 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3569 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3570 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3571 short_channel_id: 1,
3574 cltv_expiry_delta: 0,
3575 htlc_minimum_msat: 0,
3576 htlc_maximum_msat: OptionalField::Present(100_000),
3578 fee_proportional_millionths: 0,
3579 excess_data: Vec::new()
3581 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3582 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3583 short_channel_id: 3,
3586 cltv_expiry_delta: 0,
3587 htlc_minimum_msat: 0,
3588 htlc_maximum_msat: OptionalField::Present(50_000),
3590 fee_proportional_millionths: 0,
3591 excess_data: Vec::new()
3594 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
3595 // (total limit 60).
3596 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3597 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3598 short_channel_id: 12,
3601 cltv_expiry_delta: 0,
3602 htlc_minimum_msat: 0,
3603 htlc_maximum_msat: OptionalField::Present(60_000),
3605 fee_proportional_millionths: 0,
3606 excess_data: Vec::new()
3608 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3609 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3610 short_channel_id: 13,
3613 cltv_expiry_delta: 0,
3614 htlc_minimum_msat: 0,
3615 htlc_maximum_msat: OptionalField::Present(60_000),
3617 fee_proportional_millionths: 0,
3618 excess_data: Vec::new()
3621 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
3622 // (total capacity 180 sats).
3623 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3624 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3625 short_channel_id: 2,
3628 cltv_expiry_delta: 0,
3629 htlc_minimum_msat: 0,
3630 htlc_maximum_msat: OptionalField::Present(200_000),
3632 fee_proportional_millionths: 0,
3633 excess_data: Vec::new()
3635 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3636 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3637 short_channel_id: 4,
3640 cltv_expiry_delta: 0,
3641 htlc_minimum_msat: 0,
3642 htlc_maximum_msat: OptionalField::Present(180_000),
3644 fee_proportional_millionths: 0,
3645 excess_data: Vec::new()
3649 // Attempt to route more than available results in a failure.
3650 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3651 &our_id, &payment_params, &network_graph, None, 300_000, 42, Arc::clone(&logger), &scorer) {
3652 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3653 } else { panic!(); }
3657 // Now, attempt to route 250 sats (just a bit below the capacity).
3658 // Our algorithm should provide us with these 3 paths.
3659 let route = get_route(&our_id, &payment_params, &network_graph, None, 250_000, 42, Arc::clone(&logger), &scorer).unwrap();
3660 assert_eq!(route.paths.len(), 3);
3661 let mut total_amount_paid_msat = 0;
3662 for path in &route.paths {
3663 assert_eq!(path.len(), 2);
3664 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3665 total_amount_paid_msat += path.last().unwrap().fee_msat;
3667 assert_eq!(total_amount_paid_msat, 250_000);
3671 // Attempt to route an exact amount is also fine
3672 let route = get_route(&our_id, &payment_params, &network_graph, None, 290_000, 42, Arc::clone(&logger), &scorer).unwrap();
3673 assert_eq!(route.paths.len(), 3);
3674 let mut total_amount_paid_msat = 0;
3675 for path in &route.paths {
3676 assert_eq!(path.len(), 2);
3677 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3678 total_amount_paid_msat += path.last().unwrap().fee_msat;
3680 assert_eq!(total_amount_paid_msat, 290_000);
3685 fn long_mpp_route_test() {
3686 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3687 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3688 let scorer = test_utils::TestScorer::with_penalty(0);
3689 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
3691 // We need a route consisting of 3 paths:
3692 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3693 // Note that these paths overlap (channels 5, 12, 13).
3694 // We will route 300 sats.
3695 // Each path will have 100 sats capacity, those channels which
3696 // are used twice will have 200 sats capacity.
3698 // Disable other potential paths.
3699 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3700 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3701 short_channel_id: 2,
3704 cltv_expiry_delta: 0,
3705 htlc_minimum_msat: 0,
3706 htlc_maximum_msat: OptionalField::Present(100_000),
3708 fee_proportional_millionths: 0,
3709 excess_data: Vec::new()
3711 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3712 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3713 short_channel_id: 7,
3716 cltv_expiry_delta: 0,
3717 htlc_minimum_msat: 0,
3718 htlc_maximum_msat: OptionalField::Present(100_000),
3720 fee_proportional_millionths: 0,
3721 excess_data: Vec::new()
3724 // Path via {node0, node2} is channels {1, 3, 5}.
3725 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3726 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3727 short_channel_id: 1,
3730 cltv_expiry_delta: 0,
3731 htlc_minimum_msat: 0,
3732 htlc_maximum_msat: OptionalField::Present(100_000),
3734 fee_proportional_millionths: 0,
3735 excess_data: Vec::new()
3737 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3738 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3739 short_channel_id: 3,
3742 cltv_expiry_delta: 0,
3743 htlc_minimum_msat: 0,
3744 htlc_maximum_msat: OptionalField::Present(100_000),
3746 fee_proportional_millionths: 0,
3747 excess_data: Vec::new()
3750 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3751 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3752 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3753 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3754 short_channel_id: 5,
3757 cltv_expiry_delta: 0,
3758 htlc_minimum_msat: 0,
3759 htlc_maximum_msat: OptionalField::Present(200_000),
3761 fee_proportional_millionths: 0,
3762 excess_data: Vec::new()
3765 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3766 // Add 100 sats to the capacities of {12, 13}, because these channels
3767 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3768 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3769 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3770 short_channel_id: 12,
3773 cltv_expiry_delta: 0,
3774 htlc_minimum_msat: 0,
3775 htlc_maximum_msat: OptionalField::Present(200_000),
3777 fee_proportional_millionths: 0,
3778 excess_data: Vec::new()
3780 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3781 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3782 short_channel_id: 13,
3785 cltv_expiry_delta: 0,
3786 htlc_minimum_msat: 0,
3787 htlc_maximum_msat: OptionalField::Present(200_000),
3789 fee_proportional_millionths: 0,
3790 excess_data: Vec::new()
3793 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3794 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3795 short_channel_id: 6,
3798 cltv_expiry_delta: 0,
3799 htlc_minimum_msat: 0,
3800 htlc_maximum_msat: OptionalField::Present(100_000),
3802 fee_proportional_millionths: 0,
3803 excess_data: Vec::new()
3805 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3806 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3807 short_channel_id: 11,
3810 cltv_expiry_delta: 0,
3811 htlc_minimum_msat: 0,
3812 htlc_maximum_msat: OptionalField::Present(100_000),
3814 fee_proportional_millionths: 0,
3815 excess_data: Vec::new()
3818 // Path via {node7, node2} is channels {12, 13, 5}.
3819 // We already limited them to 200 sats (they are used twice for 100 sats).
3820 // Nothing to do here.
3823 // Attempt to route more than available results in a failure.
3824 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3825 &our_id, &payment_params, &network_graph, None, 350_000, 42, Arc::clone(&logger), &scorer) {
3826 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3827 } else { panic!(); }
3831 // Now, attempt to route 300 sats (exact amount we can route).
3832 // Our algorithm should provide us with these 3 paths, 100 sats each.
3833 let route = get_route(&our_id, &payment_params, &network_graph, None, 300_000, 42, Arc::clone(&logger), &scorer).unwrap();
3834 assert_eq!(route.paths.len(), 3);
3836 let mut total_amount_paid_msat = 0;
3837 for path in &route.paths {
3838 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3839 total_amount_paid_msat += path.last().unwrap().fee_msat;
3841 assert_eq!(total_amount_paid_msat, 300_000);
3847 fn mpp_cheaper_route_test() {
3848 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3849 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3850 let scorer = test_utils::TestScorer::with_penalty(0);
3851 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
3853 // This test checks that if we have two cheaper paths and one more expensive path,
3854 // so that liquidity-wise any 2 of 3 combination is sufficient,
3855 // two cheaper paths will be taken.
3856 // These paths have equal available liquidity.
3858 // We need a combination of 3 paths:
3859 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3860 // Note that these paths overlap (channels 5, 12, 13).
3861 // Each path will have 100 sats capacity, those channels which
3862 // are used twice will have 200 sats capacity.
3864 // Disable other potential paths.
3865 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3866 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3867 short_channel_id: 2,
3870 cltv_expiry_delta: 0,
3871 htlc_minimum_msat: 0,
3872 htlc_maximum_msat: OptionalField::Present(100_000),
3874 fee_proportional_millionths: 0,
3875 excess_data: Vec::new()
3877 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3878 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3879 short_channel_id: 7,
3882 cltv_expiry_delta: 0,
3883 htlc_minimum_msat: 0,
3884 htlc_maximum_msat: OptionalField::Present(100_000),
3886 fee_proportional_millionths: 0,
3887 excess_data: Vec::new()
3890 // Path via {node0, node2} is channels {1, 3, 5}.
3891 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3892 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3893 short_channel_id: 1,
3896 cltv_expiry_delta: 0,
3897 htlc_minimum_msat: 0,
3898 htlc_maximum_msat: OptionalField::Present(100_000),
3900 fee_proportional_millionths: 0,
3901 excess_data: Vec::new()
3903 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3904 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3905 short_channel_id: 3,
3908 cltv_expiry_delta: 0,
3909 htlc_minimum_msat: 0,
3910 htlc_maximum_msat: OptionalField::Present(100_000),
3912 fee_proportional_millionths: 0,
3913 excess_data: Vec::new()
3916 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3917 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3918 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3919 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3920 short_channel_id: 5,
3923 cltv_expiry_delta: 0,
3924 htlc_minimum_msat: 0,
3925 htlc_maximum_msat: OptionalField::Present(200_000),
3927 fee_proportional_millionths: 0,
3928 excess_data: Vec::new()
3931 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3932 // Add 100 sats to the capacities of {12, 13}, because these channels
3933 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3934 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3935 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3936 short_channel_id: 12,
3939 cltv_expiry_delta: 0,
3940 htlc_minimum_msat: 0,
3941 htlc_maximum_msat: OptionalField::Present(200_000),
3943 fee_proportional_millionths: 0,
3944 excess_data: Vec::new()
3946 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3947 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3948 short_channel_id: 13,
3951 cltv_expiry_delta: 0,
3952 htlc_minimum_msat: 0,
3953 htlc_maximum_msat: OptionalField::Present(200_000),
3955 fee_proportional_millionths: 0,
3956 excess_data: Vec::new()
3959 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3960 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3961 short_channel_id: 6,
3964 cltv_expiry_delta: 0,
3965 htlc_minimum_msat: 0,
3966 htlc_maximum_msat: OptionalField::Present(100_000),
3967 fee_base_msat: 1_000,
3968 fee_proportional_millionths: 0,
3969 excess_data: Vec::new()
3971 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3972 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3973 short_channel_id: 11,
3976 cltv_expiry_delta: 0,
3977 htlc_minimum_msat: 0,
3978 htlc_maximum_msat: OptionalField::Present(100_000),
3980 fee_proportional_millionths: 0,
3981 excess_data: Vec::new()
3984 // Path via {node7, node2} is channels {12, 13, 5}.
3985 // We already limited them to 200 sats (they are used twice for 100 sats).
3986 // Nothing to do here.
3989 // Now, attempt to route 180 sats.
3990 // Our algorithm should provide us with these 2 paths.
3991 let route = get_route(&our_id, &payment_params, &network_graph, None, 180_000, 42, Arc::clone(&logger), &scorer).unwrap();
3992 assert_eq!(route.paths.len(), 2);
3994 let mut total_value_transferred_msat = 0;
3995 let mut total_paid_msat = 0;
3996 for path in &route.paths {
3997 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3998 total_value_transferred_msat += path.last().unwrap().fee_msat;
4000 total_paid_msat += hop.fee_msat;
4003 // If we paid fee, this would be higher.
4004 assert_eq!(total_value_transferred_msat, 180_000);
4005 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
4006 assert_eq!(total_fees_paid, 0);
4011 fn fees_on_mpp_route_test() {
4012 // This test makes sure that MPP algorithm properly takes into account
4013 // fees charged on the channels, by making the fees impactful:
4014 // if the fee is not properly accounted for, the behavior is different.
4015 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4016 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4017 let scorer = test_utils::TestScorer::with_penalty(0);
4018 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
4020 // We need a route consisting of 2 paths:
4021 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
4022 // We will route 200 sats, Each path will have 100 sats capacity.
4024 // This test is not particularly stable: e.g.,
4025 // there's a way to route via {node0, node2, node4}.
4026 // It works while pathfinding is deterministic, but can be broken otherwise.
4027 // It's fine to ignore this concern for now.
4029 // Disable other potential paths.
4030 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4031 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4032 short_channel_id: 2,
4035 cltv_expiry_delta: 0,
4036 htlc_minimum_msat: 0,
4037 htlc_maximum_msat: OptionalField::Present(100_000),
4039 fee_proportional_millionths: 0,
4040 excess_data: Vec::new()
4043 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4044 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4045 short_channel_id: 7,
4048 cltv_expiry_delta: 0,
4049 htlc_minimum_msat: 0,
4050 htlc_maximum_msat: OptionalField::Present(100_000),
4052 fee_proportional_millionths: 0,
4053 excess_data: Vec::new()
4056 // Path via {node0, node2} is channels {1, 3, 5}.
4057 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4058 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4059 short_channel_id: 1,
4062 cltv_expiry_delta: 0,
4063 htlc_minimum_msat: 0,
4064 htlc_maximum_msat: OptionalField::Present(100_000),
4066 fee_proportional_millionths: 0,
4067 excess_data: Vec::new()
4069 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4070 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4071 short_channel_id: 3,
4074 cltv_expiry_delta: 0,
4075 htlc_minimum_msat: 0,
4076 htlc_maximum_msat: OptionalField::Present(100_000),
4078 fee_proportional_millionths: 0,
4079 excess_data: Vec::new()
4082 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4083 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4084 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4085 short_channel_id: 5,
4088 cltv_expiry_delta: 0,
4089 htlc_minimum_msat: 0,
4090 htlc_maximum_msat: OptionalField::Present(100_000),
4092 fee_proportional_millionths: 0,
4093 excess_data: Vec::new()
4096 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4097 // All channels should be 100 sats capacity. But for the fee experiment,
4098 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
4099 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
4100 // 100 sats (and pay 150 sats in fees for the use of channel 6),
4101 // so no matter how large are other channels,
4102 // the whole path will be limited by 100 sats with just these 2 conditions:
4103 // - channel 12 capacity is 250 sats
4104 // - fee for channel 6 is 150 sats
4105 // Let's test this by enforcing these 2 conditions and removing other limits.
4106 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4107 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4108 short_channel_id: 12,
4111 cltv_expiry_delta: 0,
4112 htlc_minimum_msat: 0,
4113 htlc_maximum_msat: OptionalField::Present(250_000),
4115 fee_proportional_millionths: 0,
4116 excess_data: Vec::new()
4118 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4119 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4120 short_channel_id: 13,
4123 cltv_expiry_delta: 0,
4124 htlc_minimum_msat: 0,
4125 htlc_maximum_msat: OptionalField::Absent,
4127 fee_proportional_millionths: 0,
4128 excess_data: Vec::new()
4131 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4132 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4133 short_channel_id: 6,
4136 cltv_expiry_delta: 0,
4137 htlc_minimum_msat: 0,
4138 htlc_maximum_msat: OptionalField::Absent,
4139 fee_base_msat: 150_000,
4140 fee_proportional_millionths: 0,
4141 excess_data: Vec::new()
4143 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4144 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4145 short_channel_id: 11,
4148 cltv_expiry_delta: 0,
4149 htlc_minimum_msat: 0,
4150 htlc_maximum_msat: OptionalField::Absent,
4152 fee_proportional_millionths: 0,
4153 excess_data: Vec::new()
4157 // Attempt to route more than available results in a failure.
4158 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4159 &our_id, &payment_params, &network_graph, None, 210_000, 42, Arc::clone(&logger), &scorer) {
4160 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4161 } else { panic!(); }
4165 // Now, attempt to route 200 sats (exact amount we can route).
4166 let route = get_route(&our_id, &payment_params, &network_graph, None, 200_000, 42, Arc::clone(&logger), &scorer).unwrap();
4167 assert_eq!(route.paths.len(), 2);
4169 let mut total_amount_paid_msat = 0;
4170 for path in &route.paths {
4171 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
4172 total_amount_paid_msat += path.last().unwrap().fee_msat;
4174 assert_eq!(total_amount_paid_msat, 200_000);
4175 assert_eq!(route.get_total_fees(), 150_000);
4180 fn mpp_with_last_hops() {
4181 // Previously, if we tried to send an MPP payment to a destination which was only reachable
4182 // via a single last-hop route hint, we'd fail to route if we first collected routes
4183 // totaling close but not quite enough to fund the full payment.
4185 // This was because we considered last-hop hints to have exactly the sought payment amount
4186 // instead of the amount we were trying to collect, needlessly limiting our path searching
4187 // at the very first hop.
4189 // Specifically, this interacted with our "all paths must fund at least 5% of total target"
4190 // criterion to cause us to refuse all routes at the last hop hint which would be considered
4191 // to only have the remaining to-collect amount in available liquidity.
4193 // This bug appeared in production in some specific channel configurations.
4194 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4195 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4196 let scorer = test_utils::TestScorer::with_penalty(0);
4197 let payment_params = PaymentParameters::from_node_id(PublicKey::from_slice(&[02; 33]).unwrap()).with_features(InvoiceFeatures::known())
4198 .with_route_hints(vec![RouteHint(vec![RouteHintHop {
4199 src_node_id: nodes[2],
4200 short_channel_id: 42,
4201 fees: RoutingFees { base_msat: 0, proportional_millionths: 0 },
4202 cltv_expiry_delta: 42,
4203 htlc_minimum_msat: None,
4204 htlc_maximum_msat: None,
4207 // Keep only two paths from us to nodes[2], both with a 99sat HTLC maximum, with one with
4208 // no fee and one with a 1msat fee. Previously, trying to route 100 sats to nodes[2] here
4209 // would first use the no-fee route and then fail to find a path along the second route as
4210 // we think we can only send up to 1 additional sat over the last-hop but refuse to as its
4211 // under 5% of our payment amount.
4212 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4213 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4214 short_channel_id: 1,
4217 cltv_expiry_delta: (5 << 4) | 5,
4218 htlc_minimum_msat: 0,
4219 htlc_maximum_msat: OptionalField::Present(99_000),
4220 fee_base_msat: u32::max_value(),
4221 fee_proportional_millionths: u32::max_value(),
4222 excess_data: Vec::new()
4224 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4225 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4226 short_channel_id: 2,
4229 cltv_expiry_delta: (5 << 4) | 3,
4230 htlc_minimum_msat: 0,
4231 htlc_maximum_msat: OptionalField::Present(99_000),
4232 fee_base_msat: u32::max_value(),
4233 fee_proportional_millionths: u32::max_value(),
4234 excess_data: Vec::new()
4236 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4237 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4238 short_channel_id: 4,
4241 cltv_expiry_delta: (4 << 4) | 1,
4242 htlc_minimum_msat: 0,
4243 htlc_maximum_msat: OptionalField::Absent,
4245 fee_proportional_millionths: 0,
4246 excess_data: Vec::new()
4248 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4249 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4250 short_channel_id: 13,
4252 flags: 0|2, // Channel disabled
4253 cltv_expiry_delta: (13 << 4) | 1,
4254 htlc_minimum_msat: 0,
4255 htlc_maximum_msat: OptionalField::Absent,
4257 fee_proportional_millionths: 2000000,
4258 excess_data: Vec::new()
4261 // Get a route for 100 sats and check that we found the MPP route no problem and didn't
4263 let route = get_route(&our_id, &payment_params, &network_graph, None, 100_000, 42, Arc::clone(&logger), &scorer).unwrap();
4264 assert_eq!(route.paths.len(), 2);
4265 // Paths are somewhat randomly ordered, but:
4266 // * the first is channel 2 (1 msat fee) -> channel 4 -> channel 42
4267 // * the second is channel 1 (0 fee, but 99 sat maximum) -> channel 3 -> channel 42
4268 assert_eq!(route.paths[0][0].short_channel_id, 2);
4269 assert_eq!(route.paths[0][0].fee_msat, 1);
4270 assert_eq!(route.paths[0][2].fee_msat, 1_000);
4271 assert_eq!(route.paths[1][0].short_channel_id, 1);
4272 assert_eq!(route.paths[1][0].fee_msat, 0);
4273 assert_eq!(route.paths[1][2].fee_msat, 99_000);
4274 assert_eq!(route.get_total_fees(), 1);
4275 assert_eq!(route.get_total_amount(), 100_000);
4279 fn drop_lowest_channel_mpp_route_test() {
4280 // This test checks that low-capacity channel is dropped when after
4281 // path finding we realize that we found more capacity than we need.
4282 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4283 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4284 let scorer = test_utils::TestScorer::with_penalty(0);
4285 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
4287 // We need a route consisting of 3 paths:
4288 // From our node to node2 via node0, node7, node1 (three paths one hop each).
4290 // The first and the second paths should be sufficient, but the third should be
4291 // cheaper, so that we select it but drop later.
4293 // First, we set limits on these (previously unlimited) channels.
4294 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
4296 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
4297 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4298 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4299 short_channel_id: 1,
4302 cltv_expiry_delta: 0,
4303 htlc_minimum_msat: 0,
4304 htlc_maximum_msat: OptionalField::Present(100_000),
4306 fee_proportional_millionths: 0,
4307 excess_data: Vec::new()
4309 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4310 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4311 short_channel_id: 3,
4314 cltv_expiry_delta: 0,
4315 htlc_minimum_msat: 0,
4316 htlc_maximum_msat: OptionalField::Present(50_000),
4318 fee_proportional_millionths: 0,
4319 excess_data: Vec::new()
4322 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
4323 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4324 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4325 short_channel_id: 12,
4328 cltv_expiry_delta: 0,
4329 htlc_minimum_msat: 0,
4330 htlc_maximum_msat: OptionalField::Present(60_000),
4332 fee_proportional_millionths: 0,
4333 excess_data: Vec::new()
4335 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4336 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4337 short_channel_id: 13,
4340 cltv_expiry_delta: 0,
4341 htlc_minimum_msat: 0,
4342 htlc_maximum_msat: OptionalField::Present(60_000),
4344 fee_proportional_millionths: 0,
4345 excess_data: Vec::new()
4348 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
4349 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4350 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4351 short_channel_id: 2,
4354 cltv_expiry_delta: 0,
4355 htlc_minimum_msat: 0,
4356 htlc_maximum_msat: OptionalField::Present(20_000),
4358 fee_proportional_millionths: 0,
4359 excess_data: Vec::new()
4361 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4362 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4363 short_channel_id: 4,
4366 cltv_expiry_delta: 0,
4367 htlc_minimum_msat: 0,
4368 htlc_maximum_msat: OptionalField::Present(20_000),
4370 fee_proportional_millionths: 0,
4371 excess_data: Vec::new()
4375 // Attempt to route more than available results in a failure.
4376 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4377 &our_id, &payment_params, &network_graph, None, 150_000, 42, Arc::clone(&logger), &scorer) {
4378 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4379 } else { panic!(); }
4383 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
4384 // Our algorithm should provide us with these 3 paths.
4385 let route = get_route(&our_id, &payment_params, &network_graph, None, 125_000, 42, Arc::clone(&logger), &scorer).unwrap();
4386 assert_eq!(route.paths.len(), 3);
4387 let mut total_amount_paid_msat = 0;
4388 for path in &route.paths {
4389 assert_eq!(path.len(), 2);
4390 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4391 total_amount_paid_msat += path.last().unwrap().fee_msat;
4393 assert_eq!(total_amount_paid_msat, 125_000);
4397 // Attempt to route without the last small cheap channel
4398 let route = get_route(&our_id, &payment_params, &network_graph, None, 90_000, 42, Arc::clone(&logger), &scorer).unwrap();
4399 assert_eq!(route.paths.len(), 2);
4400 let mut total_amount_paid_msat = 0;
4401 for path in &route.paths {
4402 assert_eq!(path.len(), 2);
4403 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4404 total_amount_paid_msat += path.last().unwrap().fee_msat;
4406 assert_eq!(total_amount_paid_msat, 90_000);
4411 fn min_criteria_consistency() {
4412 // Test that we don't use an inconsistent metric between updating and walking nodes during
4413 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
4414 // was updated with a different criterion from the heap sorting, resulting in loops in
4415 // calculated paths. We test for that specific case here.
4417 // We construct a network that looks like this:
4419 // node2 -1(3)2- node3
4423 // node1 -1(5)2- node4 -1(1)2- node6
4429 // We create a loop on the side of our real path - our destination is node 6, with a
4430 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
4431 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
4432 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
4433 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
4434 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
4435 // "previous hop" being set to node 3, creating a loop in the path.
4436 let secp_ctx = Secp256k1::new();
4437 let logger = Arc::new(test_utils::TestLogger::new());
4438 let network_graph = Arc::new(NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash()));
4439 let net_graph_msg_handler = NetGraphMsgHandler::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
4440 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4441 let scorer = test_utils::TestScorer::with_penalty(0);
4442 let payment_params = PaymentParameters::from_node_id(nodes[6]);
4444 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
4445 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4446 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4447 short_channel_id: 6,
4450 cltv_expiry_delta: (6 << 4) | 0,
4451 htlc_minimum_msat: 0,
4452 htlc_maximum_msat: OptionalField::Absent,
4454 fee_proportional_millionths: 0,
4455 excess_data: Vec::new()
4457 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
4459 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4460 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4461 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4462 short_channel_id: 5,
4465 cltv_expiry_delta: (5 << 4) | 0,
4466 htlc_minimum_msat: 0,
4467 htlc_maximum_msat: OptionalField::Absent,
4469 fee_proportional_millionths: 0,
4470 excess_data: Vec::new()
4472 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
4474 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
4475 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4476 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4477 short_channel_id: 4,
4480 cltv_expiry_delta: (4 << 4) | 0,
4481 htlc_minimum_msat: 0,
4482 htlc_maximum_msat: OptionalField::Absent,
4484 fee_proportional_millionths: 0,
4485 excess_data: Vec::new()
4487 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
4489 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
4490 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
4491 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4492 short_channel_id: 3,
4495 cltv_expiry_delta: (3 << 4) | 0,
4496 htlc_minimum_msat: 0,
4497 htlc_maximum_msat: OptionalField::Absent,
4499 fee_proportional_millionths: 0,
4500 excess_data: Vec::new()
4502 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
4504 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
4505 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4506 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4507 short_channel_id: 2,
4510 cltv_expiry_delta: (2 << 4) | 0,
4511 htlc_minimum_msat: 0,
4512 htlc_maximum_msat: OptionalField::Absent,
4514 fee_proportional_millionths: 0,
4515 excess_data: Vec::new()
4518 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
4519 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4520 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4521 short_channel_id: 1,
4524 cltv_expiry_delta: (1 << 4) | 0,
4525 htlc_minimum_msat: 100,
4526 htlc_maximum_msat: OptionalField::Absent,
4528 fee_proportional_millionths: 0,
4529 excess_data: Vec::new()
4531 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
4534 // Now ensure the route flows simply over nodes 1 and 4 to 6.
4535 let route = get_route(&our_id, &payment_params, &network_graph, None, 10_000, 42, Arc::clone(&logger), &scorer).unwrap();
4536 assert_eq!(route.paths.len(), 1);
4537 assert_eq!(route.paths[0].len(), 3);
4539 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
4540 assert_eq!(route.paths[0][0].short_channel_id, 6);
4541 assert_eq!(route.paths[0][0].fee_msat, 100);
4542 assert_eq!(route.paths[0][0].cltv_expiry_delta, (5 << 4) | 0);
4543 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(1));
4544 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(6));
4546 assert_eq!(route.paths[0][1].pubkey, nodes[4]);
4547 assert_eq!(route.paths[0][1].short_channel_id, 5);
4548 assert_eq!(route.paths[0][1].fee_msat, 0);
4549 assert_eq!(route.paths[0][1].cltv_expiry_delta, (1 << 4) | 0);
4550 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(4));
4551 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(5));
4553 assert_eq!(route.paths[0][2].pubkey, nodes[6]);
4554 assert_eq!(route.paths[0][2].short_channel_id, 1);
4555 assert_eq!(route.paths[0][2].fee_msat, 10_000);
4556 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
4557 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
4558 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(1));
4564 fn exact_fee_liquidity_limit() {
4565 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
4566 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
4567 // we calculated fees on a higher value, resulting in us ignoring such paths.
4568 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4569 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
4570 let scorer = test_utils::TestScorer::with_penalty(0);
4571 let payment_params = PaymentParameters::from_node_id(nodes[2]);
4573 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
4575 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4576 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4577 short_channel_id: 2,
4580 cltv_expiry_delta: 0,
4581 htlc_minimum_msat: 0,
4582 htlc_maximum_msat: OptionalField::Present(85_000),
4584 fee_proportional_millionths: 0,
4585 excess_data: Vec::new()
4588 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4589 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4590 short_channel_id: 12,
4593 cltv_expiry_delta: (4 << 4) | 1,
4594 htlc_minimum_msat: 0,
4595 htlc_maximum_msat: OptionalField::Present(270_000),
4597 fee_proportional_millionths: 1000000,
4598 excess_data: Vec::new()
4602 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
4603 // 200% fee charged channel 13 in the 1-to-2 direction.
4604 let route = get_route(&our_id, &payment_params, &network_graph, None, 90_000, 42, Arc::clone(&logger), &scorer).unwrap();
4605 assert_eq!(route.paths.len(), 1);
4606 assert_eq!(route.paths[0].len(), 2);
4608 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
4609 assert_eq!(route.paths[0][0].short_channel_id, 12);
4610 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
4611 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
4612 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
4613 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
4615 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
4616 assert_eq!(route.paths[0][1].short_channel_id, 13);
4617 assert_eq!(route.paths[0][1].fee_msat, 90_000);
4618 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
4619 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
4620 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
4625 fn htlc_max_reduction_below_min() {
4626 // Test that if, while walking the graph, we reduce the value being sent to meet an
4627 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
4628 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
4629 // resulting in us thinking there is no possible path, even if other paths exist.
4630 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4631 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4632 let scorer = test_utils::TestScorer::with_penalty(0);
4633 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
4635 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
4636 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
4637 // then try to send 90_000.
4638 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4639 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4640 short_channel_id: 2,
4643 cltv_expiry_delta: 0,
4644 htlc_minimum_msat: 0,
4645 htlc_maximum_msat: OptionalField::Present(80_000),
4647 fee_proportional_millionths: 0,
4648 excess_data: Vec::new()
4650 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4651 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4652 short_channel_id: 4,
4655 cltv_expiry_delta: (4 << 4) | 1,
4656 htlc_minimum_msat: 90_000,
4657 htlc_maximum_msat: OptionalField::Absent,
4659 fee_proportional_millionths: 0,
4660 excess_data: Vec::new()
4664 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
4665 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
4666 // expensive) channels 12-13 path.
4667 let route = get_route(&our_id, &payment_params, &network_graph, None, 90_000, 42, Arc::clone(&logger), &scorer).unwrap();
4668 assert_eq!(route.paths.len(), 1);
4669 assert_eq!(route.paths[0].len(), 2);
4671 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
4672 assert_eq!(route.paths[0][0].short_channel_id, 12);
4673 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
4674 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
4675 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
4676 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
4678 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
4679 assert_eq!(route.paths[0][1].short_channel_id, 13);
4680 assert_eq!(route.paths[0][1].fee_msat, 90_000);
4681 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
4682 assert_eq!(route.paths[0][1].node_features.le_flags(), InvoiceFeatures::known().le_flags());
4683 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
4688 fn multiple_direct_first_hops() {
4689 // Previously we'd only ever considered one first hop path per counterparty.
4690 // However, as we don't restrict users to one channel per peer, we really need to support
4691 // looking at all first hop paths.
4692 // Here we test that we do not ignore all-but-the-last first hop paths per counterparty (as
4693 // we used to do by overwriting the `first_hop_targets` hashmap entry) and that we can MPP
4694 // route over multiple channels with the same first hop.
4695 let secp_ctx = Secp256k1::new();
4696 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4697 let logger = Arc::new(test_utils::TestLogger::new());
4698 let network_graph = NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash());
4699 let scorer = test_utils::TestScorer::with_penalty(0);
4700 let payment_params = PaymentParameters::from_node_id(nodes[0]).with_features(InvoiceFeatures::known());
4703 let route = get_route(&our_id, &payment_params, &network_graph, Some(&[
4704 &get_channel_details(Some(3), nodes[0], InitFeatures::known(), 200_000),
4705 &get_channel_details(Some(2), nodes[0], InitFeatures::known(), 10_000),
4706 ]), 100_000, 42, Arc::clone(&logger), &scorer).unwrap();
4707 assert_eq!(route.paths.len(), 1);
4708 assert_eq!(route.paths[0].len(), 1);
4710 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
4711 assert_eq!(route.paths[0][0].short_channel_id, 3);
4712 assert_eq!(route.paths[0][0].fee_msat, 100_000);
4715 let route = get_route(&our_id, &payment_params, &network_graph, Some(&[
4716 &get_channel_details(Some(3), nodes[0], InitFeatures::known(), 50_000),
4717 &get_channel_details(Some(2), nodes[0], InitFeatures::known(), 50_000),
4718 ]), 100_000, 42, Arc::clone(&logger), &scorer).unwrap();
4719 assert_eq!(route.paths.len(), 2);
4720 assert_eq!(route.paths[0].len(), 1);
4721 assert_eq!(route.paths[1].len(), 1);
4723 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
4724 assert_eq!(route.paths[0][0].short_channel_id, 3);
4725 assert_eq!(route.paths[0][0].fee_msat, 50_000);
4727 assert_eq!(route.paths[1][0].pubkey, nodes[0]);
4728 assert_eq!(route.paths[1][0].short_channel_id, 2);
4729 assert_eq!(route.paths[1][0].fee_msat, 50_000);
4734 fn prefers_shorter_route_with_higher_fees() {
4735 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4736 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4737 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
4739 // Without penalizing each hop 100 msats, a longer path with lower fees is chosen.
4740 let scorer = test_utils::TestScorer::with_penalty(0);
4741 let route = get_route(
4742 &our_id, &payment_params, &network_graph, None, 100, 42,
4743 Arc::clone(&logger), &scorer
4745 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4747 assert_eq!(route.get_total_fees(), 100);
4748 assert_eq!(route.get_total_amount(), 100);
4749 assert_eq!(path, vec![2, 4, 6, 11, 8]);
4751 // Applying a 100 msat penalty to each hop results in taking channels 7 and 10 to nodes[6]
4752 // from nodes[2] rather than channel 6, 11, and 8, even though the longer path is cheaper.
4753 let scorer = test_utils::TestScorer::with_penalty(100);
4754 let route = get_route(
4755 &our_id, &payment_params, &network_graph, None, 100, 42,
4756 Arc::clone(&logger), &scorer
4758 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4760 assert_eq!(route.get_total_fees(), 300);
4761 assert_eq!(route.get_total_amount(), 100);
4762 assert_eq!(path, vec![2, 4, 7, 10]);
4765 struct BadChannelScorer {
4766 short_channel_id: u64,
4770 impl Writeable for BadChannelScorer {
4771 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), ::io::Error> { unimplemented!() }
4773 impl Score for BadChannelScorer {
4774 fn channel_penalty_msat(&self, short_channel_id: u64, _send_amt: u64, _capacity_msat: u64, _source: &NodeId, _target: &NodeId) -> u64 {
4775 if short_channel_id == self.short_channel_id { u64::max_value() } else { 0 }
4778 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
4779 fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
4782 struct BadNodeScorer {
4787 impl Writeable for BadNodeScorer {
4788 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), ::io::Error> { unimplemented!() }
4791 impl Score for BadNodeScorer {
4792 fn channel_penalty_msat(&self, _short_channel_id: u64, _send_amt: u64, _capacity_msat: u64, _source: &NodeId, target: &NodeId) -> u64 {
4793 if *target == self.node_id { u64::max_value() } else { 0 }
4796 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
4797 fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
4801 fn avoids_routing_through_bad_channels_and_nodes() {
4802 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4803 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4804 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
4806 // A path to nodes[6] exists when no penalties are applied to any channel.
4807 let scorer = test_utils::TestScorer::with_penalty(0);
4808 let route = get_route(
4809 &our_id, &payment_params, &network_graph, None, 100, 42,
4810 Arc::clone(&logger), &scorer
4812 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4814 assert_eq!(route.get_total_fees(), 100);
4815 assert_eq!(route.get_total_amount(), 100);
4816 assert_eq!(path, vec![2, 4, 6, 11, 8]);
4818 // A different path to nodes[6] exists if channel 6 cannot be routed over.
4819 let scorer = BadChannelScorer { short_channel_id: 6 };
4820 let route = get_route(
4821 &our_id, &payment_params, &network_graph, None, 100, 42,
4822 Arc::clone(&logger), &scorer
4824 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4826 assert_eq!(route.get_total_fees(), 300);
4827 assert_eq!(route.get_total_amount(), 100);
4828 assert_eq!(path, vec![2, 4, 7, 10]);
4830 // A path to nodes[6] does not exist if nodes[2] cannot be routed through.
4831 let scorer = BadNodeScorer { node_id: NodeId::from_pubkey(&nodes[2]) };
4833 &our_id, &payment_params, &network_graph, None, 100, 42,
4834 Arc::clone(&logger), &scorer
4836 Err(LightningError { err, .. } ) => {
4837 assert_eq!(err, "Failed to find a path to the given destination");
4839 Ok(_) => panic!("Expected error"),
4844 fn total_fees_single_path() {
4848 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
4849 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4850 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
4853 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
4854 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4855 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
4858 pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
4859 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4860 short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0
4863 payment_params: None,
4866 assert_eq!(route.get_total_fees(), 250);
4867 assert_eq!(route.get_total_amount(), 225);
4871 fn total_fees_multi_path() {
4875 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
4876 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4877 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
4880 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
4881 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4882 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
4886 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
4887 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4888 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
4891 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
4892 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4893 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
4896 payment_params: None,
4899 assert_eq!(route.get_total_fees(), 200);
4900 assert_eq!(route.get_total_amount(), 300);
4904 fn total_empty_route_no_panic() {
4905 // In an earlier version of `Route::get_total_fees` and `Route::get_total_amount`, they
4906 // would both panic if the route was completely empty. We test to ensure they return 0
4907 // here, even though its somewhat nonsensical as a route.
4908 let route = Route { paths: Vec::new(), payment_params: None };
4910 assert_eq!(route.get_total_fees(), 0);
4911 assert_eq!(route.get_total_amount(), 0);
4915 fn limits_total_cltv_delta() {
4916 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4917 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4919 let scorer = test_utils::TestScorer::with_penalty(0);
4921 // Make sure that generally there is at least one route available
4922 let feasible_max_total_cltv_delta = 1008;
4923 let feasible_payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes))
4924 .with_max_total_cltv_expiry_delta(feasible_max_total_cltv_delta);
4925 let route = get_route(&our_id, &feasible_payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
4926 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4927 assert_ne!(path.len(), 0);
4929 // But not if we exclude all paths on the basis of their accumulated CLTV delta
4930 let fail_max_total_cltv_delta = 23;
4931 let fail_payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes))
4932 .with_max_total_cltv_expiry_delta(fail_max_total_cltv_delta);
4933 match get_route(&our_id, &fail_payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer)
4935 Err(LightningError { err, .. } ) => {
4936 assert_eq!(err, "Failed to find a path to the given destination");
4938 Ok(_) => panic!("Expected error"),
4942 #[cfg(not(feature = "no-std"))]
4943 pub(super) fn random_init_seed() -> u64 {
4944 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
4945 use core::hash::{BuildHasher, Hasher};
4946 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
4947 println!("Using seed of {}", seed);
4950 #[cfg(not(feature = "no-std"))]
4951 use util::ser::Readable;
4954 #[cfg(not(feature = "no-std"))]
4955 fn generate_routes() {
4956 let mut d = match super::test_utils::get_route_file() {
4963 let graph = NetworkGraph::read(&mut d).unwrap();
4965 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
4966 let mut seed = random_init_seed() as usize;
4967 let nodes = graph.read_only().nodes().clone();
4968 'load_endpoints: for _ in 0..10 {
4970 seed = seed.overflowing_mul(0xdeadbeef).0;
4971 let src = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4972 seed = seed.overflowing_mul(0xdeadbeef).0;
4973 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4974 let payment_params = PaymentParameters::from_node_id(dst);
4975 let amt = seed as u64 % 200_000_000;
4976 let params = ProbabilisticScoringParameters::default();
4977 let scorer = ProbabilisticScorer::new(params, &graph);
4978 if get_route(src, &payment_params, &graph, None, amt, 42, &test_utils::TestLogger::new(), &scorer).is_ok() {
4979 continue 'load_endpoints;
4986 #[cfg(not(feature = "no-std"))]
4987 fn generate_routes_mpp() {
4988 let mut d = match super::test_utils::get_route_file() {
4995 let graph = NetworkGraph::read(&mut d).unwrap();
4997 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
4998 let mut seed = random_init_seed() as usize;
4999 let nodes = graph.read_only().nodes().clone();
5000 'load_endpoints: for _ in 0..10 {
5002 seed = seed.overflowing_mul(0xdeadbeef).0;
5003 let src = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5004 seed = seed.overflowing_mul(0xdeadbeef).0;
5005 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5006 let payment_params = PaymentParameters::from_node_id(dst).with_features(InvoiceFeatures::known());
5007 let amt = seed as u64 % 200_000_000;
5008 let params = ProbabilisticScoringParameters::default();
5009 let scorer = ProbabilisticScorer::new(params, &graph);
5010 if get_route(src, &payment_params, &graph, None, amt, 42, &test_utils::TestLogger::new(), &scorer).is_ok() {
5011 continue 'load_endpoints;
5018 #[cfg(all(test, not(feature = "no-std")))]
5019 pub(crate) mod test_utils {
5021 /// Tries to open a network graph file, or panics with a URL to fetch it.
5022 pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
5023 let res = File::open("net_graph-2021-05-31.bin") // By default we're run in RL/lightning
5024 .or_else(|_| File::open("lightning/net_graph-2021-05-31.bin")) // We may be run manually in RL/
5025 .or_else(|_| { // Fall back to guessing based on the binary location
5026 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
5027 let mut path = std::env::current_exe().unwrap();
5028 path.pop(); // lightning-...
5030 path.pop(); // debug
5031 path.pop(); // target
5032 path.push("lightning");
5033 path.push("net_graph-2021-05-31.bin");
5034 eprintln!("{}", path.to_str().unwrap());
5037 .map_err(|_| "Please fetch https://bitcoin.ninja/ldk-net_graph-v0.0.15-2021-05-31.bin and place it at lightning/net_graph-2021-05-31.bin");
5038 #[cfg(require_route_graph_test)]
5039 return Ok(res.unwrap());
5040 #[cfg(not(require_route_graph_test))]
5045 #[cfg(all(test, feature = "unstable", not(feature = "no-std")))]
5048 use bitcoin::hashes::Hash;
5049 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
5050 use chain::transaction::OutPoint;
5051 use ln::channelmanager::{ChannelCounterparty, ChannelDetails};
5052 use ln::features::{InitFeatures, InvoiceFeatures};
5053 use routing::scoring::{FixedPenaltyScorer, ProbabilisticScorer, ProbabilisticScoringParameters, Scorer};
5054 use util::logger::{Logger, Record};
5058 struct DummyLogger {}
5059 impl Logger for DummyLogger {
5060 fn log(&self, _record: &Record) {}
5063 fn read_network_graph() -> NetworkGraph {
5064 let mut d = test_utils::get_route_file().unwrap();
5065 NetworkGraph::read(&mut d).unwrap()
5068 fn payer_pubkey() -> PublicKey {
5069 let secp_ctx = Secp256k1::new();
5070 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
5074 fn first_hop(node_id: PublicKey) -> ChannelDetails {
5076 channel_id: [0; 32],
5077 counterparty: ChannelCounterparty {
5078 features: InitFeatures::known(),
5080 unspendable_punishment_reserve: 0,
5081 forwarding_info: None,
5083 funding_txo: Some(OutPoint {
5084 txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0
5086 short_channel_id: Some(1),
5087 channel_value_satoshis: 10_000_000,
5089 balance_msat: 10_000_000,
5090 outbound_capacity_msat: 10_000_000,
5091 inbound_capacity_msat: 0,
5092 unspendable_punishment_reserve: None,
5093 confirmations_required: None,
5094 force_close_spend_delay: None,
5096 is_funding_locked: true,
5103 fn generate_routes_with_zero_penalty_scorer(bench: &mut Bencher) {
5104 let network_graph = read_network_graph();
5105 let scorer = FixedPenaltyScorer::with_penalty(0);
5106 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::empty());
5110 fn generate_mpp_routes_with_zero_penalty_scorer(bench: &mut Bencher) {
5111 let network_graph = read_network_graph();
5112 let scorer = FixedPenaltyScorer::with_penalty(0);
5113 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::known());
5117 fn generate_routes_with_default_scorer(bench: &mut Bencher) {
5118 let network_graph = read_network_graph();
5119 let scorer = Scorer::default();
5120 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::empty());
5124 fn generate_mpp_routes_with_default_scorer(bench: &mut Bencher) {
5125 let network_graph = read_network_graph();
5126 let scorer = Scorer::default();
5127 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::known());
5131 fn generate_routes_with_probabilistic_scorer(bench: &mut Bencher) {
5132 let network_graph = read_network_graph();
5133 let params = ProbabilisticScoringParameters::default();
5134 let scorer = ProbabilisticScorer::new(params, &network_graph);
5135 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::empty());
5139 fn generate_mpp_routes_with_probabilistic_scorer(bench: &mut Bencher) {
5140 let network_graph = read_network_graph();
5141 let params = ProbabilisticScoringParameters::default();
5142 let scorer = ProbabilisticScorer::new(params, &network_graph);
5143 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::known());
5146 fn generate_routes<S: Score>(
5147 bench: &mut Bencher, graph: &NetworkGraph, mut scorer: S, features: InvoiceFeatures
5149 let nodes = graph.read_only().nodes().clone();
5150 let payer = payer_pubkey();
5152 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
5153 let mut routes = Vec::new();
5154 let mut route_endpoints = Vec::new();
5155 let mut seed: usize = 0xdeadbeef;
5156 'load_endpoints: for _ in 0..100 {
5159 let src = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5161 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5162 let params = PaymentParameters::from_node_id(dst).with_features(features.clone());
5163 let first_hop = first_hop(src);
5164 let amt = seed as u64 % 1_000_000;
5165 if let Ok(route) = get_route(&payer, ¶ms, &graph, Some(&[&first_hop]), amt, 42, &DummyLogger{}, &scorer) {
5167 route_endpoints.push((first_hop, params, amt));
5168 continue 'load_endpoints;
5173 // ...and seed the scorer with success and failure data...
5174 for route in routes {
5175 let amount = route.get_total_amount();
5176 if amount < 250_000 {
5177 for path in route.paths {
5178 scorer.payment_path_successful(&path.iter().collect::<Vec<_>>());
5180 } else if amount > 750_000 {
5181 for path in route.paths {
5182 let short_channel_id = path[path.len() / 2].short_channel_id;
5183 scorer.payment_path_failed(&path.iter().collect::<Vec<_>>(), short_channel_id);
5188 // ...then benchmark finding paths between the nodes we learned.
5191 let (first_hop, params, amt) = &route_endpoints[idx % route_endpoints.len()];
5192 assert!(get_route(&payer, params, &graph, Some(&[first_hop]), *amt, 42, &DummyLogger{}, &scorer).is_ok());