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, ReadOnlyNetworkGraph, NodeId, RoutingFees};
22 use util::ser::{Writeable, Readable};
23 use util::logger::{Level, Logger};
24 use util::chacha20::ChaCha20;
28 use alloc::collections::BinaryHeap;
33 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
35 /// The node_id of the node at this hop.
36 pub pubkey: PublicKey,
37 /// The node_announcement features of the node at this hop. For the last hop, these may be
38 /// amended to match the features present in the invoice this node generated.
39 pub node_features: NodeFeatures,
40 /// The channel that should be used from the previous hop to reach this node.
41 pub short_channel_id: u64,
42 /// The channel_announcement features of the channel that should be used from the previous hop
43 /// to reach this node.
44 pub channel_features: ChannelFeatures,
45 /// The fee taken on this hop (for paying for the use of the *next* channel in the path).
46 /// For the last hop, this should be the full value of the payment (might be more than
47 /// requested if we had to match htlc_minimum_msat).
49 /// The CLTV delta added for this hop. For the last hop, this should be the full CLTV value
50 /// expected at the destination, in excess of the current block height.
51 pub cltv_expiry_delta: u32,
54 impl_writeable_tlv_based!(RouteHop, {
55 (0, pubkey, required),
56 (2, node_features, required),
57 (4, short_channel_id, required),
58 (6, channel_features, required),
59 (8, fee_msat, required),
60 (10, cltv_expiry_delta, required),
63 /// A route directs a payment from the sender (us) to the recipient. If the recipient supports MPP,
64 /// it can take multiple paths. Each path is composed of one or more hops through the network.
65 #[derive(Clone, Hash, PartialEq, Eq)]
67 /// The list of routes taken for a single (potentially-)multi-part payment. The pubkey of the
68 /// last RouteHop in each path must be the same.
69 /// Each entry represents a list of hops, NOT INCLUDING our own, where the last hop is the
70 /// destination. Thus, this must always be at least length one. While the maximum length of any
71 /// given path is variable, keeping the length of any path to less than 20 should currently
72 /// ensure it is viable.
73 pub paths: Vec<Vec<RouteHop>>,
74 /// The `payment_params` parameter passed to [`find_route`].
75 /// This is used by `ChannelManager` to track information which may be required for retries,
76 /// provided back to you via [`Event::PaymentPathFailed`].
78 /// [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed
79 pub payment_params: Option<PaymentParameters>,
82 pub(crate) trait RoutePath {
83 /// Gets the fees for a given path, excluding any excess paid to the recipient.
84 fn get_path_fees(&self) -> u64;
86 impl RoutePath for Vec<RouteHop> {
87 fn get_path_fees(&self) -> u64 {
88 // Do not count last hop of each path since that's the full value of the payment
89 self.split_last().map(|(_, path_prefix)| path_prefix).unwrap_or(&[])
90 .iter().map(|hop| &hop.fee_msat)
96 /// Returns the total amount of fees paid on this [`Route`].
98 /// This doesn't include any extra payment made to the recipient, which can happen in excess of
99 /// the amount passed to [`find_route`]'s `params.final_value_msat`.
100 pub fn get_total_fees(&self) -> u64 {
101 self.paths.iter().map(|path| path.get_path_fees()).sum()
104 /// Returns the total amount paid on this [`Route`], excluding the fees.
105 pub fn get_total_amount(&self) -> u64 {
106 return self.paths.iter()
107 .map(|path| path.split_last().map(|(hop, _)| hop.fee_msat).unwrap_or(0))
112 const SERIALIZATION_VERSION: u8 = 1;
113 const MIN_SERIALIZATION_VERSION: u8 = 1;
115 impl Writeable for Route {
116 fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
117 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
118 (self.paths.len() as u64).write(writer)?;
119 for hops in self.paths.iter() {
120 (hops.len() as u8).write(writer)?;
121 for hop in hops.iter() {
125 write_tlv_fields!(writer, {
126 (1, self.payment_params, option),
132 impl Readable for Route {
133 fn read<R: io::Read>(reader: &mut R) -> Result<Route, DecodeError> {
134 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
135 let path_count: u64 = Readable::read(reader)?;
136 let mut paths = Vec::with_capacity(cmp::min(path_count, 128) as usize);
137 for _ in 0..path_count {
138 let hop_count: u8 = Readable::read(reader)?;
139 let mut hops = Vec::with_capacity(hop_count as usize);
140 for _ in 0..hop_count {
141 hops.push(Readable::read(reader)?);
145 let mut payment_params = None;
146 read_tlv_fields!(reader, {
147 (1, payment_params, option),
149 Ok(Route { paths, payment_params })
153 /// Parameters needed to find a [`Route`].
155 /// Passed to [`find_route`] and also provided in [`Event::PaymentPathFailed`] for retrying a failed
158 /// [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed
159 #[derive(Clone, Debug)]
160 pub struct RouteParameters {
161 /// The parameters of the failed payment path.
162 pub payment_params: PaymentParameters,
164 /// The amount in msats sent on the failed payment path.
165 pub final_value_msat: u64,
167 /// The CLTV on the final hop of the failed payment path.
168 pub final_cltv_expiry_delta: u32,
171 impl_writeable_tlv_based!(RouteParameters, {
172 (0, payment_params, required),
173 (2, final_value_msat, required),
174 (4, final_cltv_expiry_delta, required),
177 /// Maximum total CTLV difference we allow for a full payment path.
178 pub const DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA: u32 = 1008;
180 /// The median hop CLTV expiry delta currently seen in the network.
181 const MEDIAN_HOP_CLTV_EXPIRY_DELTA: u32 = 40;
183 /// The recipient of a payment.
184 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
185 pub struct PaymentParameters {
186 /// The node id of the payee.
187 pub payee_pubkey: PublicKey,
189 /// Features supported by the payee.
191 /// May be set from the payee's invoice or via [`for_keysend`]. May be `None` if the invoice
192 /// does not contain any features.
194 /// [`for_keysend`]: Self::for_keysend
195 pub features: Option<InvoiceFeatures>,
197 /// Hints for routing to the payee, containing channels connecting the payee to public nodes.
198 pub route_hints: Vec<RouteHint>,
200 /// Expiration of a payment to the payee, in seconds relative to the UNIX epoch.
201 pub expiry_time: Option<u64>,
203 /// The maximum total CLTV delta we accept for the route.
204 pub max_total_cltv_expiry_delta: u32,
207 impl_writeable_tlv_based!(PaymentParameters, {
208 (0, payee_pubkey, required),
209 (1, max_total_cltv_expiry_delta, (default_value, DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA)),
210 (2, features, option),
211 (4, route_hints, vec_type),
212 (6, expiry_time, option),
215 impl PaymentParameters {
216 /// Creates a payee with the node id of the given `pubkey`.
217 pub fn from_node_id(payee_pubkey: PublicKey) -> Self {
223 max_total_cltv_expiry_delta: DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA,
227 /// Creates a payee with the node id of the given `pubkey` to use for keysend payments.
228 pub fn for_keysend(payee_pubkey: PublicKey) -> Self {
229 Self::from_node_id(payee_pubkey).with_features(InvoiceFeatures::for_keysend())
232 /// Includes the payee's features.
234 /// (C-not exported) since bindings don't support move semantics
235 pub fn with_features(self, features: InvoiceFeatures) -> Self {
236 Self { features: Some(features), ..self }
239 /// Includes hints for routing to the payee.
241 /// (C-not exported) since bindings don't support move semantics
242 pub fn with_route_hints(self, route_hints: Vec<RouteHint>) -> Self {
243 Self { route_hints, ..self }
246 /// Includes a payment expiration in seconds relative to the UNIX epoch.
248 /// (C-not exported) since bindings don't support move semantics
249 pub fn with_expiry_time(self, expiry_time: u64) -> Self {
250 Self { expiry_time: Some(expiry_time), ..self }
253 /// Includes a limit for the total CLTV expiry delta which is considered during routing
255 /// (C-not exported) since bindings don't support move semantics
256 pub fn with_max_total_cltv_expiry_delta(self, max_total_cltv_expiry_delta: u32) -> Self {
257 Self { max_total_cltv_expiry_delta, ..self }
261 /// A list of hops along a payment path terminating with a channel to the recipient.
262 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
263 pub struct RouteHint(pub Vec<RouteHintHop>);
265 impl Writeable for RouteHint {
266 fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
267 (self.0.len() as u64).write(writer)?;
268 for hop in self.0.iter() {
275 impl Readable for RouteHint {
276 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
277 let hop_count: u64 = Readable::read(reader)?;
278 let mut hops = Vec::with_capacity(cmp::min(hop_count, 16) as usize);
279 for _ in 0..hop_count {
280 hops.push(Readable::read(reader)?);
286 /// A channel descriptor for a hop along a payment path.
287 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
288 pub struct RouteHintHop {
289 /// The node_id of the non-target end of the route
290 pub src_node_id: PublicKey,
291 /// The short_channel_id of this channel
292 pub short_channel_id: u64,
293 /// The fees which must be paid to use this channel
294 pub fees: RoutingFees,
295 /// The difference in CLTV values between this node and the next node.
296 pub cltv_expiry_delta: u16,
297 /// The minimum value, in msat, which must be relayed to the next hop.
298 pub htlc_minimum_msat: Option<u64>,
299 /// The maximum value in msat available for routing with a single HTLC.
300 pub htlc_maximum_msat: Option<u64>,
303 impl_writeable_tlv_based!(RouteHintHop, {
304 (0, src_node_id, required),
305 (1, htlc_minimum_msat, option),
306 (2, short_channel_id, required),
307 (3, htlc_maximum_msat, option),
309 (6, cltv_expiry_delta, required),
312 #[derive(Eq, PartialEq)]
313 struct RouteGraphNode {
315 lowest_fee_to_peer_through_node: u64,
316 lowest_fee_to_node: u64,
317 total_cltv_delta: u32,
318 // The maximum value a yet-to-be-constructed payment path might flow through this node.
319 // This value is upper-bounded by us by:
320 // - how much is needed for a path being constructed
321 // - how much value can channels following this node (up to the destination) can contribute,
322 // considering their capacity and fees
323 value_contribution_msat: u64,
324 /// The effective htlc_minimum_msat at this hop. If a later hop on the path had a higher HTLC
325 /// minimum, we use it, plus the fees required at each earlier hop to meet it.
326 path_htlc_minimum_msat: u64,
327 /// All penalties incurred from this hop on the way to the destination, as calculated using
329 path_penalty_msat: u64,
332 impl cmp::Ord for RouteGraphNode {
333 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
334 let other_score = cmp::max(other.lowest_fee_to_peer_through_node, other.path_htlc_minimum_msat)
335 .saturating_add(other.path_penalty_msat);
336 let self_score = cmp::max(self.lowest_fee_to_peer_through_node, self.path_htlc_minimum_msat)
337 .saturating_add(self.path_penalty_msat);
338 other_score.cmp(&self_score).then_with(|| other.node_id.cmp(&self.node_id))
342 impl cmp::PartialOrd for RouteGraphNode {
343 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
344 Some(self.cmp(other))
348 /// A wrapper around the various hop representations.
350 /// Used to construct a [`PathBuildingHop`] and to estimate [`EffectiveCapacity`].
351 #[derive(Clone, Debug)]
352 enum CandidateRouteHop<'a> {
353 /// A hop from the payer, where the outbound liquidity is known.
355 details: &'a ChannelDetails,
357 /// A hop found in the [`NetworkGraph`], where the channel capacity may or may not be known.
359 info: DirectedChannelInfoWithUpdate<'a>,
360 short_channel_id: u64,
362 /// A hop to the payee found in the payment invoice, though not necessarily a direct channel.
364 hint: &'a RouteHintHop,
368 impl<'a> CandidateRouteHop<'a> {
369 fn short_channel_id(&self) -> u64 {
371 CandidateRouteHop::FirstHop { details } => details.short_channel_id.unwrap(),
372 CandidateRouteHop::PublicHop { short_channel_id, .. } => *short_channel_id,
373 CandidateRouteHop::PrivateHop { hint } => hint.short_channel_id,
377 // NOTE: This may alloc memory so avoid calling it in a hot code path.
378 fn features(&self) -> ChannelFeatures {
380 CandidateRouteHop::FirstHop { details } => details.counterparty.features.to_context(),
381 CandidateRouteHop::PublicHop { info, .. } => info.channel().features.clone(),
382 CandidateRouteHop::PrivateHop { .. } => ChannelFeatures::empty(),
386 fn cltv_expiry_delta(&self) -> u32 {
388 CandidateRouteHop::FirstHop { .. } => 0,
389 CandidateRouteHop::PublicHop { info, .. } => info.direction().cltv_expiry_delta as u32,
390 CandidateRouteHop::PrivateHop { hint } => hint.cltv_expiry_delta as u32,
394 fn htlc_minimum_msat(&self) -> u64 {
396 CandidateRouteHop::FirstHop { .. } => 0,
397 CandidateRouteHop::PublicHop { info, .. } => info.direction().htlc_minimum_msat,
398 CandidateRouteHop::PrivateHop { hint } => hint.htlc_minimum_msat.unwrap_or(0),
402 fn fees(&self) -> RoutingFees {
404 CandidateRouteHop::FirstHop { .. } => RoutingFees {
405 base_msat: 0, proportional_millionths: 0,
407 CandidateRouteHop::PublicHop { info, .. } => info.direction().fees,
408 CandidateRouteHop::PrivateHop { hint } => hint.fees,
412 fn effective_capacity(&self) -> EffectiveCapacity {
414 CandidateRouteHop::FirstHop { details } => EffectiveCapacity::ExactLiquidity {
415 liquidity_msat: details.next_outbound_htlc_limit_msat,
417 CandidateRouteHop::PublicHop { info, .. } => info.effective_capacity(),
418 CandidateRouteHop::PrivateHop { .. } => EffectiveCapacity::Infinite,
423 /// It's useful to keep track of the hops associated with the fees required to use them,
424 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
425 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
426 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
428 struct PathBuildingHop<'a> {
429 // Note that this should be dropped in favor of loading it from CandidateRouteHop, but doing so
430 // is a larger refactor and will require careful performance analysis.
432 candidate: CandidateRouteHop<'a>,
435 /// Minimal fees required to route to the source node of the current hop via any of its inbound channels.
436 src_lowest_inbound_fees: RoutingFees,
437 /// All the fees paid *after* this channel on the way to the destination
438 next_hops_fee_msat: u64,
439 /// Fee paid for the use of the current channel (see candidate.fees()).
440 /// The value will be actually deducted from the counterparty balance on the previous link.
441 hop_use_fee_msat: u64,
442 /// Used to compare channels when choosing the for routing.
443 /// Includes paying for the use of a hop and the following hops, as well as
444 /// an estimated cost of reaching this hop.
445 /// Might get stale when fees are recomputed. Primarily for internal use.
447 /// A mirror of the same field in RouteGraphNode. Note that this is only used during the graph
448 /// walk and may be invalid thereafter.
449 path_htlc_minimum_msat: u64,
450 /// All penalties incurred from this channel on the way to the destination, as calculated using
452 path_penalty_msat: u64,
453 /// If we've already processed a node as the best node, we shouldn't process it again. Normally
454 /// we'd just ignore it if we did as all channels would have a higher new fee, but because we
455 /// may decrease the amounts in use as we walk the graph, the actual calculated fee may
456 /// decrease as well. Thus, we have to explicitly track which nodes have been processed and
457 /// avoid processing them again.
459 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
460 // In tests, we apply further sanity checks on cases where we skip nodes we already processed
461 // to ensure it is specifically in cases where the fee has gone down because of a decrease in
462 // value_contribution_msat, which requires tracking it here. See comments below where it is
463 // used for more info.
464 value_contribution_msat: u64,
467 impl<'a> core::fmt::Debug for PathBuildingHop<'a> {
468 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
469 f.debug_struct("PathBuildingHop")
470 .field("node_id", &self.node_id)
471 .field("short_channel_id", &self.candidate.short_channel_id())
472 .field("total_fee_msat", &self.total_fee_msat)
473 .field("next_hops_fee_msat", &self.next_hops_fee_msat)
474 .field("hop_use_fee_msat", &self.hop_use_fee_msat)
475 .field("total_fee_msat - (next_hops_fee_msat + hop_use_fee_msat)", &(&self.total_fee_msat - (&self.next_hops_fee_msat + &self.hop_use_fee_msat)))
476 .field("path_penalty_msat", &self.path_penalty_msat)
477 .field("path_htlc_minimum_msat", &self.path_htlc_minimum_msat)
478 .field("cltv_expiry_delta", &self.candidate.cltv_expiry_delta())
483 // Instantiated with a list of hops with correct data in them collected during path finding,
484 // an instance of this struct should be further modified only via given methods.
486 struct PaymentPath<'a> {
487 hops: Vec<(PathBuildingHop<'a>, NodeFeatures)>,
490 impl<'a> PaymentPath<'a> {
491 // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
492 fn get_value_msat(&self) -> u64 {
493 self.hops.last().unwrap().0.fee_msat
496 fn get_path_penalty_msat(&self) -> u64 {
497 self.hops.first().map(|h| h.0.path_penalty_msat).unwrap_or(u64::max_value())
500 fn get_total_fee_paid_msat(&self) -> u64 {
501 if self.hops.len() < 1 {
505 // Can't use next_hops_fee_msat because it gets outdated.
506 for (i, (hop, _)) in self.hops.iter().enumerate() {
507 if i != self.hops.len() - 1 {
508 result += hop.fee_msat;
514 fn get_cost_msat(&self) -> u64 {
515 self.get_total_fee_paid_msat().saturating_add(self.get_path_penalty_msat())
518 // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
519 // to change fees may result in an inconsistency.
521 // Sometimes we call this function right after constructing a path which is inconsistent in
522 // that it the value being transferred has decreased while we were doing path finding, leading
523 // to the fees being paid not lining up with the actual limits.
525 // Note that this function is not aware of the available_liquidity limit, and thus does not
526 // support increasing the value being transferred.
527 fn update_value_and_recompute_fees(&mut self, value_msat: u64) {
528 assert!(value_msat <= self.hops.last().unwrap().0.fee_msat);
530 let mut total_fee_paid_msat = 0 as u64;
531 for i in (0..self.hops.len()).rev() {
532 let last_hop = i == self.hops.len() - 1;
534 // For non-last-hop, this value will represent the fees paid on the current hop. It
535 // will consist of the fees for the use of the next hop, and extra fees to match
536 // htlc_minimum_msat of the current channel. Last hop is handled separately.
537 let mut cur_hop_fees_msat = 0;
539 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().0.hop_use_fee_msat;
542 let mut cur_hop = &mut self.hops.get_mut(i).unwrap().0;
543 cur_hop.next_hops_fee_msat = total_fee_paid_msat;
544 // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
545 // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
546 // set it too high just to maliciously take more fees by exploiting this
547 // match htlc_minimum_msat logic.
548 let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
549 if let Some(extra_fees_msat) = cur_hop.candidate.htlc_minimum_msat().checked_sub(cur_hop_transferred_amount_msat) {
550 // Note that there is a risk that *previous hops* (those closer to us, as we go
551 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
553 // This might make us end up with a broken route, although this should be super-rare
554 // in practice, both because of how healthy channels look like, and how we pick
555 // channels in add_entry.
556 // Also, this can't be exploited more heavily than *announce a free path and fail
558 cur_hop_transferred_amount_msat += extra_fees_msat;
559 total_fee_paid_msat += extra_fees_msat;
560 cur_hop_fees_msat += extra_fees_msat;
564 // Final hop is a special case: it usually has just value_msat (by design), but also
565 // it still could overpay for the htlc_minimum_msat.
566 cur_hop.fee_msat = cur_hop_transferred_amount_msat;
568 // Propagate updated fees for the use of the channels to one hop back, where they
569 // will be actually paid (fee_msat). The last hop is handled above separately.
570 cur_hop.fee_msat = cur_hop_fees_msat;
573 // Fee for the use of the current hop which will be deducted on the previous hop.
574 // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
575 // this channel is free for us.
577 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.candidate.fees()) {
578 cur_hop.hop_use_fee_msat = new_fee;
579 total_fee_paid_msat += new_fee;
581 // It should not be possible because this function is called only to reduce the
582 // value. In that case, compute_fee was already called with the same fees for
583 // larger amount and there was no overflow.
591 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
592 let proportional_fee_millions =
593 amount_msat.checked_mul(channel_fees.proportional_millionths as u64);
594 if let Some(new_fee) = proportional_fee_millions.and_then(|part| {
595 (channel_fees.base_msat as u64).checked_add(part / 1_000_000) }) {
599 // This function may be (indirectly) called without any verification,
600 // with channel_fees provided by a caller. We should handle it gracefully.
605 /// The default `features` we assume for a node in a route, when no `features` are known about that
608 /// Default features are:
609 /// * variable_length_onion_optional
610 fn default_node_features() -> NodeFeatures {
611 let mut features = NodeFeatures::empty();
612 features.set_variable_length_onion_optional();
616 /// Finds a route from us (payer) to the given target node (payee).
618 /// If the payee provided features in their invoice, they should be provided via `params.payee`.
619 /// Without this, MPP will only be used if the payee's features are available in the network graph.
621 /// Private routing paths between a public node and the target may be included in `params.payee`.
623 /// If some channels aren't announced, it may be useful to fill in `first_hops` with the results
624 /// from [`ChannelManager::list_usable_channels`]. If it is filled in, the view of our local
625 /// channels from [`NetworkGraph`] will be ignored, and only those in `first_hops` will be used.
627 /// The fees on channels from us to the next hop are ignored as they are assumed to all be equal.
628 /// However, the enabled/disabled bit on such channels as well as the `htlc_minimum_msat` /
629 /// `htlc_maximum_msat` *are* checked as they may change based on the receiving node.
633 /// May be used to re-compute a [`Route`] when handling a [`Event::PaymentPathFailed`]. Any
634 /// adjustments to the [`NetworkGraph`] and channel scores should be made prior to calling this
639 /// Panics if first_hops contains channels without short_channel_ids;
640 /// [`ChannelManager::list_usable_channels`] will never include such channels.
642 /// [`ChannelManager::list_usable_channels`]: crate::ln::channelmanager::ChannelManager::list_usable_channels
643 /// [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed
644 pub fn find_route<L: Deref, S: Score>(
645 our_node_pubkey: &PublicKey, route_params: &RouteParameters, network: &NetworkGraph,
646 first_hops: Option<&[&ChannelDetails]>, logger: L, scorer: &S, random_seed_bytes: &[u8; 32]
647 ) -> Result<Route, LightningError>
648 where L::Target: Logger {
649 let network_graph = network.read_only();
651 our_node_pubkey, &route_params.payment_params, &network_graph, first_hops, route_params.final_value_msat,
652 route_params.final_cltv_expiry_delta, logger, scorer, random_seed_bytes
655 add_random_cltv_offset(&mut route, &route_params.payment_params, &network_graph, random_seed_bytes);
658 Err(err) => Err(err),
662 pub(crate) fn get_route<L: Deref, S: Score>(
663 our_node_pubkey: &PublicKey, payment_params: &PaymentParameters, network_graph: &ReadOnlyNetworkGraph,
664 first_hops: Option<&[&ChannelDetails]>, final_value_msat: u64, final_cltv_expiry_delta: u32,
665 logger: L, scorer: &S, random_seed_bytes: &[u8; 32]
666 ) -> Result<Route, LightningError>
667 where L::Target: Logger {
668 let payee_node_id = NodeId::from_pubkey(&payment_params.payee_pubkey);
669 let our_node_id = NodeId::from_pubkey(&our_node_pubkey);
671 if payee_node_id == our_node_id {
672 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
675 if final_value_msat > MAX_VALUE_MSAT {
676 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
679 if final_value_msat == 0 {
680 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
683 for route in payment_params.route_hints.iter() {
684 for hop in &route.0 {
685 if hop.src_node_id == payment_params.payee_pubkey {
686 return Err(LightningError{err: "Route hint cannot have the payee as the source.".to_owned(), action: ErrorAction::IgnoreError});
690 if payment_params.max_total_cltv_expiry_delta <= final_cltv_expiry_delta {
691 return Err(LightningError{err: "Can't find a route where the maximum total CLTV expiry delta is below the final CLTV expiry.".to_owned(), action: ErrorAction::IgnoreError});
694 // The general routing idea is the following:
695 // 1. Fill first/last hops communicated by the caller.
696 // 2. Attempt to construct a path from payer to payee for transferring
697 // any ~sufficient (described later) value.
698 // If succeed, remember which channels were used and how much liquidity they have available,
699 // so that future paths don't rely on the same liquidity.
700 // 3. Proceed to the next step if:
701 // - we hit the recommended target value;
702 // - OR if we could not construct a new path. Any next attempt will fail too.
703 // Otherwise, repeat step 2.
704 // 4. See if we managed to collect paths which aggregately are able to transfer target value
705 // (not recommended value).
706 // 5. If yes, proceed. If not, fail routing.
707 // 6. Randomly combine paths into routes having enough to fulfill the payment. (TODO: knapsack)
708 // 7. Of all the found paths, select only those with the lowest total fee.
709 // 8. The last path in every selected route is likely to be more than we need.
710 // Reduce its value-to-transfer and recompute fees.
711 // 9. Choose the best route by the lowest total fee.
713 // As for the actual search algorithm,
714 // we do a payee-to-payer pseudo-Dijkstra's sorting by each node's distance from the payee
715 // plus the minimum per-HTLC fee to get from it to another node (aka "shitty pseudo-A*").
717 // We are not a faithful Dijkstra's implementation because we can change values which impact
718 // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
719 // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) than
720 // the value we are currently attempting to send over a path, we simply reduce the value being
721 // sent along the path for any hops after that channel. This may imply that later fees (which
722 // we've already tabulated) are lower because a smaller value is passing through the channels
723 // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
724 // channels which were selected earlier (and which may still be used for other paths without a
725 // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
728 // One potentially problematic case for this algorithm would be if there are many
729 // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
730 // graph walking), we may never find a path which is not liquidity-limited and has lower
731 // proportional fee (and only lower absolute fee when considering the ultimate value sent).
732 // Because we only consider paths with at least 5% of the total value being sent, the damage
733 // from such a case should be limited, however this could be further reduced in the future by
734 // calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
735 // limits for the purposes of fee calculation.
737 // Alternatively, we could store more detailed path information in the heap (targets, below)
738 // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
739 // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
740 // and practically (as we would need to store dynamically-allocated path information in heap
741 // objects, increasing malloc traffic and indirect memory access significantly). Further, the
742 // results of such an algorithm would likely be biased towards lower-value paths.
744 // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
745 // outside of our current search value, running a path search more times to gather candidate
746 // paths at different values. While this may be acceptable, further path searches may increase
747 // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
748 // graph for candidate paths, calculating the maximum value which can realistically be sent at
749 // the same time, remaining generic across different payment values.
751 // TODO: There are a few tweaks we could do, including possibly pre-calculating more stuff
752 // to use as the A* heuristic beyond just the cost to get one node further than the current
755 let network_channels = network_graph.channels();
756 let network_nodes = network_graph.nodes();
758 // Allow MPP only if we have a features set from somewhere that indicates the payee supports
759 // it. If the payee supports it they're supposed to include it in the invoice, so that should
761 let allow_mpp = if let Some(features) = &payment_params.features {
762 features.supports_basic_mpp()
763 } else if let Some(node) = network_nodes.get(&payee_node_id) {
764 if let Some(node_info) = node.announcement_info.as_ref() {
765 node_info.features.supports_basic_mpp()
768 log_trace!(logger, "Searching for a route from payer {} to payee {} {} MPP and {} first hops {}overriding the network graph", our_node_pubkey,
769 payment_params.payee_pubkey, if allow_mpp { "with" } else { "without" },
770 first_hops.map(|hops| hops.len()).unwrap_or(0), if first_hops.is_some() { "" } else { "not " });
773 // Prepare the data we'll use for payee-to-payer search by
774 // inserting first hops suggested by the caller as targets.
775 // Our search will then attempt to reach them while traversing from the payee node.
776 let mut first_hop_targets: HashMap<_, Vec<&ChannelDetails>> =
777 HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
778 if let Some(hops) = first_hops {
780 if chan.short_channel_id.is_none() {
781 panic!("first_hops should be filled in with usable channels, not pending ones");
783 if chan.counterparty.node_id == *our_node_pubkey {
784 return Err(LightningError{err: "First hop cannot have our_node_pubkey as a destination.".to_owned(), action: ErrorAction::IgnoreError});
787 .entry(NodeId::from_pubkey(&chan.counterparty.node_id))
788 .or_insert(Vec::new())
791 if first_hop_targets.is_empty() {
792 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
796 // The main heap containing all candidate next-hops sorted by their score (max(A* fee,
797 // htlc_minimum)). Ideally this would be a heap which allowed cheap score reduction instead of
798 // adding duplicate entries when we find a better path to a given node.
799 let mut targets = BinaryHeap::new();
801 // Map from node_id to information about the best current path to that node, including feerate
803 let mut dist = HashMap::with_capacity(network_nodes.len());
805 // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
806 // indicating that we may wish to try again with a higher value, potentially paying to meet an
807 // htlc_minimum with extra fees while still finding a cheaper path.
808 let mut hit_minimum_limit;
810 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
811 // We start with a path_value of the exact amount we want, and if that generates a route we may
812 // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
813 // amount we want in total across paths, selecting the best subset at the end.
814 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
815 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
816 let mut path_value_msat = final_value_msat;
818 // We don't want multiple paths (as per MPP) share liquidity of the same channels.
819 // This map allows paths to be aware of the channel use by other paths in the same call.
820 // This would help to make a better path finding decisions and not "overbook" channels.
821 // It is unaware of the directions (except for `next_outbound_htlc_limit_msat` in
823 let mut bookkept_channels_liquidity_available_msat = HashMap::with_capacity(network_nodes.len());
825 // Keeping track of how much value we already collected across other paths. Helps to decide:
826 // - how much a new path should be transferring (upper bound);
827 // - whether a channel should be disregarded because
828 // it's available liquidity is too small comparing to how much more we need to collect;
829 // - when we want to stop looking for new paths.
830 let mut already_collected_value_msat = 0;
832 for (_, channels) in first_hop_targets.iter_mut() {
833 // Sort the first_hops channels to the same node(s) in priority order of which channel we'd
836 // First, if channels are below `recommended_value_msat`, sort them in descending order,
837 // preferring larger channels to avoid splitting the payment into more MPP parts than is
840 // Second, because simply always sorting in descending order would always use our largest
841 // available outbound capacity, needlessly fragmenting our available channel capacities,
842 // sort channels above `recommended_value_msat` in ascending order, preferring channels
843 // which have enough, but not too much, capacity for the payment.
844 channels.sort_unstable_by(|chan_a, chan_b| {
845 if chan_b.next_outbound_htlc_limit_msat < recommended_value_msat || chan_a.next_outbound_htlc_limit_msat < recommended_value_msat {
846 // Sort in descending order
847 chan_b.next_outbound_htlc_limit_msat.cmp(&chan_a.next_outbound_htlc_limit_msat)
849 // Sort in ascending order
850 chan_a.next_outbound_htlc_limit_msat.cmp(&chan_b.next_outbound_htlc_limit_msat)
855 log_trace!(logger, "Building path from {} (payee) to {} (us/payer) for value {} msat.", payment_params.payee_pubkey, our_node_pubkey, final_value_msat);
857 macro_rules! add_entry {
858 // Adds entry which goes from $src_node_id to $dest_node_id over the $candidate hop.
859 // $next_hops_fee_msat represents the fees paid for using all the channels *after* this one,
860 // since that value has to be transferred over this channel.
861 // Returns whether this channel caused an update to `targets`.
862 ( $candidate: expr, $src_node_id: expr, $dest_node_id: expr, $next_hops_fee_msat: expr,
863 $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr,
864 $next_hops_path_penalty_msat: expr, $next_hops_cltv_delta: expr ) => { {
865 // We "return" whether we updated the path at the end, via this:
866 let mut did_add_update_path_to_src_node = false;
867 // Channels to self should not be used. This is more of belt-and-suspenders, because in
868 // practice these cases should be caught earlier:
869 // - for regular channels at channel announcement (TODO)
870 // - for first and last hops early in get_route
871 if $src_node_id != $dest_node_id {
872 let short_channel_id = $candidate.short_channel_id();
873 let available_liquidity_msat = bookkept_channels_liquidity_available_msat
874 .entry(short_channel_id)
875 .or_insert_with(|| $candidate.effective_capacity().as_msat());
877 // It is tricky to subtract $next_hops_fee_msat from available liquidity here.
878 // It may be misleading because we might later choose to reduce the value transferred
879 // over these channels, and the channel which was insufficient might become sufficient.
880 // Worst case: we drop a good channel here because it can't cover the high following
881 // fees caused by one expensive channel, but then this channel could have been used
882 // if the amount being transferred over this path is lower.
883 // We do this for now, but this is a subject for removal.
884 if let Some(available_value_contribution_msat) = available_liquidity_msat.checked_sub($next_hops_fee_msat) {
886 // Routing Fragmentation Mitigation heuristic:
888 // Routing fragmentation across many payment paths increases the overall routing
889 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
890 // Taking too many smaller paths also increases the chance of payment failure.
891 // Thus to avoid this effect, we require from our collected links to provide
892 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
894 // This requirement is currently 5% of the remaining-to-be-collected value.
895 // This means as we successfully advance in our collection,
896 // the absolute liquidity contribution is lowered,
897 // thus increasing the number of potential channels to be selected.
899 // Derive the minimal liquidity contribution with a ratio of 20 (5%, rounded up)
900 // or 100% if we're not allowed to do multipath payments.
901 let minimal_value_contribution_msat: u64 = if allow_mpp {
902 (recommended_value_msat - already_collected_value_msat + 19) / 20
906 // Verify the liquidity offered by this channel complies to the minimal contribution.
907 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
909 // Do not consider candidates that exceed the maximum total cltv expiry limit.
910 // In order to already account for some of the privacy enhancing random CLTV
911 // expiry delta offset we add on top later, we subtract a rough estimate
912 // (2*MEDIAN_HOP_CLTV_EXPIRY_DELTA) here.
913 let max_total_cltv_expiry_delta = (payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta)
914 .checked_sub(2*MEDIAN_HOP_CLTV_EXPIRY_DELTA)
915 .unwrap_or(payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta);
916 let hop_total_cltv_delta = ($next_hops_cltv_delta as u32)
917 .saturating_add($candidate.cltv_expiry_delta());
918 let doesnt_exceed_cltv_delta_limit = hop_total_cltv_delta <= max_total_cltv_expiry_delta;
920 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
921 // Includes paying fees for the use of the following channels.
922 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
923 Some(result) => result,
924 // Can't overflow due to how the values were computed right above.
925 None => unreachable!(),
927 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
928 let over_path_minimum_msat = amount_to_transfer_over_msat >= $candidate.htlc_minimum_msat() &&
929 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
931 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
932 let may_overpay_to_meet_path_minimum_msat =
933 ((amount_to_transfer_over_msat < $candidate.htlc_minimum_msat() &&
934 recommended_value_msat > $candidate.htlc_minimum_msat()) ||
935 (amount_to_transfer_over_msat < $next_hops_path_htlc_minimum_msat &&
936 recommended_value_msat > $next_hops_path_htlc_minimum_msat));
938 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
939 // bother considering this channel. If retrying with recommended_value_msat may
940 // allow us to hit the HTLC minimum limit, set htlc_minimum_limit so that we go
941 // around again with a higher amount.
942 if contributes_sufficient_value && doesnt_exceed_cltv_delta_limit && may_overpay_to_meet_path_minimum_msat {
943 hit_minimum_limit = true;
944 } else if contributes_sufficient_value && doesnt_exceed_cltv_delta_limit && over_path_minimum_msat {
945 // Note that low contribution here (limited by available_liquidity_msat)
946 // might violate htlc_minimum_msat on the hops which are next along the
947 // payment path (upstream to the payee). To avoid that, we recompute
948 // path fees knowing the final path contribution after constructing it.
949 let path_htlc_minimum_msat = compute_fees($next_hops_path_htlc_minimum_msat, $candidate.fees())
950 .and_then(|fee_msat| fee_msat.checked_add($next_hops_path_htlc_minimum_msat))
951 .map(|fee_msat| cmp::max(fee_msat, $candidate.htlc_minimum_msat()))
952 .unwrap_or_else(|| u64::max_value());
953 let hm_entry = dist.entry($src_node_id);
954 let old_entry = hm_entry.or_insert_with(|| {
955 // If there was previously no known way to access the source node
956 // (recall it goes payee-to-payer) of short_channel_id, first add a
957 // semi-dummy record just to compute the fees to reach the source node.
958 // This will affect our decision on selecting short_channel_id
959 // as a way to reach the $dest_node_id.
960 let mut fee_base_msat = 0;
961 let mut fee_proportional_millionths = 0;
962 if let Some(Some(fees)) = network_nodes.get(&$src_node_id).map(|node| node.lowest_inbound_channel_fees) {
963 fee_base_msat = fees.base_msat;
964 fee_proportional_millionths = fees.proportional_millionths;
967 node_id: $dest_node_id.clone(),
968 candidate: $candidate.clone(),
970 src_lowest_inbound_fees: RoutingFees {
971 base_msat: fee_base_msat,
972 proportional_millionths: fee_proportional_millionths,
974 next_hops_fee_msat: u64::max_value(),
975 hop_use_fee_msat: u64::max_value(),
976 total_fee_msat: u64::max_value(),
977 path_htlc_minimum_msat,
978 path_penalty_msat: u64::max_value(),
979 was_processed: false,
980 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
981 value_contribution_msat,
985 #[allow(unused_mut)] // We only use the mut in cfg(test)
986 let mut should_process = !old_entry.was_processed;
987 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
989 // In test/fuzzing builds, we do extra checks to make sure the skipping
990 // of already-seen nodes only happens in cases we expect (see below).
991 if !should_process { should_process = true; }
995 let mut hop_use_fee_msat = 0;
996 let mut total_fee_msat = $next_hops_fee_msat;
998 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
999 // will have the same effective-fee
1000 if $src_node_id != our_node_id {
1001 match compute_fees(amount_to_transfer_over_msat, $candidate.fees()) {
1002 // max_value means we'll always fail
1003 // the old_entry.total_fee_msat > total_fee_msat check
1004 None => total_fee_msat = u64::max_value(),
1006 hop_use_fee_msat = fee_msat;
1007 total_fee_msat += hop_use_fee_msat;
1008 // When calculating the lowest inbound fees to a node, we
1009 // calculate fees here not based on the actual value we think
1010 // will flow over this channel, but on the minimum value that
1011 // we'll accept flowing over it. The minimum accepted value
1012 // is a constant through each path collection run, ensuring
1013 // consistent basis. Otherwise we may later find a
1014 // different path to the source node that is more expensive,
1015 // but which we consider to be cheaper because we are capacity
1016 // constrained and the relative fee becomes lower.
1017 match compute_fees(minimal_value_contribution_msat, old_entry.src_lowest_inbound_fees)
1018 .map(|a| a.checked_add(total_fee_msat)) {
1023 total_fee_msat = u64::max_value();
1030 let path_penalty_msat = $next_hops_path_penalty_msat.saturating_add(
1031 scorer.channel_penalty_msat(short_channel_id, amount_to_transfer_over_msat,
1032 *available_liquidity_msat, &$src_node_id, &$dest_node_id));
1033 let new_graph_node = RouteGraphNode {
1034 node_id: $src_node_id,
1035 lowest_fee_to_peer_through_node: total_fee_msat,
1036 lowest_fee_to_node: $next_hops_fee_msat as u64 + hop_use_fee_msat,
1037 total_cltv_delta: hop_total_cltv_delta,
1038 value_contribution_msat: value_contribution_msat,
1039 path_htlc_minimum_msat,
1043 // Update the way of reaching $src_node_id with the given short_channel_id (from $dest_node_id),
1044 // if this way is cheaper than the already known
1045 // (considering the cost to "reach" this channel from the route destination,
1046 // the cost of using this channel,
1047 // and the cost of routing to the source node of this channel).
1048 // Also, consider that htlc_minimum_msat_difference, because we might end up
1049 // paying it. Consider the following exploit:
1050 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
1051 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
1052 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
1053 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
1055 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
1056 // but it may require additional tracking - we don't want to double-count
1057 // the fees included in $next_hops_path_htlc_minimum_msat, but also
1058 // can't use something that may decrease on future hops.
1059 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat)
1060 .saturating_add(old_entry.path_penalty_msat);
1061 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat)
1062 .saturating_add(path_penalty_msat);
1064 if !old_entry.was_processed && new_cost < old_cost {
1065 targets.push(new_graph_node);
1066 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
1067 old_entry.hop_use_fee_msat = hop_use_fee_msat;
1068 old_entry.total_fee_msat = total_fee_msat;
1069 old_entry.node_id = $dest_node_id.clone();
1070 old_entry.candidate = $candidate.clone();
1071 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
1072 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
1073 old_entry.path_penalty_msat = path_penalty_msat;
1074 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
1076 old_entry.value_contribution_msat = value_contribution_msat;
1078 did_add_update_path_to_src_node = true;
1079 } else if old_entry.was_processed && new_cost < old_cost {
1080 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
1082 // If we're skipping processing a node which was previously
1083 // processed even though we found another path to it with a
1084 // cheaper fee, check that it was because the second path we
1085 // found (which we are processing now) has a lower value
1086 // contribution due to an HTLC minimum limit.
1088 // e.g. take a graph with two paths from node 1 to node 2, one
1089 // through channel A, and one through channel B. Channel A and
1090 // B are both in the to-process heap, with their scores set by
1091 // a higher htlc_minimum than fee.
1092 // Channel A is processed first, and the channels onwards from
1093 // node 1 are added to the to-process heap. Thereafter, we pop
1094 // Channel B off of the heap, note that it has a much more
1095 // restrictive htlc_maximum_msat, and recalculate the fees for
1096 // all of node 1's channels using the new, reduced, amount.
1098 // This would be bogus - we'd be selecting a higher-fee path
1099 // with a lower htlc_maximum_msat instead of the one we'd
1100 // already decided to use.
1101 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
1103 value_contribution_msat + path_penalty_msat <
1104 old_entry.value_contribution_msat + old_entry.path_penalty_msat
1112 did_add_update_path_to_src_node
1116 let default_node_features = default_node_features();
1118 // Find ways (channels with destination) to reach a given node and store them
1119 // in the corresponding data structures (routing graph etc).
1120 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
1121 // meaning how much will be paid in fees after this node (to the best of our knowledge).
1122 // This data can later be helpful to optimize routing (pay lower fees).
1123 macro_rules! add_entries_to_cheapest_to_target_node {
1124 ( $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 ) => {
1125 let skip_node = if let Some(elem) = dist.get_mut(&$node_id) {
1126 let was_processed = elem.was_processed;
1127 elem.was_processed = true;
1130 // Entries are added to dist in add_entry!() when there is a channel from a node.
1131 // Because there are no channels from payee, it will not have a dist entry at this point.
1132 // If we're processing any other node, it is always be the result of a channel from it.
1133 assert_eq!($node_id, payee_node_id);
1138 if let Some(first_channels) = first_hop_targets.get(&$node_id) {
1139 for details in first_channels {
1140 let candidate = CandidateRouteHop::FirstHop { details };
1141 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);
1145 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
1148 &default_node_features
1151 if !features.requires_unknown_bits() {
1152 for chan_id in $node.channels.iter() {
1153 let chan = network_channels.get(chan_id).unwrap();
1154 if !chan.features.requires_unknown_bits() {
1155 let (directed_channel, source) =
1156 chan.as_directed_to(&$node_id).expect("inconsistent NetworkGraph");
1157 if first_hops.is_none() || *source != our_node_id {
1158 if let Some(direction) = directed_channel.direction() {
1159 if direction.enabled {
1160 let candidate = CandidateRouteHop::PublicHop {
1161 info: directed_channel.with_update().unwrap(),
1162 short_channel_id: *chan_id,
1164 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);
1175 let mut payment_paths = Vec::<PaymentPath>::new();
1177 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
1178 'paths_collection: loop {
1179 // For every new path, start from scratch, except
1180 // bookkept_channels_liquidity_available_msat, which will improve
1181 // the further iterations of path finding. Also don't erase first_hop_targets.
1184 hit_minimum_limit = false;
1186 // If first hop is a private channel and the only way to reach the payee, this is the only
1187 // place where it could be added.
1188 if let Some(first_channels) = first_hop_targets.get(&payee_node_id) {
1189 for details in first_channels {
1190 let candidate = CandidateRouteHop::FirstHop { details };
1191 let added = add_entry!(candidate, our_node_id, payee_node_id, 0, path_value_msat, 0, 0u64, 0);
1192 log_trace!(logger, "{} direct route to payee via SCID {}", if added { "Added" } else { "Skipped" }, candidate.short_channel_id());
1196 // Add the payee as a target, so that the payee-to-payer
1197 // search algorithm knows what to start with.
1198 match network_nodes.get(&payee_node_id) {
1199 // The payee is not in our network graph, so nothing to add here.
1200 // There is still a chance of reaching them via last_hops though,
1201 // so don't yet fail the payment here.
1202 // If not, targets.pop() will not even let us enter the loop in step 2.
1205 add_entries_to_cheapest_to_target_node!(node, payee_node_id, 0, path_value_msat, 0, 0u64, 0);
1210 // If a caller provided us with last hops, add them to routing targets. Since this happens
1211 // earlier than general path finding, they will be somewhat prioritized, although currently
1212 // it matters only if the fees are exactly the same.
1213 for route in payment_params.route_hints.iter().filter(|route| !route.0.is_empty()) {
1214 let first_hop_in_route = &(route.0)[0];
1215 let have_hop_src_in_graph =
1216 // Only add the hops in this route to our candidate set if either
1217 // we have a direct channel to the first hop or the first hop is
1218 // in the regular network graph.
1219 first_hop_targets.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some() ||
1220 network_nodes.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some();
1221 if have_hop_src_in_graph {
1222 // We start building the path from reverse, i.e., from payee
1223 // to the first RouteHintHop in the path.
1224 let hop_iter = route.0.iter().rev();
1225 let prev_hop_iter = core::iter::once(&payment_params.payee_pubkey).chain(
1226 route.0.iter().skip(1).rev().map(|hop| &hop.src_node_id));
1227 let mut hop_used = true;
1228 let mut aggregate_next_hops_fee_msat: u64 = 0;
1229 let mut aggregate_next_hops_path_htlc_minimum_msat: u64 = 0;
1230 let mut aggregate_next_hops_path_penalty_msat: u64 = 0;
1231 let mut aggregate_next_hops_cltv_delta: u32 = 0;
1233 for (idx, (hop, prev_hop_id)) in hop_iter.zip(prev_hop_iter).enumerate() {
1234 let source = NodeId::from_pubkey(&hop.src_node_id);
1235 let target = NodeId::from_pubkey(&prev_hop_id);
1236 let candidate = network_channels
1237 .get(&hop.short_channel_id)
1238 .and_then(|channel| channel.as_directed_to(&target))
1239 .and_then(|(channel, _)| channel.with_update())
1240 .map(|info| CandidateRouteHop::PublicHop {
1242 short_channel_id: hop.short_channel_id,
1244 .unwrap_or_else(|| CandidateRouteHop::PrivateHop { hint: hop });
1245 let capacity_msat = candidate.effective_capacity().as_msat();
1246 aggregate_next_hops_path_penalty_msat = aggregate_next_hops_path_penalty_msat
1247 .saturating_add(scorer.channel_penalty_msat(hop.short_channel_id, final_value_msat, capacity_msat, &source, &target));
1249 aggregate_next_hops_cltv_delta = aggregate_next_hops_cltv_delta
1250 .saturating_add(hop.cltv_expiry_delta as u32);
1252 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) {
1253 // If this hop was not used then there is no use checking the preceding hops
1254 // in the RouteHint. We can break by just searching for a direct channel between
1255 // last checked hop and first_hop_targets
1259 // Searching for a direct channel between last checked hop and first_hop_targets
1260 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&prev_hop_id)) {
1261 for details in first_channels {
1262 let candidate = CandidateRouteHop::FirstHop { details };
1263 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);
1271 // In the next values of the iterator, the aggregate fees already reflects
1272 // the sum of value sent from payer (final_value_msat) and routing fees
1273 // for the last node in the RouteHint. We need to just add the fees to
1274 // route through the current node so that the preceeding node (next iteration)
1276 let hops_fee = compute_fees(aggregate_next_hops_fee_msat + final_value_msat, hop.fees)
1277 .map_or(None, |inc| inc.checked_add(aggregate_next_hops_fee_msat));
1278 aggregate_next_hops_fee_msat = if let Some(val) = hops_fee { val } else { break; };
1280 let hop_htlc_minimum_msat = candidate.htlc_minimum_msat();
1281 let hop_htlc_minimum_msat_inc = if let Some(val) = compute_fees(aggregate_next_hops_path_htlc_minimum_msat, hop.fees) { val } else { break; };
1282 let hops_path_htlc_minimum = aggregate_next_hops_path_htlc_minimum_msat
1283 .checked_add(hop_htlc_minimum_msat_inc);
1284 aggregate_next_hops_path_htlc_minimum_msat = if let Some(val) = hops_path_htlc_minimum { cmp::max(hop_htlc_minimum_msat, val) } else { break; };
1286 if idx == route.0.len() - 1 {
1287 // The last hop in this iterator is the first hop in
1288 // overall RouteHint.
1289 // If this hop connects to a node with which we have a direct channel,
1290 // ignore the network graph and, if the last hop was added, add our
1291 // direct channel to the candidate set.
1293 // Note that we *must* check if the last hop was added as `add_entry`
1294 // always assumes that the third argument is a node to which we have a
1296 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&hop.src_node_id)) {
1297 for details in first_channels {
1298 let candidate = CandidateRouteHop::FirstHop { details };
1299 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);
1307 log_trace!(logger, "Starting main path collection loop with {} nodes pre-filled from first/last hops.", targets.len());
1309 // At this point, targets are filled with the data from first and
1310 // last hops communicated by the caller, and the payment receiver.
1311 let mut found_new_path = false;
1314 // If this loop terminates due the exhaustion of targets, two situations are possible:
1315 // - not enough outgoing liquidity:
1316 // 0 < already_collected_value_msat < final_value_msat
1317 // - enough outgoing liquidity:
1318 // final_value_msat <= already_collected_value_msat < recommended_value_msat
1319 // Both these cases (and other cases except reaching recommended_value_msat) mean that
1320 // paths_collection will be stopped because found_new_path==false.
1321 // This is not necessarily a routing failure.
1322 '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() {
1324 // Since we're going payee-to-payer, hitting our node as a target means we should stop
1325 // traversing the graph and arrange the path out of what we found.
1326 if node_id == our_node_id {
1327 let mut new_entry = dist.remove(&our_node_id).unwrap();
1328 let mut ordered_hops = vec!((new_entry.clone(), default_node_features.clone()));
1331 let mut features_set = false;
1332 if let Some(first_channels) = first_hop_targets.get(&ordered_hops.last().unwrap().0.node_id) {
1333 for details in first_channels {
1334 if details.short_channel_id.unwrap() == ordered_hops.last().unwrap().0.candidate.short_channel_id() {
1335 ordered_hops.last_mut().unwrap().1 = details.counterparty.features.to_context();
1336 features_set = true;
1342 if let Some(node) = network_nodes.get(&ordered_hops.last().unwrap().0.node_id) {
1343 if let Some(node_info) = node.announcement_info.as_ref() {
1344 ordered_hops.last_mut().unwrap().1 = node_info.features.clone();
1346 ordered_hops.last_mut().unwrap().1 = default_node_features.clone();
1349 // We can fill in features for everything except hops which were
1350 // provided via the invoice we're paying. We could guess based on the
1351 // recipient's features but for now we simply avoid guessing at all.
1355 // Means we succesfully traversed from the payer to the payee, now
1356 // save this path for the payment route. Also, update the liquidity
1357 // remaining on the used hops, so that we take them into account
1358 // while looking for more paths.
1359 if ordered_hops.last().unwrap().0.node_id == payee_node_id {
1363 new_entry = match dist.remove(&ordered_hops.last().unwrap().0.node_id) {
1364 Some(payment_hop) => payment_hop,
1365 // We can't arrive at None because, if we ever add an entry to targets,
1366 // we also fill in the entry in dist (see add_entry!).
1367 None => unreachable!(),
1369 // We "propagate" the fees one hop backward (topologically) here,
1370 // so that fees paid for a HTLC forwarding on the current channel are
1371 // associated with the previous channel (where they will be subtracted).
1372 ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
1373 ordered_hops.push((new_entry.clone(), default_node_features.clone()));
1375 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
1376 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
1378 log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: \n {:#?}",
1379 ordered_hops.len(), value_contribution_msat, ordered_hops.iter().map(|h| &(h.0)).collect::<Vec<&PathBuildingHop>>());
1381 let mut payment_path = PaymentPath {hops: ordered_hops};
1383 // We could have possibly constructed a slightly inconsistent path: since we reduce
1384 // value being transferred along the way, we could have violated htlc_minimum_msat
1385 // on some channels we already passed (assuming dest->source direction). Here, we
1386 // recompute the fees again, so that if that's the case, we match the currently
1387 // underpaid htlc_minimum_msat with fees.
1388 payment_path.update_value_and_recompute_fees(cmp::min(value_contribution_msat, final_value_msat));
1390 // Since a path allows to transfer as much value as
1391 // the smallest channel it has ("bottleneck"), we should recompute
1392 // the fees so sender HTLC don't overpay fees when traversing
1393 // larger channels than the bottleneck. This may happen because
1394 // when we were selecting those channels we were not aware how much value
1395 // this path will transfer, and the relative fee for them
1396 // might have been computed considering a larger value.
1397 // Remember that we used these channels so that we don't rely
1398 // on the same liquidity in future paths.
1399 let mut prevented_redundant_path_selection = false;
1400 for (payment_hop, _) in payment_path.hops.iter() {
1401 let channel_liquidity_available_msat = bookkept_channels_liquidity_available_msat.get_mut(&payment_hop.candidate.short_channel_id()).unwrap();
1402 let mut spent_on_hop_msat = value_contribution_msat;
1403 let next_hops_fee_msat = payment_hop.next_hops_fee_msat;
1404 spent_on_hop_msat += next_hops_fee_msat;
1405 if spent_on_hop_msat == *channel_liquidity_available_msat {
1406 // If this path used all of this channel's available liquidity, we know
1407 // this path will not be selected again in the next loop iteration.
1408 prevented_redundant_path_selection = true;
1410 *channel_liquidity_available_msat -= spent_on_hop_msat;
1412 if !prevented_redundant_path_selection {
1413 // If we weren't capped by hitting a liquidity limit on a channel in the path,
1414 // we'll probably end up picking the same path again on the next iteration.
1415 // Decrease the available liquidity of a hop in the middle of the path.
1416 let victim_scid = payment_path.hops[(payment_path.hops.len()) / 2].0.candidate.short_channel_id();
1417 log_trace!(logger, "Disabling channel {} for future path building iterations to avoid duplicates.", victim_scid);
1418 let victim_liquidity = bookkept_channels_liquidity_available_msat.get_mut(&victim_scid).unwrap();
1419 *victim_liquidity = 0;
1422 // Track the total amount all our collected paths allow to send so that we:
1423 // - know when to stop looking for more paths
1424 // - know which of the hops are useless considering how much more sats we need
1425 // (contributes_sufficient_value)
1426 already_collected_value_msat += value_contribution_msat;
1428 payment_paths.push(payment_path);
1429 found_new_path = true;
1430 break 'path_construction;
1433 // If we found a path back to the payee, we shouldn't try to process it again. This is
1434 // the equivalent of the `elem.was_processed` check in
1435 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
1436 if node_id == payee_node_id { continue 'path_construction; }
1438 // Otherwise, since the current target node is not us,
1439 // keep "unrolling" the payment graph from payee to payer by
1440 // finding a way to reach the current target from the payer side.
1441 match network_nodes.get(&node_id) {
1444 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);
1450 // If we don't support MPP, no use trying to gather more value ever.
1451 break 'paths_collection;
1455 // Stop either when the recommended value is reached or if no new path was found in this
1457 // In the latter case, making another path finding attempt won't help,
1458 // because we deterministically terminated the search due to low liquidity.
1459 if already_collected_value_msat >= recommended_value_msat || !found_new_path {
1460 log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
1461 already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
1462 break 'paths_collection;
1463 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
1464 // Further, if this was our first walk of the graph, and we weren't limited by an
1465 // htlc_minimum_msat, return immediately because this path should suffice. If we were
1466 // limited by an htlc_minimum_msat value, find another path with a higher value,
1467 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
1468 // still keeping a lower total fee than this path.
1469 if !hit_minimum_limit {
1470 log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
1471 break 'paths_collection;
1473 log_trace!(logger, "Collected our payment amount on the first pass, but running again to collect extra paths with a potentially higher limit.");
1474 path_value_msat = recommended_value_msat;
1479 if payment_paths.len() == 0 {
1480 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1483 if already_collected_value_msat < final_value_msat {
1484 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1487 // Sort by total fees and take the best paths.
1488 payment_paths.sort_unstable_by_key(|path| path.get_total_fee_paid_msat());
1489 if payment_paths.len() > 50 {
1490 payment_paths.truncate(50);
1493 // Draw multiple sufficient routes by randomly combining the selected paths.
1494 let mut drawn_routes = Vec::new();
1495 let mut prng = ChaCha20::new(random_seed_bytes, &[0u8; 12]);
1496 let mut random_index_bytes = [0u8; ::core::mem::size_of::<usize>()];
1498 let num_permutations = payment_paths.len();
1499 for _ in 0..num_permutations {
1500 let mut cur_route = Vec::<PaymentPath>::new();
1501 let mut aggregate_route_value_msat = 0;
1504 // Do a Fisher-Yates shuffle to create a random permutation of the payment paths
1505 for cur_index in (1..payment_paths.len()).rev() {
1506 prng.process_in_place(&mut random_index_bytes);
1507 let random_index = usize::from_be_bytes(random_index_bytes).wrapping_rem(cur_index+1);
1508 payment_paths.swap(cur_index, random_index);
1512 for payment_path in &payment_paths {
1513 cur_route.push(payment_path.clone());
1514 aggregate_route_value_msat += payment_path.get_value_msat();
1515 if aggregate_route_value_msat > final_value_msat {
1516 // Last path likely overpaid. Substract it from the most expensive
1517 // (in terms of proportional fee) path in this route and recompute fees.
1518 // This might be not the most economically efficient way, but fewer paths
1519 // also makes routing more reliable.
1520 let mut overpaid_value_msat = aggregate_route_value_msat - final_value_msat;
1522 // First, we drop some expensive low-value paths entirely if possible, since fewer
1523 // paths is better: the payment is less likely to fail. In order to do so, we sort
1524 // by value and fall back to total fees paid, i.e., in case of equal values we
1525 // prefer lower cost paths.
1526 cur_route.sort_unstable_by(|a, b| {
1527 a.get_value_msat().cmp(&b.get_value_msat())
1528 // Reverse ordering for cost, so we drop higher-cost paths first
1529 .then_with(|| b.get_cost_msat().cmp(&a.get_cost_msat()))
1532 // We should make sure that at least 1 path left.
1533 let mut paths_left = cur_route.len();
1534 cur_route.retain(|path| {
1535 if paths_left == 1 {
1538 let mut keep = true;
1539 let path_value_msat = path.get_value_msat();
1540 if path_value_msat <= overpaid_value_msat {
1542 overpaid_value_msat -= path_value_msat;
1548 if overpaid_value_msat == 0 {
1552 assert!(cur_route.len() > 0);
1555 // Now, subtract the overpaid value from the most-expensive path.
1556 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1557 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1558 cur_route.sort_unstable_by_key(|path| { path.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>() });
1559 let expensive_payment_path = cur_route.first_mut().unwrap();
1561 // We already dropped all the small value paths above, meaning all the
1562 // remaining paths are larger than remaining overpaid_value_msat.
1563 // Thus, this can't be negative.
1564 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
1565 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
1569 drawn_routes.push(cur_route);
1573 // Select the best route by lowest total cost.
1574 drawn_routes.sort_unstable_by_key(|paths| paths.iter().map(|path| path.get_cost_msat()).sum::<u64>());
1575 let mut selected_paths = Vec::<Vec<Result<RouteHop, LightningError>>>::new();
1576 for payment_path in drawn_routes.first().unwrap() {
1577 let mut path = payment_path.hops.iter().map(|(payment_hop, node_features)| {
1579 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)})?,
1580 node_features: node_features.clone(),
1581 short_channel_id: payment_hop.candidate.short_channel_id(),
1582 channel_features: payment_hop.candidate.features(),
1583 fee_msat: payment_hop.fee_msat,
1584 cltv_expiry_delta: payment_hop.candidate.cltv_expiry_delta(),
1586 }).collect::<Vec<_>>();
1587 // Propagate the cltv_expiry_delta one hop backwards since the delta from the current hop is
1588 // applicable for the previous hop.
1589 path.iter_mut().rev().fold(final_cltv_expiry_delta, |prev_cltv_expiry_delta, hop| {
1590 core::mem::replace(&mut hop.as_mut().unwrap().cltv_expiry_delta, prev_cltv_expiry_delta)
1592 selected_paths.push(path);
1595 if let Some(features) = &payment_params.features {
1596 for path in selected_paths.iter_mut() {
1597 if let Ok(route_hop) = path.last_mut().unwrap() {
1598 route_hop.node_features = features.to_context();
1604 paths: selected_paths.into_iter().map(|path| path.into_iter().collect()).collect::<Result<Vec<_>, _>>()?,
1605 payment_params: Some(payment_params.clone()),
1607 log_info!(logger, "Got route to {}: {}", payment_params.payee_pubkey, log_route!(route));
1611 // When an adversarial intermediary node observes a payment, it may be able to infer its
1612 // destination, if the remaining CLTV expiry delta exactly matches a feasible path in the network
1613 // graph. In order to improve privacy, this method obfuscates the CLTV expiry deltas along the
1614 // payment path by adding a randomized 'shadow route' offset to the final hop.
1615 fn add_random_cltv_offset(route: &mut Route, payment_params: &PaymentParameters, network_graph: &ReadOnlyNetworkGraph, random_seed_bytes: &[u8; 32]) {
1616 let network_channels = network_graph.channels();
1617 let network_nodes = network_graph.nodes();
1619 for path in route.paths.iter_mut() {
1620 let mut shadow_ctlv_expiry_delta_offset: u32 = 0;
1622 // Remember the last three nodes of the random walk and avoid looping back on them.
1623 // Init with the last three nodes from the actual path, if possible.
1624 let mut nodes_to_avoid: [NodeId; 3] = [NodeId::from_pubkey(&path.last().unwrap().pubkey),
1625 NodeId::from_pubkey(&path.get(path.len().saturating_sub(2)).unwrap().pubkey),
1626 NodeId::from_pubkey(&path.get(path.len().saturating_sub(3)).unwrap().pubkey)];
1628 // Choose the last publicly known node as the starting point for the random walk.
1629 let mut cur_hop: Option<NodeId> = None;
1630 let mut path_nonce = [0u8; 12];
1631 if let Some(starting_hop) = path.iter().rev()
1632 .find(|h| network_nodes.contains_key(&NodeId::from_pubkey(&h.pubkey))) {
1633 cur_hop = Some(NodeId::from_pubkey(&starting_hop.pubkey));
1634 path_nonce.copy_from_slice(&cur_hop.unwrap().as_slice()[..12]);
1637 // Init PRNG with the path-dependant nonce, which is static for private paths.
1638 let mut prng = ChaCha20::new(random_seed_bytes, &path_nonce);
1639 let mut random_path_bytes = [0u8; ::core::mem::size_of::<usize>()];
1641 // Pick a random path length in [1 .. 3]
1642 prng.process_in_place(&mut random_path_bytes);
1643 let random_walk_length = usize::from_be_bytes(random_path_bytes).wrapping_rem(3).wrapping_add(1);
1645 for random_hop in 0..random_walk_length {
1646 // If we don't find a suitable offset in the public network graph, we default to
1647 // MEDIAN_HOP_CLTV_EXPIRY_DELTA.
1648 let mut random_hop_offset = MEDIAN_HOP_CLTV_EXPIRY_DELTA;
1650 if let Some(cur_node_id) = cur_hop {
1651 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
1652 // Randomly choose the next unvisited hop.
1653 prng.process_in_place(&mut random_path_bytes);
1654 if let Some(random_channel) = usize::from_be_bytes(random_path_bytes)
1655 .checked_rem(cur_node.channels.len())
1656 .and_then(|index| cur_node.channels.get(index))
1657 .and_then(|id| network_channels.get(id)) {
1658 random_channel.as_directed_from(&cur_node_id).map(|(dir_info, next_id)| {
1659 if !nodes_to_avoid.iter().any(|x| x == next_id) {
1660 nodes_to_avoid[random_hop] = *next_id;
1661 dir_info.direction().map(|channel_update_info| {
1662 random_hop_offset = channel_update_info.cltv_expiry_delta.into();
1663 cur_hop = Some(*next_id);
1671 shadow_ctlv_expiry_delta_offset = shadow_ctlv_expiry_delta_offset
1672 .checked_add(random_hop_offset)
1673 .unwrap_or(shadow_ctlv_expiry_delta_offset);
1676 // Limit the total offset to reduce the worst-case locked liquidity timevalue
1677 const MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET: u32 = 3*144;
1678 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET);
1680 // Limit the offset so we never exceed the max_total_cltv_expiry_delta. To improve plausibility,
1681 // we choose the limit to be the largest possible multiple of MEDIAN_HOP_CLTV_EXPIRY_DELTA.
1682 let path_total_cltv_expiry_delta: u32 = path.iter().map(|h| h.cltv_expiry_delta).sum();
1683 let mut max_path_offset = payment_params.max_total_cltv_expiry_delta - path_total_cltv_expiry_delta;
1684 max_path_offset = cmp::max(
1685 max_path_offset - (max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA),
1686 max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA);
1687 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, max_path_offset);
1689 // Add 'shadow' CLTV offset to the final hop
1690 if let Some(last_hop) = path.last_mut() {
1691 last_hop.cltv_expiry_delta = last_hop.cltv_expiry_delta
1692 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(last_hop.cltv_expiry_delta);
1699 use routing::network_graph::{NetworkGraph, NetGraphMsgHandler, NodeId};
1700 use routing::router::{get_route, add_random_cltv_offset, default_node_features, PaymentParameters, Route, RouteHint, RouteHintHop, RouteHop, RoutingFees, DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA};
1701 use routing::scoring::Score;
1702 use chain::transaction::OutPoint;
1703 use chain::keysinterface::KeysInterface;
1704 use ln::features::{ChannelFeatures, InitFeatures, InvoiceFeatures, NodeFeatures};
1705 use ln::msgs::{ErrorAction, LightningError, OptionalField, UnsignedChannelAnnouncement, ChannelAnnouncement, RoutingMessageHandler,
1706 NodeAnnouncement, UnsignedNodeAnnouncement, ChannelUpdate, UnsignedChannelUpdate};
1707 use ln::channelmanager;
1708 use util::test_utils;
1709 use util::chacha20::ChaCha20;
1710 use util::ser::Writeable;
1712 use util::ser::Writer;
1714 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
1715 use bitcoin::hashes::Hash;
1716 use bitcoin::network::constants::Network;
1717 use bitcoin::blockdata::constants::genesis_block;
1718 use bitcoin::blockdata::script::Builder;
1719 use bitcoin::blockdata::opcodes;
1720 use bitcoin::blockdata::transaction::TxOut;
1724 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
1725 use bitcoin::secp256k1::{Secp256k1, All};
1728 use sync::{self, Arc};
1730 fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
1731 features: InitFeatures, outbound_capacity_msat: u64) -> channelmanager::ChannelDetails {
1732 channelmanager::ChannelDetails {
1733 channel_id: [0; 32],
1734 counterparty: channelmanager::ChannelCounterparty {
1737 unspendable_punishment_reserve: 0,
1738 forwarding_info: None,
1739 outbound_htlc_minimum_msat: None,
1740 outbound_htlc_maximum_msat: None,
1742 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
1745 inbound_scid_alias: None,
1746 channel_value_satoshis: 0,
1749 outbound_capacity_msat,
1750 next_outbound_htlc_limit_msat: outbound_capacity_msat,
1751 inbound_capacity_msat: 42,
1752 unspendable_punishment_reserve: None,
1753 confirmations_required: None,
1754 force_close_spend_delay: None,
1755 is_outbound: true, is_funding_locked: true,
1756 is_usable: true, is_public: true,
1757 inbound_htlc_minimum_msat: None,
1758 inbound_htlc_maximum_msat: None,
1762 // Using the same keys for LN and BTC ids
1764 net_graph_msg_handler: &NetGraphMsgHandler<Arc<NetworkGraph>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1765 secp_ctx: &Secp256k1<All>, node_1_privkey: &SecretKey, node_2_privkey: &SecretKey, features: ChannelFeatures, short_channel_id: u64
1767 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1768 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1770 let unsigned_announcement = UnsignedChannelAnnouncement {
1772 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1776 bitcoin_key_1: node_id_1,
1777 bitcoin_key_2: node_id_2,
1778 excess_data: Vec::new(),
1781 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1782 let valid_announcement = ChannelAnnouncement {
1783 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1784 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1785 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1786 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1787 contents: unsigned_announcement.clone(),
1789 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1790 Ok(res) => assert!(res),
1796 net_graph_msg_handler: &NetGraphMsgHandler<Arc<NetworkGraph>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1797 secp_ctx: &Secp256k1<All>, node_privkey: &SecretKey, update: UnsignedChannelUpdate
1799 let msghash = hash_to_message!(&Sha256dHash::hash(&update.encode()[..])[..]);
1800 let valid_channel_update = ChannelUpdate {
1801 signature: secp_ctx.sign(&msghash, node_privkey),
1802 contents: update.clone()
1805 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1806 Ok(res) => assert!(res),
1811 fn add_or_update_node(
1812 net_graph_msg_handler: &NetGraphMsgHandler<Arc<NetworkGraph>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1813 secp_ctx: &Secp256k1<All>, node_privkey: &SecretKey, features: NodeFeatures, timestamp: u32
1815 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
1816 let unsigned_announcement = UnsignedNodeAnnouncement {
1822 addresses: Vec::new(),
1823 excess_address_data: Vec::new(),
1824 excess_data: Vec::new(),
1826 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1827 let valid_announcement = NodeAnnouncement {
1828 signature: secp_ctx.sign(&msghash, node_privkey),
1829 contents: unsigned_announcement.clone()
1832 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1838 fn get_nodes(secp_ctx: &Secp256k1<All>) -> (SecretKey, PublicKey, Vec<SecretKey>, Vec<PublicKey>) {
1839 let privkeys: Vec<SecretKey> = (2..10).map(|i| {
1840 SecretKey::from_slice(&hex::decode(format!("{:02x}", i).repeat(32)).unwrap()[..]).unwrap()
1843 let pubkeys = privkeys.iter().map(|secret| PublicKey::from_secret_key(&secp_ctx, secret)).collect();
1845 let our_privkey = SecretKey::from_slice(&hex::decode("01".repeat(32)).unwrap()[..]).unwrap();
1846 let our_id = PublicKey::from_secret_key(&secp_ctx, &our_privkey);
1848 (our_privkey, our_id, privkeys, pubkeys)
1851 fn id_to_feature_flags(id: u8) -> Vec<u8> {
1852 // Set the feature flags to the id'th odd (ie non-required) feature bit so that we can
1853 // test for it later.
1854 let idx = (id - 1) * 2 + 1;
1856 vec![1 << (idx - 8*3), 0, 0, 0]
1857 } else if idx > 8*2 {
1858 vec![1 << (idx - 8*2), 0, 0]
1859 } else if idx > 8*1 {
1860 vec![1 << (idx - 8*1), 0]
1866 fn build_graph() -> (
1868 sync::Arc<NetworkGraph>,
1869 NetGraphMsgHandler<sync::Arc<NetworkGraph>, sync::Arc<test_utils::TestChainSource>, sync::Arc<crate::util::test_utils::TestLogger>>,
1870 sync::Arc<test_utils::TestChainSource>,
1871 sync::Arc<test_utils::TestLogger>,
1873 let secp_ctx = Secp256k1::new();
1874 let logger = Arc::new(test_utils::TestLogger::new());
1875 let chain_monitor = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1876 let network_graph = Arc::new(NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash()));
1877 let net_graph_msg_handler = NetGraphMsgHandler::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
1878 // Build network from our_id to node6:
1880 // -1(1)2- node0 -1(3)2-
1882 // our_id -1(12)2- node7 -1(13)2--- node2
1884 // -1(2)2- node1 -1(4)2-
1887 // chan1 1-to-2: disabled
1888 // chan1 2-to-1: enabled, 0 fee
1890 // chan2 1-to-2: enabled, ignored fee
1891 // chan2 2-to-1: enabled, 0 fee
1893 // chan3 1-to-2: enabled, 0 fee
1894 // chan3 2-to-1: enabled, 100 msat fee
1896 // chan4 1-to-2: enabled, 100% fee
1897 // chan4 2-to-1: enabled, 0 fee
1899 // chan12 1-to-2: enabled, ignored fee
1900 // chan12 2-to-1: enabled, 0 fee
1902 // chan13 1-to-2: enabled, 200% fee
1903 // chan13 2-to-1: enabled, 0 fee
1906 // -1(5)2- node3 -1(8)2--
1910 // node2--1(6)2- node4 -1(9)2--- node6 (not in global route map)
1912 // -1(7)2- node5 -1(10)2-
1914 // Channels 5, 8, 9 and 10 are private channels.
1916 // chan5 1-to-2: enabled, 100 msat fee
1917 // chan5 2-to-1: enabled, 0 fee
1919 // chan6 1-to-2: enabled, 0 fee
1920 // chan6 2-to-1: enabled, 0 fee
1922 // chan7 1-to-2: enabled, 100% fee
1923 // chan7 2-to-1: enabled, 0 fee
1925 // chan8 1-to-2: enabled, variable fee (0 then 1000 msat)
1926 // chan8 2-to-1: enabled, 0 fee
1928 // chan9 1-to-2: enabled, 1001 msat fee
1929 // chan9 2-to-1: enabled, 0 fee
1931 // chan10 1-to-2: enabled, 0 fee
1932 // chan10 2-to-1: enabled, 0 fee
1934 // chan11 1-to-2: enabled, 0 fee
1935 // chan11 2-to-1: enabled, 0 fee
1937 let (our_privkey, _, privkeys, _) = get_nodes(&secp_ctx);
1939 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[0], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
1940 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1941 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1942 short_channel_id: 1,
1945 cltv_expiry_delta: 0,
1946 htlc_minimum_msat: 0,
1947 htlc_maximum_msat: OptionalField::Absent,
1949 fee_proportional_millionths: 0,
1950 excess_data: Vec::new()
1953 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
1955 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
1956 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1957 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1958 short_channel_id: 2,
1961 cltv_expiry_delta: (5 << 4) | 3,
1962 htlc_minimum_msat: 0,
1963 htlc_maximum_msat: OptionalField::Absent,
1964 fee_base_msat: u32::max_value(),
1965 fee_proportional_millionths: u32::max_value(),
1966 excess_data: Vec::new()
1968 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1969 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1970 short_channel_id: 2,
1973 cltv_expiry_delta: 0,
1974 htlc_minimum_msat: 0,
1975 htlc_maximum_msat: OptionalField::Absent,
1977 fee_proportional_millionths: 0,
1978 excess_data: Vec::new()
1981 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
1983 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[7], ChannelFeatures::from_le_bytes(id_to_feature_flags(12)), 12);
1984 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1985 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1986 short_channel_id: 12,
1989 cltv_expiry_delta: (5 << 4) | 3,
1990 htlc_minimum_msat: 0,
1991 htlc_maximum_msat: OptionalField::Absent,
1992 fee_base_msat: u32::max_value(),
1993 fee_proportional_millionths: u32::max_value(),
1994 excess_data: Vec::new()
1996 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1997 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1998 short_channel_id: 12,
2001 cltv_expiry_delta: 0,
2002 htlc_minimum_msat: 0,
2003 htlc_maximum_msat: OptionalField::Absent,
2005 fee_proportional_millionths: 0,
2006 excess_data: Vec::new()
2009 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], NodeFeatures::from_le_bytes(id_to_feature_flags(8)), 0);
2011 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
2012 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2013 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2014 short_channel_id: 3,
2017 cltv_expiry_delta: (3 << 4) | 1,
2018 htlc_minimum_msat: 0,
2019 htlc_maximum_msat: OptionalField::Absent,
2021 fee_proportional_millionths: 0,
2022 excess_data: Vec::new()
2024 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2025 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2026 short_channel_id: 3,
2029 cltv_expiry_delta: (3 << 4) | 2,
2030 htlc_minimum_msat: 0,
2031 htlc_maximum_msat: OptionalField::Absent,
2033 fee_proportional_millionths: 0,
2034 excess_data: Vec::new()
2037 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
2038 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2039 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2040 short_channel_id: 4,
2043 cltv_expiry_delta: (4 << 4) | 1,
2044 htlc_minimum_msat: 0,
2045 htlc_maximum_msat: OptionalField::Absent,
2047 fee_proportional_millionths: 1000000,
2048 excess_data: Vec::new()
2050 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2051 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2052 short_channel_id: 4,
2055 cltv_expiry_delta: (4 << 4) | 2,
2056 htlc_minimum_msat: 0,
2057 htlc_maximum_msat: OptionalField::Absent,
2059 fee_proportional_millionths: 0,
2060 excess_data: Vec::new()
2063 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(13)), 13);
2064 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2065 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2066 short_channel_id: 13,
2069 cltv_expiry_delta: (13 << 4) | 1,
2070 htlc_minimum_msat: 0,
2071 htlc_maximum_msat: OptionalField::Absent,
2073 fee_proportional_millionths: 2000000,
2074 excess_data: Vec::new()
2076 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2077 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2078 short_channel_id: 13,
2081 cltv_expiry_delta: (13 << 4) | 2,
2082 htlc_minimum_msat: 0,
2083 htlc_maximum_msat: OptionalField::Absent,
2085 fee_proportional_millionths: 0,
2086 excess_data: Vec::new()
2089 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
2091 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
2092 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2093 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2094 short_channel_id: 6,
2097 cltv_expiry_delta: (6 << 4) | 1,
2098 htlc_minimum_msat: 0,
2099 htlc_maximum_msat: OptionalField::Absent,
2101 fee_proportional_millionths: 0,
2102 excess_data: Vec::new()
2104 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
2105 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2106 short_channel_id: 6,
2109 cltv_expiry_delta: (6 << 4) | 2,
2110 htlc_minimum_msat: 0,
2111 htlc_maximum_msat: OptionalField::Absent,
2113 fee_proportional_millionths: 0,
2114 excess_data: Vec::new(),
2117 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(11)), 11);
2118 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
2119 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2120 short_channel_id: 11,
2123 cltv_expiry_delta: (11 << 4) | 1,
2124 htlc_minimum_msat: 0,
2125 htlc_maximum_msat: OptionalField::Absent,
2127 fee_proportional_millionths: 0,
2128 excess_data: Vec::new()
2130 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
2131 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2132 short_channel_id: 11,
2135 cltv_expiry_delta: (11 << 4) | 2,
2136 htlc_minimum_msat: 0,
2137 htlc_maximum_msat: OptionalField::Absent,
2139 fee_proportional_millionths: 0,
2140 excess_data: Vec::new()
2143 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(5)), 0);
2145 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
2147 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[5], ChannelFeatures::from_le_bytes(id_to_feature_flags(7)), 7);
2148 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2149 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2150 short_channel_id: 7,
2153 cltv_expiry_delta: (7 << 4) | 1,
2154 htlc_minimum_msat: 0,
2155 htlc_maximum_msat: OptionalField::Absent,
2157 fee_proportional_millionths: 1000000,
2158 excess_data: Vec::new()
2160 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[5], UnsignedChannelUpdate {
2161 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2162 short_channel_id: 7,
2165 cltv_expiry_delta: (7 << 4) | 2,
2166 htlc_minimum_msat: 0,
2167 htlc_maximum_msat: OptionalField::Absent,
2169 fee_proportional_millionths: 0,
2170 excess_data: Vec::new()
2173 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[5], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
2175 (secp_ctx, network_graph, net_graph_msg_handler, chain_monitor, logger)
2179 fn simple_route_test() {
2180 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2181 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2182 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2183 let scorer = test_utils::TestScorer::with_penalty(0);
2184 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2185 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2187 // Simple route to 2 via 1
2189 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 0, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
2190 assert_eq!(err, "Cannot send a payment of 0 msat");
2191 } else { panic!(); }
2193 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2194 assert_eq!(route.paths[0].len(), 2);
2196 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2197 assert_eq!(route.paths[0][0].short_channel_id, 2);
2198 assert_eq!(route.paths[0][0].fee_msat, 100);
2199 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2200 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2201 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2203 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2204 assert_eq!(route.paths[0][1].short_channel_id, 4);
2205 assert_eq!(route.paths[0][1].fee_msat, 100);
2206 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2207 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2208 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2212 fn invalid_first_hop_test() {
2213 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2214 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2215 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2216 let scorer = test_utils::TestScorer::with_penalty(0);
2217 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2218 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2220 // Simple route to 2 via 1
2222 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
2224 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) =
2225 get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&our_chans.iter().collect::<Vec<_>>()), 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
2226 assert_eq!(err, "First hop cannot have our_node_pubkey as a destination.");
2227 } else { panic!(); }
2229 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2230 assert_eq!(route.paths[0].len(), 2);
2234 fn htlc_minimum_test() {
2235 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2236 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2237 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2238 let scorer = test_utils::TestScorer::with_penalty(0);
2239 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2240 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2242 // Simple route to 2 via 1
2244 // Disable other paths
2245 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2246 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2247 short_channel_id: 12,
2249 flags: 2, // to disable
2250 cltv_expiry_delta: 0,
2251 htlc_minimum_msat: 0,
2252 htlc_maximum_msat: OptionalField::Absent,
2254 fee_proportional_millionths: 0,
2255 excess_data: Vec::new()
2257 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2258 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2259 short_channel_id: 3,
2261 flags: 2, // to disable
2262 cltv_expiry_delta: 0,
2263 htlc_minimum_msat: 0,
2264 htlc_maximum_msat: OptionalField::Absent,
2266 fee_proportional_millionths: 0,
2267 excess_data: Vec::new()
2269 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2270 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2271 short_channel_id: 13,
2273 flags: 2, // to disable
2274 cltv_expiry_delta: 0,
2275 htlc_minimum_msat: 0,
2276 htlc_maximum_msat: OptionalField::Absent,
2278 fee_proportional_millionths: 0,
2279 excess_data: Vec::new()
2281 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2282 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2283 short_channel_id: 6,
2285 flags: 2, // to disable
2286 cltv_expiry_delta: 0,
2287 htlc_minimum_msat: 0,
2288 htlc_maximum_msat: OptionalField::Absent,
2290 fee_proportional_millionths: 0,
2291 excess_data: Vec::new()
2293 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2294 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2295 short_channel_id: 7,
2297 flags: 2, // to disable
2298 cltv_expiry_delta: 0,
2299 htlc_minimum_msat: 0,
2300 htlc_maximum_msat: OptionalField::Absent,
2302 fee_proportional_millionths: 0,
2303 excess_data: Vec::new()
2306 // Check against amount_to_transfer_over_msat.
2307 // Set minimal HTLC of 200_000_000 msat.
2308 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2309 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2310 short_channel_id: 2,
2313 cltv_expiry_delta: 0,
2314 htlc_minimum_msat: 200_000_000,
2315 htlc_maximum_msat: OptionalField::Absent,
2317 fee_proportional_millionths: 0,
2318 excess_data: Vec::new()
2321 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
2323 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2324 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2325 short_channel_id: 4,
2328 cltv_expiry_delta: 0,
2329 htlc_minimum_msat: 0,
2330 htlc_maximum_msat: OptionalField::Present(199_999_999),
2332 fee_proportional_millionths: 0,
2333 excess_data: Vec::new()
2336 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
2337 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 199_999_999, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
2338 assert_eq!(err, "Failed to find a path to the given destination");
2339 } else { panic!(); }
2341 // Lift the restriction on the first hop.
2342 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2343 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2344 short_channel_id: 2,
2347 cltv_expiry_delta: 0,
2348 htlc_minimum_msat: 0,
2349 htlc_maximum_msat: OptionalField::Absent,
2351 fee_proportional_millionths: 0,
2352 excess_data: Vec::new()
2355 // A payment above the minimum should pass
2356 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 199_999_999, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2357 assert_eq!(route.paths[0].len(), 2);
2361 fn htlc_minimum_overpay_test() {
2362 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2363 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2364 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
2365 let scorer = test_utils::TestScorer::with_penalty(0);
2366 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2367 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2369 // A route to node#2 via two paths.
2370 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
2371 // Thus, they can't send 60 without overpaying.
2372 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2373 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2374 short_channel_id: 2,
2377 cltv_expiry_delta: 0,
2378 htlc_minimum_msat: 35_000,
2379 htlc_maximum_msat: OptionalField::Present(40_000),
2381 fee_proportional_millionths: 0,
2382 excess_data: Vec::new()
2384 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2385 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2386 short_channel_id: 12,
2389 cltv_expiry_delta: 0,
2390 htlc_minimum_msat: 35_000,
2391 htlc_maximum_msat: OptionalField::Present(40_000),
2393 fee_proportional_millionths: 0,
2394 excess_data: Vec::new()
2398 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2399 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2400 short_channel_id: 13,
2403 cltv_expiry_delta: 0,
2404 htlc_minimum_msat: 0,
2405 htlc_maximum_msat: OptionalField::Absent,
2407 fee_proportional_millionths: 0,
2408 excess_data: Vec::new()
2410 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2411 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2412 short_channel_id: 4,
2415 cltv_expiry_delta: 0,
2416 htlc_minimum_msat: 0,
2417 htlc_maximum_msat: OptionalField::Absent,
2419 fee_proportional_millionths: 0,
2420 excess_data: Vec::new()
2423 // Disable other paths
2424 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2425 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2426 short_channel_id: 1,
2428 flags: 2, // to disable
2429 cltv_expiry_delta: 0,
2430 htlc_minimum_msat: 0,
2431 htlc_maximum_msat: OptionalField::Absent,
2433 fee_proportional_millionths: 0,
2434 excess_data: Vec::new()
2437 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 60_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2438 // Overpay fees to hit htlc_minimum_msat.
2439 let overpaid_fees = route.paths[0][0].fee_msat + route.paths[1][0].fee_msat;
2440 // TODO: this could be better balanced to overpay 10k and not 15k.
2441 assert_eq!(overpaid_fees, 15_000);
2443 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
2444 // while taking even more fee to match htlc_minimum_msat.
2445 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2446 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2447 short_channel_id: 12,
2450 cltv_expiry_delta: 0,
2451 htlc_minimum_msat: 65_000,
2452 htlc_maximum_msat: OptionalField::Present(80_000),
2454 fee_proportional_millionths: 0,
2455 excess_data: Vec::new()
2457 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2458 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2459 short_channel_id: 2,
2462 cltv_expiry_delta: 0,
2463 htlc_minimum_msat: 0,
2464 htlc_maximum_msat: OptionalField::Absent,
2466 fee_proportional_millionths: 0,
2467 excess_data: Vec::new()
2469 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2470 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2471 short_channel_id: 4,
2474 cltv_expiry_delta: 0,
2475 htlc_minimum_msat: 0,
2476 htlc_maximum_msat: OptionalField::Absent,
2478 fee_proportional_millionths: 100_000,
2479 excess_data: Vec::new()
2482 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 60_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2483 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
2484 assert_eq!(route.paths.len(), 1);
2485 assert_eq!(route.paths[0][0].short_channel_id, 12);
2486 let fees = route.paths[0][0].fee_msat;
2487 assert_eq!(fees, 5_000);
2489 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2490 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
2491 // the other channel.
2492 assert_eq!(route.paths.len(), 1);
2493 assert_eq!(route.paths[0][0].short_channel_id, 2);
2494 let fees = route.paths[0][0].fee_msat;
2495 assert_eq!(fees, 5_000);
2499 fn disable_channels_test() {
2500 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2501 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2502 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2503 let scorer = test_utils::TestScorer::with_penalty(0);
2504 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2505 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2507 // // Disable channels 4 and 12 by flags=2
2508 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2509 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2510 short_channel_id: 4,
2512 flags: 2, // to disable
2513 cltv_expiry_delta: 0,
2514 htlc_minimum_msat: 0,
2515 htlc_maximum_msat: OptionalField::Absent,
2517 fee_proportional_millionths: 0,
2518 excess_data: Vec::new()
2520 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2521 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2522 short_channel_id: 12,
2524 flags: 2, // to disable
2525 cltv_expiry_delta: 0,
2526 htlc_minimum_msat: 0,
2527 htlc_maximum_msat: OptionalField::Absent,
2529 fee_proportional_millionths: 0,
2530 excess_data: Vec::new()
2533 // If all the channels require some features we don't understand, route should fail
2534 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
2535 assert_eq!(err, "Failed to find a path to the given destination");
2536 } else { panic!(); }
2538 // If we specify a channel to node7, that overrides our local channel view and that gets used
2539 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2540 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&our_chans.iter().collect::<Vec<_>>()), 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2541 assert_eq!(route.paths[0].len(), 2);
2543 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2544 assert_eq!(route.paths[0][0].short_channel_id, 42);
2545 assert_eq!(route.paths[0][0].fee_msat, 200);
2546 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2547 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2548 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2550 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2551 assert_eq!(route.paths[0][1].short_channel_id, 13);
2552 assert_eq!(route.paths[0][1].fee_msat, 100);
2553 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2554 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2555 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2559 fn disable_node_test() {
2560 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2561 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2562 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2563 let scorer = test_utils::TestScorer::with_penalty(0);
2564 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2565 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2567 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
2568 let mut unknown_features = NodeFeatures::known();
2569 unknown_features.set_unknown_feature_required();
2570 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
2571 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
2572 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
2574 // If all nodes require some features we don't understand, route should fail
2575 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
2576 assert_eq!(err, "Failed to find a path to the given destination");
2577 } else { panic!(); }
2579 // If we specify a channel to node7, that overrides our local channel view and that gets used
2580 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2581 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&our_chans.iter().collect::<Vec<_>>()), 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2582 assert_eq!(route.paths[0].len(), 2);
2584 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2585 assert_eq!(route.paths[0][0].short_channel_id, 42);
2586 assert_eq!(route.paths[0][0].fee_msat, 200);
2587 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2588 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2589 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2591 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2592 assert_eq!(route.paths[0][1].short_channel_id, 13);
2593 assert_eq!(route.paths[0][1].fee_msat, 100);
2594 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2595 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2596 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2598 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
2599 // naively) assume that the user checked the feature bits on the invoice, which override
2600 // the node_announcement.
2604 fn our_chans_test() {
2605 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2606 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2607 let scorer = test_utils::TestScorer::with_penalty(0);
2608 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2609 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2611 // Route to 1 via 2 and 3 because our channel to 1 is disabled
2612 let payment_params = PaymentParameters::from_node_id(nodes[0]);
2613 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2614 assert_eq!(route.paths[0].len(), 3);
2616 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2617 assert_eq!(route.paths[0][0].short_channel_id, 2);
2618 assert_eq!(route.paths[0][0].fee_msat, 200);
2619 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2620 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2621 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2623 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2624 assert_eq!(route.paths[0][1].short_channel_id, 4);
2625 assert_eq!(route.paths[0][1].fee_msat, 100);
2626 assert_eq!(route.paths[0][1].cltv_expiry_delta, (3 << 4) | 2);
2627 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2628 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2630 assert_eq!(route.paths[0][2].pubkey, nodes[0]);
2631 assert_eq!(route.paths[0][2].short_channel_id, 3);
2632 assert_eq!(route.paths[0][2].fee_msat, 100);
2633 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
2634 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(1));
2635 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(3));
2637 // If we specify a channel to node7, that overrides our local channel view and that gets used
2638 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2639 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2640 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&our_chans.iter().collect::<Vec<_>>()), 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2641 assert_eq!(route.paths[0].len(), 2);
2643 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2644 assert_eq!(route.paths[0][0].short_channel_id, 42);
2645 assert_eq!(route.paths[0][0].fee_msat, 200);
2646 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2647 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2648 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2650 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2651 assert_eq!(route.paths[0][1].short_channel_id, 13);
2652 assert_eq!(route.paths[0][1].fee_msat, 100);
2653 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
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(13));
2658 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2659 let zero_fees = RoutingFees {
2661 proportional_millionths: 0,
2663 vec![RouteHint(vec![RouteHintHop {
2664 src_node_id: nodes[3],
2665 short_channel_id: 8,
2667 cltv_expiry_delta: (8 << 4) | 1,
2668 htlc_minimum_msat: None,
2669 htlc_maximum_msat: None,
2671 ]), RouteHint(vec![RouteHintHop {
2672 src_node_id: nodes[4],
2673 short_channel_id: 9,
2676 proportional_millionths: 0,
2678 cltv_expiry_delta: (9 << 4) | 1,
2679 htlc_minimum_msat: None,
2680 htlc_maximum_msat: None,
2681 }]), RouteHint(vec![RouteHintHop {
2682 src_node_id: nodes[5],
2683 short_channel_id: 10,
2685 cltv_expiry_delta: (10 << 4) | 1,
2686 htlc_minimum_msat: None,
2687 htlc_maximum_msat: None,
2691 fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2692 let zero_fees = RoutingFees {
2694 proportional_millionths: 0,
2696 vec![RouteHint(vec![RouteHintHop {
2697 src_node_id: nodes[2],
2698 short_channel_id: 5,
2701 proportional_millionths: 0,
2703 cltv_expiry_delta: (5 << 4) | 1,
2704 htlc_minimum_msat: None,
2705 htlc_maximum_msat: None,
2707 src_node_id: nodes[3],
2708 short_channel_id: 8,
2710 cltv_expiry_delta: (8 << 4) | 1,
2711 htlc_minimum_msat: None,
2712 htlc_maximum_msat: None,
2714 ]), RouteHint(vec![RouteHintHop {
2715 src_node_id: nodes[4],
2716 short_channel_id: 9,
2719 proportional_millionths: 0,
2721 cltv_expiry_delta: (9 << 4) | 1,
2722 htlc_minimum_msat: None,
2723 htlc_maximum_msat: None,
2724 }]), RouteHint(vec![RouteHintHop {
2725 src_node_id: nodes[5],
2726 short_channel_id: 10,
2728 cltv_expiry_delta: (10 << 4) | 1,
2729 htlc_minimum_msat: None,
2730 htlc_maximum_msat: None,
2735 fn partial_route_hint_test() {
2736 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2737 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2738 let scorer = test_utils::TestScorer::with_penalty(0);
2739 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2740 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2742 // Simple test across 2, 3, 5, and 4 via a last_hop channel
2743 // Tests the behaviour when the RouteHint contains a suboptimal hop.
2744 // RouteHint may be partially used by the algo to build the best path.
2746 // First check that last hop can't have its source as the payee.
2747 let invalid_last_hop = RouteHint(vec![RouteHintHop {
2748 src_node_id: nodes[6],
2749 short_channel_id: 8,
2752 proportional_millionths: 0,
2754 cltv_expiry_delta: (8 << 4) | 1,
2755 htlc_minimum_msat: None,
2756 htlc_maximum_msat: None,
2759 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
2760 invalid_last_hops.push(invalid_last_hop);
2762 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(invalid_last_hops);
2763 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
2764 assert_eq!(err, "Route hint cannot have the payee as the source.");
2765 } else { panic!(); }
2768 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops_multi_private_channels(&nodes));
2769 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2770 assert_eq!(route.paths[0].len(), 5);
2772 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2773 assert_eq!(route.paths[0][0].short_channel_id, 2);
2774 assert_eq!(route.paths[0][0].fee_msat, 100);
2775 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2776 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2777 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2779 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2780 assert_eq!(route.paths[0][1].short_channel_id, 4);
2781 assert_eq!(route.paths[0][1].fee_msat, 0);
2782 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
2783 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2784 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2786 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2787 assert_eq!(route.paths[0][2].short_channel_id, 6);
2788 assert_eq!(route.paths[0][2].fee_msat, 0);
2789 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
2790 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2791 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2793 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2794 assert_eq!(route.paths[0][3].short_channel_id, 11);
2795 assert_eq!(route.paths[0][3].fee_msat, 0);
2796 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
2797 // If we have a peer in the node map, we'll use their features here since we don't have
2798 // a way of figuring out their features from the invoice:
2799 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2800 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2802 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2803 assert_eq!(route.paths[0][4].short_channel_id, 8);
2804 assert_eq!(route.paths[0][4].fee_msat, 100);
2805 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2806 assert_eq!(route.paths[0][4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
2807 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2810 fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2811 let zero_fees = RoutingFees {
2813 proportional_millionths: 0,
2815 vec![RouteHint(vec![RouteHintHop {
2816 src_node_id: nodes[3],
2817 short_channel_id: 8,
2819 cltv_expiry_delta: (8 << 4) | 1,
2820 htlc_minimum_msat: None,
2821 htlc_maximum_msat: None,
2822 }]), RouteHint(vec![
2824 ]), RouteHint(vec![RouteHintHop {
2825 src_node_id: nodes[5],
2826 short_channel_id: 10,
2828 cltv_expiry_delta: (10 << 4) | 1,
2829 htlc_minimum_msat: None,
2830 htlc_maximum_msat: None,
2835 fn ignores_empty_last_hops_test() {
2836 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2837 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2838 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(empty_last_hop(&nodes));
2839 let scorer = test_utils::TestScorer::with_penalty(0);
2840 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2841 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2843 // Test handling of an empty RouteHint passed in Invoice.
2845 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2846 assert_eq!(route.paths[0].len(), 5);
2848 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2849 assert_eq!(route.paths[0][0].short_channel_id, 2);
2850 assert_eq!(route.paths[0][0].fee_msat, 100);
2851 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2852 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2853 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2855 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2856 assert_eq!(route.paths[0][1].short_channel_id, 4);
2857 assert_eq!(route.paths[0][1].fee_msat, 0);
2858 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
2859 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2860 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2862 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2863 assert_eq!(route.paths[0][2].short_channel_id, 6);
2864 assert_eq!(route.paths[0][2].fee_msat, 0);
2865 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
2866 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2867 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2869 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2870 assert_eq!(route.paths[0][3].short_channel_id, 11);
2871 assert_eq!(route.paths[0][3].fee_msat, 0);
2872 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
2873 // If we have a peer in the node map, we'll use their features here since we don't have
2874 // a way of figuring out their features from the invoice:
2875 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2876 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2878 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2879 assert_eq!(route.paths[0][4].short_channel_id, 8);
2880 assert_eq!(route.paths[0][4].fee_msat, 100);
2881 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2882 assert_eq!(route.paths[0][4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
2883 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2886 /// Builds a trivial last-hop hint that passes through the two nodes given, with channel 0xff00
2888 fn multi_hop_last_hops_hint(hint_hops: [PublicKey; 2]) -> Vec<RouteHint> {
2889 let zero_fees = RoutingFees {
2891 proportional_millionths: 0,
2893 vec![RouteHint(vec![RouteHintHop {
2894 src_node_id: hint_hops[0],
2895 short_channel_id: 0xff00,
2898 proportional_millionths: 0,
2900 cltv_expiry_delta: (5 << 4) | 1,
2901 htlc_minimum_msat: None,
2902 htlc_maximum_msat: None,
2904 src_node_id: hint_hops[1],
2905 short_channel_id: 0xff01,
2907 cltv_expiry_delta: (8 << 4) | 1,
2908 htlc_minimum_msat: None,
2909 htlc_maximum_msat: None,
2914 fn multi_hint_last_hops_test() {
2915 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2916 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2917 let last_hops = multi_hop_last_hops_hint([nodes[2], nodes[3]]);
2918 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops.clone());
2919 let scorer = test_utils::TestScorer::with_penalty(0);
2920 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2921 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2922 // Test through channels 2, 3, 0xff00, 0xff01.
2923 // Test shows that multiple hop hints are considered.
2925 // Disabling channels 6 & 7 by flags=2
2926 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2927 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2928 short_channel_id: 6,
2930 flags: 2, // to disable
2931 cltv_expiry_delta: 0,
2932 htlc_minimum_msat: 0,
2933 htlc_maximum_msat: OptionalField::Absent,
2935 fee_proportional_millionths: 0,
2936 excess_data: Vec::new()
2938 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2939 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2940 short_channel_id: 7,
2942 flags: 2, // to disable
2943 cltv_expiry_delta: 0,
2944 htlc_minimum_msat: 0,
2945 htlc_maximum_msat: OptionalField::Absent,
2947 fee_proportional_millionths: 0,
2948 excess_data: Vec::new()
2951 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2952 assert_eq!(route.paths[0].len(), 4);
2954 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2955 assert_eq!(route.paths[0][0].short_channel_id, 2);
2956 assert_eq!(route.paths[0][0].fee_msat, 200);
2957 assert_eq!(route.paths[0][0].cltv_expiry_delta, 65);
2958 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2959 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2961 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2962 assert_eq!(route.paths[0][1].short_channel_id, 4);
2963 assert_eq!(route.paths[0][1].fee_msat, 100);
2964 assert_eq!(route.paths[0][1].cltv_expiry_delta, 81);
2965 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2966 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2968 assert_eq!(route.paths[0][2].pubkey, nodes[3]);
2969 assert_eq!(route.paths[0][2].short_channel_id, last_hops[0].0[0].short_channel_id);
2970 assert_eq!(route.paths[0][2].fee_msat, 0);
2971 assert_eq!(route.paths[0][2].cltv_expiry_delta, 129);
2972 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(4));
2973 assert_eq!(route.paths[0][2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2975 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2976 assert_eq!(route.paths[0][3].short_channel_id, last_hops[0].0[1].short_channel_id);
2977 assert_eq!(route.paths[0][3].fee_msat, 100);
2978 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2979 assert_eq!(route.paths[0][3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
2980 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2984 fn private_multi_hint_last_hops_test() {
2985 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2986 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2988 let non_announced_privkey = SecretKey::from_slice(&hex::decode(format!("{:02x}", 0xf0).repeat(32)).unwrap()[..]).unwrap();
2989 let non_announced_pubkey = PublicKey::from_secret_key(&secp_ctx, &non_announced_privkey);
2991 let last_hops = multi_hop_last_hops_hint([nodes[2], non_announced_pubkey]);
2992 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops.clone());
2993 let scorer = test_utils::TestScorer::with_penalty(0);
2994 // Test through channels 2, 3, 0xff00, 0xff01.
2995 // Test shows that multiple hop hints are considered.
2997 // Disabling channels 6 & 7 by flags=2
2998 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2999 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3000 short_channel_id: 6,
3002 flags: 2, // to disable
3003 cltv_expiry_delta: 0,
3004 htlc_minimum_msat: 0,
3005 htlc_maximum_msat: OptionalField::Absent,
3007 fee_proportional_millionths: 0,
3008 excess_data: Vec::new()
3010 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3011 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3012 short_channel_id: 7,
3014 flags: 2, // to disable
3015 cltv_expiry_delta: 0,
3016 htlc_minimum_msat: 0,
3017 htlc_maximum_msat: OptionalField::Absent,
3019 fee_proportional_millionths: 0,
3020 excess_data: Vec::new()
3023 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &[42u8; 32]).unwrap();
3024 assert_eq!(route.paths[0].len(), 4);
3026 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3027 assert_eq!(route.paths[0][0].short_channel_id, 2);
3028 assert_eq!(route.paths[0][0].fee_msat, 200);
3029 assert_eq!(route.paths[0][0].cltv_expiry_delta, 65);
3030 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3031 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3033 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3034 assert_eq!(route.paths[0][1].short_channel_id, 4);
3035 assert_eq!(route.paths[0][1].fee_msat, 100);
3036 assert_eq!(route.paths[0][1].cltv_expiry_delta, 81);
3037 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3038 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3040 assert_eq!(route.paths[0][2].pubkey, non_announced_pubkey);
3041 assert_eq!(route.paths[0][2].short_channel_id, last_hops[0].0[0].short_channel_id);
3042 assert_eq!(route.paths[0][2].fee_msat, 0);
3043 assert_eq!(route.paths[0][2].cltv_expiry_delta, 129);
3044 assert_eq!(route.paths[0][2].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3045 assert_eq!(route.paths[0][2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3047 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
3048 assert_eq!(route.paths[0][3].short_channel_id, last_hops[0].0[1].short_channel_id);
3049 assert_eq!(route.paths[0][3].fee_msat, 100);
3050 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
3051 assert_eq!(route.paths[0][3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3052 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3055 fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3056 let zero_fees = RoutingFees {
3058 proportional_millionths: 0,
3060 vec![RouteHint(vec![RouteHintHop {
3061 src_node_id: nodes[4],
3062 short_channel_id: 11,
3064 cltv_expiry_delta: (11 << 4) | 1,
3065 htlc_minimum_msat: None,
3066 htlc_maximum_msat: None,
3068 src_node_id: nodes[3],
3069 short_channel_id: 8,
3071 cltv_expiry_delta: (8 << 4) | 1,
3072 htlc_minimum_msat: None,
3073 htlc_maximum_msat: None,
3074 }]), RouteHint(vec![RouteHintHop {
3075 src_node_id: nodes[4],
3076 short_channel_id: 9,
3079 proportional_millionths: 0,
3081 cltv_expiry_delta: (9 << 4) | 1,
3082 htlc_minimum_msat: None,
3083 htlc_maximum_msat: None,
3084 }]), RouteHint(vec![RouteHintHop {
3085 src_node_id: nodes[5],
3086 short_channel_id: 10,
3088 cltv_expiry_delta: (10 << 4) | 1,
3089 htlc_minimum_msat: None,
3090 htlc_maximum_msat: None,
3095 fn last_hops_with_public_channel_test() {
3096 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3097 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3098 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops_with_public_channel(&nodes));
3099 let scorer = test_utils::TestScorer::with_penalty(0);
3100 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3101 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3102 // This test shows that public routes can be present in the invoice
3103 // which would be handled in the same manner.
3105 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3106 assert_eq!(route.paths[0].len(), 5);
3108 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3109 assert_eq!(route.paths[0][0].short_channel_id, 2);
3110 assert_eq!(route.paths[0][0].fee_msat, 100);
3111 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
3112 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3113 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3115 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3116 assert_eq!(route.paths[0][1].short_channel_id, 4);
3117 assert_eq!(route.paths[0][1].fee_msat, 0);
3118 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
3119 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3120 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3122 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
3123 assert_eq!(route.paths[0][2].short_channel_id, 6);
3124 assert_eq!(route.paths[0][2].fee_msat, 0);
3125 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
3126 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
3127 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
3129 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
3130 assert_eq!(route.paths[0][3].short_channel_id, 11);
3131 assert_eq!(route.paths[0][3].fee_msat, 0);
3132 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
3133 // If we have a peer in the node map, we'll use their features here since we don't have
3134 // a way of figuring out their features from the invoice:
3135 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
3136 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
3138 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
3139 assert_eq!(route.paths[0][4].short_channel_id, 8);
3140 assert_eq!(route.paths[0][4].fee_msat, 100);
3141 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
3142 assert_eq!(route.paths[0][4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3143 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3147 fn our_chans_last_hop_connect_test() {
3148 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3149 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3150 let scorer = test_utils::TestScorer::with_penalty(0);
3151 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3152 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3154 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
3155 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3156 let mut last_hops = last_hops(&nodes);
3157 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops.clone());
3158 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&our_chans.iter().collect::<Vec<_>>()), 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3159 assert_eq!(route.paths[0].len(), 2);
3161 assert_eq!(route.paths[0][0].pubkey, nodes[3]);
3162 assert_eq!(route.paths[0][0].short_channel_id, 42);
3163 assert_eq!(route.paths[0][0].fee_msat, 0);
3164 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 4) | 1);
3165 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
3166 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3168 assert_eq!(route.paths[0][1].pubkey, nodes[6]);
3169 assert_eq!(route.paths[0][1].short_channel_id, 8);
3170 assert_eq!(route.paths[0][1].fee_msat, 100);
3171 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
3172 assert_eq!(route.paths[0][1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3173 assert_eq!(route.paths[0][1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3175 last_hops[0].0[0].fees.base_msat = 1000;
3177 // Revert to via 6 as the fee on 8 goes up
3178 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops);
3179 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3180 assert_eq!(route.paths[0].len(), 4);
3182 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3183 assert_eq!(route.paths[0][0].short_channel_id, 2);
3184 assert_eq!(route.paths[0][0].fee_msat, 200); // fee increased as its % of value transferred across node
3185 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
3186 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3187 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3189 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3190 assert_eq!(route.paths[0][1].short_channel_id, 4);
3191 assert_eq!(route.paths[0][1].fee_msat, 100);
3192 assert_eq!(route.paths[0][1].cltv_expiry_delta, (7 << 4) | 1);
3193 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3194 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3196 assert_eq!(route.paths[0][2].pubkey, nodes[5]);
3197 assert_eq!(route.paths[0][2].short_channel_id, 7);
3198 assert_eq!(route.paths[0][2].fee_msat, 0);
3199 assert_eq!(route.paths[0][2].cltv_expiry_delta, (10 << 4) | 1);
3200 // If we have a peer in the node map, we'll use their features here since we don't have
3201 // a way of figuring out their features from the invoice:
3202 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
3203 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(7));
3205 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
3206 assert_eq!(route.paths[0][3].short_channel_id, 10);
3207 assert_eq!(route.paths[0][3].fee_msat, 100);
3208 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
3209 assert_eq!(route.paths[0][3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3210 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3212 // ...but still use 8 for larger payments as 6 has a variable feerate
3213 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 2000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3214 assert_eq!(route.paths[0].len(), 5);
3216 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3217 assert_eq!(route.paths[0][0].short_channel_id, 2);
3218 assert_eq!(route.paths[0][0].fee_msat, 3000);
3219 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
3220 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3221 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3223 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3224 assert_eq!(route.paths[0][1].short_channel_id, 4);
3225 assert_eq!(route.paths[0][1].fee_msat, 0);
3226 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
3227 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3228 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3230 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
3231 assert_eq!(route.paths[0][2].short_channel_id, 6);
3232 assert_eq!(route.paths[0][2].fee_msat, 0);
3233 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
3234 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
3235 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
3237 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
3238 assert_eq!(route.paths[0][3].short_channel_id, 11);
3239 assert_eq!(route.paths[0][3].fee_msat, 1000);
3240 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
3241 // If we have a peer in the node map, we'll use their features here since we don't have
3242 // a way of figuring out their features from the invoice:
3243 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
3244 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
3246 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
3247 assert_eq!(route.paths[0][4].short_channel_id, 8);
3248 assert_eq!(route.paths[0][4].fee_msat, 2000);
3249 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
3250 assert_eq!(route.paths[0][4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3251 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3254 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> {
3255 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
3256 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3257 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3259 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
3260 let last_hops = RouteHint(vec![RouteHintHop {
3261 src_node_id: middle_node_id,
3262 short_channel_id: 8,
3265 proportional_millionths: last_hop_fee_prop,
3267 cltv_expiry_delta: (8 << 4) | 1,
3268 htlc_minimum_msat: None,
3269 htlc_maximum_msat: last_hop_htlc_max,
3271 let payment_params = PaymentParameters::from_node_id(target_node_id).with_route_hints(vec![last_hops]);
3272 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
3273 let scorer = test_utils::TestScorer::with_penalty(0);
3274 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3275 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3276 get_route(&source_node_id, &payment_params, &NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash()).read_only(),
3277 Some(&our_chans.iter().collect::<Vec<_>>()), route_val, 42, &test_utils::TestLogger::new(), &scorer, &random_seed_bytes)
3281 fn unannounced_path_test() {
3282 // We should be able to send a payment to a destination without any help of a routing graph
3283 // if we have a channel with a common counterparty that appears in the first and last hop
3285 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
3287 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3288 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3289 assert_eq!(route.paths[0].len(), 2);
3291 assert_eq!(route.paths[0][0].pubkey, middle_node_id);
3292 assert_eq!(route.paths[0][0].short_channel_id, 42);
3293 assert_eq!(route.paths[0][0].fee_msat, 1001);
3294 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 4) | 1);
3295 assert_eq!(route.paths[0][0].node_features.le_flags(), &[0b11]);
3296 assert_eq!(route.paths[0][0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3298 assert_eq!(route.paths[0][1].pubkey, target_node_id);
3299 assert_eq!(route.paths[0][1].short_channel_id, 8);
3300 assert_eq!(route.paths[0][1].fee_msat, 1000000);
3301 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
3302 assert_eq!(route.paths[0][1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3303 assert_eq!(route.paths[0][1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3307 fn overflow_unannounced_path_test_liquidity_underflow() {
3308 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
3309 // the last-hop had a fee which overflowed a u64, we'd panic.
3310 // This was due to us adding the first-hop from us unconditionally, causing us to think
3311 // we'd built a path (as our node is in the "best candidate" set), when we had not.
3312 // In this test, we previously hit a subtraction underflow due to having less available
3313 // liquidity at the last hop than 0.
3314 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());
3318 fn overflow_unannounced_path_test_feerate_overflow() {
3319 // This tests for the same case as above, except instead of hitting a subtraction
3320 // underflow, we hit a case where the fee charged at a hop overflowed.
3321 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());
3325 fn available_amount_while_routing_test() {
3326 // Tests whether we choose the correct available channel amount while routing.
3328 let (secp_ctx, network_graph, mut net_graph_msg_handler, chain_monitor, logger) = build_graph();
3329 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3330 let scorer = test_utils::TestScorer::with_penalty(0);
3331 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3332 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3333 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
3335 // We will use a simple single-path route from
3336 // our node to node2 via node0: channels {1, 3}.
3338 // First disable all other paths.
3339 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3340 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3341 short_channel_id: 2,
3344 cltv_expiry_delta: 0,
3345 htlc_minimum_msat: 0,
3346 htlc_maximum_msat: OptionalField::Present(100_000),
3348 fee_proportional_millionths: 0,
3349 excess_data: Vec::new()
3351 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3352 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3353 short_channel_id: 12,
3356 cltv_expiry_delta: 0,
3357 htlc_minimum_msat: 0,
3358 htlc_maximum_msat: OptionalField::Present(100_000),
3360 fee_proportional_millionths: 0,
3361 excess_data: Vec::new()
3364 // Make the first channel (#1) very permissive,
3365 // and we will be testing all limits on the second channel.
3366 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3367 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3368 short_channel_id: 1,
3371 cltv_expiry_delta: 0,
3372 htlc_minimum_msat: 0,
3373 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3375 fee_proportional_millionths: 0,
3376 excess_data: Vec::new()
3379 // First, let's see if routing works if we have absolutely no idea about the available amount.
3380 // In this case, it should be set to 250_000 sats.
3381 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3382 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3383 short_channel_id: 3,
3386 cltv_expiry_delta: 0,
3387 htlc_minimum_msat: 0,
3388 htlc_maximum_msat: OptionalField::Absent,
3390 fee_proportional_millionths: 0,
3391 excess_data: Vec::new()
3395 // Attempt to route more than available results in a failure.
3396 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3397 &our_id, &payment_params, &network_graph.read_only(), None, 250_000_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3398 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3399 } else { panic!(); }
3403 // Now, attempt to route an exact amount we have should be fine.
3404 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 250_000_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3405 assert_eq!(route.paths.len(), 1);
3406 let path = route.paths.last().unwrap();
3407 assert_eq!(path.len(), 2);
3408 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3409 assert_eq!(path.last().unwrap().fee_msat, 250_000_000);
3412 // Check that setting next_outbound_htlc_limit_msat in first_hops limits the channels.
3413 // Disable channel #1 and use another first hop.
3414 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3415 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3416 short_channel_id: 1,
3419 cltv_expiry_delta: 0,
3420 htlc_minimum_msat: 0,
3421 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3423 fee_proportional_millionths: 0,
3424 excess_data: Vec::new()
3427 // Now, limit the first_hop by the next_outbound_htlc_limit_msat of 200_000 sats.
3428 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
3431 // Attempt to route more than available results in a failure.
3432 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3433 &our_id, &payment_params, &network_graph.read_only(), Some(&our_chans.iter().collect::<Vec<_>>()), 200_000_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3434 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3435 } else { panic!(); }
3439 // Now, attempt to route an exact amount we have should be fine.
3440 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&our_chans.iter().collect::<Vec<_>>()), 200_000_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3441 assert_eq!(route.paths.len(), 1);
3442 let path = route.paths.last().unwrap();
3443 assert_eq!(path.len(), 2);
3444 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3445 assert_eq!(path.last().unwrap().fee_msat, 200_000_000);
3448 // Enable channel #1 back.
3449 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3450 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3451 short_channel_id: 1,
3454 cltv_expiry_delta: 0,
3455 htlc_minimum_msat: 0,
3456 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3458 fee_proportional_millionths: 0,
3459 excess_data: Vec::new()
3463 // Now let's see if routing works if we know only htlc_maximum_msat.
3464 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3465 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3466 short_channel_id: 3,
3469 cltv_expiry_delta: 0,
3470 htlc_minimum_msat: 0,
3471 htlc_maximum_msat: OptionalField::Present(15_000),
3473 fee_proportional_millionths: 0,
3474 excess_data: Vec::new()
3478 // Attempt to route more than available results in a failure.
3479 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3480 &our_id, &payment_params, &network_graph.read_only(), None, 15_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3481 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3482 } else { panic!(); }
3486 // Now, attempt to route an exact amount we have should be fine.
3487 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 15_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3488 assert_eq!(route.paths.len(), 1);
3489 let path = route.paths.last().unwrap();
3490 assert_eq!(path.len(), 2);
3491 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3492 assert_eq!(path.last().unwrap().fee_msat, 15_000);
3495 // Now let's see if routing works if we know only capacity from the UTXO.
3497 // We can't change UTXO capacity on the fly, so we'll disable
3498 // the existing channel and add another one with the capacity we need.
3499 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3500 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3501 short_channel_id: 3,
3504 cltv_expiry_delta: 0,
3505 htlc_minimum_msat: 0,
3506 htlc_maximum_msat: OptionalField::Absent,
3508 fee_proportional_millionths: 0,
3509 excess_data: Vec::new()
3512 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
3513 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
3514 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
3515 .push_opcode(opcodes::all::OP_PUSHNUM_2)
3516 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
3518 *chain_monitor.utxo_ret.lock().unwrap() = Ok(TxOut { value: 15, script_pubkey: good_script.clone() });
3519 net_graph_msg_handler.add_chain_access(Some(chain_monitor));
3521 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
3522 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3523 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3524 short_channel_id: 333,
3527 cltv_expiry_delta: (3 << 4) | 1,
3528 htlc_minimum_msat: 0,
3529 htlc_maximum_msat: OptionalField::Absent,
3531 fee_proportional_millionths: 0,
3532 excess_data: Vec::new()
3534 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3535 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3536 short_channel_id: 333,
3539 cltv_expiry_delta: (3 << 4) | 2,
3540 htlc_minimum_msat: 0,
3541 htlc_maximum_msat: OptionalField::Absent,
3543 fee_proportional_millionths: 0,
3544 excess_data: Vec::new()
3548 // Attempt to route more than available results in a failure.
3549 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3550 &our_id, &payment_params, &network_graph.read_only(), None, 15_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3551 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3552 } else { panic!(); }
3556 // Now, attempt to route an exact amount we have should be fine.
3557 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 15_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3558 assert_eq!(route.paths.len(), 1);
3559 let path = route.paths.last().unwrap();
3560 assert_eq!(path.len(), 2);
3561 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3562 assert_eq!(path.last().unwrap().fee_msat, 15_000);
3565 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
3566 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3567 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3568 short_channel_id: 333,
3571 cltv_expiry_delta: 0,
3572 htlc_minimum_msat: 0,
3573 htlc_maximum_msat: OptionalField::Present(10_000),
3575 fee_proportional_millionths: 0,
3576 excess_data: Vec::new()
3580 // Attempt to route more than available results in a failure.
3581 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3582 &our_id, &payment_params, &network_graph.read_only(), None, 10_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3583 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3584 } else { panic!(); }
3588 // Now, attempt to route an exact amount we have should be fine.
3589 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 10_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3590 assert_eq!(route.paths.len(), 1);
3591 let path = route.paths.last().unwrap();
3592 assert_eq!(path.len(), 2);
3593 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3594 assert_eq!(path.last().unwrap().fee_msat, 10_000);
3599 fn available_liquidity_last_hop_test() {
3600 // Check that available liquidity properly limits the path even when only
3601 // one of the latter hops is limited.
3602 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3603 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3604 let scorer = test_utils::TestScorer::with_penalty(0);
3605 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3606 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3607 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
3609 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3610 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
3611 // Total capacity: 50 sats.
3613 // Disable other potential paths.
3614 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3615 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3616 short_channel_id: 2,
3619 cltv_expiry_delta: 0,
3620 htlc_minimum_msat: 0,
3621 htlc_maximum_msat: OptionalField::Present(100_000),
3623 fee_proportional_millionths: 0,
3624 excess_data: Vec::new()
3626 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3627 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3628 short_channel_id: 7,
3631 cltv_expiry_delta: 0,
3632 htlc_minimum_msat: 0,
3633 htlc_maximum_msat: OptionalField::Present(100_000),
3635 fee_proportional_millionths: 0,
3636 excess_data: Vec::new()
3641 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3642 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3643 short_channel_id: 12,
3646 cltv_expiry_delta: 0,
3647 htlc_minimum_msat: 0,
3648 htlc_maximum_msat: OptionalField::Present(100_000),
3650 fee_proportional_millionths: 0,
3651 excess_data: Vec::new()
3653 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3654 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3655 short_channel_id: 13,
3658 cltv_expiry_delta: 0,
3659 htlc_minimum_msat: 0,
3660 htlc_maximum_msat: OptionalField::Present(100_000),
3662 fee_proportional_millionths: 0,
3663 excess_data: Vec::new()
3666 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3667 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3668 short_channel_id: 6,
3671 cltv_expiry_delta: 0,
3672 htlc_minimum_msat: 0,
3673 htlc_maximum_msat: OptionalField::Present(50_000),
3675 fee_proportional_millionths: 0,
3676 excess_data: Vec::new()
3678 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3679 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3680 short_channel_id: 11,
3683 cltv_expiry_delta: 0,
3684 htlc_minimum_msat: 0,
3685 htlc_maximum_msat: OptionalField::Present(100_000),
3687 fee_proportional_millionths: 0,
3688 excess_data: Vec::new()
3691 // Attempt to route more than available results in a failure.
3692 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3693 &our_id, &payment_params, &network_graph.read_only(), None, 60_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3694 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3695 } else { panic!(); }
3699 // Now, attempt to route 49 sats (just a bit below the capacity).
3700 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 49_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3701 assert_eq!(route.paths.len(), 1);
3702 let mut total_amount_paid_msat = 0;
3703 for path in &route.paths {
3704 assert_eq!(path.len(), 4);
3705 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3706 total_amount_paid_msat += path.last().unwrap().fee_msat;
3708 assert_eq!(total_amount_paid_msat, 49_000);
3712 // Attempt to route an exact amount is also fine
3713 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3714 assert_eq!(route.paths.len(), 1);
3715 let mut total_amount_paid_msat = 0;
3716 for path in &route.paths {
3717 assert_eq!(path.len(), 4);
3718 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3719 total_amount_paid_msat += path.last().unwrap().fee_msat;
3721 assert_eq!(total_amount_paid_msat, 50_000);
3726 fn ignore_fee_first_hop_test() {
3727 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3728 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3729 let scorer = test_utils::TestScorer::with_penalty(0);
3730 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3731 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3732 let payment_params = PaymentParameters::from_node_id(nodes[2]);
3734 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3735 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3736 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3737 short_channel_id: 1,
3740 cltv_expiry_delta: 0,
3741 htlc_minimum_msat: 0,
3742 htlc_maximum_msat: OptionalField::Present(100_000),
3743 fee_base_msat: 1_000_000,
3744 fee_proportional_millionths: 0,
3745 excess_data: Vec::new()
3747 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3748 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3749 short_channel_id: 3,
3752 cltv_expiry_delta: 0,
3753 htlc_minimum_msat: 0,
3754 htlc_maximum_msat: OptionalField::Present(50_000),
3756 fee_proportional_millionths: 0,
3757 excess_data: Vec::new()
3761 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3762 assert_eq!(route.paths.len(), 1);
3763 let mut total_amount_paid_msat = 0;
3764 for path in &route.paths {
3765 assert_eq!(path.len(), 2);
3766 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3767 total_amount_paid_msat += path.last().unwrap().fee_msat;
3769 assert_eq!(total_amount_paid_msat, 50_000);
3774 fn simple_mpp_route_test() {
3775 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3776 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3777 let scorer = test_utils::TestScorer::with_penalty(0);
3778 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3779 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3780 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
3782 // We need a route consisting of 3 paths:
3783 // From our node to node2 via node0, node7, node1 (three paths one hop each).
3784 // To achieve this, the amount being transferred should be around
3785 // the total capacity of these 3 paths.
3787 // First, we set limits on these (previously unlimited) channels.
3788 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
3790 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3791 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3792 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3793 short_channel_id: 1,
3796 cltv_expiry_delta: 0,
3797 htlc_minimum_msat: 0,
3798 htlc_maximum_msat: OptionalField::Present(100_000),
3800 fee_proportional_millionths: 0,
3801 excess_data: Vec::new()
3803 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3804 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3805 short_channel_id: 3,
3808 cltv_expiry_delta: 0,
3809 htlc_minimum_msat: 0,
3810 htlc_maximum_msat: OptionalField::Present(50_000),
3812 fee_proportional_millionths: 0,
3813 excess_data: Vec::new()
3816 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
3817 // (total limit 60).
3818 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3819 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3820 short_channel_id: 12,
3823 cltv_expiry_delta: 0,
3824 htlc_minimum_msat: 0,
3825 htlc_maximum_msat: OptionalField::Present(60_000),
3827 fee_proportional_millionths: 0,
3828 excess_data: Vec::new()
3830 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3831 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3832 short_channel_id: 13,
3835 cltv_expiry_delta: 0,
3836 htlc_minimum_msat: 0,
3837 htlc_maximum_msat: OptionalField::Present(60_000),
3839 fee_proportional_millionths: 0,
3840 excess_data: Vec::new()
3843 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
3844 // (total capacity 180 sats).
3845 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3846 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3847 short_channel_id: 2,
3850 cltv_expiry_delta: 0,
3851 htlc_minimum_msat: 0,
3852 htlc_maximum_msat: OptionalField::Present(200_000),
3854 fee_proportional_millionths: 0,
3855 excess_data: Vec::new()
3857 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3858 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3859 short_channel_id: 4,
3862 cltv_expiry_delta: 0,
3863 htlc_minimum_msat: 0,
3864 htlc_maximum_msat: OptionalField::Present(180_000),
3866 fee_proportional_millionths: 0,
3867 excess_data: Vec::new()
3871 // Attempt to route more than available results in a failure.
3872 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3873 &our_id, &payment_params, &network_graph.read_only(), None, 300_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3874 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3875 } else { panic!(); }
3879 // Now, attempt to route 250 sats (just a bit below the capacity).
3880 // Our algorithm should provide us with these 3 paths.
3881 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 250_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3882 assert_eq!(route.paths.len(), 3);
3883 let mut total_amount_paid_msat = 0;
3884 for path in &route.paths {
3885 assert_eq!(path.len(), 2);
3886 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3887 total_amount_paid_msat += path.last().unwrap().fee_msat;
3889 assert_eq!(total_amount_paid_msat, 250_000);
3893 // Attempt to route an exact amount is also fine
3894 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 290_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3895 assert_eq!(route.paths.len(), 3);
3896 let mut total_amount_paid_msat = 0;
3897 for path in &route.paths {
3898 assert_eq!(path.len(), 2);
3899 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3900 total_amount_paid_msat += path.last().unwrap().fee_msat;
3902 assert_eq!(total_amount_paid_msat, 290_000);
3907 fn long_mpp_route_test() {
3908 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3909 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3910 let scorer = test_utils::TestScorer::with_penalty(0);
3911 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3912 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3913 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
3915 // We need a route consisting of 3 paths:
3916 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3917 // Note that these paths overlap (channels 5, 12, 13).
3918 // We will route 300 sats.
3919 // Each path will have 100 sats capacity, those channels which
3920 // are used twice will have 200 sats capacity.
3922 // Disable other potential paths.
3923 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3924 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3925 short_channel_id: 2,
3928 cltv_expiry_delta: 0,
3929 htlc_minimum_msat: 0,
3930 htlc_maximum_msat: OptionalField::Present(100_000),
3932 fee_proportional_millionths: 0,
3933 excess_data: Vec::new()
3935 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3936 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3937 short_channel_id: 7,
3940 cltv_expiry_delta: 0,
3941 htlc_minimum_msat: 0,
3942 htlc_maximum_msat: OptionalField::Present(100_000),
3944 fee_proportional_millionths: 0,
3945 excess_data: Vec::new()
3948 // Path via {node0, node2} is channels {1, 3, 5}.
3949 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3950 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3951 short_channel_id: 1,
3954 cltv_expiry_delta: 0,
3955 htlc_minimum_msat: 0,
3956 htlc_maximum_msat: OptionalField::Present(100_000),
3958 fee_proportional_millionths: 0,
3959 excess_data: Vec::new()
3961 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3962 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3963 short_channel_id: 3,
3966 cltv_expiry_delta: 0,
3967 htlc_minimum_msat: 0,
3968 htlc_maximum_msat: OptionalField::Present(100_000),
3970 fee_proportional_millionths: 0,
3971 excess_data: Vec::new()
3974 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3975 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3976 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3977 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3978 short_channel_id: 5,
3981 cltv_expiry_delta: 0,
3982 htlc_minimum_msat: 0,
3983 htlc_maximum_msat: OptionalField::Present(200_000),
3985 fee_proportional_millionths: 0,
3986 excess_data: Vec::new()
3989 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3990 // Add 100 sats to the capacities of {12, 13}, because these channels
3991 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3992 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3993 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3994 short_channel_id: 12,
3997 cltv_expiry_delta: 0,
3998 htlc_minimum_msat: 0,
3999 htlc_maximum_msat: OptionalField::Present(200_000),
4001 fee_proportional_millionths: 0,
4002 excess_data: Vec::new()
4004 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4005 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4006 short_channel_id: 13,
4009 cltv_expiry_delta: 0,
4010 htlc_minimum_msat: 0,
4011 htlc_maximum_msat: OptionalField::Present(200_000),
4013 fee_proportional_millionths: 0,
4014 excess_data: Vec::new()
4017 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4018 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4019 short_channel_id: 6,
4022 cltv_expiry_delta: 0,
4023 htlc_minimum_msat: 0,
4024 htlc_maximum_msat: OptionalField::Present(100_000),
4026 fee_proportional_millionths: 0,
4027 excess_data: Vec::new()
4029 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4030 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4031 short_channel_id: 11,
4034 cltv_expiry_delta: 0,
4035 htlc_minimum_msat: 0,
4036 htlc_maximum_msat: OptionalField::Present(100_000),
4038 fee_proportional_millionths: 0,
4039 excess_data: Vec::new()
4042 // Path via {node7, node2} is channels {12, 13, 5}.
4043 // We already limited them to 200 sats (they are used twice for 100 sats).
4044 // Nothing to do here.
4047 // Attempt to route more than available results in a failure.
4048 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4049 &our_id, &payment_params, &network_graph.read_only(), None, 350_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
4050 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4051 } else { panic!(); }
4055 // Now, attempt to route 300 sats (exact amount we can route).
4056 // Our algorithm should provide us with these 3 paths, 100 sats each.
4057 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 300_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4058 assert_eq!(route.paths.len(), 3);
4060 let mut total_amount_paid_msat = 0;
4061 for path in &route.paths {
4062 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
4063 total_amount_paid_msat += path.last().unwrap().fee_msat;
4065 assert_eq!(total_amount_paid_msat, 300_000);
4071 fn mpp_cheaper_route_test() {
4072 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4073 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4074 let scorer = test_utils::TestScorer::with_penalty(0);
4075 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4076 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4077 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
4079 // This test checks that if we have two cheaper paths and one more expensive path,
4080 // so that liquidity-wise any 2 of 3 combination is sufficient,
4081 // two cheaper paths will be taken.
4082 // These paths have equal available liquidity.
4084 // We need a combination of 3 paths:
4085 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
4086 // Note that these paths overlap (channels 5, 12, 13).
4087 // Each path will have 100 sats capacity, those channels which
4088 // are used twice will have 200 sats capacity.
4090 // Disable other potential paths.
4091 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4092 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4093 short_channel_id: 2,
4096 cltv_expiry_delta: 0,
4097 htlc_minimum_msat: 0,
4098 htlc_maximum_msat: OptionalField::Present(100_000),
4100 fee_proportional_millionths: 0,
4101 excess_data: Vec::new()
4103 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4104 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4105 short_channel_id: 7,
4108 cltv_expiry_delta: 0,
4109 htlc_minimum_msat: 0,
4110 htlc_maximum_msat: OptionalField::Present(100_000),
4112 fee_proportional_millionths: 0,
4113 excess_data: Vec::new()
4116 // Path via {node0, node2} is channels {1, 3, 5}.
4117 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4118 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4119 short_channel_id: 1,
4122 cltv_expiry_delta: 0,
4123 htlc_minimum_msat: 0,
4124 htlc_maximum_msat: OptionalField::Present(100_000),
4126 fee_proportional_millionths: 0,
4127 excess_data: Vec::new()
4129 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4130 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4131 short_channel_id: 3,
4134 cltv_expiry_delta: 0,
4135 htlc_minimum_msat: 0,
4136 htlc_maximum_msat: OptionalField::Present(100_000),
4138 fee_proportional_millionths: 0,
4139 excess_data: Vec::new()
4142 // Capacity of 200 sats because this channel will be used by 3rd path as well.
4143 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4144 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4145 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4146 short_channel_id: 5,
4149 cltv_expiry_delta: 0,
4150 htlc_minimum_msat: 0,
4151 htlc_maximum_msat: OptionalField::Present(200_000),
4153 fee_proportional_millionths: 0,
4154 excess_data: Vec::new()
4157 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4158 // Add 100 sats to the capacities of {12, 13}, because these channels
4159 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
4160 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4161 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4162 short_channel_id: 12,
4165 cltv_expiry_delta: 0,
4166 htlc_minimum_msat: 0,
4167 htlc_maximum_msat: OptionalField::Present(200_000),
4169 fee_proportional_millionths: 0,
4170 excess_data: Vec::new()
4172 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4173 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4174 short_channel_id: 13,
4177 cltv_expiry_delta: 0,
4178 htlc_minimum_msat: 0,
4179 htlc_maximum_msat: OptionalField::Present(200_000),
4181 fee_proportional_millionths: 0,
4182 excess_data: Vec::new()
4185 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4186 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4187 short_channel_id: 6,
4190 cltv_expiry_delta: 0,
4191 htlc_minimum_msat: 0,
4192 htlc_maximum_msat: OptionalField::Present(100_000),
4193 fee_base_msat: 1_000,
4194 fee_proportional_millionths: 0,
4195 excess_data: Vec::new()
4197 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4198 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4199 short_channel_id: 11,
4202 cltv_expiry_delta: 0,
4203 htlc_minimum_msat: 0,
4204 htlc_maximum_msat: OptionalField::Present(100_000),
4206 fee_proportional_millionths: 0,
4207 excess_data: Vec::new()
4210 // Path via {node7, node2} is channels {12, 13, 5}.
4211 // We already limited them to 200 sats (they are used twice for 100 sats).
4212 // Nothing to do here.
4215 // Now, attempt to route 180 sats.
4216 // Our algorithm should provide us with these 2 paths.
4217 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 180_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4218 assert_eq!(route.paths.len(), 2);
4220 let mut total_value_transferred_msat = 0;
4221 let mut total_paid_msat = 0;
4222 for path in &route.paths {
4223 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
4224 total_value_transferred_msat += path.last().unwrap().fee_msat;
4226 total_paid_msat += hop.fee_msat;
4229 // If we paid fee, this would be higher.
4230 assert_eq!(total_value_transferred_msat, 180_000);
4231 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
4232 assert_eq!(total_fees_paid, 0);
4237 fn fees_on_mpp_route_test() {
4238 // This test makes sure that MPP algorithm properly takes into account
4239 // fees charged on the channels, by making the fees impactful:
4240 // if the fee is not properly accounted for, the behavior is different.
4241 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4242 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4243 let scorer = test_utils::TestScorer::with_penalty(0);
4244 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4245 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4246 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
4248 // We need a route consisting of 2 paths:
4249 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
4250 // We will route 200 sats, Each path will have 100 sats capacity.
4252 // This test is not particularly stable: e.g.,
4253 // there's a way to route via {node0, node2, node4}.
4254 // It works while pathfinding is deterministic, but can be broken otherwise.
4255 // It's fine to ignore this concern for now.
4257 // Disable other potential paths.
4258 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4259 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4260 short_channel_id: 2,
4263 cltv_expiry_delta: 0,
4264 htlc_minimum_msat: 0,
4265 htlc_maximum_msat: OptionalField::Present(100_000),
4267 fee_proportional_millionths: 0,
4268 excess_data: Vec::new()
4271 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4272 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4273 short_channel_id: 7,
4276 cltv_expiry_delta: 0,
4277 htlc_minimum_msat: 0,
4278 htlc_maximum_msat: OptionalField::Present(100_000),
4280 fee_proportional_millionths: 0,
4281 excess_data: Vec::new()
4284 // Path via {node0, node2} is channels {1, 3, 5}.
4285 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4286 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4287 short_channel_id: 1,
4290 cltv_expiry_delta: 0,
4291 htlc_minimum_msat: 0,
4292 htlc_maximum_msat: OptionalField::Present(100_000),
4294 fee_proportional_millionths: 0,
4295 excess_data: Vec::new()
4297 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4298 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4299 short_channel_id: 3,
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()
4310 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4311 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4312 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4313 short_channel_id: 5,
4316 cltv_expiry_delta: 0,
4317 htlc_minimum_msat: 0,
4318 htlc_maximum_msat: OptionalField::Present(100_000),
4320 fee_proportional_millionths: 0,
4321 excess_data: Vec::new()
4324 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4325 // All channels should be 100 sats capacity. But for the fee experiment,
4326 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
4327 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
4328 // 100 sats (and pay 150 sats in fees for the use of channel 6),
4329 // so no matter how large are other channels,
4330 // the whole path will be limited by 100 sats with just these 2 conditions:
4331 // - channel 12 capacity is 250 sats
4332 // - fee for channel 6 is 150 sats
4333 // Let's test this by enforcing these 2 conditions and removing other limits.
4334 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4335 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4336 short_channel_id: 12,
4339 cltv_expiry_delta: 0,
4340 htlc_minimum_msat: 0,
4341 htlc_maximum_msat: OptionalField::Present(250_000),
4343 fee_proportional_millionths: 0,
4344 excess_data: Vec::new()
4346 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4347 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4348 short_channel_id: 13,
4351 cltv_expiry_delta: 0,
4352 htlc_minimum_msat: 0,
4353 htlc_maximum_msat: OptionalField::Absent,
4355 fee_proportional_millionths: 0,
4356 excess_data: Vec::new()
4359 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4360 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4361 short_channel_id: 6,
4364 cltv_expiry_delta: 0,
4365 htlc_minimum_msat: 0,
4366 htlc_maximum_msat: OptionalField::Absent,
4367 fee_base_msat: 150_000,
4368 fee_proportional_millionths: 0,
4369 excess_data: Vec::new()
4371 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4372 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4373 short_channel_id: 11,
4376 cltv_expiry_delta: 0,
4377 htlc_minimum_msat: 0,
4378 htlc_maximum_msat: OptionalField::Absent,
4380 fee_proportional_millionths: 0,
4381 excess_data: Vec::new()
4385 // Attempt to route more than available results in a failure.
4386 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4387 &our_id, &payment_params, &network_graph.read_only(), None, 210_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
4388 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4389 } else { panic!(); }
4393 // Now, attempt to route 200 sats (exact amount we can route).
4394 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 200_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4395 assert_eq!(route.paths.len(), 2);
4397 let mut total_amount_paid_msat = 0;
4398 for path in &route.paths {
4399 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
4400 total_amount_paid_msat += path.last().unwrap().fee_msat;
4402 assert_eq!(total_amount_paid_msat, 200_000);
4403 assert_eq!(route.get_total_fees(), 150_000);
4408 fn mpp_with_last_hops() {
4409 // Previously, if we tried to send an MPP payment to a destination which was only reachable
4410 // via a single last-hop route hint, we'd fail to route if we first collected routes
4411 // totaling close but not quite enough to fund the full payment.
4413 // This was because we considered last-hop hints to have exactly the sought payment amount
4414 // instead of the amount we were trying to collect, needlessly limiting our path searching
4415 // at the very first hop.
4417 // Specifically, this interacted with our "all paths must fund at least 5% of total target"
4418 // criterion to cause us to refuse all routes at the last hop hint which would be considered
4419 // to only have the remaining to-collect amount in available liquidity.
4421 // This bug appeared in production in some specific channel configurations.
4422 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4423 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4424 let scorer = test_utils::TestScorer::with_penalty(0);
4425 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4426 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4427 let payment_params = PaymentParameters::from_node_id(PublicKey::from_slice(&[02; 33]).unwrap()).with_features(InvoiceFeatures::known())
4428 .with_route_hints(vec![RouteHint(vec![RouteHintHop {
4429 src_node_id: nodes[2],
4430 short_channel_id: 42,
4431 fees: RoutingFees { base_msat: 0, proportional_millionths: 0 },
4432 cltv_expiry_delta: 42,
4433 htlc_minimum_msat: None,
4434 htlc_maximum_msat: None,
4437 // Keep only two paths from us to nodes[2], both with a 99sat HTLC maximum, with one with
4438 // no fee and one with a 1msat fee. Previously, trying to route 100 sats to nodes[2] here
4439 // would first use the no-fee route and then fail to find a path along the second route as
4440 // we think we can only send up to 1 additional sat over the last-hop but refuse to as its
4441 // under 5% of our payment amount.
4442 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4443 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4444 short_channel_id: 1,
4447 cltv_expiry_delta: (5 << 4) | 5,
4448 htlc_minimum_msat: 0,
4449 htlc_maximum_msat: OptionalField::Present(99_000),
4450 fee_base_msat: u32::max_value(),
4451 fee_proportional_millionths: u32::max_value(),
4452 excess_data: Vec::new()
4454 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4455 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4456 short_channel_id: 2,
4459 cltv_expiry_delta: (5 << 4) | 3,
4460 htlc_minimum_msat: 0,
4461 htlc_maximum_msat: OptionalField::Present(99_000),
4462 fee_base_msat: u32::max_value(),
4463 fee_proportional_millionths: u32::max_value(),
4464 excess_data: Vec::new()
4466 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4467 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4468 short_channel_id: 4,
4471 cltv_expiry_delta: (4 << 4) | 1,
4472 htlc_minimum_msat: 0,
4473 htlc_maximum_msat: OptionalField::Absent,
4475 fee_proportional_millionths: 0,
4476 excess_data: Vec::new()
4478 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4479 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4480 short_channel_id: 13,
4482 flags: 0|2, // Channel disabled
4483 cltv_expiry_delta: (13 << 4) | 1,
4484 htlc_minimum_msat: 0,
4485 htlc_maximum_msat: OptionalField::Absent,
4487 fee_proportional_millionths: 2000000,
4488 excess_data: Vec::new()
4491 // Get a route for 100 sats and check that we found the MPP route no problem and didn't
4493 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4494 assert_eq!(route.paths.len(), 2);
4495 // Paths are somewhat randomly ordered, but:
4496 // * the first is channel 2 (1 msat fee) -> channel 4 -> channel 42
4497 // * the second is channel 1 (0 fee, but 99 sat maximum) -> channel 3 -> channel 42
4498 assert_eq!(route.paths[0][0].short_channel_id, 2);
4499 assert_eq!(route.paths[0][0].fee_msat, 1);
4500 assert_eq!(route.paths[0][2].fee_msat, 1_000);
4501 assert_eq!(route.paths[1][0].short_channel_id, 1);
4502 assert_eq!(route.paths[1][0].fee_msat, 0);
4503 assert_eq!(route.paths[1][2].fee_msat, 99_000);
4504 assert_eq!(route.get_total_fees(), 1);
4505 assert_eq!(route.get_total_amount(), 100_000);
4509 fn drop_lowest_channel_mpp_route_test() {
4510 // This test checks that low-capacity channel is dropped when after
4511 // path finding we realize that we found more capacity than we need.
4512 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4513 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4514 let scorer = test_utils::TestScorer::with_penalty(0);
4515 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4516 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4517 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
4519 // We need a route consisting of 3 paths:
4520 // From our node to node2 via node0, node7, node1 (three paths one hop each).
4522 // The first and the second paths should be sufficient, but the third should be
4523 // cheaper, so that we select it but drop later.
4525 // First, we set limits on these (previously unlimited) channels.
4526 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
4528 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
4529 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4530 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4531 short_channel_id: 1,
4534 cltv_expiry_delta: 0,
4535 htlc_minimum_msat: 0,
4536 htlc_maximum_msat: OptionalField::Present(100_000),
4538 fee_proportional_millionths: 0,
4539 excess_data: Vec::new()
4541 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4542 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4543 short_channel_id: 3,
4546 cltv_expiry_delta: 0,
4547 htlc_minimum_msat: 0,
4548 htlc_maximum_msat: OptionalField::Present(50_000),
4550 fee_proportional_millionths: 0,
4551 excess_data: Vec::new()
4554 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
4555 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4556 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4557 short_channel_id: 12,
4560 cltv_expiry_delta: 0,
4561 htlc_minimum_msat: 0,
4562 htlc_maximum_msat: OptionalField::Present(60_000),
4564 fee_proportional_millionths: 0,
4565 excess_data: Vec::new()
4567 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4568 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4569 short_channel_id: 13,
4572 cltv_expiry_delta: 0,
4573 htlc_minimum_msat: 0,
4574 htlc_maximum_msat: OptionalField::Present(60_000),
4576 fee_proportional_millionths: 0,
4577 excess_data: Vec::new()
4580 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
4581 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4582 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4583 short_channel_id: 2,
4586 cltv_expiry_delta: 0,
4587 htlc_minimum_msat: 0,
4588 htlc_maximum_msat: OptionalField::Present(20_000),
4590 fee_proportional_millionths: 0,
4591 excess_data: Vec::new()
4593 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4594 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4595 short_channel_id: 4,
4598 cltv_expiry_delta: 0,
4599 htlc_minimum_msat: 0,
4600 htlc_maximum_msat: OptionalField::Present(20_000),
4602 fee_proportional_millionths: 0,
4603 excess_data: Vec::new()
4607 // Attempt to route more than available results in a failure.
4608 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4609 &our_id, &payment_params, &network_graph.read_only(), None, 150_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
4610 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4611 } else { panic!(); }
4615 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
4616 // Our algorithm should provide us with these 3 paths.
4617 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 125_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4618 assert_eq!(route.paths.len(), 3);
4619 let mut total_amount_paid_msat = 0;
4620 for path in &route.paths {
4621 assert_eq!(path.len(), 2);
4622 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4623 total_amount_paid_msat += path.last().unwrap().fee_msat;
4625 assert_eq!(total_amount_paid_msat, 125_000);
4629 // Attempt to route without the last small cheap channel
4630 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4631 assert_eq!(route.paths.len(), 2);
4632 let mut total_amount_paid_msat = 0;
4633 for path in &route.paths {
4634 assert_eq!(path.len(), 2);
4635 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4636 total_amount_paid_msat += path.last().unwrap().fee_msat;
4638 assert_eq!(total_amount_paid_msat, 90_000);
4643 fn min_criteria_consistency() {
4644 // Test that we don't use an inconsistent metric between updating and walking nodes during
4645 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
4646 // was updated with a different criterion from the heap sorting, resulting in loops in
4647 // calculated paths. We test for that specific case here.
4649 // We construct a network that looks like this:
4651 // node2 -1(3)2- node3
4655 // node1 -1(5)2- node4 -1(1)2- node6
4661 // We create a loop on the side of our real path - our destination is node 6, with a
4662 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
4663 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
4664 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
4665 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
4666 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
4667 // "previous hop" being set to node 3, creating a loop in the path.
4668 let secp_ctx = Secp256k1::new();
4669 let logger = Arc::new(test_utils::TestLogger::new());
4670 let network = Arc::new(NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash()));
4671 let net_graph_msg_handler = NetGraphMsgHandler::new(Arc::clone(&network), None, Arc::clone(&logger));
4672 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4673 let scorer = test_utils::TestScorer::with_penalty(0);
4674 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4675 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4676 let payment_params = PaymentParameters::from_node_id(nodes[6]);
4678 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
4679 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4680 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4681 short_channel_id: 6,
4684 cltv_expiry_delta: (6 << 4) | 0,
4685 htlc_minimum_msat: 0,
4686 htlc_maximum_msat: OptionalField::Absent,
4688 fee_proportional_millionths: 0,
4689 excess_data: Vec::new()
4691 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
4693 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4694 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4695 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4696 short_channel_id: 5,
4699 cltv_expiry_delta: (5 << 4) | 0,
4700 htlc_minimum_msat: 0,
4701 htlc_maximum_msat: OptionalField::Absent,
4703 fee_proportional_millionths: 0,
4704 excess_data: Vec::new()
4706 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
4708 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
4709 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4710 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4711 short_channel_id: 4,
4714 cltv_expiry_delta: (4 << 4) | 0,
4715 htlc_minimum_msat: 0,
4716 htlc_maximum_msat: OptionalField::Absent,
4718 fee_proportional_millionths: 0,
4719 excess_data: Vec::new()
4721 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
4723 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
4724 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
4725 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4726 short_channel_id: 3,
4729 cltv_expiry_delta: (3 << 4) | 0,
4730 htlc_minimum_msat: 0,
4731 htlc_maximum_msat: OptionalField::Absent,
4733 fee_proportional_millionths: 0,
4734 excess_data: Vec::new()
4736 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
4738 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
4739 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4740 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4741 short_channel_id: 2,
4744 cltv_expiry_delta: (2 << 4) | 0,
4745 htlc_minimum_msat: 0,
4746 htlc_maximum_msat: OptionalField::Absent,
4748 fee_proportional_millionths: 0,
4749 excess_data: Vec::new()
4752 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
4753 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4754 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4755 short_channel_id: 1,
4758 cltv_expiry_delta: (1 << 4) | 0,
4759 htlc_minimum_msat: 100,
4760 htlc_maximum_msat: OptionalField::Absent,
4762 fee_proportional_millionths: 0,
4763 excess_data: Vec::new()
4765 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
4768 // Now ensure the route flows simply over nodes 1 and 4 to 6.
4769 let route = get_route(&our_id, &payment_params, &network.read_only(), None, 10_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4770 assert_eq!(route.paths.len(), 1);
4771 assert_eq!(route.paths[0].len(), 3);
4773 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
4774 assert_eq!(route.paths[0][0].short_channel_id, 6);
4775 assert_eq!(route.paths[0][0].fee_msat, 100);
4776 assert_eq!(route.paths[0][0].cltv_expiry_delta, (5 << 4) | 0);
4777 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(1));
4778 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(6));
4780 assert_eq!(route.paths[0][1].pubkey, nodes[4]);
4781 assert_eq!(route.paths[0][1].short_channel_id, 5);
4782 assert_eq!(route.paths[0][1].fee_msat, 0);
4783 assert_eq!(route.paths[0][1].cltv_expiry_delta, (1 << 4) | 0);
4784 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(4));
4785 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(5));
4787 assert_eq!(route.paths[0][2].pubkey, nodes[6]);
4788 assert_eq!(route.paths[0][2].short_channel_id, 1);
4789 assert_eq!(route.paths[0][2].fee_msat, 10_000);
4790 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
4791 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
4792 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(1));
4798 fn exact_fee_liquidity_limit() {
4799 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
4800 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
4801 // we calculated fees on a higher value, resulting in us ignoring such paths.
4802 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4803 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
4804 let scorer = test_utils::TestScorer::with_penalty(0);
4805 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4806 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4807 let payment_params = PaymentParameters::from_node_id(nodes[2]);
4809 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
4811 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4812 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4813 short_channel_id: 2,
4816 cltv_expiry_delta: 0,
4817 htlc_minimum_msat: 0,
4818 htlc_maximum_msat: OptionalField::Present(85_000),
4820 fee_proportional_millionths: 0,
4821 excess_data: Vec::new()
4824 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4825 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4826 short_channel_id: 12,
4829 cltv_expiry_delta: (4 << 4) | 1,
4830 htlc_minimum_msat: 0,
4831 htlc_maximum_msat: OptionalField::Present(270_000),
4833 fee_proportional_millionths: 1000000,
4834 excess_data: Vec::new()
4838 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
4839 // 200% fee charged channel 13 in the 1-to-2 direction.
4840 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4841 assert_eq!(route.paths.len(), 1);
4842 assert_eq!(route.paths[0].len(), 2);
4844 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
4845 assert_eq!(route.paths[0][0].short_channel_id, 12);
4846 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
4847 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
4848 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
4849 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
4851 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
4852 assert_eq!(route.paths[0][1].short_channel_id, 13);
4853 assert_eq!(route.paths[0][1].fee_msat, 90_000);
4854 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
4855 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
4856 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
4861 fn htlc_max_reduction_below_min() {
4862 // Test that if, while walking the graph, we reduce the value being sent to meet an
4863 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
4864 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
4865 // resulting in us thinking there is no possible path, even if other paths exist.
4866 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4867 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4868 let scorer = test_utils::TestScorer::with_penalty(0);
4869 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4870 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4871 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
4873 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
4874 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
4875 // then try to send 90_000.
4876 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4877 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4878 short_channel_id: 2,
4881 cltv_expiry_delta: 0,
4882 htlc_minimum_msat: 0,
4883 htlc_maximum_msat: OptionalField::Present(80_000),
4885 fee_proportional_millionths: 0,
4886 excess_data: Vec::new()
4888 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4889 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4890 short_channel_id: 4,
4893 cltv_expiry_delta: (4 << 4) | 1,
4894 htlc_minimum_msat: 90_000,
4895 htlc_maximum_msat: OptionalField::Absent,
4897 fee_proportional_millionths: 0,
4898 excess_data: Vec::new()
4902 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
4903 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
4904 // expensive) channels 12-13 path.
4905 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4906 assert_eq!(route.paths.len(), 1);
4907 assert_eq!(route.paths[0].len(), 2);
4909 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
4910 assert_eq!(route.paths[0][0].short_channel_id, 12);
4911 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
4912 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
4913 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
4914 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
4916 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
4917 assert_eq!(route.paths[0][1].short_channel_id, 13);
4918 assert_eq!(route.paths[0][1].fee_msat, 90_000);
4919 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
4920 assert_eq!(route.paths[0][1].node_features.le_flags(), InvoiceFeatures::known().le_flags());
4921 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
4926 fn multiple_direct_first_hops() {
4927 // Previously we'd only ever considered one first hop path per counterparty.
4928 // However, as we don't restrict users to one channel per peer, we really need to support
4929 // looking at all first hop paths.
4930 // Here we test that we do not ignore all-but-the-last first hop paths per counterparty (as
4931 // we used to do by overwriting the `first_hop_targets` hashmap entry) and that we can MPP
4932 // route over multiple channels with the same first hop.
4933 let secp_ctx = Secp256k1::new();
4934 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4935 let logger = Arc::new(test_utils::TestLogger::new());
4936 let network_graph = NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash());
4937 let scorer = test_utils::TestScorer::with_penalty(0);
4938 let payment_params = PaymentParameters::from_node_id(nodes[0]).with_features(InvoiceFeatures::known());
4939 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4940 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4943 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
4944 &get_channel_details(Some(3), nodes[0], InitFeatures::known(), 200_000),
4945 &get_channel_details(Some(2), nodes[0], InitFeatures::known(), 10_000),
4946 ]), 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4947 assert_eq!(route.paths.len(), 1);
4948 assert_eq!(route.paths[0].len(), 1);
4950 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
4951 assert_eq!(route.paths[0][0].short_channel_id, 3);
4952 assert_eq!(route.paths[0][0].fee_msat, 100_000);
4955 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
4956 &get_channel_details(Some(3), nodes[0], InitFeatures::known(), 50_000),
4957 &get_channel_details(Some(2), nodes[0], InitFeatures::known(), 50_000),
4958 ]), 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4959 assert_eq!(route.paths.len(), 2);
4960 assert_eq!(route.paths[0].len(), 1);
4961 assert_eq!(route.paths[1].len(), 1);
4963 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
4964 assert_eq!(route.paths[0][0].short_channel_id, 3);
4965 assert_eq!(route.paths[0][0].fee_msat, 50_000);
4967 assert_eq!(route.paths[1][0].pubkey, nodes[0]);
4968 assert_eq!(route.paths[1][0].short_channel_id, 2);
4969 assert_eq!(route.paths[1][0].fee_msat, 50_000);
4973 // If we have a bunch of outbound channels to the same node, where most are not
4974 // sufficient to pay the full payment, but one is, we should default to just using the
4975 // one single channel that has sufficient balance, avoiding MPP.
4977 // If we have several options above the 3xpayment value threshold, we should pick the
4978 // smallest of them, avoiding further fragmenting our available outbound balance to
4980 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
4981 &get_channel_details(Some(2), nodes[0], InitFeatures::known(), 50_000),
4982 &get_channel_details(Some(3), nodes[0], InitFeatures::known(), 50_000),
4983 &get_channel_details(Some(5), nodes[0], InitFeatures::known(), 50_000),
4984 &get_channel_details(Some(6), nodes[0], InitFeatures::known(), 300_000),
4985 &get_channel_details(Some(7), nodes[0], InitFeatures::known(), 50_000),
4986 &get_channel_details(Some(8), nodes[0], InitFeatures::known(), 50_000),
4987 &get_channel_details(Some(9), nodes[0], InitFeatures::known(), 50_000),
4988 &get_channel_details(Some(4), nodes[0], InitFeatures::known(), 1_000_000),
4989 ]), 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4990 assert_eq!(route.paths.len(), 1);
4991 assert_eq!(route.paths[0].len(), 1);
4993 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
4994 assert_eq!(route.paths[0][0].short_channel_id, 6);
4995 assert_eq!(route.paths[0][0].fee_msat, 100_000);
5000 fn prefers_shorter_route_with_higher_fees() {
5001 let (secp_ctx, network_graph, _, _, logger) = build_graph();
5002 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5003 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
5005 // Without penalizing each hop 100 msats, a longer path with lower fees is chosen.
5006 let scorer = test_utils::TestScorer::with_penalty(0);
5007 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5008 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5009 let route = get_route(
5010 &our_id, &payment_params, &network_graph.read_only(), None, 100, 42,
5011 Arc::clone(&logger), &scorer, &random_seed_bytes
5013 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5015 assert_eq!(route.get_total_fees(), 100);
5016 assert_eq!(route.get_total_amount(), 100);
5017 assert_eq!(path, vec![2, 4, 6, 11, 8]);
5019 // Applying a 100 msat penalty to each hop results in taking channels 7 and 10 to nodes[6]
5020 // from nodes[2] rather than channel 6, 11, and 8, even though the longer path is cheaper.
5021 let scorer = test_utils::TestScorer::with_penalty(100);
5022 let route = get_route(
5023 &our_id, &payment_params, &network_graph.read_only(), None, 100, 42,
5024 Arc::clone(&logger), &scorer, &random_seed_bytes
5026 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5028 assert_eq!(route.get_total_fees(), 300);
5029 assert_eq!(route.get_total_amount(), 100);
5030 assert_eq!(path, vec![2, 4, 7, 10]);
5033 struct BadChannelScorer {
5034 short_channel_id: u64,
5038 impl Writeable for BadChannelScorer {
5039 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), ::io::Error> { unimplemented!() }
5041 impl Score for BadChannelScorer {
5042 fn channel_penalty_msat(&self, short_channel_id: u64, _send_amt: u64, _capacity_msat: u64, _source: &NodeId, _target: &NodeId) -> u64 {
5043 if short_channel_id == self.short_channel_id { u64::max_value() } else { 0 }
5046 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
5047 fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
5050 struct BadNodeScorer {
5055 impl Writeable for BadNodeScorer {
5056 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), ::io::Error> { unimplemented!() }
5059 impl Score for BadNodeScorer {
5060 fn channel_penalty_msat(&self, _short_channel_id: u64, _send_amt: u64, _capacity_msat: u64, _source: &NodeId, target: &NodeId) -> u64 {
5061 if *target == self.node_id { u64::max_value() } else { 0 }
5064 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
5065 fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
5069 fn avoids_routing_through_bad_channels_and_nodes() {
5070 let (secp_ctx, network, _, _, logger) = build_graph();
5071 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5072 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
5073 let network_graph = network.read_only();
5075 // A path to nodes[6] exists when no penalties are applied to any channel.
5076 let scorer = test_utils::TestScorer::with_penalty(0);
5077 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5078 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5079 let route = get_route(
5080 &our_id, &payment_params, &network_graph, None, 100, 42,
5081 Arc::clone(&logger), &scorer, &random_seed_bytes
5083 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5085 assert_eq!(route.get_total_fees(), 100);
5086 assert_eq!(route.get_total_amount(), 100);
5087 assert_eq!(path, vec![2, 4, 6, 11, 8]);
5089 // A different path to nodes[6] exists if channel 6 cannot be routed over.
5090 let scorer = BadChannelScorer { short_channel_id: 6 };
5091 let route = get_route(
5092 &our_id, &payment_params, &network_graph, None, 100, 42,
5093 Arc::clone(&logger), &scorer, &random_seed_bytes
5095 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5097 assert_eq!(route.get_total_fees(), 300);
5098 assert_eq!(route.get_total_amount(), 100);
5099 assert_eq!(path, vec![2, 4, 7, 10]);
5101 // A path to nodes[6] does not exist if nodes[2] cannot be routed through.
5102 let scorer = BadNodeScorer { node_id: NodeId::from_pubkey(&nodes[2]) };
5104 &our_id, &payment_params, &network_graph, None, 100, 42,
5105 Arc::clone(&logger), &scorer, &random_seed_bytes
5107 Err(LightningError { err, .. } ) => {
5108 assert_eq!(err, "Failed to find a path to the given destination");
5110 Ok(_) => panic!("Expected error"),
5115 fn total_fees_single_path() {
5119 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5120 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5121 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5124 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5125 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5126 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5129 pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
5130 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5131 short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0
5134 payment_params: None,
5137 assert_eq!(route.get_total_fees(), 250);
5138 assert_eq!(route.get_total_amount(), 225);
5142 fn total_fees_multi_path() {
5146 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5147 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5148 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5151 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5152 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5153 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5157 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5158 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5159 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5162 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5163 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5164 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5167 payment_params: None,
5170 assert_eq!(route.get_total_fees(), 200);
5171 assert_eq!(route.get_total_amount(), 300);
5175 fn total_empty_route_no_panic() {
5176 // In an earlier version of `Route::get_total_fees` and `Route::get_total_amount`, they
5177 // would both panic if the route was completely empty. We test to ensure they return 0
5178 // here, even though its somewhat nonsensical as a route.
5179 let route = Route { paths: Vec::new(), payment_params: None };
5181 assert_eq!(route.get_total_fees(), 0);
5182 assert_eq!(route.get_total_amount(), 0);
5186 fn limits_total_cltv_delta() {
5187 let (secp_ctx, network, _, _, logger) = build_graph();
5188 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5189 let network_graph = network.read_only();
5191 let scorer = test_utils::TestScorer::with_penalty(0);
5193 // Make sure that generally there is at least one route available
5194 let feasible_max_total_cltv_delta = 1008;
5195 let feasible_payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes))
5196 .with_max_total_cltv_expiry_delta(feasible_max_total_cltv_delta);
5197 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5198 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5199 let route = get_route(&our_id, &feasible_payment_params, &network_graph, None, 100, 0, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5200 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5201 assert_ne!(path.len(), 0);
5203 // But not if we exclude all paths on the basis of their accumulated CLTV delta
5204 let fail_max_total_cltv_delta = 23;
5205 let fail_payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes))
5206 .with_max_total_cltv_expiry_delta(fail_max_total_cltv_delta);
5207 match get_route(&our_id, &fail_payment_params, &network_graph, None, 100, 0, Arc::clone(&logger), &scorer, &random_seed_bytes)
5209 Err(LightningError { err, .. } ) => {
5210 assert_eq!(err, "Failed to find a path to the given destination");
5212 Ok(_) => panic!("Expected error"),
5217 fn adds_and_limits_cltv_offset() {
5218 let (secp_ctx, network_graph, _, _, logger) = build_graph();
5219 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5221 let scorer = test_utils::TestScorer::with_penalty(0);
5223 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
5224 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5225 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5226 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5227 assert_eq!(route.paths.len(), 1);
5229 let cltv_expiry_deltas_before = route.paths[0].iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5231 // Check whether the offset added to the last hop by default is in [1 .. DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA]
5232 let mut route_default = route.clone();
5233 add_random_cltv_offset(&mut route_default, &payment_params, &network_graph.read_only(), &random_seed_bytes);
5234 let cltv_expiry_deltas_default = route_default.paths[0].iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5235 assert_eq!(cltv_expiry_deltas_before.split_last().unwrap().1, cltv_expiry_deltas_default.split_last().unwrap().1);
5236 assert!(cltv_expiry_deltas_default.last() > cltv_expiry_deltas_before.last());
5237 assert!(cltv_expiry_deltas_default.last().unwrap() <= &DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA);
5239 // Check that no offset is added when we restrict the max_total_cltv_expiry_delta
5240 let mut route_limited = route.clone();
5241 let limited_max_total_cltv_expiry_delta = cltv_expiry_deltas_before.iter().sum();
5242 let limited_payment_params = payment_params.with_max_total_cltv_expiry_delta(limited_max_total_cltv_expiry_delta);
5243 add_random_cltv_offset(&mut route_limited, &limited_payment_params, &network_graph.read_only(), &random_seed_bytes);
5244 let cltv_expiry_deltas_limited = route_limited.paths[0].iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5245 assert_eq!(cltv_expiry_deltas_before, cltv_expiry_deltas_limited);
5249 fn adds_plausible_cltv_offset() {
5250 let (secp_ctx, network, _, _, logger) = build_graph();
5251 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5252 let network_graph = network.read_only();
5253 let network_nodes = network_graph.nodes();
5254 let network_channels = network_graph.channels();
5255 let scorer = test_utils::TestScorer::with_penalty(0);
5256 let payment_params = PaymentParameters::from_node_id(nodes[3]);
5257 let keys_manager = test_utils::TestKeysInterface::new(&[4u8; 32], Network::Testnet);
5258 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5260 let mut route = get_route(&our_id, &payment_params, &network_graph, None, 100, 0,
5261 Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5262 add_random_cltv_offset(&mut route, &payment_params, &network_graph, &random_seed_bytes);
5264 let mut path_plausibility = vec![];
5266 for p in route.paths {
5267 // 1. Select random observation point
5268 let mut prng = ChaCha20::new(&random_seed_bytes, &[0u8; 12]);
5269 let mut random_bytes = [0u8; ::core::mem::size_of::<usize>()];
5271 prng.process_in_place(&mut random_bytes);
5272 let random_path_index = usize::from_be_bytes(random_bytes).wrapping_rem(p.len());
5273 let observation_point = NodeId::from_pubkey(&p.get(random_path_index).unwrap().pubkey);
5275 // 2. Calculate what CLTV expiry delta we would observe there
5276 let observed_cltv_expiry_delta: u32 = p[random_path_index..].iter().map(|h| h.cltv_expiry_delta).sum();
5278 // 3. Starting from the observation point, find candidate paths
5279 let mut candidates: VecDeque<(NodeId, Vec<u32>)> = VecDeque::new();
5280 candidates.push_back((observation_point, vec![]));
5282 let mut found_plausible_candidate = false;
5284 'candidate_loop: while let Some((cur_node_id, cur_path_cltv_deltas)) = candidates.pop_front() {
5285 if let Some(remaining) = observed_cltv_expiry_delta.checked_sub(cur_path_cltv_deltas.iter().sum::<u32>()) {
5286 if remaining == 0 || remaining.wrapping_rem(40) == 0 || remaining.wrapping_rem(144) == 0 {
5287 found_plausible_candidate = true;
5288 break 'candidate_loop;
5292 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
5293 for channel_id in &cur_node.channels {
5294 if let Some(channel_info) = network_channels.get(&channel_id) {
5295 if let Some((dir_info, next_id)) = channel_info.as_directed_from(&cur_node_id) {
5296 if let Some(channel_update_info) = dir_info.direction() {
5297 let next_cltv_expiry_delta = channel_update_info.cltv_expiry_delta as u32;
5298 if cur_path_cltv_deltas.iter().sum::<u32>()
5299 .saturating_add(next_cltv_expiry_delta) <= observed_cltv_expiry_delta {
5300 let mut new_path_cltv_deltas = cur_path_cltv_deltas.clone();
5301 new_path_cltv_deltas.push(next_cltv_expiry_delta);
5302 candidates.push_back((*next_id, new_path_cltv_deltas));
5311 path_plausibility.push(found_plausible_candidate);
5313 assert!(path_plausibility.iter().all(|x| *x));
5316 #[cfg(not(feature = "no-std"))]
5317 pub(super) fn random_init_seed() -> u64 {
5318 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
5319 use core::hash::{BuildHasher, Hasher};
5320 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
5321 println!("Using seed of {}", seed);
5324 #[cfg(not(feature = "no-std"))]
5325 use util::ser::Readable;
5328 #[cfg(not(feature = "no-std"))]
5329 fn generate_routes() {
5330 use routing::scoring::{ProbabilisticScorer, ProbabilisticScoringParameters};
5332 let mut d = match super::test_utils::get_route_file() {
5339 let graph = NetworkGraph::read(&mut d).unwrap();
5340 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5341 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5343 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
5344 let mut seed = random_init_seed() as usize;
5345 let nodes = graph.read_only().nodes().clone();
5346 'load_endpoints: for _ in 0..10 {
5348 seed = seed.overflowing_mul(0xdeadbeef).0;
5349 let src = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5350 seed = seed.overflowing_mul(0xdeadbeef).0;
5351 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5352 let payment_params = PaymentParameters::from_node_id(dst);
5353 let amt = seed as u64 % 200_000_000;
5354 let params = ProbabilisticScoringParameters::default();
5355 let logger = test_utils::TestLogger::new();
5356 let scorer = ProbabilisticScorer::new(params, &graph, &logger);
5357 if get_route(src, &payment_params, &graph.read_only(), None, amt, 42, &logger, &scorer, &random_seed_bytes).is_ok() {
5358 continue 'load_endpoints;
5365 #[cfg(not(feature = "no-std"))]
5366 fn generate_routes_mpp() {
5367 use routing::scoring::{ProbabilisticScorer, ProbabilisticScoringParameters};
5369 let mut d = match super::test_utils::get_route_file() {
5376 let graph = NetworkGraph::read(&mut d).unwrap();
5377 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5378 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5380 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
5381 let mut seed = random_init_seed() as usize;
5382 let nodes = graph.read_only().nodes().clone();
5383 'load_endpoints: for _ in 0..10 {
5385 seed = seed.overflowing_mul(0xdeadbeef).0;
5386 let src = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5387 seed = seed.overflowing_mul(0xdeadbeef).0;
5388 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5389 let payment_params = PaymentParameters::from_node_id(dst).with_features(InvoiceFeatures::known());
5390 let amt = seed as u64 % 200_000_000;
5391 let params = ProbabilisticScoringParameters::default();
5392 let logger = test_utils::TestLogger::new();
5393 let scorer = ProbabilisticScorer::new(params, &graph, &logger);
5394 if get_route(src, &payment_params, &graph.read_only(), None, amt, 42, &logger, &scorer, &random_seed_bytes).is_ok() {
5395 continue 'load_endpoints;
5402 #[cfg(all(test, not(feature = "no-std")))]
5403 pub(crate) mod test_utils {
5405 /// Tries to open a network graph file, or panics with a URL to fetch it.
5406 pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
5407 let res = File::open("net_graph-2021-05-31.bin") // By default we're run in RL/lightning
5408 .or_else(|_| File::open("lightning/net_graph-2021-05-31.bin")) // We may be run manually in RL/
5409 .or_else(|_| { // Fall back to guessing based on the binary location
5410 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
5411 let mut path = std::env::current_exe().unwrap();
5412 path.pop(); // lightning-...
5414 path.pop(); // debug
5415 path.pop(); // target
5416 path.push("lightning");
5417 path.push("net_graph-2021-05-31.bin");
5418 eprintln!("{}", path.to_str().unwrap());
5421 .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");
5422 #[cfg(require_route_graph_test)]
5423 return Ok(res.unwrap());
5424 #[cfg(not(require_route_graph_test))]
5429 #[cfg(all(test, feature = "_bench_unstable", not(feature = "no-std")))]
5432 use bitcoin::hashes::Hash;
5433 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
5434 use chain::transaction::OutPoint;
5435 use chain::keysinterface::{KeysManager,KeysInterface};
5436 use ln::channelmanager::{ChannelCounterparty, ChannelDetails};
5437 use ln::features::{InitFeatures, InvoiceFeatures};
5438 use routing::scoring::{FixedPenaltyScorer, ProbabilisticScorer, ProbabilisticScoringParameters, Scorer};
5439 use util::logger::{Logger, Record};
5440 use util::test_utils::TestLogger;
5444 struct DummyLogger {}
5445 impl Logger for DummyLogger {
5446 fn log(&self, _record: &Record) {}
5449 fn read_network_graph() -> NetworkGraph {
5450 let mut d = test_utils::get_route_file().unwrap();
5451 NetworkGraph::read(&mut d).unwrap()
5454 fn payer_pubkey() -> PublicKey {
5455 let secp_ctx = Secp256k1::new();
5456 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
5460 fn first_hop(node_id: PublicKey) -> ChannelDetails {
5462 channel_id: [0; 32],
5463 counterparty: ChannelCounterparty {
5464 features: InitFeatures::known(),
5466 unspendable_punishment_reserve: 0,
5467 forwarding_info: None,
5468 outbound_htlc_minimum_msat: None,
5469 outbound_htlc_maximum_msat: None,
5471 funding_txo: Some(OutPoint {
5472 txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0
5475 short_channel_id: Some(1),
5476 inbound_scid_alias: None,
5477 channel_value_satoshis: 10_000_000,
5479 balance_msat: 10_000_000,
5480 outbound_capacity_msat: 10_000_000,
5481 next_outbound_htlc_limit_msat: 10_000_000,
5482 inbound_capacity_msat: 0,
5483 unspendable_punishment_reserve: None,
5484 confirmations_required: None,
5485 force_close_spend_delay: None,
5487 is_funding_locked: true,
5490 inbound_htlc_minimum_msat: None,
5491 inbound_htlc_maximum_msat: None,
5496 fn generate_routes_with_zero_penalty_scorer(bench: &mut Bencher) {
5497 let network_graph = read_network_graph();
5498 let scorer = FixedPenaltyScorer::with_penalty(0);
5499 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::empty());
5503 fn generate_mpp_routes_with_zero_penalty_scorer(bench: &mut Bencher) {
5504 let network_graph = read_network_graph();
5505 let scorer = FixedPenaltyScorer::with_penalty(0);
5506 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::known());
5510 fn generate_routes_with_default_scorer(bench: &mut Bencher) {
5511 let network_graph = read_network_graph();
5512 let scorer = Scorer::default();
5513 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::empty());
5517 fn generate_mpp_routes_with_default_scorer(bench: &mut Bencher) {
5518 let network_graph = read_network_graph();
5519 let scorer = Scorer::default();
5520 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::known());
5524 fn generate_routes_with_probabilistic_scorer(bench: &mut Bencher) {
5525 let logger = TestLogger::new();
5526 let network_graph = read_network_graph();
5527 let params = ProbabilisticScoringParameters::default();
5528 let scorer = ProbabilisticScorer::new(params, &network_graph, &logger);
5529 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::empty());
5533 fn generate_mpp_routes_with_probabilistic_scorer(bench: &mut Bencher) {
5534 let logger = TestLogger::new();
5535 let network_graph = read_network_graph();
5536 let params = ProbabilisticScoringParameters::default();
5537 let scorer = ProbabilisticScorer::new(params, &network_graph, &logger);
5538 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::known());
5541 fn generate_routes<S: Score>(
5542 bench: &mut Bencher, graph: &NetworkGraph, mut scorer: S, features: InvoiceFeatures
5544 let nodes = graph.read_only().nodes().clone();
5545 let payer = payer_pubkey();
5546 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
5547 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5549 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
5550 let mut routes = Vec::new();
5551 let mut route_endpoints = Vec::new();
5552 let mut seed: usize = 0xdeadbeef;
5553 'load_endpoints: for _ in 0..150 {
5556 let src = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5558 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5559 let params = PaymentParameters::from_node_id(dst).with_features(features.clone());
5560 let first_hop = first_hop(src);
5561 let amt = seed as u64 % 1_000_000;
5562 if let Ok(route) = get_route(&payer, ¶ms, &graph.read_only(), Some(&[&first_hop]), amt, 42, &DummyLogger{}, &scorer, &random_seed_bytes) {
5564 route_endpoints.push((first_hop, params, amt));
5565 continue 'load_endpoints;
5570 // ...and seed the scorer with success and failure data...
5571 for route in routes {
5572 let amount = route.get_total_amount();
5573 if amount < 250_000 {
5574 for path in route.paths {
5575 scorer.payment_path_successful(&path.iter().collect::<Vec<_>>());
5577 } else if amount > 750_000 {
5578 for path in route.paths {
5579 let short_channel_id = path[path.len() / 2].short_channel_id;
5580 scorer.payment_path_failed(&path.iter().collect::<Vec<_>>(), short_channel_id);
5585 // Because we've changed channel scores, its possible we'll take different routes to the
5586 // selected destinations, possibly causing us to fail because, eg, the newly-selected path
5587 // requires a too-high CLTV delta.
5588 route_endpoints.retain(|(first_hop, params, amt)| {
5589 get_route(&payer, params, &graph.read_only(), Some(&[first_hop]), *amt, 42, &DummyLogger{}, &scorer, &random_seed_bytes).is_ok()
5591 route_endpoints.truncate(100);
5592 assert_eq!(route_endpoints.len(), 100);
5594 // ...then benchmark finding paths between the nodes we learned.
5597 let (first_hop, params, amt) = &route_endpoints[idx % route_endpoints.len()];
5598 assert!(get_route(&payer, params, &graph.read_only(), Some(&[first_hop]), *amt, 42, &DummyLogger{}, &scorer, &random_seed_bytes).is_ok());