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 P2PGossipSync and use that as your RoutingMessageHandler and then
13 //! interrogate it to get routes for your own payments.
15 use bitcoin::secp256k1::PublicKey;
17 use crate::ln::PaymentHash;
18 use crate::ln::channelmanager::{ChannelDetails, PaymentId};
19 use crate::ln::features::{ChannelFeatures, InvoiceFeatures, NodeFeatures};
20 use crate::ln::msgs::{DecodeError, ErrorAction, LightningError, MAX_VALUE_MSAT};
21 use crate::routing::gossip::{DirectedChannelInfo, EffectiveCapacity, ReadOnlyNetworkGraph, NetworkGraph, NodeId, RoutingFees};
22 use crate::routing::scoring::{ChannelUsage, Score};
23 use crate::util::ser::{Writeable, Readable, Writer};
24 use crate::util::logger::{Level, Logger};
25 use crate::util::chacha20::ChaCha20;
28 use crate::prelude::*;
29 use alloc::collections::BinaryHeap;
33 /// A trait defining behavior for routing a payment.
35 /// Finds a [`Route`] between `payer` and `payee` for a payment with the given values.
37 &self, payer: &PublicKey, route_params: &RouteParameters,
38 first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: InFlightHtlcs
39 ) -> Result<Route, LightningError>;
40 /// Finds a [`Route`] between `payer` and `payee` for a payment with the given values. Includes
41 /// `PaymentHash` and `PaymentId` to be able to correlate the request with a specific payment.
42 fn find_route_with_id(
43 &self, payer: &PublicKey, route_params: &RouteParameters,
44 first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: InFlightHtlcs,
45 _payment_hash: PaymentHash, _payment_id: PaymentId
46 ) -> Result<Route, LightningError> {
47 self.find_route(payer, route_params, first_hops, inflight_htlcs)
49 /// Lets the router know that payment through a specific path has failed.
50 fn notify_payment_path_failed(&self, path: &[&RouteHop], short_channel_id: u64);
51 /// Lets the router know that payment through a specific path was successful.
52 fn notify_payment_path_successful(&self, path: &[&RouteHop]);
53 /// Lets the router know that a payment probe was successful.
54 fn notify_payment_probe_successful(&self, path: &[&RouteHop]);
55 /// Lets the router know that a payment probe failed.
56 fn notify_payment_probe_failed(&self, path: &[&RouteHop], short_channel_id: u64);
59 /// A data structure for tracking in-flight HTLCs. May be used during pathfinding to account for
60 /// in-use channel liquidity.
61 pub struct InFlightHtlcs(
62 // A map with liquidity value (in msat) keyed by a short channel id and the direction the HTLC
63 // is traveling in. The direction boolean is determined by checking if the HTLC source's public
64 // key is less than its destination. See `InFlightHtlcs::used_liquidity_msat` for more
66 HashMap<(u64, bool), u64>
70 /// Constructs an empty `InFlightHtlcs`.
71 pub fn new() -> Self { InFlightHtlcs(HashMap::new()) }
73 /// Takes in a path with payer's node id and adds the path's details to `InFlightHtlcs`.
74 pub fn process_path(&mut self, path: &[RouteHop], payer_node_id: PublicKey) {
75 if path.is_empty() { return };
76 // total_inflight_map needs to be direction-sensitive when keeping track of the HTLC value
77 // that is held up. However, the `hops` array, which is a path returned by `find_route` in
78 // the router excludes the payer node. In the following lines, the payer's information is
79 // hardcoded with an inflight value of 0 so that we can correctly represent the first hop
80 // in our sliding window of two.
81 let reversed_hops_with_payer = path.iter().rev().skip(1)
82 .map(|hop| hop.pubkey)
83 .chain(core::iter::once(payer_node_id));
84 let mut cumulative_msat = 0;
86 // Taking the reversed vector from above, we zip it with just the reversed hops list to
87 // work "backwards" of the given path, since the last hop's `fee_msat` actually represents
88 // the total amount sent.
89 for (next_hop, prev_hop) in path.iter().rev().zip(reversed_hops_with_payer) {
90 cumulative_msat += next_hop.fee_msat;
92 .entry((next_hop.short_channel_id, NodeId::from_pubkey(&prev_hop) < NodeId::from_pubkey(&next_hop.pubkey)))
93 .and_modify(|used_liquidity_msat| *used_liquidity_msat += cumulative_msat)
94 .or_insert(cumulative_msat);
98 /// Returns liquidity in msat given the public key of the HTLC source, target, and short channel
100 pub fn used_liquidity_msat(&self, source: &NodeId, target: &NodeId, channel_scid: u64) -> Option<u64> {
101 self.0.get(&(channel_scid, source < target)).map(|v| *v)
105 impl Writeable for InFlightHtlcs {
106 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> { self.0.write(writer) }
109 impl Readable for InFlightHtlcs {
110 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
111 let infight_map: HashMap<(u64, bool), u64> = Readable::read(reader)?;
112 Ok(Self(infight_map))
117 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
118 pub struct RouteHop {
119 /// The node_id of the node at this hop.
120 pub pubkey: PublicKey,
121 /// The node_announcement features of the node at this hop. For the last hop, these may be
122 /// amended to match the features present in the invoice this node generated.
123 pub node_features: NodeFeatures,
124 /// The channel that should be used from the previous hop to reach this node.
125 pub short_channel_id: u64,
126 /// The channel_announcement features of the channel that should be used from the previous hop
127 /// to reach this node.
128 pub channel_features: ChannelFeatures,
129 /// The fee taken on this hop (for paying for the use of the *next* channel in the path).
130 /// For the last hop, this should be the full value of the payment (might be more than
131 /// requested if we had to match htlc_minimum_msat).
133 /// The CLTV delta added for this hop. For the last hop, this should be the full CLTV value
134 /// expected at the destination, in excess of the current block height.
135 pub cltv_expiry_delta: u32,
138 impl_writeable_tlv_based!(RouteHop, {
139 (0, pubkey, required),
140 (2, node_features, required),
141 (4, short_channel_id, required),
142 (6, channel_features, required),
143 (8, fee_msat, required),
144 (10, cltv_expiry_delta, required),
147 /// A route directs a payment from the sender (us) to the recipient. If the recipient supports MPP,
148 /// it can take multiple paths. Each path is composed of one or more hops through the network.
149 #[derive(Clone, Hash, PartialEq, Eq)]
151 /// The list of routes taken for a single (potentially-)multi-part payment. The pubkey of the
152 /// last RouteHop in each path must be the same. Each entry represents a list of hops, NOT
153 /// INCLUDING our own, where the last hop is the destination. Thus, this must always be at
154 /// least length one. While the maximum length of any given path is variable, keeping the length
155 /// of any path less or equal to 19 should currently ensure it is viable.
156 pub paths: Vec<Vec<RouteHop>>,
157 /// The `payment_params` parameter passed to [`find_route`].
158 /// This is used by `ChannelManager` to track information which may be required for retries,
159 /// provided back to you via [`Event::PaymentPathFailed`].
161 /// [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed
162 pub payment_params: Option<PaymentParameters>,
165 pub(crate) trait RoutePath {
166 /// Gets the fees for a given path, excluding any excess paid to the recipient.
167 fn get_path_fees(&self) -> u64;
169 impl RoutePath for Vec<RouteHop> {
170 fn get_path_fees(&self) -> u64 {
171 // Do not count last hop of each path since that's the full value of the payment
172 self.split_last().map(|(_, path_prefix)| path_prefix).unwrap_or(&[])
173 .iter().map(|hop| &hop.fee_msat)
179 /// Returns the total amount of fees paid on this [`Route`].
181 /// This doesn't include any extra payment made to the recipient, which can happen in excess of
182 /// the amount passed to [`find_route`]'s `params.final_value_msat`.
183 pub fn get_total_fees(&self) -> u64 {
184 self.paths.iter().map(|path| path.get_path_fees()).sum()
187 /// Returns the total amount paid on this [`Route`], excluding the fees.
188 pub fn get_total_amount(&self) -> u64 {
189 return self.paths.iter()
190 .map(|path| path.split_last().map(|(hop, _)| hop.fee_msat).unwrap_or(0))
195 const SERIALIZATION_VERSION: u8 = 1;
196 const MIN_SERIALIZATION_VERSION: u8 = 1;
198 impl Writeable for Route {
199 fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
200 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
201 (self.paths.len() as u64).write(writer)?;
202 for hops in self.paths.iter() {
203 (hops.len() as u8).write(writer)?;
204 for hop in hops.iter() {
208 write_tlv_fields!(writer, {
209 (1, self.payment_params, option),
215 impl Readable for Route {
216 fn read<R: io::Read>(reader: &mut R) -> Result<Route, DecodeError> {
217 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
218 let path_count: u64 = Readable::read(reader)?;
219 let mut paths = Vec::with_capacity(cmp::min(path_count, 128) as usize);
220 for _ in 0..path_count {
221 let hop_count: u8 = Readable::read(reader)?;
222 let mut hops = Vec::with_capacity(hop_count as usize);
223 for _ in 0..hop_count {
224 hops.push(Readable::read(reader)?);
228 let mut payment_params = None;
229 read_tlv_fields!(reader, {
230 (1, payment_params, option),
232 Ok(Route { paths, payment_params })
236 /// Parameters needed to find a [`Route`].
238 /// Passed to [`find_route`] and [`build_route_from_hops`], but also provided in
239 /// [`Event::PaymentPathFailed`] for retrying a failed payment path.
241 /// [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed
242 #[derive(Clone, Debug)]
243 pub struct RouteParameters {
244 /// The parameters of the failed payment path.
245 pub payment_params: PaymentParameters,
247 /// The amount in msats sent on the failed payment path.
248 pub final_value_msat: u64,
250 /// The CLTV on the final hop of the failed payment path.
251 pub final_cltv_expiry_delta: u32,
254 impl_writeable_tlv_based!(RouteParameters, {
255 (0, payment_params, required),
256 (2, final_value_msat, required),
257 (4, final_cltv_expiry_delta, required),
260 /// Maximum total CTLV difference we allow for a full payment path.
261 pub const DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA: u32 = 1008;
263 /// Maximum number of paths we allow an (MPP) payment to have.
264 // The default limit is currently set rather arbitrary - there aren't any real fundamental path-count
265 // limits, but for now more than 10 paths likely carries too much one-path failure.
266 pub const DEFAULT_MAX_PATH_COUNT: u8 = 10;
268 // The median hop CLTV expiry delta currently seen in the network.
269 const MEDIAN_HOP_CLTV_EXPIRY_DELTA: u32 = 40;
271 // During routing, we only consider paths shorter than our maximum length estimate.
272 // In the TLV onion format, there is no fixed maximum length, but the `hop_payloads`
273 // field is always 1300 bytes. As the `tlv_payload` for each hop may vary in length, we have to
274 // estimate how many hops the route may have so that it actually fits the `hop_payloads` field.
276 // We estimate 3+32 (payload length and HMAC) + 2+8 (amt_to_forward) + 2+4 (outgoing_cltv_value) +
277 // 2+8 (short_channel_id) = 61 bytes for each intermediate hop and 3+32
278 // (payload length and HMAC) + 2+8 (amt_to_forward) + 2+4 (outgoing_cltv_value) + 2+32+8
279 // (payment_secret and total_msat) = 93 bytes for the final hop.
280 // Since the length of the potentially included `payment_metadata` is unknown to us, we round
281 // down from (1300-93) / 61 = 19.78... to arrive at a conservative estimate of 19.
282 const MAX_PATH_LENGTH_ESTIMATE: u8 = 19;
284 /// The recipient of a payment.
285 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
286 pub struct PaymentParameters {
287 /// The node id of the payee.
288 pub payee_pubkey: PublicKey,
290 /// Features supported by the payee.
292 /// May be set from the payee's invoice or via [`for_keysend`]. May be `None` if the invoice
293 /// does not contain any features.
295 /// [`for_keysend`]: Self::for_keysend
296 pub features: Option<InvoiceFeatures>,
298 /// Hints for routing to the payee, containing channels connecting the payee to public nodes.
299 pub route_hints: Vec<RouteHint>,
301 /// Expiration of a payment to the payee, in seconds relative to the UNIX epoch.
302 pub expiry_time: Option<u64>,
304 /// The maximum total CLTV delta we accept for the route.
305 /// Defaults to [`DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA`].
306 pub max_total_cltv_expiry_delta: u32,
308 /// The maximum number of paths that may be used by (MPP) payments.
309 /// Defaults to [`DEFAULT_MAX_PATH_COUNT`].
310 pub max_path_count: u8,
312 /// Selects the maximum share of a channel's total capacity which will be sent over a channel,
313 /// as a power of 1/2. A higher value prefers to send the payment using more MPP parts whereas
314 /// a lower value prefers to send larger MPP parts, potentially saturating channels and
315 /// increasing failure probability for those paths.
317 /// Note that this restriction will be relaxed during pathfinding after paths which meet this
318 /// restriction have been found. While paths which meet this criteria will be searched for, it
319 /// is ultimately up to the scorer to select them over other paths.
321 /// A value of 0 will allow payments up to and including a channel's total announced usable
322 /// capacity, a value of one will only use up to half its capacity, two 1/4, etc.
325 pub max_channel_saturation_power_of_half: u8,
327 /// A list of SCIDs which this payment was previously attempted over and which caused the
328 /// payment to fail. Future attempts for the same payment shouldn't be relayed through any of
330 pub previously_failed_channels: Vec<u64>,
333 impl_writeable_tlv_based!(PaymentParameters, {
334 (0, payee_pubkey, required),
335 (1, max_total_cltv_expiry_delta, (default_value, DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA)),
336 (2, features, option),
337 (3, max_path_count, (default_value, DEFAULT_MAX_PATH_COUNT)),
338 (4, route_hints, vec_type),
339 (5, max_channel_saturation_power_of_half, (default_value, 2)),
340 (6, expiry_time, option),
341 (7, previously_failed_channels, vec_type),
344 impl PaymentParameters {
345 /// Creates a payee with the node id of the given `pubkey`.
346 pub fn from_node_id(payee_pubkey: PublicKey) -> Self {
352 max_total_cltv_expiry_delta: DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA,
353 max_path_count: DEFAULT_MAX_PATH_COUNT,
354 max_channel_saturation_power_of_half: 2,
355 previously_failed_channels: Vec::new(),
359 /// Creates a payee with the node id of the given `pubkey` to use for keysend payments.
360 pub fn for_keysend(payee_pubkey: PublicKey) -> Self {
361 Self::from_node_id(payee_pubkey).with_features(InvoiceFeatures::for_keysend())
364 /// Includes the payee's features.
366 /// (C-not exported) since bindings don't support move semantics
367 pub fn with_features(self, features: InvoiceFeatures) -> Self {
368 Self { features: Some(features), ..self }
371 /// Includes hints for routing to the payee.
373 /// (C-not exported) since bindings don't support move semantics
374 pub fn with_route_hints(self, route_hints: Vec<RouteHint>) -> Self {
375 Self { route_hints, ..self }
378 /// Includes a payment expiration in seconds relative to the UNIX epoch.
380 /// (C-not exported) since bindings don't support move semantics
381 pub fn with_expiry_time(self, expiry_time: u64) -> Self {
382 Self { expiry_time: Some(expiry_time), ..self }
385 /// Includes a limit for the total CLTV expiry delta which is considered during routing
387 /// (C-not exported) since bindings don't support move semantics
388 pub fn with_max_total_cltv_expiry_delta(self, max_total_cltv_expiry_delta: u32) -> Self {
389 Self { max_total_cltv_expiry_delta, ..self }
392 /// Includes a limit for the maximum number of payment paths that may be used.
394 /// (C-not exported) since bindings don't support move semantics
395 pub fn with_max_path_count(self, max_path_count: u8) -> Self {
396 Self { max_path_count, ..self }
399 /// Includes a limit for the maximum number of payment paths that may be used.
401 /// (C-not exported) since bindings don't support move semantics
402 pub fn with_max_channel_saturation_power_of_half(self, max_channel_saturation_power_of_half: u8) -> Self {
403 Self { max_channel_saturation_power_of_half, ..self }
407 /// A list of hops along a payment path terminating with a channel to the recipient.
408 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
409 pub struct RouteHint(pub Vec<RouteHintHop>);
411 impl Writeable for RouteHint {
412 fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
413 (self.0.len() as u64).write(writer)?;
414 for hop in self.0.iter() {
421 impl Readable for RouteHint {
422 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
423 let hop_count: u64 = Readable::read(reader)?;
424 let mut hops = Vec::with_capacity(cmp::min(hop_count, 16) as usize);
425 for _ in 0..hop_count {
426 hops.push(Readable::read(reader)?);
432 /// A channel descriptor for a hop along a payment path.
433 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
434 pub struct RouteHintHop {
435 /// The node_id of the non-target end of the route
436 pub src_node_id: PublicKey,
437 /// The short_channel_id of this channel
438 pub short_channel_id: u64,
439 /// The fees which must be paid to use this channel
440 pub fees: RoutingFees,
441 /// The difference in CLTV values between this node and the next node.
442 pub cltv_expiry_delta: u16,
443 /// The minimum value, in msat, which must be relayed to the next hop.
444 pub htlc_minimum_msat: Option<u64>,
445 /// The maximum value in msat available for routing with a single HTLC.
446 pub htlc_maximum_msat: Option<u64>,
449 impl_writeable_tlv_based!(RouteHintHop, {
450 (0, src_node_id, required),
451 (1, htlc_minimum_msat, option),
452 (2, short_channel_id, required),
453 (3, htlc_maximum_msat, option),
455 (6, cltv_expiry_delta, required),
458 #[derive(Eq, PartialEq)]
459 struct RouteGraphNode {
461 lowest_fee_to_peer_through_node: u64,
462 lowest_fee_to_node: u64,
463 total_cltv_delta: u32,
464 // The maximum value a yet-to-be-constructed payment path might flow through this node.
465 // This value is upper-bounded by us by:
466 // - how much is needed for a path being constructed
467 // - how much value can channels following this node (up to the destination) can contribute,
468 // considering their capacity and fees
469 value_contribution_msat: u64,
470 /// The effective htlc_minimum_msat at this hop. If a later hop on the path had a higher HTLC
471 /// minimum, we use it, plus the fees required at each earlier hop to meet it.
472 path_htlc_minimum_msat: u64,
473 /// All penalties incurred from this hop on the way to the destination, as calculated using
475 path_penalty_msat: u64,
476 /// The number of hops walked up to this node.
477 path_length_to_node: u8,
480 impl cmp::Ord for RouteGraphNode {
481 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
482 let other_score = cmp::max(other.lowest_fee_to_peer_through_node, other.path_htlc_minimum_msat)
483 .saturating_add(other.path_penalty_msat);
484 let self_score = cmp::max(self.lowest_fee_to_peer_through_node, self.path_htlc_minimum_msat)
485 .saturating_add(self.path_penalty_msat);
486 other_score.cmp(&self_score).then_with(|| other.node_id.cmp(&self.node_id))
490 impl cmp::PartialOrd for RouteGraphNode {
491 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
492 Some(self.cmp(other))
496 /// A wrapper around the various hop representations.
498 /// Used to construct a [`PathBuildingHop`] and to estimate [`EffectiveCapacity`].
499 #[derive(Clone, Debug)]
500 enum CandidateRouteHop<'a> {
501 /// A hop from the payer, where the outbound liquidity is known.
503 details: &'a ChannelDetails,
505 /// A hop found in the [`ReadOnlyNetworkGraph`], where the channel capacity may be unknown.
507 info: DirectedChannelInfo<'a>,
508 short_channel_id: u64,
510 /// A hop to the payee found in the payment invoice, though not necessarily a direct channel.
512 hint: &'a RouteHintHop,
516 impl<'a> CandidateRouteHop<'a> {
517 fn short_channel_id(&self) -> u64 {
519 CandidateRouteHop::FirstHop { details } => details.get_outbound_payment_scid().unwrap(),
520 CandidateRouteHop::PublicHop { short_channel_id, .. } => *short_channel_id,
521 CandidateRouteHop::PrivateHop { hint } => hint.short_channel_id,
525 // NOTE: This may alloc memory so avoid calling it in a hot code path.
526 fn features(&self) -> ChannelFeatures {
528 CandidateRouteHop::FirstHop { details } => details.counterparty.features.to_context(),
529 CandidateRouteHop::PublicHop { info, .. } => info.channel().features.clone(),
530 CandidateRouteHop::PrivateHop { .. } => ChannelFeatures::empty(),
534 fn cltv_expiry_delta(&self) -> u32 {
536 CandidateRouteHop::FirstHop { .. } => 0,
537 CandidateRouteHop::PublicHop { info, .. } => info.direction().cltv_expiry_delta as u32,
538 CandidateRouteHop::PrivateHop { hint } => hint.cltv_expiry_delta as u32,
542 fn htlc_minimum_msat(&self) -> u64 {
544 CandidateRouteHop::FirstHop { .. } => 0,
545 CandidateRouteHop::PublicHop { info, .. } => info.direction().htlc_minimum_msat,
546 CandidateRouteHop::PrivateHop { hint } => hint.htlc_minimum_msat.unwrap_or(0),
550 fn fees(&self) -> RoutingFees {
552 CandidateRouteHop::FirstHop { .. } => RoutingFees {
553 base_msat: 0, proportional_millionths: 0,
555 CandidateRouteHop::PublicHop { info, .. } => info.direction().fees,
556 CandidateRouteHop::PrivateHop { hint } => hint.fees,
560 fn effective_capacity(&self) -> EffectiveCapacity {
562 CandidateRouteHop::FirstHop { details } => EffectiveCapacity::ExactLiquidity {
563 liquidity_msat: details.next_outbound_htlc_limit_msat,
565 CandidateRouteHop::PublicHop { info, .. } => info.effective_capacity(),
566 CandidateRouteHop::PrivateHop { .. } => EffectiveCapacity::Infinite,
572 fn max_htlc_from_capacity(capacity: EffectiveCapacity, max_channel_saturation_power_of_half: u8) -> u64 {
573 let saturation_shift: u32 = max_channel_saturation_power_of_half as u32;
575 EffectiveCapacity::ExactLiquidity { liquidity_msat } => liquidity_msat,
576 EffectiveCapacity::Infinite => u64::max_value(),
577 EffectiveCapacity::Unknown => EffectiveCapacity::Unknown.as_msat(),
578 EffectiveCapacity::MaximumHTLC { amount_msat } =>
579 amount_msat.checked_shr(saturation_shift).unwrap_or(0),
580 EffectiveCapacity::Total { capacity_msat, htlc_maximum_msat } =>
581 cmp::min(capacity_msat.checked_shr(saturation_shift).unwrap_or(0), htlc_maximum_msat),
585 fn iter_equal<I1: Iterator, I2: Iterator>(mut iter_a: I1, mut iter_b: I2)
586 -> bool where I1::Item: PartialEq<I2::Item> {
588 let a = iter_a.next();
589 let b = iter_b.next();
590 if a.is_none() && b.is_none() { return true; }
591 if a.is_none() || b.is_none() { return false; }
592 if a.unwrap().ne(&b.unwrap()) { return false; }
596 /// It's useful to keep track of the hops associated with the fees required to use them,
597 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
598 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
599 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
601 struct PathBuildingHop<'a> {
602 // Note that this should be dropped in favor of loading it from CandidateRouteHop, but doing so
603 // is a larger refactor and will require careful performance analysis.
605 candidate: CandidateRouteHop<'a>,
608 /// Minimal fees required to route to the source node of the current hop via any of its inbound channels.
609 src_lowest_inbound_fees: RoutingFees,
610 /// All the fees paid *after* this channel on the way to the destination
611 next_hops_fee_msat: u64,
612 /// Fee paid for the use of the current channel (see candidate.fees()).
613 /// The value will be actually deducted from the counterparty balance on the previous link.
614 hop_use_fee_msat: u64,
615 /// Used to compare channels when choosing the for routing.
616 /// Includes paying for the use of a hop and the following hops, as well as
617 /// an estimated cost of reaching this hop.
618 /// Might get stale when fees are recomputed. Primarily for internal use.
620 /// A mirror of the same field in RouteGraphNode. Note that this is only used during the graph
621 /// walk and may be invalid thereafter.
622 path_htlc_minimum_msat: u64,
623 /// All penalties incurred from this channel on the way to the destination, as calculated using
625 path_penalty_msat: u64,
626 /// If we've already processed a node as the best node, we shouldn't process it again. Normally
627 /// we'd just ignore it if we did as all channels would have a higher new fee, but because we
628 /// may decrease the amounts in use as we walk the graph, the actual calculated fee may
629 /// decrease as well. Thus, we have to explicitly track which nodes have been processed and
630 /// avoid processing them again.
632 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
633 // In tests, we apply further sanity checks on cases where we skip nodes we already processed
634 // to ensure it is specifically in cases where the fee has gone down because of a decrease in
635 // value_contribution_msat, which requires tracking it here. See comments below where it is
636 // used for more info.
637 value_contribution_msat: u64,
640 impl<'a> core::fmt::Debug for PathBuildingHop<'a> {
641 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
642 let mut debug_struct = f.debug_struct("PathBuildingHop");
644 .field("node_id", &self.node_id)
645 .field("short_channel_id", &self.candidate.short_channel_id())
646 .field("total_fee_msat", &self.total_fee_msat)
647 .field("next_hops_fee_msat", &self.next_hops_fee_msat)
648 .field("hop_use_fee_msat", &self.hop_use_fee_msat)
649 .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)))
650 .field("path_penalty_msat", &self.path_penalty_msat)
651 .field("path_htlc_minimum_msat", &self.path_htlc_minimum_msat)
652 .field("cltv_expiry_delta", &self.candidate.cltv_expiry_delta());
653 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
654 let debug_struct = debug_struct
655 .field("value_contribution_msat", &self.value_contribution_msat);
656 debug_struct.finish()
660 // Instantiated with a list of hops with correct data in them collected during path finding,
661 // an instance of this struct should be further modified only via given methods.
663 struct PaymentPath<'a> {
664 hops: Vec<(PathBuildingHop<'a>, NodeFeatures)>,
667 impl<'a> PaymentPath<'a> {
668 // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
669 fn get_value_msat(&self) -> u64 {
670 self.hops.last().unwrap().0.fee_msat
673 fn get_path_penalty_msat(&self) -> u64 {
674 self.hops.first().map(|h| h.0.path_penalty_msat).unwrap_or(u64::max_value())
677 fn get_total_fee_paid_msat(&self) -> u64 {
678 if self.hops.len() < 1 {
682 // Can't use next_hops_fee_msat because it gets outdated.
683 for (i, (hop, _)) in self.hops.iter().enumerate() {
684 if i != self.hops.len() - 1 {
685 result += hop.fee_msat;
691 fn get_cost_msat(&self) -> u64 {
692 self.get_total_fee_paid_msat().saturating_add(self.get_path_penalty_msat())
695 // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
696 // to change fees may result in an inconsistency.
698 // Sometimes we call this function right after constructing a path which is inconsistent in
699 // that it the value being transferred has decreased while we were doing path finding, leading
700 // to the fees being paid not lining up with the actual limits.
702 // Note that this function is not aware of the available_liquidity limit, and thus does not
703 // support increasing the value being transferred beyond what was selected during the initial
705 fn update_value_and_recompute_fees(&mut self, value_msat: u64) {
706 let mut total_fee_paid_msat = 0 as u64;
707 for i in (0..self.hops.len()).rev() {
708 let last_hop = i == self.hops.len() - 1;
710 // For non-last-hop, this value will represent the fees paid on the current hop. It
711 // will consist of the fees for the use of the next hop, and extra fees to match
712 // htlc_minimum_msat of the current channel. Last hop is handled separately.
713 let mut cur_hop_fees_msat = 0;
715 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().0.hop_use_fee_msat;
718 let mut cur_hop = &mut self.hops.get_mut(i).unwrap().0;
719 cur_hop.next_hops_fee_msat = total_fee_paid_msat;
720 // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
721 // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
722 // set it too high just to maliciously take more fees by exploiting this
723 // match htlc_minimum_msat logic.
724 let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
725 if let Some(extra_fees_msat) = cur_hop.candidate.htlc_minimum_msat().checked_sub(cur_hop_transferred_amount_msat) {
726 // Note that there is a risk that *previous hops* (those closer to us, as we go
727 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
729 // This might make us end up with a broken route, although this should be super-rare
730 // in practice, both because of how healthy channels look like, and how we pick
731 // channels in add_entry.
732 // Also, this can't be exploited more heavily than *announce a free path and fail
734 cur_hop_transferred_amount_msat += extra_fees_msat;
735 total_fee_paid_msat += extra_fees_msat;
736 cur_hop_fees_msat += extra_fees_msat;
740 // Final hop is a special case: it usually has just value_msat (by design), but also
741 // it still could overpay for the htlc_minimum_msat.
742 cur_hop.fee_msat = cur_hop_transferred_amount_msat;
744 // Propagate updated fees for the use of the channels to one hop back, where they
745 // will be actually paid (fee_msat). The last hop is handled above separately.
746 cur_hop.fee_msat = cur_hop_fees_msat;
749 // Fee for the use of the current hop which will be deducted on the previous hop.
750 // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
751 // this channel is free for us.
753 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.candidate.fees()) {
754 cur_hop.hop_use_fee_msat = new_fee;
755 total_fee_paid_msat += new_fee;
757 // It should not be possible because this function is called only to reduce the
758 // value. In that case, compute_fee was already called with the same fees for
759 // larger amount and there was no overflow.
767 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
768 let proportional_fee_millions =
769 amount_msat.checked_mul(channel_fees.proportional_millionths as u64);
770 if let Some(new_fee) = proportional_fee_millions.and_then(|part| {
771 (channel_fees.base_msat as u64).checked_add(part / 1_000_000) }) {
775 // This function may be (indirectly) called without any verification,
776 // with channel_fees provided by a caller. We should handle it gracefully.
781 /// The default `features` we assume for a node in a route, when no `features` are known about that
784 /// Default features are:
785 /// * variable_length_onion_optional
786 fn default_node_features() -> NodeFeatures {
787 let mut features = NodeFeatures::empty();
788 features.set_variable_length_onion_optional();
792 /// Finds a route from us (payer) to the given target node (payee).
794 /// If the payee provided features in their invoice, they should be provided via `params.payee`.
795 /// Without this, MPP will only be used if the payee's features are available in the network graph.
797 /// Private routing paths between a public node and the target may be included in `params.payee`.
799 /// If some channels aren't announced, it may be useful to fill in `first_hops` with the results
800 /// from [`ChannelManager::list_usable_channels`]. If it is filled in, the view of these channels
801 /// from `network_graph` will be ignored, and only those in `first_hops` will be used.
803 /// The fees on channels from us to the next hop are ignored as they are assumed to all be equal.
804 /// However, the enabled/disabled bit on such channels as well as the `htlc_minimum_msat` /
805 /// `htlc_maximum_msat` *are* checked as they may change based on the receiving node.
809 /// May be used to re-compute a [`Route`] when handling a [`Event::PaymentPathFailed`]. Any
810 /// adjustments to the [`NetworkGraph`] and channel scores should be made prior to calling this
815 /// Panics if first_hops contains channels without short_channel_ids;
816 /// [`ChannelManager::list_usable_channels`] will never include such channels.
818 /// [`ChannelManager::list_usable_channels`]: crate::ln::channelmanager::ChannelManager::list_usable_channels
819 /// [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed
820 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
821 pub fn find_route<L: Deref, GL: Deref, S: Score>(
822 our_node_pubkey: &PublicKey, route_params: &RouteParameters,
823 network_graph: &NetworkGraph<GL>, first_hops: Option<&[&ChannelDetails]>, logger: L,
824 scorer: &S, random_seed_bytes: &[u8; 32]
825 ) -> Result<Route, LightningError>
826 where L::Target: Logger, GL::Target: Logger {
827 let graph_lock = network_graph.read_only();
828 let mut route = get_route(our_node_pubkey, &route_params.payment_params, &graph_lock, first_hops,
829 route_params.final_value_msat, route_params.final_cltv_expiry_delta, logger, scorer,
831 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
835 pub(crate) fn get_route<L: Deref, S: Score>(
836 our_node_pubkey: &PublicKey, payment_params: &PaymentParameters, network_graph: &ReadOnlyNetworkGraph,
837 first_hops: Option<&[&ChannelDetails]>, final_value_msat: u64, final_cltv_expiry_delta: u32,
838 logger: L, scorer: &S, _random_seed_bytes: &[u8; 32]
839 ) -> Result<Route, LightningError>
840 where L::Target: Logger {
841 let payee_node_id = NodeId::from_pubkey(&payment_params.payee_pubkey);
842 let our_node_id = NodeId::from_pubkey(&our_node_pubkey);
844 if payee_node_id == our_node_id {
845 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
848 if final_value_msat > MAX_VALUE_MSAT {
849 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
852 if final_value_msat == 0 {
853 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
856 for route in payment_params.route_hints.iter() {
857 for hop in &route.0 {
858 if hop.src_node_id == payment_params.payee_pubkey {
859 return Err(LightningError{err: "Route hint cannot have the payee as the source.".to_owned(), action: ErrorAction::IgnoreError});
863 if payment_params.max_total_cltv_expiry_delta <= final_cltv_expiry_delta {
864 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});
867 // The general routing idea is the following:
868 // 1. Fill first/last hops communicated by the caller.
869 // 2. Attempt to construct a path from payer to payee for transferring
870 // any ~sufficient (described later) value.
871 // If succeed, remember which channels were used and how much liquidity they have available,
872 // so that future paths don't rely on the same liquidity.
873 // 3. Proceed to the next step if:
874 // - we hit the recommended target value;
875 // - OR if we could not construct a new path. Any next attempt will fail too.
876 // Otherwise, repeat step 2.
877 // 4. See if we managed to collect paths which aggregately are able to transfer target value
878 // (not recommended value).
879 // 5. If yes, proceed. If not, fail routing.
880 // 6. Select the paths which have the lowest cost (fee plus scorer penalty) per amount
881 // transferred up to the transfer target value.
882 // 7. Reduce the value of the last path until we are sending only the target value.
883 // 8. If our maximum channel saturation limit caused us to pick two identical paths, combine
884 // them so that we're not sending two HTLCs along the same path.
886 // As for the actual search algorithm,
887 // we do a payee-to-payer pseudo-Dijkstra's sorting by each node's distance from the payee
888 // plus the minimum per-HTLC fee to get from it to another node (aka "shitty pseudo-A*").
890 // We are not a faithful Dijkstra's implementation because we can change values which impact
891 // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
892 // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) than
893 // the value we are currently attempting to send over a path, we simply reduce the value being
894 // sent along the path for any hops after that channel. This may imply that later fees (which
895 // we've already tabulated) are lower because a smaller value is passing through the channels
896 // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
897 // channels which were selected earlier (and which may still be used for other paths without a
898 // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
901 // One potentially problematic case for this algorithm would be if there are many
902 // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
903 // graph walking), we may never find a path which is not liquidity-limited and has lower
904 // proportional fee (and only lower absolute fee when considering the ultimate value sent).
905 // Because we only consider paths with at least 5% of the total value being sent, the damage
906 // from such a case should be limited, however this could be further reduced in the future by
907 // calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
908 // limits for the purposes of fee calculation.
910 // Alternatively, we could store more detailed path information in the heap (targets, below)
911 // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
912 // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
913 // and practically (as we would need to store dynamically-allocated path information in heap
914 // objects, increasing malloc traffic and indirect memory access significantly). Further, the
915 // results of such an algorithm would likely be biased towards lower-value paths.
917 // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
918 // outside of our current search value, running a path search more times to gather candidate
919 // paths at different values. While this may be acceptable, further path searches may increase
920 // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
921 // graph for candidate paths, calculating the maximum value which can realistically be sent at
922 // the same time, remaining generic across different payment values.
924 // TODO: There are a few tweaks we could do, including possibly pre-calculating more stuff
925 // to use as the A* heuristic beyond just the cost to get one node further than the current
928 let network_channels = network_graph.channels();
929 let network_nodes = network_graph.nodes();
931 if payment_params.max_path_count == 0 {
932 return Err(LightningError{err: "Can't find a route with no paths allowed.".to_owned(), action: ErrorAction::IgnoreError});
935 // Allow MPP only if we have a features set from somewhere that indicates the payee supports
936 // it. If the payee supports it they're supposed to include it in the invoice, so that should
938 let allow_mpp = if payment_params.max_path_count == 1 {
940 } else if let Some(features) = &payment_params.features {
941 features.supports_basic_mpp()
942 } else if let Some(node) = network_nodes.get(&payee_node_id) {
943 if let Some(node_info) = node.announcement_info.as_ref() {
944 node_info.features.supports_basic_mpp()
948 log_trace!(logger, "Searching for a route from payer {} to payee {} {} MPP and {} first hops {}overriding the network graph", our_node_pubkey,
949 payment_params.payee_pubkey, if allow_mpp { "with" } else { "without" },
950 first_hops.map(|hops| hops.len()).unwrap_or(0), if first_hops.is_some() { "" } else { "not " });
953 // Prepare the data we'll use for payee-to-payer search by
954 // inserting first hops suggested by the caller as targets.
955 // Our search will then attempt to reach them while traversing from the payee node.
956 let mut first_hop_targets: HashMap<_, Vec<&ChannelDetails>> =
957 HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
958 if let Some(hops) = first_hops {
960 if chan.get_outbound_payment_scid().is_none() {
961 panic!("first_hops should be filled in with usable channels, not pending ones");
963 if chan.counterparty.node_id == *our_node_pubkey {
964 return Err(LightningError{err: "First hop cannot have our_node_pubkey as a destination.".to_owned(), action: ErrorAction::IgnoreError});
967 .entry(NodeId::from_pubkey(&chan.counterparty.node_id))
968 .or_insert(Vec::new())
971 if first_hop_targets.is_empty() {
972 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
976 // The main heap containing all candidate next-hops sorted by their score (max(A* fee,
977 // htlc_minimum)). Ideally this would be a heap which allowed cheap score reduction instead of
978 // adding duplicate entries when we find a better path to a given node.
979 let mut targets: BinaryHeap<RouteGraphNode> = BinaryHeap::new();
981 // Map from node_id to information about the best current path to that node, including feerate
983 let mut dist: HashMap<NodeId, PathBuildingHop> = HashMap::with_capacity(network_nodes.len());
985 // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
986 // indicating that we may wish to try again with a higher value, potentially paying to meet an
987 // htlc_minimum with extra fees while still finding a cheaper path.
988 let mut hit_minimum_limit;
990 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
991 // We start with a path_value of the exact amount we want, and if that generates a route we may
992 // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
993 // amount we want in total across paths, selecting the best subset at the end.
994 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
995 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
996 let mut path_value_msat = final_value_msat;
998 // Routing Fragmentation Mitigation heuristic:
1000 // Routing fragmentation across many payment paths increases the overall routing
1001 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
1002 // Taking too many smaller paths also increases the chance of payment failure.
1003 // Thus to avoid this effect, we require from our collected links to provide
1004 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
1005 // This requirement is currently set to be 1/max_path_count of the payment
1006 // value to ensure we only ever return routes that do not violate this limit.
1007 let minimal_value_contribution_msat: u64 = if allow_mpp {
1008 (final_value_msat + (payment_params.max_path_count as u64 - 1)) / payment_params.max_path_count as u64
1013 // When we start collecting routes we enforce the max_channel_saturation_power_of_half
1014 // requirement strictly. After we've collected enough (or if we fail to find new routes) we
1015 // drop the requirement by setting this to 0.
1016 let mut channel_saturation_pow_half = payment_params.max_channel_saturation_power_of_half;
1018 // Keep track of how much liquidity has been used in selected channels. Used to determine
1019 // if the channel can be used by additional MPP paths or to inform path finding decisions. It is
1020 // aware of direction *only* to ensure that the correct htlc_maximum_msat value is used. Hence,
1021 // liquidity used in one direction will not offset any used in the opposite direction.
1022 let mut used_channel_liquidities: HashMap<(u64, bool), u64> =
1023 HashMap::with_capacity(network_nodes.len());
1025 // Keeping track of how much value we already collected across other paths. Helps to decide
1026 // when we want to stop looking for new paths.
1027 let mut already_collected_value_msat = 0;
1029 for (_, channels) in first_hop_targets.iter_mut() {
1030 // Sort the first_hops channels to the same node(s) in priority order of which channel we'd
1031 // most like to use.
1033 // First, if channels are below `recommended_value_msat`, sort them in descending order,
1034 // preferring larger channels to avoid splitting the payment into more MPP parts than is
1037 // Second, because simply always sorting in descending order would always use our largest
1038 // available outbound capacity, needlessly fragmenting our available channel capacities,
1039 // sort channels above `recommended_value_msat` in ascending order, preferring channels
1040 // which have enough, but not too much, capacity for the payment.
1041 channels.sort_unstable_by(|chan_a, chan_b| {
1042 if chan_b.next_outbound_htlc_limit_msat < recommended_value_msat || chan_a.next_outbound_htlc_limit_msat < recommended_value_msat {
1043 // Sort in descending order
1044 chan_b.next_outbound_htlc_limit_msat.cmp(&chan_a.next_outbound_htlc_limit_msat)
1046 // Sort in ascending order
1047 chan_a.next_outbound_htlc_limit_msat.cmp(&chan_b.next_outbound_htlc_limit_msat)
1052 log_trace!(logger, "Building path from {} (payee) to {} (us/payer) for value {} msat.", payment_params.payee_pubkey, our_node_pubkey, final_value_msat);
1054 macro_rules! add_entry {
1055 // Adds entry which goes from $src_node_id to $dest_node_id over the $candidate hop.
1056 // $next_hops_fee_msat represents the fees paid for using all the channels *after* this one,
1057 // since that value has to be transferred over this channel.
1058 // Returns whether this channel caused an update to `targets`.
1059 ( $candidate: expr, $src_node_id: expr, $dest_node_id: expr, $next_hops_fee_msat: expr,
1060 $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr,
1061 $next_hops_path_penalty_msat: expr, $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => { {
1062 // We "return" whether we updated the path at the end, via this:
1063 let mut did_add_update_path_to_src_node = false;
1064 // Channels to self should not be used. This is more of belt-and-suspenders, because in
1065 // practice these cases should be caught earlier:
1066 // - for regular channels at channel announcement (TODO)
1067 // - for first and last hops early in get_route
1068 if $src_node_id != $dest_node_id {
1069 let short_channel_id = $candidate.short_channel_id();
1070 let effective_capacity = $candidate.effective_capacity();
1071 let htlc_maximum_msat = max_htlc_from_capacity(effective_capacity, channel_saturation_pow_half);
1073 // It is tricky to subtract $next_hops_fee_msat from available liquidity here.
1074 // It may be misleading because we might later choose to reduce the value transferred
1075 // over these channels, and the channel which was insufficient might become sufficient.
1076 // Worst case: we drop a good channel here because it can't cover the high following
1077 // fees caused by one expensive channel, but then this channel could have been used
1078 // if the amount being transferred over this path is lower.
1079 // We do this for now, but this is a subject for removal.
1080 if let Some(mut available_value_contribution_msat) = htlc_maximum_msat.checked_sub($next_hops_fee_msat) {
1081 let used_liquidity_msat = used_channel_liquidities
1082 .get(&(short_channel_id, $src_node_id < $dest_node_id))
1083 .map_or(0, |used_liquidity_msat| {
1084 available_value_contribution_msat = available_value_contribution_msat
1085 .saturating_sub(*used_liquidity_msat);
1086 *used_liquidity_msat
1089 // Verify the liquidity offered by this channel complies to the minimal contribution.
1090 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
1091 // Do not consider candidate hops that would exceed the maximum path length.
1092 let path_length_to_node = $next_hops_path_length + 1;
1093 let exceeds_max_path_length = path_length_to_node > MAX_PATH_LENGTH_ESTIMATE;
1095 // Do not consider candidates that exceed the maximum total cltv expiry limit.
1096 // In order to already account for some of the privacy enhancing random CLTV
1097 // expiry delta offset we add on top later, we subtract a rough estimate
1098 // (2*MEDIAN_HOP_CLTV_EXPIRY_DELTA) here.
1099 let max_total_cltv_expiry_delta = (payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta)
1100 .checked_sub(2*MEDIAN_HOP_CLTV_EXPIRY_DELTA)
1101 .unwrap_or(payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta);
1102 let hop_total_cltv_delta = ($next_hops_cltv_delta as u32)
1103 .saturating_add($candidate.cltv_expiry_delta());
1104 let exceeds_cltv_delta_limit = hop_total_cltv_delta > max_total_cltv_expiry_delta;
1106 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
1107 // Includes paying fees for the use of the following channels.
1108 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
1109 Some(result) => result,
1110 // Can't overflow due to how the values were computed right above.
1111 None => unreachable!(),
1113 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
1114 let over_path_minimum_msat = amount_to_transfer_over_msat >= $candidate.htlc_minimum_msat() &&
1115 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
1117 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
1118 let may_overpay_to_meet_path_minimum_msat =
1119 ((amount_to_transfer_over_msat < $candidate.htlc_minimum_msat() &&
1120 recommended_value_msat > $candidate.htlc_minimum_msat()) ||
1121 (amount_to_transfer_over_msat < $next_hops_path_htlc_minimum_msat &&
1122 recommended_value_msat > $next_hops_path_htlc_minimum_msat));
1124 let payment_failed_on_this_channel =
1125 payment_params.previously_failed_channels.contains(&short_channel_id);
1127 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
1128 // bother considering this channel. If retrying with recommended_value_msat may
1129 // allow us to hit the HTLC minimum limit, set htlc_minimum_limit so that we go
1130 // around again with a higher amount.
1131 if !contributes_sufficient_value || exceeds_max_path_length ||
1132 exceeds_cltv_delta_limit || payment_failed_on_this_channel {
1133 // Path isn't useful, ignore it and move on.
1134 } else if may_overpay_to_meet_path_minimum_msat {
1135 hit_minimum_limit = true;
1136 } else if over_path_minimum_msat {
1137 // Note that low contribution here (limited by available_liquidity_msat)
1138 // might violate htlc_minimum_msat on the hops which are next along the
1139 // payment path (upstream to the payee). To avoid that, we recompute
1140 // path fees knowing the final path contribution after constructing it.
1141 let path_htlc_minimum_msat = compute_fees($next_hops_path_htlc_minimum_msat, $candidate.fees())
1142 .and_then(|fee_msat| fee_msat.checked_add($next_hops_path_htlc_minimum_msat))
1143 .map(|fee_msat| cmp::max(fee_msat, $candidate.htlc_minimum_msat()))
1144 .unwrap_or_else(|| u64::max_value());
1145 let hm_entry = dist.entry($src_node_id);
1146 let old_entry = hm_entry.or_insert_with(|| {
1147 // If there was previously no known way to access the source node
1148 // (recall it goes payee-to-payer) of short_channel_id, first add a
1149 // semi-dummy record just to compute the fees to reach the source node.
1150 // This will affect our decision on selecting short_channel_id
1151 // as a way to reach the $dest_node_id.
1152 let mut fee_base_msat = 0;
1153 let mut fee_proportional_millionths = 0;
1154 if let Some(Some(fees)) = network_nodes.get(&$src_node_id).map(|node| node.lowest_inbound_channel_fees) {
1155 fee_base_msat = fees.base_msat;
1156 fee_proportional_millionths = fees.proportional_millionths;
1159 node_id: $dest_node_id.clone(),
1160 candidate: $candidate.clone(),
1162 src_lowest_inbound_fees: RoutingFees {
1163 base_msat: fee_base_msat,
1164 proportional_millionths: fee_proportional_millionths,
1166 next_hops_fee_msat: u64::max_value(),
1167 hop_use_fee_msat: u64::max_value(),
1168 total_fee_msat: u64::max_value(),
1169 path_htlc_minimum_msat,
1170 path_penalty_msat: u64::max_value(),
1171 was_processed: false,
1172 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
1173 value_contribution_msat,
1177 #[allow(unused_mut)] // We only use the mut in cfg(test)
1178 let mut should_process = !old_entry.was_processed;
1179 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
1181 // In test/fuzzing builds, we do extra checks to make sure the skipping
1182 // of already-seen nodes only happens in cases we expect (see below).
1183 if !should_process { should_process = true; }
1187 let mut hop_use_fee_msat = 0;
1188 let mut total_fee_msat = $next_hops_fee_msat;
1190 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
1191 // will have the same effective-fee
1192 if $src_node_id != our_node_id {
1193 match compute_fees(amount_to_transfer_over_msat, $candidate.fees()) {
1194 // max_value means we'll always fail
1195 // the old_entry.total_fee_msat > total_fee_msat check
1196 None => total_fee_msat = u64::max_value(),
1198 hop_use_fee_msat = fee_msat;
1199 total_fee_msat += hop_use_fee_msat;
1200 // When calculating the lowest inbound fees to a node, we
1201 // calculate fees here not based on the actual value we think
1202 // will flow over this channel, but on the minimum value that
1203 // we'll accept flowing over it. The minimum accepted value
1204 // is a constant through each path collection run, ensuring
1205 // consistent basis. Otherwise we may later find a
1206 // different path to the source node that is more expensive,
1207 // but which we consider to be cheaper because we are capacity
1208 // constrained and the relative fee becomes lower.
1209 match compute_fees(minimal_value_contribution_msat, old_entry.src_lowest_inbound_fees)
1210 .map(|a| a.checked_add(total_fee_msat)) {
1215 total_fee_msat = u64::max_value();
1222 let channel_usage = ChannelUsage {
1223 amount_msat: amount_to_transfer_over_msat,
1224 inflight_htlc_msat: used_liquidity_msat,
1227 let channel_penalty_msat = scorer.channel_penalty_msat(
1228 short_channel_id, &$src_node_id, &$dest_node_id, channel_usage
1230 let path_penalty_msat = $next_hops_path_penalty_msat
1231 .saturating_add(channel_penalty_msat);
1232 let new_graph_node = RouteGraphNode {
1233 node_id: $src_node_id,
1234 lowest_fee_to_peer_through_node: total_fee_msat,
1235 lowest_fee_to_node: $next_hops_fee_msat as u64 + hop_use_fee_msat,
1236 total_cltv_delta: hop_total_cltv_delta,
1237 value_contribution_msat,
1238 path_htlc_minimum_msat,
1240 path_length_to_node,
1243 // Update the way of reaching $src_node_id with the given short_channel_id (from $dest_node_id),
1244 // if this way is cheaper than the already known
1245 // (considering the cost to "reach" this channel from the route destination,
1246 // the cost of using this channel,
1247 // and the cost of routing to the source node of this channel).
1248 // Also, consider that htlc_minimum_msat_difference, because we might end up
1249 // paying it. Consider the following exploit:
1250 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
1251 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
1252 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
1253 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
1255 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
1256 // but it may require additional tracking - we don't want to double-count
1257 // the fees included in $next_hops_path_htlc_minimum_msat, but also
1258 // can't use something that may decrease on future hops.
1259 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat)
1260 .saturating_add(old_entry.path_penalty_msat);
1261 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat)
1262 .saturating_add(path_penalty_msat);
1264 if !old_entry.was_processed && new_cost < old_cost {
1265 targets.push(new_graph_node);
1266 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
1267 old_entry.hop_use_fee_msat = hop_use_fee_msat;
1268 old_entry.total_fee_msat = total_fee_msat;
1269 old_entry.node_id = $dest_node_id.clone();
1270 old_entry.candidate = $candidate.clone();
1271 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
1272 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
1273 old_entry.path_penalty_msat = path_penalty_msat;
1274 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
1276 old_entry.value_contribution_msat = value_contribution_msat;
1278 did_add_update_path_to_src_node = true;
1279 } else if old_entry.was_processed && new_cost < old_cost {
1280 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
1282 // If we're skipping processing a node which was previously
1283 // processed even though we found another path to it with a
1284 // cheaper fee, check that it was because the second path we
1285 // found (which we are processing now) has a lower value
1286 // contribution due to an HTLC minimum limit.
1288 // e.g. take a graph with two paths from node 1 to node 2, one
1289 // through channel A, and one through channel B. Channel A and
1290 // B are both in the to-process heap, with their scores set by
1291 // a higher htlc_minimum than fee.
1292 // Channel A is processed first, and the channels onwards from
1293 // node 1 are added to the to-process heap. Thereafter, we pop
1294 // Channel B off of the heap, note that it has a much more
1295 // restrictive htlc_maximum_msat, and recalculate the fees for
1296 // all of node 1's channels using the new, reduced, amount.
1298 // This would be bogus - we'd be selecting a higher-fee path
1299 // with a lower htlc_maximum_msat instead of the one we'd
1300 // already decided to use.
1301 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
1303 value_contribution_msat + path_penalty_msat <
1304 old_entry.value_contribution_msat + old_entry.path_penalty_msat
1312 did_add_update_path_to_src_node
1316 let default_node_features = default_node_features();
1318 // Find ways (channels with destination) to reach a given node and store them
1319 // in the corresponding data structures (routing graph etc).
1320 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
1321 // meaning how much will be paid in fees after this node (to the best of our knowledge).
1322 // This data can later be helpful to optimize routing (pay lower fees).
1323 macro_rules! add_entries_to_cheapest_to_target_node {
1324 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr, $next_hops_value_contribution: expr,
1325 $next_hops_path_htlc_minimum_msat: expr, $next_hops_path_penalty_msat: expr,
1326 $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => {
1327 let skip_node = if let Some(elem) = dist.get_mut(&$node_id) {
1328 let was_processed = elem.was_processed;
1329 elem.was_processed = true;
1332 // Entries are added to dist in add_entry!() when there is a channel from a node.
1333 // Because there are no channels from payee, it will not have a dist entry at this point.
1334 // If we're processing any other node, it is always be the result of a channel from it.
1335 assert_eq!($node_id, payee_node_id);
1340 if let Some(first_channels) = first_hop_targets.get(&$node_id) {
1341 for details in first_channels {
1342 let candidate = CandidateRouteHop::FirstHop { details };
1343 add_entry!(candidate, our_node_id, $node_id, $fee_to_target_msat,
1344 $next_hops_value_contribution,
1345 $next_hops_path_htlc_minimum_msat, $next_hops_path_penalty_msat,
1346 $next_hops_cltv_delta, $next_hops_path_length);
1350 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
1353 &default_node_features
1356 if !features.requires_unknown_bits() {
1357 for chan_id in $node.channels.iter() {
1358 let chan = network_channels.get(chan_id).unwrap();
1359 if !chan.features.requires_unknown_bits() {
1360 if let Some((directed_channel, source)) = chan.as_directed_to(&$node_id) {
1361 if first_hops.is_none() || *source != our_node_id {
1362 if directed_channel.direction().enabled {
1363 let candidate = CandidateRouteHop::PublicHop {
1364 info: directed_channel,
1365 short_channel_id: *chan_id,
1367 add_entry!(candidate, *source, $node_id,
1368 $fee_to_target_msat,
1369 $next_hops_value_contribution,
1370 $next_hops_path_htlc_minimum_msat,
1371 $next_hops_path_penalty_msat,
1372 $next_hops_cltv_delta, $next_hops_path_length);
1383 let mut payment_paths = Vec::<PaymentPath>::new();
1385 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
1386 'paths_collection: loop {
1387 // For every new path, start from scratch, except for used_channel_liquidities, which
1388 // helps to avoid reusing previously selected paths in future iterations.
1391 hit_minimum_limit = false;
1393 // If first hop is a private channel and the only way to reach the payee, this is the only
1394 // place where it could be added.
1395 if let Some(first_channels) = first_hop_targets.get(&payee_node_id) {
1396 for details in first_channels {
1397 let candidate = CandidateRouteHop::FirstHop { details };
1398 let added = add_entry!(candidate, our_node_id, payee_node_id, 0, path_value_msat,
1400 log_trace!(logger, "{} direct route to payee via SCID {}",
1401 if added { "Added" } else { "Skipped" }, candidate.short_channel_id());
1405 // Add the payee as a target, so that the payee-to-payer
1406 // search algorithm knows what to start with.
1407 match network_nodes.get(&payee_node_id) {
1408 // The payee is not in our network graph, so nothing to add here.
1409 // There is still a chance of reaching them via last_hops though,
1410 // so don't yet fail the payment here.
1411 // If not, targets.pop() will not even let us enter the loop in step 2.
1414 add_entries_to_cheapest_to_target_node!(node, payee_node_id, 0, path_value_msat, 0, 0u64, 0, 0);
1419 // If a caller provided us with last hops, add them to routing targets. Since this happens
1420 // earlier than general path finding, they will be somewhat prioritized, although currently
1421 // it matters only if the fees are exactly the same.
1422 for route in payment_params.route_hints.iter().filter(|route| !route.0.is_empty()) {
1423 let first_hop_in_route = &(route.0)[0];
1424 let have_hop_src_in_graph =
1425 // Only add the hops in this route to our candidate set if either
1426 // we have a direct channel to the first hop or the first hop is
1427 // in the regular network graph.
1428 first_hop_targets.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some() ||
1429 network_nodes.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some();
1430 if have_hop_src_in_graph {
1431 // We start building the path from reverse, i.e., from payee
1432 // to the first RouteHintHop in the path.
1433 let hop_iter = route.0.iter().rev();
1434 let prev_hop_iter = core::iter::once(&payment_params.payee_pubkey).chain(
1435 route.0.iter().skip(1).rev().map(|hop| &hop.src_node_id));
1436 let mut hop_used = true;
1437 let mut aggregate_next_hops_fee_msat: u64 = 0;
1438 let mut aggregate_next_hops_path_htlc_minimum_msat: u64 = 0;
1439 let mut aggregate_next_hops_path_penalty_msat: u64 = 0;
1440 let mut aggregate_next_hops_cltv_delta: u32 = 0;
1441 let mut aggregate_next_hops_path_length: u8 = 0;
1443 for (idx, (hop, prev_hop_id)) in hop_iter.zip(prev_hop_iter).enumerate() {
1444 let source = NodeId::from_pubkey(&hop.src_node_id);
1445 let target = NodeId::from_pubkey(&prev_hop_id);
1446 let candidate = network_channels
1447 .get(&hop.short_channel_id)
1448 .and_then(|channel| channel.as_directed_to(&target))
1449 .map(|(info, _)| CandidateRouteHop::PublicHop {
1451 short_channel_id: hop.short_channel_id,
1453 .unwrap_or_else(|| CandidateRouteHop::PrivateHop { hint: hop });
1455 if !add_entry!(candidate, source, target, aggregate_next_hops_fee_msat,
1456 path_value_msat, aggregate_next_hops_path_htlc_minimum_msat,
1457 aggregate_next_hops_path_penalty_msat,
1458 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length) {
1459 // If this hop was not used then there is no use checking the preceding
1460 // hops in the RouteHint. We can break by just searching for a direct
1461 // channel between last checked hop and first_hop_targets.
1465 let used_liquidity_msat = used_channel_liquidities
1466 .get(&(hop.short_channel_id, source < target)).copied().unwrap_or(0);
1467 let channel_usage = ChannelUsage {
1468 amount_msat: final_value_msat + aggregate_next_hops_fee_msat,
1469 inflight_htlc_msat: used_liquidity_msat,
1470 effective_capacity: candidate.effective_capacity(),
1472 let channel_penalty_msat = scorer.channel_penalty_msat(
1473 hop.short_channel_id, &source, &target, channel_usage
1475 aggregate_next_hops_path_penalty_msat = aggregate_next_hops_path_penalty_msat
1476 .saturating_add(channel_penalty_msat);
1478 aggregate_next_hops_cltv_delta = aggregate_next_hops_cltv_delta
1479 .saturating_add(hop.cltv_expiry_delta as u32);
1481 aggregate_next_hops_path_length = aggregate_next_hops_path_length
1484 // Searching for a direct channel between last checked hop and first_hop_targets
1485 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&prev_hop_id)) {
1486 for details in first_channels {
1487 let candidate = CandidateRouteHop::FirstHop { details };
1488 add_entry!(candidate, our_node_id, NodeId::from_pubkey(&prev_hop_id),
1489 aggregate_next_hops_fee_msat, path_value_msat,
1490 aggregate_next_hops_path_htlc_minimum_msat,
1491 aggregate_next_hops_path_penalty_msat, aggregate_next_hops_cltv_delta,
1492 aggregate_next_hops_path_length);
1500 // In the next values of the iterator, the aggregate fees already reflects
1501 // the sum of value sent from payer (final_value_msat) and routing fees
1502 // for the last node in the RouteHint. We need to just add the fees to
1503 // route through the current node so that the preceding node (next iteration)
1505 let hops_fee = compute_fees(aggregate_next_hops_fee_msat + final_value_msat, hop.fees)
1506 .map_or(None, |inc| inc.checked_add(aggregate_next_hops_fee_msat));
1507 aggregate_next_hops_fee_msat = if let Some(val) = hops_fee { val } else { break; };
1509 let hop_htlc_minimum_msat = candidate.htlc_minimum_msat();
1510 let hop_htlc_minimum_msat_inc = if let Some(val) = compute_fees(aggregate_next_hops_path_htlc_minimum_msat, hop.fees) { val } else { break; };
1511 let hops_path_htlc_minimum = aggregate_next_hops_path_htlc_minimum_msat
1512 .checked_add(hop_htlc_minimum_msat_inc);
1513 aggregate_next_hops_path_htlc_minimum_msat = if let Some(val) = hops_path_htlc_minimum { cmp::max(hop_htlc_minimum_msat, val) } else { break; };
1515 if idx == route.0.len() - 1 {
1516 // The last hop in this iterator is the first hop in
1517 // overall RouteHint.
1518 // If this hop connects to a node with which we have a direct channel,
1519 // ignore the network graph and, if the last hop was added, add our
1520 // direct channel to the candidate set.
1522 // Note that we *must* check if the last hop was added as `add_entry`
1523 // always assumes that the third argument is a node to which we have a
1525 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&hop.src_node_id)) {
1526 for details in first_channels {
1527 let candidate = CandidateRouteHop::FirstHop { details };
1528 add_entry!(candidate, our_node_id,
1529 NodeId::from_pubkey(&hop.src_node_id),
1530 aggregate_next_hops_fee_msat, path_value_msat,
1531 aggregate_next_hops_path_htlc_minimum_msat,
1532 aggregate_next_hops_path_penalty_msat,
1533 aggregate_next_hops_cltv_delta,
1534 aggregate_next_hops_path_length);
1542 log_trace!(logger, "Starting main path collection loop with {} nodes pre-filled from first/last hops.", targets.len());
1544 // At this point, targets are filled with the data from first and
1545 // last hops communicated by the caller, and the payment receiver.
1546 let mut found_new_path = false;
1549 // If this loop terminates due the exhaustion of targets, two situations are possible:
1550 // - not enough outgoing liquidity:
1551 // 0 < already_collected_value_msat < final_value_msat
1552 // - enough outgoing liquidity:
1553 // final_value_msat <= already_collected_value_msat < recommended_value_msat
1554 // Both these cases (and other cases except reaching recommended_value_msat) mean that
1555 // paths_collection will be stopped because found_new_path==false.
1556 // This is not necessarily a routing failure.
1557 'path_construction: while let Some(RouteGraphNode { node_id, lowest_fee_to_node, total_cltv_delta, mut value_contribution_msat, path_htlc_minimum_msat, path_penalty_msat, path_length_to_node, .. }) = targets.pop() {
1559 // Since we're going payee-to-payer, hitting our node as a target means we should stop
1560 // traversing the graph and arrange the path out of what we found.
1561 if node_id == our_node_id {
1562 let mut new_entry = dist.remove(&our_node_id).unwrap();
1563 let mut ordered_hops: Vec<(PathBuildingHop, NodeFeatures)> = vec!((new_entry.clone(), default_node_features.clone()));
1566 let mut features_set = false;
1567 if let Some(first_channels) = first_hop_targets.get(&ordered_hops.last().unwrap().0.node_id) {
1568 for details in first_channels {
1569 if details.get_outbound_payment_scid().unwrap() == ordered_hops.last().unwrap().0.candidate.short_channel_id() {
1570 ordered_hops.last_mut().unwrap().1 = details.counterparty.features.to_context();
1571 features_set = true;
1577 if let Some(node) = network_nodes.get(&ordered_hops.last().unwrap().0.node_id) {
1578 if let Some(node_info) = node.announcement_info.as_ref() {
1579 ordered_hops.last_mut().unwrap().1 = node_info.features.clone();
1581 ordered_hops.last_mut().unwrap().1 = default_node_features.clone();
1584 // We can fill in features for everything except hops which were
1585 // provided via the invoice we're paying. We could guess based on the
1586 // recipient's features but for now we simply avoid guessing at all.
1590 // Means we succesfully traversed from the payer to the payee, now
1591 // save this path for the payment route. Also, update the liquidity
1592 // remaining on the used hops, so that we take them into account
1593 // while looking for more paths.
1594 if ordered_hops.last().unwrap().0.node_id == payee_node_id {
1598 new_entry = match dist.remove(&ordered_hops.last().unwrap().0.node_id) {
1599 Some(payment_hop) => payment_hop,
1600 // We can't arrive at None because, if we ever add an entry to targets,
1601 // we also fill in the entry in dist (see add_entry!).
1602 None => unreachable!(),
1604 // We "propagate" the fees one hop backward (topologically) here,
1605 // so that fees paid for a HTLC forwarding on the current channel are
1606 // associated with the previous channel (where they will be subtracted).
1607 ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
1608 ordered_hops.push((new_entry.clone(), default_node_features.clone()));
1610 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
1611 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
1613 log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: \n {:#?}",
1614 ordered_hops.len(), value_contribution_msat, ordered_hops.iter().map(|h| &(h.0)).collect::<Vec<&PathBuildingHop>>());
1616 let mut payment_path = PaymentPath {hops: ordered_hops};
1618 // We could have possibly constructed a slightly inconsistent path: since we reduce
1619 // value being transferred along the way, we could have violated htlc_minimum_msat
1620 // on some channels we already passed (assuming dest->source direction). Here, we
1621 // recompute the fees again, so that if that's the case, we match the currently
1622 // underpaid htlc_minimum_msat with fees.
1623 debug_assert_eq!(payment_path.get_value_msat(), value_contribution_msat);
1624 value_contribution_msat = cmp::min(value_contribution_msat, final_value_msat);
1625 payment_path.update_value_and_recompute_fees(value_contribution_msat);
1627 // Since a path allows to transfer as much value as
1628 // the smallest channel it has ("bottleneck"), we should recompute
1629 // the fees so sender HTLC don't overpay fees when traversing
1630 // larger channels than the bottleneck. This may happen because
1631 // when we were selecting those channels we were not aware how much value
1632 // this path will transfer, and the relative fee for them
1633 // might have been computed considering a larger value.
1634 // Remember that we used these channels so that we don't rely
1635 // on the same liquidity in future paths.
1636 let mut prevented_redundant_path_selection = false;
1637 let prev_hop_iter = core::iter::once(&our_node_id)
1638 .chain(payment_path.hops.iter().map(|(hop, _)| &hop.node_id));
1639 for (prev_hop, (hop, _)) in prev_hop_iter.zip(payment_path.hops.iter()) {
1640 let spent_on_hop_msat = value_contribution_msat + hop.next_hops_fee_msat;
1641 let used_liquidity_msat = used_channel_liquidities
1642 .entry((hop.candidate.short_channel_id(), *prev_hop < hop.node_id))
1643 .and_modify(|used_liquidity_msat| *used_liquidity_msat += spent_on_hop_msat)
1644 .or_insert(spent_on_hop_msat);
1645 let hop_capacity = hop.candidate.effective_capacity();
1646 let hop_max_msat = max_htlc_from_capacity(hop_capacity, channel_saturation_pow_half);
1647 if *used_liquidity_msat == hop_max_msat {
1648 // If this path used all of this channel's available liquidity, we know
1649 // this path will not be selected again in the next loop iteration.
1650 prevented_redundant_path_selection = true;
1652 debug_assert!(*used_liquidity_msat <= hop_max_msat);
1654 if !prevented_redundant_path_selection {
1655 // If we weren't capped by hitting a liquidity limit on a channel in the path,
1656 // we'll probably end up picking the same path again on the next iteration.
1657 // Decrease the available liquidity of a hop in the middle of the path.
1658 let victim_scid = payment_path.hops[(payment_path.hops.len()) / 2].0.candidate.short_channel_id();
1659 let exhausted = u64::max_value();
1660 log_trace!(logger, "Disabling channel {} for future path building iterations to avoid duplicates.", victim_scid);
1661 *used_channel_liquidities.entry((victim_scid, false)).or_default() = exhausted;
1662 *used_channel_liquidities.entry((victim_scid, true)).or_default() = exhausted;
1665 // Track the total amount all our collected paths allow to send so that we know
1666 // when to stop looking for more paths
1667 already_collected_value_msat += value_contribution_msat;
1669 payment_paths.push(payment_path);
1670 found_new_path = true;
1671 break 'path_construction;
1674 // If we found a path back to the payee, we shouldn't try to process it again. This is
1675 // the equivalent of the `elem.was_processed` check in
1676 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
1677 if node_id == payee_node_id { continue 'path_construction; }
1679 // Otherwise, since the current target node is not us,
1680 // keep "unrolling" the payment graph from payee to payer by
1681 // finding a way to reach the current target from the payer side.
1682 match network_nodes.get(&node_id) {
1685 add_entries_to_cheapest_to_target_node!(node, node_id, lowest_fee_to_node,
1686 value_contribution_msat, path_htlc_minimum_msat, path_penalty_msat,
1687 total_cltv_delta, path_length_to_node);
1693 if !found_new_path && channel_saturation_pow_half != 0 {
1694 channel_saturation_pow_half = 0;
1695 continue 'paths_collection;
1697 // If we don't support MPP, no use trying to gather more value ever.
1698 break 'paths_collection;
1702 // Stop either when the recommended value is reached or if no new path was found in this
1704 // In the latter case, making another path finding attempt won't help,
1705 // because we deterministically terminated the search due to low liquidity.
1706 if !found_new_path && channel_saturation_pow_half != 0 {
1707 channel_saturation_pow_half = 0;
1708 } else if already_collected_value_msat >= recommended_value_msat || !found_new_path {
1709 log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
1710 already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
1711 break 'paths_collection;
1712 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
1713 // Further, if this was our first walk of the graph, and we weren't limited by an
1714 // htlc_minimum_msat, return immediately because this path should suffice. If we were
1715 // limited by an htlc_minimum_msat value, find another path with a higher value,
1716 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
1717 // still keeping a lower total fee than this path.
1718 if !hit_minimum_limit {
1719 log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
1720 break 'paths_collection;
1722 log_trace!(logger, "Collected our payment amount on the first pass, but running again to collect extra paths with a potentially higher limit.");
1723 path_value_msat = recommended_value_msat;
1728 if payment_paths.len() == 0 {
1729 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1732 if already_collected_value_msat < final_value_msat {
1733 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1737 let mut selected_route = payment_paths;
1739 debug_assert_eq!(selected_route.iter().map(|p| p.get_value_msat()).sum::<u64>(), already_collected_value_msat);
1740 let mut overpaid_value_msat = already_collected_value_msat - final_value_msat;
1742 // First, sort by the cost-per-value of the path, dropping the paths that cost the most for
1743 // the value they contribute towards the payment amount.
1744 // We sort in descending order as we will remove from the front in `retain`, next.
1745 selected_route.sort_unstable_by(|a, b|
1746 (((b.get_cost_msat() as u128) << 64) / (b.get_value_msat() as u128))
1747 .cmp(&(((a.get_cost_msat() as u128) << 64) / (a.get_value_msat() as u128)))
1750 // We should make sure that at least 1 path left.
1751 let mut paths_left = selected_route.len();
1752 selected_route.retain(|path| {
1753 if paths_left == 1 {
1756 let path_value_msat = path.get_value_msat();
1757 if path_value_msat <= overpaid_value_msat {
1758 overpaid_value_msat -= path_value_msat;
1764 debug_assert!(selected_route.len() > 0);
1766 if overpaid_value_msat != 0 {
1768 // Now, subtract the remaining overpaid value from the most-expensive path.
1769 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1770 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1771 selected_route.sort_unstable_by(|a, b| {
1772 let a_f = a.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
1773 let b_f = b.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
1774 a_f.cmp(&b_f).then_with(|| b.get_cost_msat().cmp(&a.get_cost_msat()))
1776 let expensive_payment_path = selected_route.first_mut().unwrap();
1778 // We already dropped all the paths with value below `overpaid_value_msat` above, thus this
1779 // can't go negative.
1780 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
1781 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
1785 // Sort by the path itself and combine redundant paths.
1786 // Note that we sort by SCIDs alone as its simpler but when combining we have to ensure we
1787 // compare both SCIDs and NodeIds as individual nodes may use random aliases causing collisions
1789 selected_route.sort_unstable_by_key(|path| {
1790 let mut key = [0u64; MAX_PATH_LENGTH_ESTIMATE as usize];
1791 debug_assert!(path.hops.len() <= key.len());
1792 for (scid, key) in path.hops.iter().map(|h| h.0.candidate.short_channel_id()).zip(key.iter_mut()) {
1797 for idx in 0..(selected_route.len() - 1) {
1798 if idx + 1 >= selected_route.len() { break; }
1799 if iter_equal(selected_route[idx ].hops.iter().map(|h| (h.0.candidate.short_channel_id(), h.0.node_id)),
1800 selected_route[idx + 1].hops.iter().map(|h| (h.0.candidate.short_channel_id(), h.0.node_id))) {
1801 let new_value = selected_route[idx].get_value_msat() + selected_route[idx + 1].get_value_msat();
1802 selected_route[idx].update_value_and_recompute_fees(new_value);
1803 selected_route.remove(idx + 1);
1807 let mut selected_paths = Vec::<Vec<Result<RouteHop, LightningError>>>::new();
1808 for payment_path in selected_route {
1809 let mut path = payment_path.hops.iter().map(|(payment_hop, node_features)| {
1811 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)})?,
1812 node_features: node_features.clone(),
1813 short_channel_id: payment_hop.candidate.short_channel_id(),
1814 channel_features: payment_hop.candidate.features(),
1815 fee_msat: payment_hop.fee_msat,
1816 cltv_expiry_delta: payment_hop.candidate.cltv_expiry_delta(),
1818 }).collect::<Vec<_>>();
1819 // Propagate the cltv_expiry_delta one hop backwards since the delta from the current hop is
1820 // applicable for the previous hop.
1821 path.iter_mut().rev().fold(final_cltv_expiry_delta, |prev_cltv_expiry_delta, hop| {
1822 core::mem::replace(&mut hop.as_mut().unwrap().cltv_expiry_delta, prev_cltv_expiry_delta)
1824 selected_paths.push(path);
1826 // Make sure we would never create a route with more paths than we allow.
1827 debug_assert!(selected_paths.len() <= payment_params.max_path_count.into());
1829 if let Some(features) = &payment_params.features {
1830 for path in selected_paths.iter_mut() {
1831 if let Ok(route_hop) = path.last_mut().unwrap() {
1832 route_hop.node_features = features.to_context();
1838 paths: selected_paths.into_iter().map(|path| path.into_iter().collect()).collect::<Result<Vec<_>, _>>()?,
1839 payment_params: Some(payment_params.clone()),
1841 log_info!(logger, "Got route to {}: {}", payment_params.payee_pubkey, log_route!(route));
1845 // When an adversarial intermediary node observes a payment, it may be able to infer its
1846 // destination, if the remaining CLTV expiry delta exactly matches a feasible path in the network
1847 // graph. In order to improve privacy, this method obfuscates the CLTV expiry deltas along the
1848 // payment path by adding a randomized 'shadow route' offset to the final hop.
1849 fn add_random_cltv_offset(route: &mut Route, payment_params: &PaymentParameters,
1850 network_graph: &ReadOnlyNetworkGraph, random_seed_bytes: &[u8; 32]
1852 let network_channels = network_graph.channels();
1853 let network_nodes = network_graph.nodes();
1855 for path in route.paths.iter_mut() {
1856 let mut shadow_ctlv_expiry_delta_offset: u32 = 0;
1858 // Remember the last three nodes of the random walk and avoid looping back on them.
1859 // Init with the last three nodes from the actual path, if possible.
1860 let mut nodes_to_avoid: [NodeId; 3] = [NodeId::from_pubkey(&path.last().unwrap().pubkey),
1861 NodeId::from_pubkey(&path.get(path.len().saturating_sub(2)).unwrap().pubkey),
1862 NodeId::from_pubkey(&path.get(path.len().saturating_sub(3)).unwrap().pubkey)];
1864 // Choose the last publicly known node as the starting point for the random walk.
1865 let mut cur_hop: Option<NodeId> = None;
1866 let mut path_nonce = [0u8; 12];
1867 if let Some(starting_hop) = path.iter().rev()
1868 .find(|h| network_nodes.contains_key(&NodeId::from_pubkey(&h.pubkey))) {
1869 cur_hop = Some(NodeId::from_pubkey(&starting_hop.pubkey));
1870 path_nonce.copy_from_slice(&cur_hop.unwrap().as_slice()[..12]);
1873 // Init PRNG with the path-dependant nonce, which is static for private paths.
1874 let mut prng = ChaCha20::new(random_seed_bytes, &path_nonce);
1875 let mut random_path_bytes = [0u8; ::core::mem::size_of::<usize>()];
1877 // Pick a random path length in [1 .. 3]
1878 prng.process_in_place(&mut random_path_bytes);
1879 let random_walk_length = usize::from_be_bytes(random_path_bytes).wrapping_rem(3).wrapping_add(1);
1881 for random_hop in 0..random_walk_length {
1882 // If we don't find a suitable offset in the public network graph, we default to
1883 // MEDIAN_HOP_CLTV_EXPIRY_DELTA.
1884 let mut random_hop_offset = MEDIAN_HOP_CLTV_EXPIRY_DELTA;
1886 if let Some(cur_node_id) = cur_hop {
1887 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
1888 // Randomly choose the next unvisited hop.
1889 prng.process_in_place(&mut random_path_bytes);
1890 if let Some(random_channel) = usize::from_be_bytes(random_path_bytes)
1891 .checked_rem(cur_node.channels.len())
1892 .and_then(|index| cur_node.channels.get(index))
1893 .and_then(|id| network_channels.get(id)) {
1894 random_channel.as_directed_from(&cur_node_id).map(|(dir_info, next_id)| {
1895 if !nodes_to_avoid.iter().any(|x| x == next_id) {
1896 nodes_to_avoid[random_hop] = *next_id;
1897 random_hop_offset = dir_info.direction().cltv_expiry_delta.into();
1898 cur_hop = Some(*next_id);
1905 shadow_ctlv_expiry_delta_offset = shadow_ctlv_expiry_delta_offset
1906 .checked_add(random_hop_offset)
1907 .unwrap_or(shadow_ctlv_expiry_delta_offset);
1910 // Limit the total offset to reduce the worst-case locked liquidity timevalue
1911 const MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET: u32 = 3*144;
1912 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET);
1914 // Limit the offset so we never exceed the max_total_cltv_expiry_delta. To improve plausibility,
1915 // we choose the limit to be the largest possible multiple of MEDIAN_HOP_CLTV_EXPIRY_DELTA.
1916 let path_total_cltv_expiry_delta: u32 = path.iter().map(|h| h.cltv_expiry_delta).sum();
1917 let mut max_path_offset = payment_params.max_total_cltv_expiry_delta - path_total_cltv_expiry_delta;
1918 max_path_offset = cmp::max(
1919 max_path_offset - (max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA),
1920 max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA);
1921 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, max_path_offset);
1923 // Add 'shadow' CLTV offset to the final hop
1924 if let Some(last_hop) = path.last_mut() {
1925 last_hop.cltv_expiry_delta = last_hop.cltv_expiry_delta
1926 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(last_hop.cltv_expiry_delta);
1931 /// Construct a route from us (payer) to the target node (payee) via the given hops (which should
1932 /// exclude the payer, but include the payee). This may be useful, e.g., for probing the chosen path.
1934 /// Re-uses logic from `find_route`, so the restrictions described there also apply here.
1935 pub fn build_route_from_hops<L: Deref, GL: Deref>(
1936 our_node_pubkey: &PublicKey, hops: &[PublicKey], route_params: &RouteParameters,
1937 network_graph: &NetworkGraph<GL>, logger: L, random_seed_bytes: &[u8; 32]
1938 ) -> Result<Route, LightningError>
1939 where L::Target: Logger, GL::Target: Logger {
1940 let graph_lock = network_graph.read_only();
1941 let mut route = build_route_from_hops_internal(
1942 our_node_pubkey, hops, &route_params.payment_params, &graph_lock,
1943 route_params.final_value_msat, route_params.final_cltv_expiry_delta, logger, random_seed_bytes)?;
1944 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
1948 fn build_route_from_hops_internal<L: Deref>(
1949 our_node_pubkey: &PublicKey, hops: &[PublicKey], payment_params: &PaymentParameters,
1950 network_graph: &ReadOnlyNetworkGraph, final_value_msat: u64, final_cltv_expiry_delta: u32,
1951 logger: L, random_seed_bytes: &[u8; 32]
1952 ) -> Result<Route, LightningError> where L::Target: Logger {
1955 our_node_id: NodeId,
1956 hop_ids: [Option<NodeId>; MAX_PATH_LENGTH_ESTIMATE as usize],
1959 impl Score for HopScorer {
1960 fn channel_penalty_msat(&self, _short_channel_id: u64, source: &NodeId, target: &NodeId,
1961 _usage: ChannelUsage) -> u64
1963 let mut cur_id = self.our_node_id;
1964 for i in 0..self.hop_ids.len() {
1965 if let Some(next_id) = self.hop_ids[i] {
1966 if cur_id == *source && next_id == *target {
1977 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
1979 fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
1981 fn probe_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
1983 fn probe_successful(&mut self, _path: &[&RouteHop]) {}
1986 impl<'a> Writeable for HopScorer {
1988 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), io::Error> {
1993 if hops.len() > MAX_PATH_LENGTH_ESTIMATE.into() {
1994 return Err(LightningError{err: "Cannot build a route exceeding the maximum path length.".to_owned(), action: ErrorAction::IgnoreError});
1997 let our_node_id = NodeId::from_pubkey(our_node_pubkey);
1998 let mut hop_ids = [None; MAX_PATH_LENGTH_ESTIMATE as usize];
1999 for i in 0..hops.len() {
2000 hop_ids[i] = Some(NodeId::from_pubkey(&hops[i]));
2003 let scorer = HopScorer { our_node_id, hop_ids };
2005 get_route(our_node_pubkey, payment_params, network_graph, None, final_value_msat,
2006 final_cltv_expiry_delta, logger, &scorer, random_seed_bytes)
2011 use crate::routing::gossip::{NetworkGraph, P2PGossipSync, NodeId, EffectiveCapacity};
2012 use crate::routing::router::{get_route, build_route_from_hops_internal, add_random_cltv_offset, default_node_features,
2013 PaymentParameters, Route, RouteHint, RouteHintHop, RouteHop, RoutingFees,
2014 DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA, MAX_PATH_LENGTH_ESTIMATE};
2015 use crate::routing::scoring::{ChannelUsage, Score, ProbabilisticScorer, ProbabilisticScoringParameters};
2016 use crate::routing::test_utils::{add_channel, add_or_update_node, build_graph, build_line_graph, id_to_feature_flags, get_nodes, update_channel};
2017 use crate::chain::transaction::OutPoint;
2018 use crate::chain::keysinterface::KeysInterface;
2019 use crate::ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
2020 use crate::ln::msgs::{ErrorAction, LightningError, UnsignedChannelUpdate, MAX_VALUE_MSAT};
2021 use crate::ln::channelmanager;
2022 use crate::util::test_utils as ln_test_utils;
2023 use crate::util::chacha20::ChaCha20;
2025 use crate::util::ser::{Writeable, Writer};
2027 use bitcoin::hashes::Hash;
2028 use bitcoin::network::constants::Network;
2029 use bitcoin::blockdata::constants::genesis_block;
2030 use bitcoin::blockdata::script::Builder;
2031 use bitcoin::blockdata::opcodes;
2032 use bitcoin::blockdata::transaction::TxOut;
2036 use bitcoin::secp256k1::{PublicKey,SecretKey};
2037 use bitcoin::secp256k1::Secp256k1;
2039 use crate::prelude::*;
2040 use crate::sync::Arc;
2042 use core::convert::TryInto;
2044 fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
2045 features: InitFeatures, outbound_capacity_msat: u64) -> channelmanager::ChannelDetails {
2046 channelmanager::ChannelDetails {
2047 channel_id: [0; 32],
2048 counterparty: channelmanager::ChannelCounterparty {
2051 unspendable_punishment_reserve: 0,
2052 forwarding_info: None,
2053 outbound_htlc_minimum_msat: None,
2054 outbound_htlc_maximum_msat: None,
2056 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
2059 outbound_scid_alias: None,
2060 inbound_scid_alias: None,
2061 channel_value_satoshis: 0,
2064 outbound_capacity_msat,
2065 next_outbound_htlc_limit_msat: outbound_capacity_msat,
2066 inbound_capacity_msat: 42,
2067 unspendable_punishment_reserve: None,
2068 confirmations_required: None,
2069 force_close_spend_delay: None,
2070 is_outbound: true, is_channel_ready: true,
2071 is_usable: true, is_public: true,
2072 inbound_htlc_minimum_msat: None,
2073 inbound_htlc_maximum_msat: None,
2079 fn simple_route_test() {
2080 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2081 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2082 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2083 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2084 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2085 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2087 // Simple route to 2 via 1
2089 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) {
2090 assert_eq!(err, "Cannot send a payment of 0 msat");
2091 } else { panic!(); }
2093 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2094 assert_eq!(route.paths[0].len(), 2);
2096 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2097 assert_eq!(route.paths[0][0].short_channel_id, 2);
2098 assert_eq!(route.paths[0][0].fee_msat, 100);
2099 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2100 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2101 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2103 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2104 assert_eq!(route.paths[0][1].short_channel_id, 4);
2105 assert_eq!(route.paths[0][1].fee_msat, 100);
2106 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2107 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2108 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2112 fn invalid_first_hop_test() {
2113 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2114 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2115 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2116 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2117 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2118 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2120 // Simple route to 2 via 1
2122 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
2124 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) =
2125 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) {
2126 assert_eq!(err, "First hop cannot have our_node_pubkey as a destination.");
2127 } else { panic!(); }
2129 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2130 assert_eq!(route.paths[0].len(), 2);
2134 fn htlc_minimum_test() {
2135 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2136 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2137 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2138 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2139 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2140 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2142 // Simple route to 2 via 1
2144 // Disable other paths
2145 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2146 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2147 short_channel_id: 12,
2149 flags: 2, // to disable
2150 cltv_expiry_delta: 0,
2151 htlc_minimum_msat: 0,
2152 htlc_maximum_msat: MAX_VALUE_MSAT,
2154 fee_proportional_millionths: 0,
2155 excess_data: Vec::new()
2157 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2158 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2159 short_channel_id: 3,
2161 flags: 2, // to disable
2162 cltv_expiry_delta: 0,
2163 htlc_minimum_msat: 0,
2164 htlc_maximum_msat: MAX_VALUE_MSAT,
2166 fee_proportional_millionths: 0,
2167 excess_data: Vec::new()
2169 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2170 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2171 short_channel_id: 13,
2173 flags: 2, // to disable
2174 cltv_expiry_delta: 0,
2175 htlc_minimum_msat: 0,
2176 htlc_maximum_msat: MAX_VALUE_MSAT,
2178 fee_proportional_millionths: 0,
2179 excess_data: Vec::new()
2181 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2182 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2183 short_channel_id: 6,
2185 flags: 2, // to disable
2186 cltv_expiry_delta: 0,
2187 htlc_minimum_msat: 0,
2188 htlc_maximum_msat: MAX_VALUE_MSAT,
2190 fee_proportional_millionths: 0,
2191 excess_data: Vec::new()
2193 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2194 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2195 short_channel_id: 7,
2197 flags: 2, // to disable
2198 cltv_expiry_delta: 0,
2199 htlc_minimum_msat: 0,
2200 htlc_maximum_msat: MAX_VALUE_MSAT,
2202 fee_proportional_millionths: 0,
2203 excess_data: Vec::new()
2206 // Check against amount_to_transfer_over_msat.
2207 // Set minimal HTLC of 200_000_000 msat.
2208 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2209 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2210 short_channel_id: 2,
2213 cltv_expiry_delta: 0,
2214 htlc_minimum_msat: 200_000_000,
2215 htlc_maximum_msat: MAX_VALUE_MSAT,
2217 fee_proportional_millionths: 0,
2218 excess_data: Vec::new()
2221 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
2223 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2224 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2225 short_channel_id: 4,
2228 cltv_expiry_delta: 0,
2229 htlc_minimum_msat: 0,
2230 htlc_maximum_msat: 199_999_999,
2232 fee_proportional_millionths: 0,
2233 excess_data: Vec::new()
2236 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
2237 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) {
2238 assert_eq!(err, "Failed to find a path to the given destination");
2239 } else { panic!(); }
2241 // Lift the restriction on the first hop.
2242 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2243 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2244 short_channel_id: 2,
2247 cltv_expiry_delta: 0,
2248 htlc_minimum_msat: 0,
2249 htlc_maximum_msat: MAX_VALUE_MSAT,
2251 fee_proportional_millionths: 0,
2252 excess_data: Vec::new()
2255 // A payment above the minimum should pass
2256 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();
2257 assert_eq!(route.paths[0].len(), 2);
2261 fn htlc_minimum_overpay_test() {
2262 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2263 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2264 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(channelmanager::provided_invoice_features());
2265 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2266 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2267 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2269 // A route to node#2 via two paths.
2270 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
2271 // Thus, they can't send 60 without overpaying.
2272 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2273 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2274 short_channel_id: 2,
2277 cltv_expiry_delta: 0,
2278 htlc_minimum_msat: 35_000,
2279 htlc_maximum_msat: 40_000,
2281 fee_proportional_millionths: 0,
2282 excess_data: Vec::new()
2284 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2285 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2286 short_channel_id: 12,
2289 cltv_expiry_delta: 0,
2290 htlc_minimum_msat: 35_000,
2291 htlc_maximum_msat: 40_000,
2293 fee_proportional_millionths: 0,
2294 excess_data: Vec::new()
2298 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2299 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2300 short_channel_id: 13,
2303 cltv_expiry_delta: 0,
2304 htlc_minimum_msat: 0,
2305 htlc_maximum_msat: MAX_VALUE_MSAT,
2307 fee_proportional_millionths: 0,
2308 excess_data: Vec::new()
2310 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2311 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2312 short_channel_id: 4,
2315 cltv_expiry_delta: 0,
2316 htlc_minimum_msat: 0,
2317 htlc_maximum_msat: MAX_VALUE_MSAT,
2319 fee_proportional_millionths: 0,
2320 excess_data: Vec::new()
2323 // Disable other paths
2324 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2325 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2326 short_channel_id: 1,
2328 flags: 2, // to disable
2329 cltv_expiry_delta: 0,
2330 htlc_minimum_msat: 0,
2331 htlc_maximum_msat: MAX_VALUE_MSAT,
2333 fee_proportional_millionths: 0,
2334 excess_data: Vec::new()
2337 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 60_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2338 // Overpay fees to hit htlc_minimum_msat.
2339 let overpaid_fees = route.paths[0][0].fee_msat + route.paths[1][0].fee_msat;
2340 // TODO: this could be better balanced to overpay 10k and not 15k.
2341 assert_eq!(overpaid_fees, 15_000);
2343 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
2344 // while taking even more fee to match htlc_minimum_msat.
2345 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2346 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2347 short_channel_id: 12,
2350 cltv_expiry_delta: 0,
2351 htlc_minimum_msat: 65_000,
2352 htlc_maximum_msat: 80_000,
2354 fee_proportional_millionths: 0,
2355 excess_data: Vec::new()
2357 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2358 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2359 short_channel_id: 2,
2362 cltv_expiry_delta: 0,
2363 htlc_minimum_msat: 0,
2364 htlc_maximum_msat: MAX_VALUE_MSAT,
2366 fee_proportional_millionths: 0,
2367 excess_data: Vec::new()
2369 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2370 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2371 short_channel_id: 4,
2374 cltv_expiry_delta: 0,
2375 htlc_minimum_msat: 0,
2376 htlc_maximum_msat: MAX_VALUE_MSAT,
2378 fee_proportional_millionths: 100_000,
2379 excess_data: Vec::new()
2382 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 60_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2383 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
2384 assert_eq!(route.paths.len(), 1);
2385 assert_eq!(route.paths[0][0].short_channel_id, 12);
2386 let fees = route.paths[0][0].fee_msat;
2387 assert_eq!(fees, 5_000);
2389 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2390 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
2391 // the other channel.
2392 assert_eq!(route.paths.len(), 1);
2393 assert_eq!(route.paths[0][0].short_channel_id, 2);
2394 let fees = route.paths[0][0].fee_msat;
2395 assert_eq!(fees, 5_000);
2399 fn disable_channels_test() {
2400 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2401 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2402 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2403 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2404 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2405 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2407 // // Disable channels 4 and 12 by flags=2
2408 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2409 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2410 short_channel_id: 4,
2412 flags: 2, // to disable
2413 cltv_expiry_delta: 0,
2414 htlc_minimum_msat: 0,
2415 htlc_maximum_msat: MAX_VALUE_MSAT,
2417 fee_proportional_millionths: 0,
2418 excess_data: Vec::new()
2420 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2421 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2422 short_channel_id: 12,
2424 flags: 2, // to disable
2425 cltv_expiry_delta: 0,
2426 htlc_minimum_msat: 0,
2427 htlc_maximum_msat: MAX_VALUE_MSAT,
2429 fee_proportional_millionths: 0,
2430 excess_data: Vec::new()
2433 // If all the channels require some features we don't understand, route should fail
2434 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) {
2435 assert_eq!(err, "Failed to find a path to the given destination");
2436 } else { panic!(); }
2438 // If we specify a channel to node7, that overrides our local channel view and that gets used
2439 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2440 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();
2441 assert_eq!(route.paths[0].len(), 2);
2443 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2444 assert_eq!(route.paths[0][0].short_channel_id, 42);
2445 assert_eq!(route.paths[0][0].fee_msat, 200);
2446 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2447 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2448 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2450 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2451 assert_eq!(route.paths[0][1].short_channel_id, 13);
2452 assert_eq!(route.paths[0][1].fee_msat, 100);
2453 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2454 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2455 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2459 fn disable_node_test() {
2460 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2461 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2462 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2463 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2464 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2465 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2467 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
2468 let mut unknown_features = NodeFeatures::empty();
2469 unknown_features.set_unknown_feature_required();
2470 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
2471 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
2472 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
2474 // If all nodes require some features we don't understand, route should fail
2475 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) {
2476 assert_eq!(err, "Failed to find a path to the given destination");
2477 } else { panic!(); }
2479 // If we specify a channel to node7, that overrides our local channel view and that gets used
2480 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2481 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();
2482 assert_eq!(route.paths[0].len(), 2);
2484 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2485 assert_eq!(route.paths[0][0].short_channel_id, 42);
2486 assert_eq!(route.paths[0][0].fee_msat, 200);
2487 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2488 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2489 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2491 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2492 assert_eq!(route.paths[0][1].short_channel_id, 13);
2493 assert_eq!(route.paths[0][1].fee_msat, 100);
2494 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2495 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2496 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2498 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
2499 // naively) assume that the user checked the feature bits on the invoice, which override
2500 // the node_announcement.
2504 fn our_chans_test() {
2505 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2506 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2507 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2508 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2509 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2511 // Route to 1 via 2 and 3 because our channel to 1 is disabled
2512 let payment_params = PaymentParameters::from_node_id(nodes[0]);
2513 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2514 assert_eq!(route.paths[0].len(), 3);
2516 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2517 assert_eq!(route.paths[0][0].short_channel_id, 2);
2518 assert_eq!(route.paths[0][0].fee_msat, 200);
2519 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2520 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2521 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2523 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2524 assert_eq!(route.paths[0][1].short_channel_id, 4);
2525 assert_eq!(route.paths[0][1].fee_msat, 100);
2526 assert_eq!(route.paths[0][1].cltv_expiry_delta, (3 << 4) | 2);
2527 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2528 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2530 assert_eq!(route.paths[0][2].pubkey, nodes[0]);
2531 assert_eq!(route.paths[0][2].short_channel_id, 3);
2532 assert_eq!(route.paths[0][2].fee_msat, 100);
2533 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
2534 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(1));
2535 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(3));
2537 // If we specify a channel to node7, that overrides our local channel view and that gets used
2538 let payment_params = PaymentParameters::from_node_id(nodes[2]);
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]);
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));
2558 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2559 let zero_fees = RoutingFees {
2561 proportional_millionths: 0,
2563 vec![RouteHint(vec![RouteHintHop {
2564 src_node_id: nodes[3],
2565 short_channel_id: 8,
2567 cltv_expiry_delta: (8 << 4) | 1,
2568 htlc_minimum_msat: None,
2569 htlc_maximum_msat: None,
2571 ]), RouteHint(vec![RouteHintHop {
2572 src_node_id: nodes[4],
2573 short_channel_id: 9,
2576 proportional_millionths: 0,
2578 cltv_expiry_delta: (9 << 4) | 1,
2579 htlc_minimum_msat: None,
2580 htlc_maximum_msat: None,
2581 }]), RouteHint(vec![RouteHintHop {
2582 src_node_id: nodes[5],
2583 short_channel_id: 10,
2585 cltv_expiry_delta: (10 << 4) | 1,
2586 htlc_minimum_msat: None,
2587 htlc_maximum_msat: None,
2591 fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2592 let zero_fees = RoutingFees {
2594 proportional_millionths: 0,
2596 vec![RouteHint(vec![RouteHintHop {
2597 src_node_id: nodes[2],
2598 short_channel_id: 5,
2601 proportional_millionths: 0,
2603 cltv_expiry_delta: (5 << 4) | 1,
2604 htlc_minimum_msat: None,
2605 htlc_maximum_msat: None,
2607 src_node_id: nodes[3],
2608 short_channel_id: 8,
2610 cltv_expiry_delta: (8 << 4) | 1,
2611 htlc_minimum_msat: None,
2612 htlc_maximum_msat: None,
2614 ]), RouteHint(vec![RouteHintHop {
2615 src_node_id: nodes[4],
2616 short_channel_id: 9,
2619 proportional_millionths: 0,
2621 cltv_expiry_delta: (9 << 4) | 1,
2622 htlc_minimum_msat: None,
2623 htlc_maximum_msat: None,
2624 }]), RouteHint(vec![RouteHintHop {
2625 src_node_id: nodes[5],
2626 short_channel_id: 10,
2628 cltv_expiry_delta: (10 << 4) | 1,
2629 htlc_minimum_msat: None,
2630 htlc_maximum_msat: None,
2635 fn partial_route_hint_test() {
2636 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2637 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2638 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2639 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2640 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2642 // Simple test across 2, 3, 5, and 4 via a last_hop channel
2643 // Tests the behaviour when the RouteHint contains a suboptimal hop.
2644 // RouteHint may be partially used by the algo to build the best path.
2646 // First check that last hop can't have its source as the payee.
2647 let invalid_last_hop = RouteHint(vec![RouteHintHop {
2648 src_node_id: nodes[6],
2649 short_channel_id: 8,
2652 proportional_millionths: 0,
2654 cltv_expiry_delta: (8 << 4) | 1,
2655 htlc_minimum_msat: None,
2656 htlc_maximum_msat: None,
2659 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
2660 invalid_last_hops.push(invalid_last_hop);
2662 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(invalid_last_hops);
2663 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) {
2664 assert_eq!(err, "Route hint cannot have the payee as the source.");
2665 } else { panic!(); }
2668 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops_multi_private_channels(&nodes));
2669 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2670 assert_eq!(route.paths[0].len(), 5);
2672 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2673 assert_eq!(route.paths[0][0].short_channel_id, 2);
2674 assert_eq!(route.paths[0][0].fee_msat, 100);
2675 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2676 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2677 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2679 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2680 assert_eq!(route.paths[0][1].short_channel_id, 4);
2681 assert_eq!(route.paths[0][1].fee_msat, 0);
2682 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
2683 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2684 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2686 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2687 assert_eq!(route.paths[0][2].short_channel_id, 6);
2688 assert_eq!(route.paths[0][2].fee_msat, 0);
2689 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
2690 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2691 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2693 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2694 assert_eq!(route.paths[0][3].short_channel_id, 11);
2695 assert_eq!(route.paths[0][3].fee_msat, 0);
2696 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
2697 // If we have a peer in the node map, we'll use their features here since we don't have
2698 // a way of figuring out their features from the invoice:
2699 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2700 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2702 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2703 assert_eq!(route.paths[0][4].short_channel_id, 8);
2704 assert_eq!(route.paths[0][4].fee_msat, 100);
2705 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2706 assert_eq!(route.paths[0][4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
2707 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2710 fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2711 let zero_fees = RoutingFees {
2713 proportional_millionths: 0,
2715 vec![RouteHint(vec![RouteHintHop {
2716 src_node_id: nodes[3],
2717 short_channel_id: 8,
2719 cltv_expiry_delta: (8 << 4) | 1,
2720 htlc_minimum_msat: None,
2721 htlc_maximum_msat: None,
2722 }]), RouteHint(vec![
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 ignores_empty_last_hops_test() {
2736 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2737 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2738 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(empty_last_hop(&nodes));
2739 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2740 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2741 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2743 // Test handling of an empty RouteHint passed in Invoice.
2745 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2746 assert_eq!(route.paths[0].len(), 5);
2748 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2749 assert_eq!(route.paths[0][0].short_channel_id, 2);
2750 assert_eq!(route.paths[0][0].fee_msat, 100);
2751 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2752 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2753 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2755 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2756 assert_eq!(route.paths[0][1].short_channel_id, 4);
2757 assert_eq!(route.paths[0][1].fee_msat, 0);
2758 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
2759 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2760 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2762 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2763 assert_eq!(route.paths[0][2].short_channel_id, 6);
2764 assert_eq!(route.paths[0][2].fee_msat, 0);
2765 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
2766 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2767 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2769 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2770 assert_eq!(route.paths[0][3].short_channel_id, 11);
2771 assert_eq!(route.paths[0][3].fee_msat, 0);
2772 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
2773 // If we have a peer in the node map, we'll use their features here since we don't have
2774 // a way of figuring out their features from the invoice:
2775 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2776 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2778 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2779 assert_eq!(route.paths[0][4].short_channel_id, 8);
2780 assert_eq!(route.paths[0][4].fee_msat, 100);
2781 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2782 assert_eq!(route.paths[0][4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
2783 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2786 /// Builds a trivial last-hop hint that passes through the two nodes given, with channel 0xff00
2788 fn multi_hop_last_hops_hint(hint_hops: [PublicKey; 2]) -> Vec<RouteHint> {
2789 let zero_fees = RoutingFees {
2791 proportional_millionths: 0,
2793 vec![RouteHint(vec![RouteHintHop {
2794 src_node_id: hint_hops[0],
2795 short_channel_id: 0xff00,
2798 proportional_millionths: 0,
2800 cltv_expiry_delta: (5 << 4) | 1,
2801 htlc_minimum_msat: None,
2802 htlc_maximum_msat: None,
2804 src_node_id: hint_hops[1],
2805 short_channel_id: 0xff01,
2807 cltv_expiry_delta: (8 << 4) | 1,
2808 htlc_minimum_msat: None,
2809 htlc_maximum_msat: None,
2814 fn multi_hint_last_hops_test() {
2815 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2816 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2817 let last_hops = multi_hop_last_hops_hint([nodes[2], nodes[3]]);
2818 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops.clone());
2819 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2820 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2821 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2822 // Test through channels 2, 3, 0xff00, 0xff01.
2823 // Test shows that multiple hop hints are considered.
2825 // Disabling channels 6 & 7 by flags=2
2826 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2827 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2828 short_channel_id: 6,
2830 flags: 2, // to disable
2831 cltv_expiry_delta: 0,
2832 htlc_minimum_msat: 0,
2833 htlc_maximum_msat: MAX_VALUE_MSAT,
2835 fee_proportional_millionths: 0,
2836 excess_data: Vec::new()
2838 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2839 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2840 short_channel_id: 7,
2842 flags: 2, // to disable
2843 cltv_expiry_delta: 0,
2844 htlc_minimum_msat: 0,
2845 htlc_maximum_msat: MAX_VALUE_MSAT,
2847 fee_proportional_millionths: 0,
2848 excess_data: Vec::new()
2851 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2852 assert_eq!(route.paths[0].len(), 4);
2854 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2855 assert_eq!(route.paths[0][0].short_channel_id, 2);
2856 assert_eq!(route.paths[0][0].fee_msat, 200);
2857 assert_eq!(route.paths[0][0].cltv_expiry_delta, 65);
2858 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2859 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2861 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2862 assert_eq!(route.paths[0][1].short_channel_id, 4);
2863 assert_eq!(route.paths[0][1].fee_msat, 100);
2864 assert_eq!(route.paths[0][1].cltv_expiry_delta, 81);
2865 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2866 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2868 assert_eq!(route.paths[0][2].pubkey, nodes[3]);
2869 assert_eq!(route.paths[0][2].short_channel_id, last_hops[0].0[0].short_channel_id);
2870 assert_eq!(route.paths[0][2].fee_msat, 0);
2871 assert_eq!(route.paths[0][2].cltv_expiry_delta, 129);
2872 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(4));
2873 assert_eq!(route.paths[0][2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2875 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2876 assert_eq!(route.paths[0][3].short_channel_id, last_hops[0].0[1].short_channel_id);
2877 assert_eq!(route.paths[0][3].fee_msat, 100);
2878 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2879 assert_eq!(route.paths[0][3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
2880 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2884 fn private_multi_hint_last_hops_test() {
2885 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2886 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2888 let non_announced_privkey = SecretKey::from_slice(&hex::decode(format!("{:02x}", 0xf0).repeat(32)).unwrap()[..]).unwrap();
2889 let non_announced_pubkey = PublicKey::from_secret_key(&secp_ctx, &non_announced_privkey);
2891 let last_hops = multi_hop_last_hops_hint([nodes[2], non_announced_pubkey]);
2892 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops.clone());
2893 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2894 // Test through channels 2, 3, 0xff00, 0xff01.
2895 // Test shows that multiple hop hints are considered.
2897 // Disabling channels 6 & 7 by flags=2
2898 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2899 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2900 short_channel_id: 6,
2902 flags: 2, // to disable
2903 cltv_expiry_delta: 0,
2904 htlc_minimum_msat: 0,
2905 htlc_maximum_msat: MAX_VALUE_MSAT,
2907 fee_proportional_millionths: 0,
2908 excess_data: Vec::new()
2910 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2911 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2912 short_channel_id: 7,
2914 flags: 2, // to disable
2915 cltv_expiry_delta: 0,
2916 htlc_minimum_msat: 0,
2917 htlc_maximum_msat: MAX_VALUE_MSAT,
2919 fee_proportional_millionths: 0,
2920 excess_data: Vec::new()
2923 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &[42u8; 32]).unwrap();
2924 assert_eq!(route.paths[0].len(), 4);
2926 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2927 assert_eq!(route.paths[0][0].short_channel_id, 2);
2928 assert_eq!(route.paths[0][0].fee_msat, 200);
2929 assert_eq!(route.paths[0][0].cltv_expiry_delta, 65);
2930 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2931 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2933 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2934 assert_eq!(route.paths[0][1].short_channel_id, 4);
2935 assert_eq!(route.paths[0][1].fee_msat, 100);
2936 assert_eq!(route.paths[0][1].cltv_expiry_delta, 81);
2937 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2938 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2940 assert_eq!(route.paths[0][2].pubkey, non_announced_pubkey);
2941 assert_eq!(route.paths[0][2].short_channel_id, last_hops[0].0[0].short_channel_id);
2942 assert_eq!(route.paths[0][2].fee_msat, 0);
2943 assert_eq!(route.paths[0][2].cltv_expiry_delta, 129);
2944 assert_eq!(route.paths[0][2].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
2945 assert_eq!(route.paths[0][2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2947 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2948 assert_eq!(route.paths[0][3].short_channel_id, last_hops[0].0[1].short_channel_id);
2949 assert_eq!(route.paths[0][3].fee_msat, 100);
2950 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2951 assert_eq!(route.paths[0][3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
2952 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2955 fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2956 let zero_fees = RoutingFees {
2958 proportional_millionths: 0,
2960 vec![RouteHint(vec![RouteHintHop {
2961 src_node_id: nodes[4],
2962 short_channel_id: 11,
2964 cltv_expiry_delta: (11 << 4) | 1,
2965 htlc_minimum_msat: None,
2966 htlc_maximum_msat: None,
2968 src_node_id: nodes[3],
2969 short_channel_id: 8,
2971 cltv_expiry_delta: (8 << 4) | 1,
2972 htlc_minimum_msat: None,
2973 htlc_maximum_msat: None,
2974 }]), RouteHint(vec![RouteHintHop {
2975 src_node_id: nodes[4],
2976 short_channel_id: 9,
2979 proportional_millionths: 0,
2981 cltv_expiry_delta: (9 << 4) | 1,
2982 htlc_minimum_msat: None,
2983 htlc_maximum_msat: None,
2984 }]), RouteHint(vec![RouteHintHop {
2985 src_node_id: nodes[5],
2986 short_channel_id: 10,
2988 cltv_expiry_delta: (10 << 4) | 1,
2989 htlc_minimum_msat: None,
2990 htlc_maximum_msat: None,
2995 fn last_hops_with_public_channel_test() {
2996 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2997 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2998 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops_with_public_channel(&nodes));
2999 let scorer = ln_test_utils::TestScorer::with_penalty(0);
3000 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3001 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3002 // This test shows that public routes can be present in the invoice
3003 // which would be handled in the same manner.
3005 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3006 assert_eq!(route.paths[0].len(), 5);
3008 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3009 assert_eq!(route.paths[0][0].short_channel_id, 2);
3010 assert_eq!(route.paths[0][0].fee_msat, 100);
3011 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
3012 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3013 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3015 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3016 assert_eq!(route.paths[0][1].short_channel_id, 4);
3017 assert_eq!(route.paths[0][1].fee_msat, 0);
3018 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
3019 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3020 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3022 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
3023 assert_eq!(route.paths[0][2].short_channel_id, 6);
3024 assert_eq!(route.paths[0][2].fee_msat, 0);
3025 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
3026 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
3027 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
3029 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
3030 assert_eq!(route.paths[0][3].short_channel_id, 11);
3031 assert_eq!(route.paths[0][3].fee_msat, 0);
3032 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
3033 // If we have a peer in the node map, we'll use their features here since we don't have
3034 // a way of figuring out their features from the invoice:
3035 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
3036 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
3038 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
3039 assert_eq!(route.paths[0][4].short_channel_id, 8);
3040 assert_eq!(route.paths[0][4].fee_msat, 100);
3041 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
3042 assert_eq!(route.paths[0][4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3043 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3047 fn our_chans_last_hop_connect_test() {
3048 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3049 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3050 let scorer = ln_test_utils::TestScorer::with_penalty(0);
3051 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3052 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3054 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
3055 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3056 let mut last_hops = last_hops(&nodes);
3057 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops.clone());
3058 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();
3059 assert_eq!(route.paths[0].len(), 2);
3061 assert_eq!(route.paths[0][0].pubkey, nodes[3]);
3062 assert_eq!(route.paths[0][0].short_channel_id, 42);
3063 assert_eq!(route.paths[0][0].fee_msat, 0);
3064 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 4) | 1);
3065 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
3066 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3068 assert_eq!(route.paths[0][1].pubkey, nodes[6]);
3069 assert_eq!(route.paths[0][1].short_channel_id, 8);
3070 assert_eq!(route.paths[0][1].fee_msat, 100);
3071 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
3072 assert_eq!(route.paths[0][1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3073 assert_eq!(route.paths[0][1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3075 last_hops[0].0[0].fees.base_msat = 1000;
3077 // Revert to via 6 as the fee on 8 goes up
3078 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops);
3079 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3080 assert_eq!(route.paths[0].len(), 4);
3082 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3083 assert_eq!(route.paths[0][0].short_channel_id, 2);
3084 assert_eq!(route.paths[0][0].fee_msat, 200); // fee increased as its % of value transferred across node
3085 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
3086 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3087 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3089 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3090 assert_eq!(route.paths[0][1].short_channel_id, 4);
3091 assert_eq!(route.paths[0][1].fee_msat, 100);
3092 assert_eq!(route.paths[0][1].cltv_expiry_delta, (7 << 4) | 1);
3093 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3094 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3096 assert_eq!(route.paths[0][2].pubkey, nodes[5]);
3097 assert_eq!(route.paths[0][2].short_channel_id, 7);
3098 assert_eq!(route.paths[0][2].fee_msat, 0);
3099 assert_eq!(route.paths[0][2].cltv_expiry_delta, (10 << 4) | 1);
3100 // If we have a peer in the node map, we'll use their features here since we don't have
3101 // a way of figuring out their features from the invoice:
3102 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
3103 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(7));
3105 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
3106 assert_eq!(route.paths[0][3].short_channel_id, 10);
3107 assert_eq!(route.paths[0][3].fee_msat, 100);
3108 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
3109 assert_eq!(route.paths[0][3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3110 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3112 // ...but still use 8 for larger payments as 6 has a variable feerate
3113 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 2000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3114 assert_eq!(route.paths[0].len(), 5);
3116 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3117 assert_eq!(route.paths[0][0].short_channel_id, 2);
3118 assert_eq!(route.paths[0][0].fee_msat, 3000);
3119 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
3120 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3121 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3123 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3124 assert_eq!(route.paths[0][1].short_channel_id, 4);
3125 assert_eq!(route.paths[0][1].fee_msat, 0);
3126 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
3127 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3128 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3130 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
3131 assert_eq!(route.paths[0][2].short_channel_id, 6);
3132 assert_eq!(route.paths[0][2].fee_msat, 0);
3133 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
3134 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
3135 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
3137 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
3138 assert_eq!(route.paths[0][3].short_channel_id, 11);
3139 assert_eq!(route.paths[0][3].fee_msat, 1000);
3140 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
3141 // If we have a peer in the node map, we'll use their features here since we don't have
3142 // a way of figuring out their features from the invoice:
3143 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
3144 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
3146 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
3147 assert_eq!(route.paths[0][4].short_channel_id, 8);
3148 assert_eq!(route.paths[0][4].fee_msat, 2000);
3149 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
3150 assert_eq!(route.paths[0][4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3151 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3154 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> {
3155 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
3156 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3157 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3159 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
3160 let last_hops = RouteHint(vec![RouteHintHop {
3161 src_node_id: middle_node_id,
3162 short_channel_id: 8,
3165 proportional_millionths: last_hop_fee_prop,
3167 cltv_expiry_delta: (8 << 4) | 1,
3168 htlc_minimum_msat: None,
3169 htlc_maximum_msat: last_hop_htlc_max,
3171 let payment_params = PaymentParameters::from_node_id(target_node_id).with_route_hints(vec![last_hops]);
3172 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
3173 let scorer = ln_test_utils::TestScorer::with_penalty(0);
3174 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3175 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3176 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
3177 let logger = ln_test_utils::TestLogger::new();
3178 let network_graph = NetworkGraph::new(genesis_hash, &logger);
3179 let route = get_route(&source_node_id, &payment_params, &network_graph.read_only(),
3180 Some(&our_chans.iter().collect::<Vec<_>>()), route_val, 42, &logger, &scorer, &random_seed_bytes);
3185 fn unannounced_path_test() {
3186 // We should be able to send a payment to a destination without any help of a routing graph
3187 // if we have a channel with a common counterparty that appears in the first and last hop
3189 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
3191 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3192 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3193 assert_eq!(route.paths[0].len(), 2);
3195 assert_eq!(route.paths[0][0].pubkey, middle_node_id);
3196 assert_eq!(route.paths[0][0].short_channel_id, 42);
3197 assert_eq!(route.paths[0][0].fee_msat, 1001);
3198 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 4) | 1);
3199 assert_eq!(route.paths[0][0].node_features.le_flags(), &[0b11]);
3200 assert_eq!(route.paths[0][0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3202 assert_eq!(route.paths[0][1].pubkey, target_node_id);
3203 assert_eq!(route.paths[0][1].short_channel_id, 8);
3204 assert_eq!(route.paths[0][1].fee_msat, 1000000);
3205 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
3206 assert_eq!(route.paths[0][1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3207 assert_eq!(route.paths[0][1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3211 fn overflow_unannounced_path_test_liquidity_underflow() {
3212 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
3213 // the last-hop had a fee which overflowed a u64, we'd panic.
3214 // This was due to us adding the first-hop from us unconditionally, causing us to think
3215 // we'd built a path (as our node is in the "best candidate" set), when we had not.
3216 // In this test, we previously hit a subtraction underflow due to having less available
3217 // liquidity at the last hop than 0.
3218 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());
3222 fn overflow_unannounced_path_test_feerate_overflow() {
3223 // This tests for the same case as above, except instead of hitting a subtraction
3224 // underflow, we hit a case where the fee charged at a hop overflowed.
3225 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());
3229 fn available_amount_while_routing_test() {
3230 // Tests whether we choose the correct available channel amount while routing.
3232 let (secp_ctx, network_graph, mut gossip_sync, chain_monitor, logger) = build_graph();
3233 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3234 let scorer = ln_test_utils::TestScorer::with_penalty(0);
3235 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3236 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3237 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(channelmanager::provided_invoice_features());
3239 // We will use a simple single-path route from
3240 // our node to node2 via node0: channels {1, 3}.
3242 // First disable all other paths.
3243 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3244 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3245 short_channel_id: 2,
3248 cltv_expiry_delta: 0,
3249 htlc_minimum_msat: 0,
3250 htlc_maximum_msat: 100_000,
3252 fee_proportional_millionths: 0,
3253 excess_data: Vec::new()
3255 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3256 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3257 short_channel_id: 12,
3260 cltv_expiry_delta: 0,
3261 htlc_minimum_msat: 0,
3262 htlc_maximum_msat: 100_000,
3264 fee_proportional_millionths: 0,
3265 excess_data: Vec::new()
3268 // Make the first channel (#1) very permissive,
3269 // and we will be testing all limits on the second channel.
3270 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3271 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3272 short_channel_id: 1,
3275 cltv_expiry_delta: 0,
3276 htlc_minimum_msat: 0,
3277 htlc_maximum_msat: 1_000_000_000,
3279 fee_proportional_millionths: 0,
3280 excess_data: Vec::new()
3283 // First, let's see if routing works if we have absolutely no idea about the available amount.
3284 // In this case, it should be set to 250_000 sats.
3285 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3286 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3287 short_channel_id: 3,
3290 cltv_expiry_delta: 0,
3291 htlc_minimum_msat: 0,
3292 htlc_maximum_msat: 250_000_000,
3294 fee_proportional_millionths: 0,
3295 excess_data: Vec::new()
3299 // Attempt to route more than available results in a failure.
3300 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3301 &our_id, &payment_params, &network_graph.read_only(), None, 250_000_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3302 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3303 } else { panic!(); }
3307 // Now, attempt to route an exact amount we have should be fine.
3308 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();
3309 assert_eq!(route.paths.len(), 1);
3310 let path = route.paths.last().unwrap();
3311 assert_eq!(path.len(), 2);
3312 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3313 assert_eq!(path.last().unwrap().fee_msat, 250_000_000);
3316 // Check that setting next_outbound_htlc_limit_msat in first_hops limits the channels.
3317 // Disable channel #1 and use another first hop.
3318 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3319 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3320 short_channel_id: 1,
3323 cltv_expiry_delta: 0,
3324 htlc_minimum_msat: 0,
3325 htlc_maximum_msat: 1_000_000_000,
3327 fee_proportional_millionths: 0,
3328 excess_data: Vec::new()
3331 // Now, limit the first_hop by the next_outbound_htlc_limit_msat of 200_000 sats.
3332 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
3335 // Attempt to route more than available results in a failure.
3336 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3337 &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) {
3338 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3339 } else { panic!(); }
3343 // Now, attempt to route an exact amount we have should be fine.
3344 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();
3345 assert_eq!(route.paths.len(), 1);
3346 let path = route.paths.last().unwrap();
3347 assert_eq!(path.len(), 2);
3348 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3349 assert_eq!(path.last().unwrap().fee_msat, 200_000_000);
3352 // Enable channel #1 back.
3353 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3354 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3355 short_channel_id: 1,
3358 cltv_expiry_delta: 0,
3359 htlc_minimum_msat: 0,
3360 htlc_maximum_msat: 1_000_000_000,
3362 fee_proportional_millionths: 0,
3363 excess_data: Vec::new()
3367 // Now let's see if routing works if we know only htlc_maximum_msat.
3368 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3369 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3370 short_channel_id: 3,
3373 cltv_expiry_delta: 0,
3374 htlc_minimum_msat: 0,
3375 htlc_maximum_msat: 15_000,
3377 fee_proportional_millionths: 0,
3378 excess_data: Vec::new()
3382 // Attempt to route more than available results in a failure.
3383 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3384 &our_id, &payment_params, &network_graph.read_only(), None, 15_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3385 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3386 } else { panic!(); }
3390 // Now, attempt to route an exact amount we have should be fine.
3391 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 15_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3392 assert_eq!(route.paths.len(), 1);
3393 let path = route.paths.last().unwrap();
3394 assert_eq!(path.len(), 2);
3395 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3396 assert_eq!(path.last().unwrap().fee_msat, 15_000);
3399 // Now let's see if routing works if we know only capacity from the UTXO.
3401 // We can't change UTXO capacity on the fly, so we'll disable
3402 // the existing channel and add another one with the capacity we need.
3403 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3404 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3405 short_channel_id: 3,
3408 cltv_expiry_delta: 0,
3409 htlc_minimum_msat: 0,
3410 htlc_maximum_msat: MAX_VALUE_MSAT,
3412 fee_proportional_millionths: 0,
3413 excess_data: Vec::new()
3416 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
3417 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
3418 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
3419 .push_opcode(opcodes::all::OP_PUSHNUM_2)
3420 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
3422 *chain_monitor.utxo_ret.lock().unwrap() = Ok(TxOut { value: 15, script_pubkey: good_script.clone() });
3423 gossip_sync.add_chain_access(Some(chain_monitor));
3425 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
3426 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3427 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3428 short_channel_id: 333,
3431 cltv_expiry_delta: (3 << 4) | 1,
3432 htlc_minimum_msat: 0,
3433 htlc_maximum_msat: 15_000,
3435 fee_proportional_millionths: 0,
3436 excess_data: Vec::new()
3438 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3439 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3440 short_channel_id: 333,
3443 cltv_expiry_delta: (3 << 4) | 2,
3444 htlc_minimum_msat: 0,
3445 htlc_maximum_msat: 15_000,
3447 fee_proportional_millionths: 0,
3448 excess_data: Vec::new()
3452 // Attempt to route more than available results in a failure.
3453 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3454 &our_id, &payment_params, &network_graph.read_only(), None, 15_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3455 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3456 } else { panic!(); }
3460 // Now, attempt to route an exact amount we have should be fine.
3461 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 15_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3462 assert_eq!(route.paths.len(), 1);
3463 let path = route.paths.last().unwrap();
3464 assert_eq!(path.len(), 2);
3465 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3466 assert_eq!(path.last().unwrap().fee_msat, 15_000);
3469 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
3470 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3471 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3472 short_channel_id: 333,
3475 cltv_expiry_delta: 0,
3476 htlc_minimum_msat: 0,
3477 htlc_maximum_msat: 10_000,
3479 fee_proportional_millionths: 0,
3480 excess_data: Vec::new()
3484 // Attempt to route more than available results in a failure.
3485 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3486 &our_id, &payment_params, &network_graph.read_only(), None, 10_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3487 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3488 } else { panic!(); }
3492 // Now, attempt to route an exact amount we have should be fine.
3493 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 10_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3494 assert_eq!(route.paths.len(), 1);
3495 let path = route.paths.last().unwrap();
3496 assert_eq!(path.len(), 2);
3497 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3498 assert_eq!(path.last().unwrap().fee_msat, 10_000);
3503 fn available_liquidity_last_hop_test() {
3504 // Check that available liquidity properly limits the path even when only
3505 // one of the latter hops is limited.
3506 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3507 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3508 let scorer = ln_test_utils::TestScorer::with_penalty(0);
3509 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3510 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3511 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(channelmanager::provided_invoice_features());
3513 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3514 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
3515 // Total capacity: 50 sats.
3517 // Disable other potential paths.
3518 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3519 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3520 short_channel_id: 2,
3523 cltv_expiry_delta: 0,
3524 htlc_minimum_msat: 0,
3525 htlc_maximum_msat: 100_000,
3527 fee_proportional_millionths: 0,
3528 excess_data: Vec::new()
3530 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3531 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3532 short_channel_id: 7,
3535 cltv_expiry_delta: 0,
3536 htlc_minimum_msat: 0,
3537 htlc_maximum_msat: 100_000,
3539 fee_proportional_millionths: 0,
3540 excess_data: Vec::new()
3545 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3546 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3547 short_channel_id: 12,
3550 cltv_expiry_delta: 0,
3551 htlc_minimum_msat: 0,
3552 htlc_maximum_msat: 100_000,
3554 fee_proportional_millionths: 0,
3555 excess_data: Vec::new()
3557 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3558 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3559 short_channel_id: 13,
3562 cltv_expiry_delta: 0,
3563 htlc_minimum_msat: 0,
3564 htlc_maximum_msat: 100_000,
3566 fee_proportional_millionths: 0,
3567 excess_data: Vec::new()
3570 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3571 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3572 short_channel_id: 6,
3575 cltv_expiry_delta: 0,
3576 htlc_minimum_msat: 0,
3577 htlc_maximum_msat: 50_000,
3579 fee_proportional_millionths: 0,
3580 excess_data: Vec::new()
3582 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3583 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3584 short_channel_id: 11,
3587 cltv_expiry_delta: 0,
3588 htlc_minimum_msat: 0,
3589 htlc_maximum_msat: 100_000,
3591 fee_proportional_millionths: 0,
3592 excess_data: Vec::new()
3595 // Attempt to route more than available results in a failure.
3596 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3597 &our_id, &payment_params, &network_graph.read_only(), None, 60_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3598 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3599 } else { panic!(); }
3603 // Now, attempt to route 49 sats (just a bit below the capacity).
3604 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 49_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3605 assert_eq!(route.paths.len(), 1);
3606 let mut total_amount_paid_msat = 0;
3607 for path in &route.paths {
3608 assert_eq!(path.len(), 4);
3609 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3610 total_amount_paid_msat += path.last().unwrap().fee_msat;
3612 assert_eq!(total_amount_paid_msat, 49_000);
3616 // Attempt to route an exact amount is also fine
3617 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3618 assert_eq!(route.paths.len(), 1);
3619 let mut total_amount_paid_msat = 0;
3620 for path in &route.paths {
3621 assert_eq!(path.len(), 4);
3622 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3623 total_amount_paid_msat += path.last().unwrap().fee_msat;
3625 assert_eq!(total_amount_paid_msat, 50_000);
3630 fn ignore_fee_first_hop_test() {
3631 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3632 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3633 let scorer = ln_test_utils::TestScorer::with_penalty(0);
3634 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3635 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3636 let payment_params = PaymentParameters::from_node_id(nodes[2]);
3638 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3639 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3640 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3641 short_channel_id: 1,
3644 cltv_expiry_delta: 0,
3645 htlc_minimum_msat: 0,
3646 htlc_maximum_msat: 100_000,
3647 fee_base_msat: 1_000_000,
3648 fee_proportional_millionths: 0,
3649 excess_data: Vec::new()
3651 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3652 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3653 short_channel_id: 3,
3656 cltv_expiry_delta: 0,
3657 htlc_minimum_msat: 0,
3658 htlc_maximum_msat: 50_000,
3660 fee_proportional_millionths: 0,
3661 excess_data: Vec::new()
3665 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3666 assert_eq!(route.paths.len(), 1);
3667 let mut total_amount_paid_msat = 0;
3668 for path in &route.paths {
3669 assert_eq!(path.len(), 2);
3670 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3671 total_amount_paid_msat += path.last().unwrap().fee_msat;
3673 assert_eq!(total_amount_paid_msat, 50_000);
3678 fn simple_mpp_route_test() {
3679 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3680 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3681 let scorer = ln_test_utils::TestScorer::with_penalty(0);
3682 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3683 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3684 let payment_params = PaymentParameters::from_node_id(nodes[2])
3685 .with_features(channelmanager::provided_invoice_features());
3687 // We need a route consisting of 3 paths:
3688 // From our node to node2 via node0, node7, node1 (three paths one hop each).
3689 // To achieve this, the amount being transferred should be around
3690 // the total capacity of these 3 paths.
3692 // First, we set limits on these (previously unlimited) channels.
3693 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
3695 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3696 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3697 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3698 short_channel_id: 1,
3701 cltv_expiry_delta: 0,
3702 htlc_minimum_msat: 0,
3703 htlc_maximum_msat: 100_000,
3705 fee_proportional_millionths: 0,
3706 excess_data: Vec::new()
3708 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3709 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3710 short_channel_id: 3,
3713 cltv_expiry_delta: 0,
3714 htlc_minimum_msat: 0,
3715 htlc_maximum_msat: 50_000,
3717 fee_proportional_millionths: 0,
3718 excess_data: Vec::new()
3721 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
3722 // (total limit 60).
3723 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3724 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3725 short_channel_id: 12,
3728 cltv_expiry_delta: 0,
3729 htlc_minimum_msat: 0,
3730 htlc_maximum_msat: 60_000,
3732 fee_proportional_millionths: 0,
3733 excess_data: Vec::new()
3735 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3736 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3737 short_channel_id: 13,
3740 cltv_expiry_delta: 0,
3741 htlc_minimum_msat: 0,
3742 htlc_maximum_msat: 60_000,
3744 fee_proportional_millionths: 0,
3745 excess_data: Vec::new()
3748 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
3749 // (total capacity 180 sats).
3750 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3751 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3752 short_channel_id: 2,
3755 cltv_expiry_delta: 0,
3756 htlc_minimum_msat: 0,
3757 htlc_maximum_msat: 200_000,
3759 fee_proportional_millionths: 0,
3760 excess_data: Vec::new()
3762 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3763 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3764 short_channel_id: 4,
3767 cltv_expiry_delta: 0,
3768 htlc_minimum_msat: 0,
3769 htlc_maximum_msat: 180_000,
3771 fee_proportional_millionths: 0,
3772 excess_data: Vec::new()
3776 // Attempt to route more than available results in a failure.
3777 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3778 &our_id, &payment_params, &network_graph.read_only(), None, 300_000, 42,
3779 Arc::clone(&logger), &scorer, &random_seed_bytes) {
3780 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3781 } else { panic!(); }
3785 // Attempt to route while setting max_path_count to 0 results in a failure.
3786 let zero_payment_params = payment_params.clone().with_max_path_count(0);
3787 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3788 &our_id, &zero_payment_params, &network_graph.read_only(), None, 100, 42,
3789 Arc::clone(&logger), &scorer, &random_seed_bytes) {
3790 assert_eq!(err, "Can't find a route with no paths allowed.");
3791 } else { panic!(); }
3795 // Attempt to route while setting max_path_count to 3 results in a failure.
3796 // This is the case because the minimal_value_contribution_msat would require each path
3797 // to account for 1/3 of the total value, which is violated by 2 out of 3 paths.
3798 let fail_payment_params = payment_params.clone().with_max_path_count(3);
3799 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3800 &our_id, &fail_payment_params, &network_graph.read_only(), None, 250_000, 42,
3801 Arc::clone(&logger), &scorer, &random_seed_bytes) {
3802 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3803 } else { panic!(); }
3807 // Now, attempt to route 250 sats (just a bit below the capacity).
3808 // Our algorithm should provide us with these 3 paths.
3809 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None,
3810 250_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3811 assert_eq!(route.paths.len(), 3);
3812 let mut total_amount_paid_msat = 0;
3813 for path in &route.paths {
3814 assert_eq!(path.len(), 2);
3815 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3816 total_amount_paid_msat += path.last().unwrap().fee_msat;
3818 assert_eq!(total_amount_paid_msat, 250_000);
3822 // Attempt to route an exact amount is also fine
3823 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None,
3824 290_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3825 assert_eq!(route.paths.len(), 3);
3826 let mut total_amount_paid_msat = 0;
3827 for path in &route.paths {
3828 assert_eq!(path.len(), 2);
3829 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3830 total_amount_paid_msat += path.last().unwrap().fee_msat;
3832 assert_eq!(total_amount_paid_msat, 290_000);
3837 fn long_mpp_route_test() {
3838 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3839 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3840 let scorer = ln_test_utils::TestScorer::with_penalty(0);
3841 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3842 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3843 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(channelmanager::provided_invoice_features());
3845 // We need a route consisting of 3 paths:
3846 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3847 // Note that these paths overlap (channels 5, 12, 13).
3848 // We will route 300 sats.
3849 // Each path will have 100 sats capacity, those channels which
3850 // are used twice will have 200 sats capacity.
3852 // Disable other potential paths.
3853 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3854 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3855 short_channel_id: 2,
3858 cltv_expiry_delta: 0,
3859 htlc_minimum_msat: 0,
3860 htlc_maximum_msat: 100_000,
3862 fee_proportional_millionths: 0,
3863 excess_data: Vec::new()
3865 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3866 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3867 short_channel_id: 7,
3870 cltv_expiry_delta: 0,
3871 htlc_minimum_msat: 0,
3872 htlc_maximum_msat: 100_000,
3874 fee_proportional_millionths: 0,
3875 excess_data: Vec::new()
3878 // Path via {node0, node2} is channels {1, 3, 5}.
3879 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3880 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3881 short_channel_id: 1,
3884 cltv_expiry_delta: 0,
3885 htlc_minimum_msat: 0,
3886 htlc_maximum_msat: 100_000,
3888 fee_proportional_millionths: 0,
3889 excess_data: Vec::new()
3891 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3892 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3893 short_channel_id: 3,
3896 cltv_expiry_delta: 0,
3897 htlc_minimum_msat: 0,
3898 htlc_maximum_msat: 100_000,
3900 fee_proportional_millionths: 0,
3901 excess_data: Vec::new()
3904 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3905 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3906 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3907 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3908 short_channel_id: 5,
3911 cltv_expiry_delta: 0,
3912 htlc_minimum_msat: 0,
3913 htlc_maximum_msat: 200_000,
3915 fee_proportional_millionths: 0,
3916 excess_data: Vec::new()
3919 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3920 // Add 100 sats to the capacities of {12, 13}, because these channels
3921 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3922 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3923 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3924 short_channel_id: 12,
3927 cltv_expiry_delta: 0,
3928 htlc_minimum_msat: 0,
3929 htlc_maximum_msat: 200_000,
3931 fee_proportional_millionths: 0,
3932 excess_data: Vec::new()
3934 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3935 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3936 short_channel_id: 13,
3939 cltv_expiry_delta: 0,
3940 htlc_minimum_msat: 0,
3941 htlc_maximum_msat: 200_000,
3943 fee_proportional_millionths: 0,
3944 excess_data: Vec::new()
3947 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3948 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3949 short_channel_id: 6,
3952 cltv_expiry_delta: 0,
3953 htlc_minimum_msat: 0,
3954 htlc_maximum_msat: 100_000,
3956 fee_proportional_millionths: 0,
3957 excess_data: Vec::new()
3959 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3960 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3961 short_channel_id: 11,
3964 cltv_expiry_delta: 0,
3965 htlc_minimum_msat: 0,
3966 htlc_maximum_msat: 100_000,
3968 fee_proportional_millionths: 0,
3969 excess_data: Vec::new()
3972 // Path via {node7, node2} is channels {12, 13, 5}.
3973 // We already limited them to 200 sats (they are used twice for 100 sats).
3974 // Nothing to do here.
3977 // Attempt to route more than available results in a failure.
3978 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3979 &our_id, &payment_params, &network_graph.read_only(), None, 350_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3980 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3981 } else { panic!(); }
3985 // Now, attempt to route 300 sats (exact amount we can route).
3986 // Our algorithm should provide us with these 3 paths, 100 sats each.
3987 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 300_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3988 assert_eq!(route.paths.len(), 3);
3990 let mut total_amount_paid_msat = 0;
3991 for path in &route.paths {
3992 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3993 total_amount_paid_msat += path.last().unwrap().fee_msat;
3995 assert_eq!(total_amount_paid_msat, 300_000);
4001 fn mpp_cheaper_route_test() {
4002 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4003 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4004 let scorer = ln_test_utils::TestScorer::with_penalty(0);
4005 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4006 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4007 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(channelmanager::provided_invoice_features());
4009 // This test checks that if we have two cheaper paths and one more expensive path,
4010 // so that liquidity-wise any 2 of 3 combination is sufficient,
4011 // two cheaper paths will be taken.
4012 // These paths have equal available liquidity.
4014 // We need a combination of 3 paths:
4015 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
4016 // Note that these paths overlap (channels 5, 12, 13).
4017 // Each path will have 100 sats capacity, those channels which
4018 // are used twice will have 200 sats capacity.
4020 // Disable other potential paths.
4021 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4022 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4023 short_channel_id: 2,
4026 cltv_expiry_delta: 0,
4027 htlc_minimum_msat: 0,
4028 htlc_maximum_msat: 100_000,
4030 fee_proportional_millionths: 0,
4031 excess_data: Vec::new()
4033 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4034 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4035 short_channel_id: 7,
4038 cltv_expiry_delta: 0,
4039 htlc_minimum_msat: 0,
4040 htlc_maximum_msat: 100_000,
4042 fee_proportional_millionths: 0,
4043 excess_data: Vec::new()
4046 // Path via {node0, node2} is channels {1, 3, 5}.
4047 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4048 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4049 short_channel_id: 1,
4052 cltv_expiry_delta: 0,
4053 htlc_minimum_msat: 0,
4054 htlc_maximum_msat: 100_000,
4056 fee_proportional_millionths: 0,
4057 excess_data: Vec::new()
4059 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4060 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4061 short_channel_id: 3,
4064 cltv_expiry_delta: 0,
4065 htlc_minimum_msat: 0,
4066 htlc_maximum_msat: 100_000,
4068 fee_proportional_millionths: 0,
4069 excess_data: Vec::new()
4072 // Capacity of 200 sats because this channel will be used by 3rd path as well.
4073 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4074 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4075 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4076 short_channel_id: 5,
4079 cltv_expiry_delta: 0,
4080 htlc_minimum_msat: 0,
4081 htlc_maximum_msat: 200_000,
4083 fee_proportional_millionths: 0,
4084 excess_data: Vec::new()
4087 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4088 // Add 100 sats to the capacities of {12, 13}, because these channels
4089 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
4090 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4091 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4092 short_channel_id: 12,
4095 cltv_expiry_delta: 0,
4096 htlc_minimum_msat: 0,
4097 htlc_maximum_msat: 200_000,
4099 fee_proportional_millionths: 0,
4100 excess_data: Vec::new()
4102 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4103 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4104 short_channel_id: 13,
4107 cltv_expiry_delta: 0,
4108 htlc_minimum_msat: 0,
4109 htlc_maximum_msat: 200_000,
4111 fee_proportional_millionths: 0,
4112 excess_data: Vec::new()
4115 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4116 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4117 short_channel_id: 6,
4120 cltv_expiry_delta: 0,
4121 htlc_minimum_msat: 0,
4122 htlc_maximum_msat: 100_000,
4123 fee_base_msat: 1_000,
4124 fee_proportional_millionths: 0,
4125 excess_data: Vec::new()
4127 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4128 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4129 short_channel_id: 11,
4132 cltv_expiry_delta: 0,
4133 htlc_minimum_msat: 0,
4134 htlc_maximum_msat: 100_000,
4136 fee_proportional_millionths: 0,
4137 excess_data: Vec::new()
4140 // Path via {node7, node2} is channels {12, 13, 5}.
4141 // We already limited them to 200 sats (they are used twice for 100 sats).
4142 // Nothing to do here.
4145 // Now, attempt to route 180 sats.
4146 // Our algorithm should provide us with these 2 paths.
4147 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 180_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4148 assert_eq!(route.paths.len(), 2);
4150 let mut total_value_transferred_msat = 0;
4151 let mut total_paid_msat = 0;
4152 for path in &route.paths {
4153 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
4154 total_value_transferred_msat += path.last().unwrap().fee_msat;
4156 total_paid_msat += hop.fee_msat;
4159 // If we paid fee, this would be higher.
4160 assert_eq!(total_value_transferred_msat, 180_000);
4161 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
4162 assert_eq!(total_fees_paid, 0);
4167 fn fees_on_mpp_route_test() {
4168 // This test makes sure that MPP algorithm properly takes into account
4169 // fees charged on the channels, by making the fees impactful:
4170 // if the fee is not properly accounted for, the behavior is different.
4171 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4172 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4173 let scorer = ln_test_utils::TestScorer::with_penalty(0);
4174 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4175 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4176 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(channelmanager::provided_invoice_features());
4178 // We need a route consisting of 2 paths:
4179 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
4180 // We will route 200 sats, Each path will have 100 sats capacity.
4182 // This test is not particularly stable: e.g.,
4183 // there's a way to route via {node0, node2, node4}.
4184 // It works while pathfinding is deterministic, but can be broken otherwise.
4185 // It's fine to ignore this concern for now.
4187 // Disable other potential paths.
4188 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4189 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4190 short_channel_id: 2,
4193 cltv_expiry_delta: 0,
4194 htlc_minimum_msat: 0,
4195 htlc_maximum_msat: 100_000,
4197 fee_proportional_millionths: 0,
4198 excess_data: Vec::new()
4201 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4202 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4203 short_channel_id: 7,
4206 cltv_expiry_delta: 0,
4207 htlc_minimum_msat: 0,
4208 htlc_maximum_msat: 100_000,
4210 fee_proportional_millionths: 0,
4211 excess_data: Vec::new()
4214 // Path via {node0, node2} is channels {1, 3, 5}.
4215 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4216 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4217 short_channel_id: 1,
4220 cltv_expiry_delta: 0,
4221 htlc_minimum_msat: 0,
4222 htlc_maximum_msat: 100_000,
4224 fee_proportional_millionths: 0,
4225 excess_data: Vec::new()
4227 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4228 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4229 short_channel_id: 3,
4232 cltv_expiry_delta: 0,
4233 htlc_minimum_msat: 0,
4234 htlc_maximum_msat: 100_000,
4236 fee_proportional_millionths: 0,
4237 excess_data: Vec::new()
4240 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4241 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4242 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4243 short_channel_id: 5,
4246 cltv_expiry_delta: 0,
4247 htlc_minimum_msat: 0,
4248 htlc_maximum_msat: 100_000,
4250 fee_proportional_millionths: 0,
4251 excess_data: Vec::new()
4254 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4255 // All channels should be 100 sats capacity. But for the fee experiment,
4256 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
4257 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
4258 // 100 sats (and pay 150 sats in fees for the use of channel 6),
4259 // so no matter how large are other channels,
4260 // the whole path will be limited by 100 sats with just these 2 conditions:
4261 // - channel 12 capacity is 250 sats
4262 // - fee for channel 6 is 150 sats
4263 // Let's test this by enforcing these 2 conditions and removing other limits.
4264 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4265 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4266 short_channel_id: 12,
4269 cltv_expiry_delta: 0,
4270 htlc_minimum_msat: 0,
4271 htlc_maximum_msat: 250_000,
4273 fee_proportional_millionths: 0,
4274 excess_data: Vec::new()
4276 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4277 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4278 short_channel_id: 13,
4281 cltv_expiry_delta: 0,
4282 htlc_minimum_msat: 0,
4283 htlc_maximum_msat: MAX_VALUE_MSAT,
4285 fee_proportional_millionths: 0,
4286 excess_data: Vec::new()
4289 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4290 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4291 short_channel_id: 6,
4294 cltv_expiry_delta: 0,
4295 htlc_minimum_msat: 0,
4296 htlc_maximum_msat: MAX_VALUE_MSAT,
4297 fee_base_msat: 150_000,
4298 fee_proportional_millionths: 0,
4299 excess_data: Vec::new()
4301 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4302 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4303 short_channel_id: 11,
4306 cltv_expiry_delta: 0,
4307 htlc_minimum_msat: 0,
4308 htlc_maximum_msat: MAX_VALUE_MSAT,
4310 fee_proportional_millionths: 0,
4311 excess_data: Vec::new()
4315 // Attempt to route more than available results in a failure.
4316 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4317 &our_id, &payment_params, &network_graph.read_only(), None, 210_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
4318 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4319 } else { panic!(); }
4323 // Now, attempt to route 200 sats (exact amount we can route).
4324 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 200_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4325 assert_eq!(route.paths.len(), 2);
4327 let mut total_amount_paid_msat = 0;
4328 for path in &route.paths {
4329 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
4330 total_amount_paid_msat += path.last().unwrap().fee_msat;
4332 assert_eq!(total_amount_paid_msat, 200_000);
4333 assert_eq!(route.get_total_fees(), 150_000);
4338 fn mpp_with_last_hops() {
4339 // Previously, if we tried to send an MPP payment to a destination which was only reachable
4340 // via a single last-hop route hint, we'd fail to route if we first collected routes
4341 // totaling close but not quite enough to fund the full payment.
4343 // This was because we considered last-hop hints to have exactly the sought payment amount
4344 // instead of the amount we were trying to collect, needlessly limiting our path searching
4345 // at the very first hop.
4347 // Specifically, this interacted with our "all paths must fund at least 5% of total target"
4348 // criterion to cause us to refuse all routes at the last hop hint which would be considered
4349 // to only have the remaining to-collect amount in available liquidity.
4351 // This bug appeared in production in some specific channel configurations.
4352 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4353 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4354 let scorer = ln_test_utils::TestScorer::with_penalty(0);
4355 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4356 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4357 let payment_params = PaymentParameters::from_node_id(PublicKey::from_slice(&[02; 33]).unwrap()).with_features(channelmanager::provided_invoice_features())
4358 .with_route_hints(vec![RouteHint(vec![RouteHintHop {
4359 src_node_id: nodes[2],
4360 short_channel_id: 42,
4361 fees: RoutingFees { base_msat: 0, proportional_millionths: 0 },
4362 cltv_expiry_delta: 42,
4363 htlc_minimum_msat: None,
4364 htlc_maximum_msat: None,
4365 }])]).with_max_channel_saturation_power_of_half(0);
4367 // Keep only two paths from us to nodes[2], both with a 99sat HTLC maximum, with one with
4368 // no fee and one with a 1msat fee. Previously, trying to route 100 sats to nodes[2] here
4369 // would first use the no-fee route and then fail to find a path along the second route as
4370 // we think we can only send up to 1 additional sat over the last-hop but refuse to as its
4371 // under 5% of our payment amount.
4372 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4373 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4374 short_channel_id: 1,
4377 cltv_expiry_delta: (5 << 4) | 5,
4378 htlc_minimum_msat: 0,
4379 htlc_maximum_msat: 99_000,
4380 fee_base_msat: u32::max_value(),
4381 fee_proportional_millionths: u32::max_value(),
4382 excess_data: Vec::new()
4384 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4385 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4386 short_channel_id: 2,
4389 cltv_expiry_delta: (5 << 4) | 3,
4390 htlc_minimum_msat: 0,
4391 htlc_maximum_msat: 99_000,
4392 fee_base_msat: u32::max_value(),
4393 fee_proportional_millionths: u32::max_value(),
4394 excess_data: Vec::new()
4396 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4397 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4398 short_channel_id: 4,
4401 cltv_expiry_delta: (4 << 4) | 1,
4402 htlc_minimum_msat: 0,
4403 htlc_maximum_msat: MAX_VALUE_MSAT,
4405 fee_proportional_millionths: 0,
4406 excess_data: Vec::new()
4408 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4409 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4410 short_channel_id: 13,
4412 flags: 0|2, // Channel disabled
4413 cltv_expiry_delta: (13 << 4) | 1,
4414 htlc_minimum_msat: 0,
4415 htlc_maximum_msat: MAX_VALUE_MSAT,
4417 fee_proportional_millionths: 2000000,
4418 excess_data: Vec::new()
4421 // Get a route for 100 sats and check that we found the MPP route no problem and didn't
4423 let mut route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4424 assert_eq!(route.paths.len(), 2);
4425 route.paths.sort_by_key(|path| path[0].short_channel_id);
4426 // Paths are manually ordered ordered by SCID, so:
4427 // * the first is channel 1 (0 fee, but 99 sat maximum) -> channel 3 -> channel 42
4428 // * the second is channel 2 (1 msat fee) -> channel 4 -> channel 42
4429 assert_eq!(route.paths[0][0].short_channel_id, 1);
4430 assert_eq!(route.paths[0][0].fee_msat, 0);
4431 assert_eq!(route.paths[0][2].fee_msat, 99_000);
4432 assert_eq!(route.paths[1][0].short_channel_id, 2);
4433 assert_eq!(route.paths[1][0].fee_msat, 1);
4434 assert_eq!(route.paths[1][2].fee_msat, 1_000);
4435 assert_eq!(route.get_total_fees(), 1);
4436 assert_eq!(route.get_total_amount(), 100_000);
4440 fn drop_lowest_channel_mpp_route_test() {
4441 // This test checks that low-capacity channel is dropped when after
4442 // path finding we realize that we found more capacity than we need.
4443 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4444 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4445 let scorer = ln_test_utils::TestScorer::with_penalty(0);
4446 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4447 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4448 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(channelmanager::provided_invoice_features())
4449 .with_max_channel_saturation_power_of_half(0);
4451 // We need a route consisting of 3 paths:
4452 // From our node to node2 via node0, node7, node1 (three paths one hop each).
4454 // The first and the second paths should be sufficient, but the third should be
4455 // cheaper, so that we select it but drop later.
4457 // First, we set limits on these (previously unlimited) channels.
4458 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
4460 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
4461 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4462 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4463 short_channel_id: 1,
4466 cltv_expiry_delta: 0,
4467 htlc_minimum_msat: 0,
4468 htlc_maximum_msat: 100_000,
4470 fee_proportional_millionths: 0,
4471 excess_data: Vec::new()
4473 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4474 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4475 short_channel_id: 3,
4478 cltv_expiry_delta: 0,
4479 htlc_minimum_msat: 0,
4480 htlc_maximum_msat: 50_000,
4482 fee_proportional_millionths: 0,
4483 excess_data: Vec::new()
4486 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
4487 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4488 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4489 short_channel_id: 12,
4492 cltv_expiry_delta: 0,
4493 htlc_minimum_msat: 0,
4494 htlc_maximum_msat: 60_000,
4496 fee_proportional_millionths: 0,
4497 excess_data: Vec::new()
4499 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4500 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4501 short_channel_id: 13,
4504 cltv_expiry_delta: 0,
4505 htlc_minimum_msat: 0,
4506 htlc_maximum_msat: 60_000,
4508 fee_proportional_millionths: 0,
4509 excess_data: Vec::new()
4512 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
4513 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4514 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4515 short_channel_id: 2,
4518 cltv_expiry_delta: 0,
4519 htlc_minimum_msat: 0,
4520 htlc_maximum_msat: 20_000,
4522 fee_proportional_millionths: 0,
4523 excess_data: Vec::new()
4525 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4526 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4527 short_channel_id: 4,
4530 cltv_expiry_delta: 0,
4531 htlc_minimum_msat: 0,
4532 htlc_maximum_msat: 20_000,
4534 fee_proportional_millionths: 0,
4535 excess_data: Vec::new()
4539 // Attempt to route more than available results in a failure.
4540 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4541 &our_id, &payment_params, &network_graph.read_only(), None, 150_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
4542 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4543 } else { panic!(); }
4547 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
4548 // Our algorithm should provide us with these 3 paths.
4549 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 125_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4550 assert_eq!(route.paths.len(), 3);
4551 let mut total_amount_paid_msat = 0;
4552 for path in &route.paths {
4553 assert_eq!(path.len(), 2);
4554 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4555 total_amount_paid_msat += path.last().unwrap().fee_msat;
4557 assert_eq!(total_amount_paid_msat, 125_000);
4561 // Attempt to route without the last small cheap channel
4562 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4563 assert_eq!(route.paths.len(), 2);
4564 let mut total_amount_paid_msat = 0;
4565 for path in &route.paths {
4566 assert_eq!(path.len(), 2);
4567 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4568 total_amount_paid_msat += path.last().unwrap().fee_msat;
4570 assert_eq!(total_amount_paid_msat, 90_000);
4575 fn min_criteria_consistency() {
4576 // Test that we don't use an inconsistent metric between updating and walking nodes during
4577 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
4578 // was updated with a different criterion from the heap sorting, resulting in loops in
4579 // calculated paths. We test for that specific case here.
4581 // We construct a network that looks like this:
4583 // node2 -1(3)2- node3
4587 // node1 -1(5)2- node4 -1(1)2- node6
4593 // We create a loop on the side of our real path - our destination is node 6, with a
4594 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
4595 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
4596 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
4597 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
4598 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
4599 // "previous hop" being set to node 3, creating a loop in the path.
4600 let secp_ctx = Secp256k1::new();
4601 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
4602 let logger = Arc::new(ln_test_utils::TestLogger::new());
4603 let network = Arc::new(NetworkGraph::new(genesis_hash, Arc::clone(&logger)));
4604 let gossip_sync = P2PGossipSync::new(Arc::clone(&network), None, Arc::clone(&logger));
4605 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4606 let scorer = ln_test_utils::TestScorer::with_penalty(0);
4607 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4608 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4609 let payment_params = PaymentParameters::from_node_id(nodes[6]);
4611 add_channel(&gossip_sync, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
4612 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4613 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4614 short_channel_id: 6,
4617 cltv_expiry_delta: (6 << 4) | 0,
4618 htlc_minimum_msat: 0,
4619 htlc_maximum_msat: MAX_VALUE_MSAT,
4621 fee_proportional_millionths: 0,
4622 excess_data: Vec::new()
4624 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
4626 add_channel(&gossip_sync, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4627 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4628 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4629 short_channel_id: 5,
4632 cltv_expiry_delta: (5 << 4) | 0,
4633 htlc_minimum_msat: 0,
4634 htlc_maximum_msat: MAX_VALUE_MSAT,
4636 fee_proportional_millionths: 0,
4637 excess_data: Vec::new()
4639 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
4641 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
4642 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4643 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4644 short_channel_id: 4,
4647 cltv_expiry_delta: (4 << 4) | 0,
4648 htlc_minimum_msat: 0,
4649 htlc_maximum_msat: MAX_VALUE_MSAT,
4651 fee_proportional_millionths: 0,
4652 excess_data: Vec::new()
4654 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
4656 add_channel(&gossip_sync, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
4657 update_channel(&gossip_sync, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
4658 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4659 short_channel_id: 3,
4662 cltv_expiry_delta: (3 << 4) | 0,
4663 htlc_minimum_msat: 0,
4664 htlc_maximum_msat: MAX_VALUE_MSAT,
4666 fee_proportional_millionths: 0,
4667 excess_data: Vec::new()
4669 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
4671 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
4672 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4673 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4674 short_channel_id: 2,
4677 cltv_expiry_delta: (2 << 4) | 0,
4678 htlc_minimum_msat: 0,
4679 htlc_maximum_msat: MAX_VALUE_MSAT,
4681 fee_proportional_millionths: 0,
4682 excess_data: Vec::new()
4685 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
4686 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4687 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4688 short_channel_id: 1,
4691 cltv_expiry_delta: (1 << 4) | 0,
4692 htlc_minimum_msat: 100,
4693 htlc_maximum_msat: MAX_VALUE_MSAT,
4695 fee_proportional_millionths: 0,
4696 excess_data: Vec::new()
4698 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
4701 // Now ensure the route flows simply over nodes 1 and 4 to 6.
4702 let route = get_route(&our_id, &payment_params, &network.read_only(), None, 10_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4703 assert_eq!(route.paths.len(), 1);
4704 assert_eq!(route.paths[0].len(), 3);
4706 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
4707 assert_eq!(route.paths[0][0].short_channel_id, 6);
4708 assert_eq!(route.paths[0][0].fee_msat, 100);
4709 assert_eq!(route.paths[0][0].cltv_expiry_delta, (5 << 4) | 0);
4710 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(1));
4711 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(6));
4713 assert_eq!(route.paths[0][1].pubkey, nodes[4]);
4714 assert_eq!(route.paths[0][1].short_channel_id, 5);
4715 assert_eq!(route.paths[0][1].fee_msat, 0);
4716 assert_eq!(route.paths[0][1].cltv_expiry_delta, (1 << 4) | 0);
4717 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(4));
4718 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(5));
4720 assert_eq!(route.paths[0][2].pubkey, nodes[6]);
4721 assert_eq!(route.paths[0][2].short_channel_id, 1);
4722 assert_eq!(route.paths[0][2].fee_msat, 10_000);
4723 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
4724 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
4725 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(1));
4731 fn exact_fee_liquidity_limit() {
4732 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
4733 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
4734 // we calculated fees on a higher value, resulting in us ignoring such paths.
4735 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4736 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
4737 let scorer = ln_test_utils::TestScorer::with_penalty(0);
4738 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4739 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4740 let payment_params = PaymentParameters::from_node_id(nodes[2]);
4742 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
4744 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4745 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4746 short_channel_id: 2,
4749 cltv_expiry_delta: 0,
4750 htlc_minimum_msat: 0,
4751 htlc_maximum_msat: 85_000,
4753 fee_proportional_millionths: 0,
4754 excess_data: Vec::new()
4757 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4758 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4759 short_channel_id: 12,
4762 cltv_expiry_delta: (4 << 4) | 1,
4763 htlc_minimum_msat: 0,
4764 htlc_maximum_msat: 270_000,
4766 fee_proportional_millionths: 1000000,
4767 excess_data: Vec::new()
4771 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
4772 // 200% fee charged channel 13 in the 1-to-2 direction.
4773 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4774 assert_eq!(route.paths.len(), 1);
4775 assert_eq!(route.paths[0].len(), 2);
4777 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
4778 assert_eq!(route.paths[0][0].short_channel_id, 12);
4779 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
4780 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
4781 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
4782 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
4784 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
4785 assert_eq!(route.paths[0][1].short_channel_id, 13);
4786 assert_eq!(route.paths[0][1].fee_msat, 90_000);
4787 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
4788 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
4789 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
4794 fn htlc_max_reduction_below_min() {
4795 // Test that if, while walking the graph, we reduce the value being sent to meet an
4796 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
4797 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
4798 // resulting in us thinking there is no possible path, even if other paths exist.
4799 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4800 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4801 let scorer = ln_test_utils::TestScorer::with_penalty(0);
4802 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4803 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4804 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(channelmanager::provided_invoice_features());
4806 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
4807 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
4808 // then try to send 90_000.
4809 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4810 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4811 short_channel_id: 2,
4814 cltv_expiry_delta: 0,
4815 htlc_minimum_msat: 0,
4816 htlc_maximum_msat: 80_000,
4818 fee_proportional_millionths: 0,
4819 excess_data: Vec::new()
4821 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4822 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4823 short_channel_id: 4,
4826 cltv_expiry_delta: (4 << 4) | 1,
4827 htlc_minimum_msat: 90_000,
4828 htlc_maximum_msat: MAX_VALUE_MSAT,
4830 fee_proportional_millionths: 0,
4831 excess_data: Vec::new()
4835 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
4836 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
4837 // expensive) channels 12-13 path.
4838 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4839 assert_eq!(route.paths.len(), 1);
4840 assert_eq!(route.paths[0].len(), 2);
4842 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
4843 assert_eq!(route.paths[0][0].short_channel_id, 12);
4844 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
4845 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
4846 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
4847 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
4849 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
4850 assert_eq!(route.paths[0][1].short_channel_id, 13);
4851 assert_eq!(route.paths[0][1].fee_msat, 90_000);
4852 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
4853 assert_eq!(route.paths[0][1].node_features.le_flags(), channelmanager::provided_invoice_features().le_flags());
4854 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
4859 fn multiple_direct_first_hops() {
4860 // Previously we'd only ever considered one first hop path per counterparty.
4861 // However, as we don't restrict users to one channel per peer, we really need to support
4862 // looking at all first hop paths.
4863 // Here we test that we do not ignore all-but-the-last first hop paths per counterparty (as
4864 // we used to do by overwriting the `first_hop_targets` hashmap entry) and that we can MPP
4865 // route over multiple channels with the same first hop.
4866 let secp_ctx = Secp256k1::new();
4867 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4868 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
4869 let logger = Arc::new(ln_test_utils::TestLogger::new());
4870 let network_graph = NetworkGraph::new(genesis_hash, Arc::clone(&logger));
4871 let scorer = ln_test_utils::TestScorer::with_penalty(0);
4872 let payment_params = PaymentParameters::from_node_id(nodes[0]).with_features(channelmanager::provided_invoice_features());
4873 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4874 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4877 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
4878 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(), 200_000),
4879 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(), 10_000),
4880 ]), 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4881 assert_eq!(route.paths.len(), 1);
4882 assert_eq!(route.paths[0].len(), 1);
4884 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
4885 assert_eq!(route.paths[0][0].short_channel_id, 3);
4886 assert_eq!(route.paths[0][0].fee_msat, 100_000);
4889 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
4890 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(), 50_000),
4891 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(), 50_000),
4892 ]), 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4893 assert_eq!(route.paths.len(), 2);
4894 assert_eq!(route.paths[0].len(), 1);
4895 assert_eq!(route.paths[1].len(), 1);
4897 assert!((route.paths[0][0].short_channel_id == 3 && route.paths[1][0].short_channel_id == 2) ||
4898 (route.paths[0][0].short_channel_id == 2 && route.paths[1][0].short_channel_id == 3));
4900 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
4901 assert_eq!(route.paths[0][0].fee_msat, 50_000);
4903 assert_eq!(route.paths[1][0].pubkey, nodes[0]);
4904 assert_eq!(route.paths[1][0].fee_msat, 50_000);
4908 // If we have a bunch of outbound channels to the same node, where most are not
4909 // sufficient to pay the full payment, but one is, we should default to just using the
4910 // one single channel that has sufficient balance, avoiding MPP.
4912 // If we have several options above the 3xpayment value threshold, we should pick the
4913 // smallest of them, avoiding further fragmenting our available outbound balance to
4915 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
4916 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(), 50_000),
4917 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(), 50_000),
4918 &get_channel_details(Some(5), nodes[0], channelmanager::provided_init_features(), 50_000),
4919 &get_channel_details(Some(6), nodes[0], channelmanager::provided_init_features(), 300_000),
4920 &get_channel_details(Some(7), nodes[0], channelmanager::provided_init_features(), 50_000),
4921 &get_channel_details(Some(8), nodes[0], channelmanager::provided_init_features(), 50_000),
4922 &get_channel_details(Some(9), nodes[0], channelmanager::provided_init_features(), 50_000),
4923 &get_channel_details(Some(4), nodes[0], channelmanager::provided_init_features(), 1_000_000),
4924 ]), 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4925 assert_eq!(route.paths.len(), 1);
4926 assert_eq!(route.paths[0].len(), 1);
4928 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
4929 assert_eq!(route.paths[0][0].short_channel_id, 6);
4930 assert_eq!(route.paths[0][0].fee_msat, 100_000);
4935 fn prefers_shorter_route_with_higher_fees() {
4936 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4937 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4938 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
4940 // Without penalizing each hop 100 msats, a longer path with lower fees is chosen.
4941 let scorer = ln_test_utils::TestScorer::with_penalty(0);
4942 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4943 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4944 let route = get_route(
4945 &our_id, &payment_params, &network_graph.read_only(), None, 100, 42,
4946 Arc::clone(&logger), &scorer, &random_seed_bytes
4948 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4950 assert_eq!(route.get_total_fees(), 100);
4951 assert_eq!(route.get_total_amount(), 100);
4952 assert_eq!(path, vec![2, 4, 6, 11, 8]);
4954 // Applying a 100 msat penalty to each hop results in taking channels 7 and 10 to nodes[6]
4955 // from nodes[2] rather than channel 6, 11, and 8, even though the longer path is cheaper.
4956 let scorer = ln_test_utils::TestScorer::with_penalty(100);
4957 let route = get_route(
4958 &our_id, &payment_params, &network_graph.read_only(), None, 100, 42,
4959 Arc::clone(&logger), &scorer, &random_seed_bytes
4961 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4963 assert_eq!(route.get_total_fees(), 300);
4964 assert_eq!(route.get_total_amount(), 100);
4965 assert_eq!(path, vec![2, 4, 7, 10]);
4968 struct BadChannelScorer {
4969 short_channel_id: u64,
4973 impl Writeable for BadChannelScorer {
4974 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
4976 impl Score for BadChannelScorer {
4977 fn channel_penalty_msat(&self, short_channel_id: u64, _: &NodeId, _: &NodeId, _: ChannelUsage) -> u64 {
4978 if short_channel_id == self.short_channel_id { u64::max_value() } else { 0 }
4981 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
4982 fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
4983 fn probe_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
4984 fn probe_successful(&mut self, _path: &[&RouteHop]) {}
4987 struct BadNodeScorer {
4992 impl Writeable for BadNodeScorer {
4993 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
4996 impl Score for BadNodeScorer {
4997 fn channel_penalty_msat(&self, _: u64, _: &NodeId, target: &NodeId, _: ChannelUsage) -> u64 {
4998 if *target == self.node_id { u64::max_value() } else { 0 }
5001 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
5002 fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
5003 fn probe_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
5004 fn probe_successful(&mut self, _path: &[&RouteHop]) {}
5008 fn avoids_routing_through_bad_channels_and_nodes() {
5009 let (secp_ctx, network, _, _, logger) = build_graph();
5010 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5011 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
5012 let network_graph = network.read_only();
5014 // A path to nodes[6] exists when no penalties are applied to any channel.
5015 let scorer = ln_test_utils::TestScorer::with_penalty(0);
5016 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5017 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5018 let route = get_route(
5019 &our_id, &payment_params, &network_graph, None, 100, 42,
5020 Arc::clone(&logger), &scorer, &random_seed_bytes
5022 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5024 assert_eq!(route.get_total_fees(), 100);
5025 assert_eq!(route.get_total_amount(), 100);
5026 assert_eq!(path, vec![2, 4, 6, 11, 8]);
5028 // A different path to nodes[6] exists if channel 6 cannot be routed over.
5029 let scorer = BadChannelScorer { short_channel_id: 6 };
5030 let route = get_route(
5031 &our_id, &payment_params, &network_graph, None, 100, 42,
5032 Arc::clone(&logger), &scorer, &random_seed_bytes
5034 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5036 assert_eq!(route.get_total_fees(), 300);
5037 assert_eq!(route.get_total_amount(), 100);
5038 assert_eq!(path, vec![2, 4, 7, 10]);
5040 // A path to nodes[6] does not exist if nodes[2] cannot be routed through.
5041 let scorer = BadNodeScorer { node_id: NodeId::from_pubkey(&nodes[2]) };
5043 &our_id, &payment_params, &network_graph, None, 100, 42,
5044 Arc::clone(&logger), &scorer, &random_seed_bytes
5046 Err(LightningError { err, .. } ) => {
5047 assert_eq!(err, "Failed to find a path to the given destination");
5049 Ok(_) => panic!("Expected error"),
5054 fn total_fees_single_path() {
5058 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5059 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5060 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5063 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5064 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5065 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5068 pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
5069 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5070 short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0
5073 payment_params: None,
5076 assert_eq!(route.get_total_fees(), 250);
5077 assert_eq!(route.get_total_amount(), 225);
5081 fn total_fees_multi_path() {
5085 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5086 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5087 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5090 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5091 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5092 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5096 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5097 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5098 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5101 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5102 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5103 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5106 payment_params: None,
5109 assert_eq!(route.get_total_fees(), 200);
5110 assert_eq!(route.get_total_amount(), 300);
5114 fn total_empty_route_no_panic() {
5115 // In an earlier version of `Route::get_total_fees` and `Route::get_total_amount`, they
5116 // would both panic if the route was completely empty. We test to ensure they return 0
5117 // here, even though its somewhat nonsensical as a route.
5118 let route = Route { paths: Vec::new(), payment_params: None };
5120 assert_eq!(route.get_total_fees(), 0);
5121 assert_eq!(route.get_total_amount(), 0);
5125 fn limits_total_cltv_delta() {
5126 let (secp_ctx, network, _, _, logger) = build_graph();
5127 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5128 let network_graph = network.read_only();
5130 let scorer = ln_test_utils::TestScorer::with_penalty(0);
5132 // Make sure that generally there is at least one route available
5133 let feasible_max_total_cltv_delta = 1008;
5134 let feasible_payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes))
5135 .with_max_total_cltv_expiry_delta(feasible_max_total_cltv_delta);
5136 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5137 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5138 let route = get_route(&our_id, &feasible_payment_params, &network_graph, None, 100, 0, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5139 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5140 assert_ne!(path.len(), 0);
5142 // But not if we exclude all paths on the basis of their accumulated CLTV delta
5143 let fail_max_total_cltv_delta = 23;
5144 let fail_payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes))
5145 .with_max_total_cltv_expiry_delta(fail_max_total_cltv_delta);
5146 match get_route(&our_id, &fail_payment_params, &network_graph, None, 100, 0, Arc::clone(&logger), &scorer, &random_seed_bytes)
5148 Err(LightningError { err, .. } ) => {
5149 assert_eq!(err, "Failed to find a path to the given destination");
5151 Ok(_) => panic!("Expected error"),
5156 fn avoids_recently_failed_paths() {
5157 // Ensure that the router always avoids all of the `previously_failed_channels` channels by
5158 // randomly inserting channels into it until we can't find a route anymore.
5159 let (secp_ctx, network, _, _, logger) = build_graph();
5160 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5161 let network_graph = network.read_only();
5163 let scorer = ln_test_utils::TestScorer::with_penalty(0);
5164 let mut payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes))
5165 .with_max_path_count(1);
5166 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5167 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5169 // We should be able to find a route initially, and then after we fail a few random
5170 // channels eventually we won't be able to any longer.
5171 assert!(get_route(&our_id, &payment_params, &network_graph, None, 100, 0, Arc::clone(&logger), &scorer, &random_seed_bytes).is_ok());
5173 if let Ok(route) = get_route(&our_id, &payment_params, &network_graph, None, 100, 0, Arc::clone(&logger), &scorer, &random_seed_bytes) {
5174 for chan in route.paths[0].iter() {
5175 assert!(!payment_params.previously_failed_channels.contains(&chan.short_channel_id));
5177 let victim = (u64::from_ne_bytes(random_seed_bytes[0..8].try_into().unwrap()) as usize)
5178 % route.paths[0].len();
5179 payment_params.previously_failed_channels.push(route.paths[0][victim].short_channel_id);
5185 fn limits_path_length() {
5186 let (secp_ctx, network, _, _, logger) = build_line_graph();
5187 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5188 let network_graph = network.read_only();
5190 let scorer = ln_test_utils::TestScorer::with_penalty(0);
5191 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5192 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5194 // First check we can actually create a long route on this graph.
5195 let feasible_payment_params = PaymentParameters::from_node_id(nodes[18]);
5196 let route = get_route(&our_id, &feasible_payment_params, &network_graph, None, 100, 0,
5197 Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5198 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5199 assert!(path.len() == MAX_PATH_LENGTH_ESTIMATE.into());
5201 // But we can't create a path surpassing the MAX_PATH_LENGTH_ESTIMATE limit.
5202 let fail_payment_params = PaymentParameters::from_node_id(nodes[19]);
5203 match get_route(&our_id, &fail_payment_params, &network_graph, None, 100, 0,
5204 Arc::clone(&logger), &scorer, &random_seed_bytes)
5206 Err(LightningError { err, .. } ) => {
5207 assert_eq!(err, "Failed to find a path to the given destination");
5209 Ok(_) => panic!("Expected error"),
5214 fn adds_and_limits_cltv_offset() {
5215 let (secp_ctx, network_graph, _, _, logger) = build_graph();
5216 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5218 let scorer = ln_test_utils::TestScorer::with_penalty(0);
5220 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
5221 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5222 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5223 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5224 assert_eq!(route.paths.len(), 1);
5226 let cltv_expiry_deltas_before = route.paths[0].iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5228 // Check whether the offset added to the last hop by default is in [1 .. DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA]
5229 let mut route_default = route.clone();
5230 add_random_cltv_offset(&mut route_default, &payment_params, &network_graph.read_only(), &random_seed_bytes);
5231 let cltv_expiry_deltas_default = route_default.paths[0].iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5232 assert_eq!(cltv_expiry_deltas_before.split_last().unwrap().1, cltv_expiry_deltas_default.split_last().unwrap().1);
5233 assert!(cltv_expiry_deltas_default.last() > cltv_expiry_deltas_before.last());
5234 assert!(cltv_expiry_deltas_default.last().unwrap() <= &DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA);
5236 // Check that no offset is added when we restrict the max_total_cltv_expiry_delta
5237 let mut route_limited = route.clone();
5238 let limited_max_total_cltv_expiry_delta = cltv_expiry_deltas_before.iter().sum();
5239 let limited_payment_params = payment_params.with_max_total_cltv_expiry_delta(limited_max_total_cltv_expiry_delta);
5240 add_random_cltv_offset(&mut route_limited, &limited_payment_params, &network_graph.read_only(), &random_seed_bytes);
5241 let cltv_expiry_deltas_limited = route_limited.paths[0].iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5242 assert_eq!(cltv_expiry_deltas_before, cltv_expiry_deltas_limited);
5246 fn adds_plausible_cltv_offset() {
5247 let (secp_ctx, network, _, _, logger) = build_graph();
5248 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5249 let network_graph = network.read_only();
5250 let network_nodes = network_graph.nodes();
5251 let network_channels = network_graph.channels();
5252 let scorer = ln_test_utils::TestScorer::with_penalty(0);
5253 let payment_params = PaymentParameters::from_node_id(nodes[3]);
5254 let keys_manager = ln_test_utils::TestKeysInterface::new(&[4u8; 32], Network::Testnet);
5255 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5257 let mut route = get_route(&our_id, &payment_params, &network_graph, None, 100, 0,
5258 Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5259 add_random_cltv_offset(&mut route, &payment_params, &network_graph, &random_seed_bytes);
5261 let mut path_plausibility = vec![];
5263 for p in route.paths {
5264 // 1. Select random observation point
5265 let mut prng = ChaCha20::new(&random_seed_bytes, &[0u8; 12]);
5266 let mut random_bytes = [0u8; ::core::mem::size_of::<usize>()];
5268 prng.process_in_place(&mut random_bytes);
5269 let random_path_index = usize::from_be_bytes(random_bytes).wrapping_rem(p.len());
5270 let observation_point = NodeId::from_pubkey(&p.get(random_path_index).unwrap().pubkey);
5272 // 2. Calculate what CLTV expiry delta we would observe there
5273 let observed_cltv_expiry_delta: u32 = p[random_path_index..].iter().map(|h| h.cltv_expiry_delta).sum();
5275 // 3. Starting from the observation point, find candidate paths
5276 let mut candidates: VecDeque<(NodeId, Vec<u32>)> = VecDeque::new();
5277 candidates.push_back((observation_point, vec![]));
5279 let mut found_plausible_candidate = false;
5281 'candidate_loop: while let Some((cur_node_id, cur_path_cltv_deltas)) = candidates.pop_front() {
5282 if let Some(remaining) = observed_cltv_expiry_delta.checked_sub(cur_path_cltv_deltas.iter().sum::<u32>()) {
5283 if remaining == 0 || remaining.wrapping_rem(40) == 0 || remaining.wrapping_rem(144) == 0 {
5284 found_plausible_candidate = true;
5285 break 'candidate_loop;
5289 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
5290 for channel_id in &cur_node.channels {
5291 if let Some(channel_info) = network_channels.get(&channel_id) {
5292 if let Some((dir_info, next_id)) = channel_info.as_directed_from(&cur_node_id) {
5293 let next_cltv_expiry_delta = dir_info.direction().cltv_expiry_delta as u32;
5294 if cur_path_cltv_deltas.iter().sum::<u32>()
5295 .saturating_add(next_cltv_expiry_delta) <= observed_cltv_expiry_delta {
5296 let mut new_path_cltv_deltas = cur_path_cltv_deltas.clone();
5297 new_path_cltv_deltas.push(next_cltv_expiry_delta);
5298 candidates.push_back((*next_id, new_path_cltv_deltas));
5306 path_plausibility.push(found_plausible_candidate);
5308 assert!(path_plausibility.iter().all(|x| *x));
5312 fn builds_correct_path_from_hops() {
5313 let (secp_ctx, network, _, _, logger) = build_graph();
5314 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5315 let network_graph = network.read_only();
5317 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5318 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5320 let payment_params = PaymentParameters::from_node_id(nodes[3]);
5321 let hops = [nodes[1], nodes[2], nodes[4], nodes[3]];
5322 let route = build_route_from_hops_internal(&our_id, &hops, &payment_params,
5323 &network_graph, 100, 0, Arc::clone(&logger), &random_seed_bytes).unwrap();
5324 let route_hop_pubkeys = route.paths[0].iter().map(|hop| hop.pubkey).collect::<Vec<_>>();
5325 assert_eq!(hops.len(), route.paths[0].len());
5326 for (idx, hop_pubkey) in hops.iter().enumerate() {
5327 assert!(*hop_pubkey == route_hop_pubkeys[idx]);
5332 fn avoids_saturating_channels() {
5333 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5334 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5336 let scorer = ProbabilisticScorer::new(Default::default(), &*network_graph, Arc::clone(&logger));
5338 // Set the fee on channel 13 to 100% to match channel 4 giving us two equivalent paths (us
5339 // -> node 7 -> node2 and us -> node 1 -> node 2) which we should balance over.
5340 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5341 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5342 short_channel_id: 4,
5345 cltv_expiry_delta: (4 << 4) | 1,
5346 htlc_minimum_msat: 0,
5347 htlc_maximum_msat: 250_000_000,
5349 fee_proportional_millionths: 0,
5350 excess_data: Vec::new()
5352 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5353 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5354 short_channel_id: 13,
5357 cltv_expiry_delta: (13 << 4) | 1,
5358 htlc_minimum_msat: 0,
5359 htlc_maximum_msat: 250_000_000,
5361 fee_proportional_millionths: 0,
5362 excess_data: Vec::new()
5365 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(channelmanager::provided_invoice_features());
5366 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5367 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5368 // 100,000 sats is less than the available liquidity on each channel, set above.
5369 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100_000_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5370 assert_eq!(route.paths.len(), 2);
5371 assert!((route.paths[0][1].short_channel_id == 4 && route.paths[1][1].short_channel_id == 13) ||
5372 (route.paths[1][1].short_channel_id == 4 && route.paths[0][1].short_channel_id == 13));
5375 #[cfg(not(feature = "no-std"))]
5376 pub(super) fn random_init_seed() -> u64 {
5377 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
5378 use core::hash::{BuildHasher, Hasher};
5379 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
5380 println!("Using seed of {}", seed);
5383 #[cfg(not(feature = "no-std"))]
5384 use crate::util::ser::ReadableArgs;
5387 #[cfg(not(feature = "no-std"))]
5388 fn generate_routes() {
5389 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringParameters};
5391 let mut d = match super::bench_utils::get_route_file() {
5398 let logger = ln_test_utils::TestLogger::new();
5399 let graph = NetworkGraph::read(&mut d, &logger).unwrap();
5400 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5401 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5403 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
5404 let mut seed = random_init_seed() as usize;
5405 let nodes = graph.read_only().nodes().clone();
5406 'load_endpoints: for _ in 0..10 {
5408 seed = seed.overflowing_mul(0xdeadbeef).0;
5409 let src = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5410 seed = seed.overflowing_mul(0xdeadbeef).0;
5411 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5412 let payment_params = PaymentParameters::from_node_id(dst);
5413 let amt = seed as u64 % 200_000_000;
5414 let params = ProbabilisticScoringParameters::default();
5415 let scorer = ProbabilisticScorer::new(params, &graph, &logger);
5416 if get_route(src, &payment_params, &graph.read_only(), None, amt, 42, &logger, &scorer, &random_seed_bytes).is_ok() {
5417 continue 'load_endpoints;
5424 #[cfg(not(feature = "no-std"))]
5425 fn generate_routes_mpp() {
5426 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringParameters};
5428 let mut d = match super::bench_utils::get_route_file() {
5435 let logger = ln_test_utils::TestLogger::new();
5436 let graph = NetworkGraph::read(&mut d, &logger).unwrap();
5437 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5438 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5440 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
5441 let mut seed = random_init_seed() as usize;
5442 let nodes = graph.read_only().nodes().clone();
5443 'load_endpoints: for _ in 0..10 {
5445 seed = seed.overflowing_mul(0xdeadbeef).0;
5446 let src = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5447 seed = seed.overflowing_mul(0xdeadbeef).0;
5448 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5449 let payment_params = PaymentParameters::from_node_id(dst).with_features(channelmanager::provided_invoice_features());
5450 let amt = seed as u64 % 200_000_000;
5451 let params = ProbabilisticScoringParameters::default();
5452 let scorer = ProbabilisticScorer::new(params, &graph, &logger);
5453 if get_route(src, &payment_params, &graph.read_only(), None, amt, 42, &logger, &scorer, &random_seed_bytes).is_ok() {
5454 continue 'load_endpoints;
5461 fn honors_manual_penalties() {
5462 let (secp_ctx, network_graph, _, _, logger) = build_line_graph();
5463 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5465 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5466 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5468 let scorer_params = ProbabilisticScoringParameters::default();
5469 let mut scorer = ProbabilisticScorer::new(scorer_params, Arc::clone(&network_graph), Arc::clone(&logger));
5471 // First check set manual penalties are returned by the scorer.
5472 let usage = ChannelUsage {
5474 inflight_htlc_msat: 0,
5475 effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_024_000, htlc_maximum_msat: 1_000 },
5477 scorer.set_manual_penalty(&NodeId::from_pubkey(&nodes[3]), 123);
5478 scorer.set_manual_penalty(&NodeId::from_pubkey(&nodes[4]), 456);
5479 assert_eq!(scorer.channel_penalty_msat(42, &NodeId::from_pubkey(&nodes[3]), &NodeId::from_pubkey(&nodes[4]), usage), 456);
5481 // Then check we can get a normal route
5482 let payment_params = PaymentParameters::from_node_id(nodes[10]);
5483 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes);
5484 assert!(route.is_ok());
5486 // Then check that we can't get a route if we ban an intermediate node.
5487 scorer.add_banned(&NodeId::from_pubkey(&nodes[3]));
5488 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes);
5489 assert!(route.is_err());
5491 // Finally make sure we can route again, when we remove the ban.
5492 scorer.remove_banned(&NodeId::from_pubkey(&nodes[3]));
5493 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes);
5494 assert!(route.is_ok());
5498 #[cfg(all(test, not(feature = "no-std")))]
5499 pub(crate) mod bench_utils {
5501 /// Tries to open a network graph file, or panics with a URL to fetch it.
5502 pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
5503 let res = File::open("net_graph-2021-05-31.bin") // By default we're run in RL/lightning
5504 .or_else(|_| File::open("lightning/net_graph-2021-05-31.bin")) // We may be run manually in RL/
5505 .or_else(|_| { // Fall back to guessing based on the binary location
5506 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
5507 let mut path = std::env::current_exe().unwrap();
5508 path.pop(); // lightning-...
5510 path.pop(); // debug
5511 path.pop(); // target
5512 path.push("lightning");
5513 path.push("net_graph-2021-05-31.bin");
5514 eprintln!("{}", path.to_str().unwrap());
5517 .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");
5518 #[cfg(require_route_graph_test)]
5519 return Ok(res.unwrap());
5520 #[cfg(not(require_route_graph_test))]
5525 #[cfg(all(test, feature = "_bench_unstable", not(feature = "no-std")))]
5528 use bitcoin::hashes::Hash;
5529 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
5530 use crate::chain::transaction::OutPoint;
5531 use crate::chain::keysinterface::{KeysManager,KeysInterface};
5532 use crate::ln::channelmanager::{self, ChannelCounterparty, ChannelDetails};
5533 use crate::ln::features::InvoiceFeatures;
5534 use crate::routing::gossip::NetworkGraph;
5535 use crate::routing::scoring::{FixedPenaltyScorer, ProbabilisticScorer, ProbabilisticScoringParameters};
5536 use crate::util::logger::{Logger, Record};
5537 use crate::util::ser::ReadableArgs;
5541 struct DummyLogger {}
5542 impl Logger for DummyLogger {
5543 fn log(&self, _record: &Record) {}
5546 fn read_network_graph(logger: &DummyLogger) -> NetworkGraph<&DummyLogger> {
5547 let mut d = bench_utils::get_route_file().unwrap();
5548 NetworkGraph::read(&mut d, logger).unwrap()
5551 fn payer_pubkey() -> PublicKey {
5552 let secp_ctx = Secp256k1::new();
5553 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
5557 fn first_hop(node_id: PublicKey) -> ChannelDetails {
5559 channel_id: [0; 32],
5560 counterparty: ChannelCounterparty {
5561 features: channelmanager::provided_init_features(),
5563 unspendable_punishment_reserve: 0,
5564 forwarding_info: None,
5565 outbound_htlc_minimum_msat: None,
5566 outbound_htlc_maximum_msat: None,
5568 funding_txo: Some(OutPoint {
5569 txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0
5572 short_channel_id: Some(1),
5573 inbound_scid_alias: None,
5574 outbound_scid_alias: None,
5575 channel_value_satoshis: 10_000_000,
5577 balance_msat: 10_000_000,
5578 outbound_capacity_msat: 10_000_000,
5579 next_outbound_htlc_limit_msat: 10_000_000,
5580 inbound_capacity_msat: 0,
5581 unspendable_punishment_reserve: None,
5582 confirmations_required: None,
5583 force_close_spend_delay: None,
5585 is_channel_ready: true,
5588 inbound_htlc_minimum_msat: None,
5589 inbound_htlc_maximum_msat: None,
5595 fn generate_routes_with_zero_penalty_scorer(bench: &mut Bencher) {
5596 let logger = DummyLogger {};
5597 let network_graph = read_network_graph(&logger);
5598 let scorer = FixedPenaltyScorer::with_penalty(0);
5599 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::empty());
5603 fn generate_mpp_routes_with_zero_penalty_scorer(bench: &mut Bencher) {
5604 let logger = DummyLogger {};
5605 let network_graph = read_network_graph(&logger);
5606 let scorer = FixedPenaltyScorer::with_penalty(0);
5607 generate_routes(bench, &network_graph, scorer, channelmanager::provided_invoice_features());
5611 fn generate_routes_with_probabilistic_scorer(bench: &mut Bencher) {
5612 let logger = DummyLogger {};
5613 let network_graph = read_network_graph(&logger);
5614 let params = ProbabilisticScoringParameters::default();
5615 let scorer = ProbabilisticScorer::new(params, &network_graph, &logger);
5616 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::empty());
5620 fn generate_mpp_routes_with_probabilistic_scorer(bench: &mut Bencher) {
5621 let logger = DummyLogger {};
5622 let network_graph = read_network_graph(&logger);
5623 let params = ProbabilisticScoringParameters::default();
5624 let scorer = ProbabilisticScorer::new(params, &network_graph, &logger);
5625 generate_routes(bench, &network_graph, scorer, channelmanager::provided_invoice_features());
5628 fn generate_routes<S: Score>(
5629 bench: &mut Bencher, graph: &NetworkGraph<&DummyLogger>, mut scorer: S,
5630 features: InvoiceFeatures
5632 let nodes = graph.read_only().nodes().clone();
5633 let payer = payer_pubkey();
5634 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
5635 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5637 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
5638 let mut routes = Vec::new();
5639 let mut route_endpoints = Vec::new();
5640 let mut seed: usize = 0xdeadbeef;
5641 'load_endpoints: for _ in 0..150 {
5644 let src = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5646 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5647 let params = PaymentParameters::from_node_id(dst).with_features(features.clone());
5648 let first_hop = first_hop(src);
5649 let amt = seed as u64 % 1_000_000;
5650 if let Ok(route) = get_route(&payer, ¶ms, &graph.read_only(), Some(&[&first_hop]), amt, 42, &DummyLogger{}, &scorer, &random_seed_bytes) {
5652 route_endpoints.push((first_hop, params, amt));
5653 continue 'load_endpoints;
5658 // ...and seed the scorer with success and failure data...
5659 for route in routes {
5660 let amount = route.get_total_amount();
5661 if amount < 250_000 {
5662 for path in route.paths {
5663 scorer.payment_path_successful(&path.iter().collect::<Vec<_>>());
5665 } else if amount > 750_000 {
5666 for path in route.paths {
5667 let short_channel_id = path[path.len() / 2].short_channel_id;
5668 scorer.payment_path_failed(&path.iter().collect::<Vec<_>>(), short_channel_id);
5673 // Because we've changed channel scores, its possible we'll take different routes to the
5674 // selected destinations, possibly causing us to fail because, eg, the newly-selected path
5675 // requires a too-high CLTV delta.
5676 route_endpoints.retain(|(first_hop, params, amt)| {
5677 get_route(&payer, params, &graph.read_only(), Some(&[first_hop]), *amt, 42, &DummyLogger{}, &scorer, &random_seed_bytes).is_ok()
5679 route_endpoints.truncate(100);
5680 assert_eq!(route_endpoints.len(), 100);
5682 // ...then benchmark finding paths between the nodes we learned.
5685 let (first_hop, params, amt) = &route_endpoints[idx % route_endpoints.len()];
5686 assert!(get_route(&payer, params, &graph.read_only(), Some(&[first_hop]), *amt, 42, &DummyLogger{}, &scorer, &random_seed_bytes).is_ok());