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::channelmanager::ChannelDetails;
18 use crate::ln::features::{ChannelFeatures, InvoiceFeatures, NodeFeatures};
19 use crate::ln::msgs::{DecodeError, ErrorAction, LightningError, MAX_VALUE_MSAT};
20 use crate::routing::gossip::{DirectedChannelInfo, EffectiveCapacity, ReadOnlyNetworkGraph, NetworkGraph, NodeId, RoutingFees};
21 use crate::routing::scoring::{ChannelUsage, Score};
22 use crate::util::ser::{Writeable, Readable, Writer};
23 use crate::util::logger::{Level, Logger};
24 use crate::util::chacha20::ChaCha20;
27 use crate::prelude::*;
28 use alloc::collections::BinaryHeap;
32 /// A trait defining behavior for routing a payment.
34 /// Finds a [`Route`] between `payer` and `payee` for a payment with the given values.
36 &self, payer: &PublicKey, route_params: &RouteParameters,
37 first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: InFlightHtlcs
38 ) -> Result<Route, LightningError>;
41 /// A data structure for tracking in-flight HTLCs. May be used during pathfinding to account for
42 /// in-use channel liquidity.
43 pub struct InFlightHtlcs(
44 // A map with liquidity value (in msat) keyed by a short channel id and the direction the HTLC
45 // is traveling in. The direction boolean is determined by checking if the HTLC source's public
46 // key is less than its destination. See `InFlightHtlcs::used_liquidity_msat` for more
48 HashMap<(u64, bool), u64>
52 /// Constructs an empty `InFlightHtlcs`.
53 pub fn new() -> Self { InFlightHtlcs(HashMap::new()) }
55 /// Takes in a path with payer's node id and adds the path's details to `InFlightHtlcs`.
56 pub fn process_path(&mut self, path: &[RouteHop], payer_node_id: PublicKey) {
57 if path.is_empty() { return };
58 // total_inflight_map needs to be direction-sensitive when keeping track of the HTLC value
59 // that is held up. However, the `hops` array, which is a path returned by `find_route` in
60 // the router excludes the payer node. In the following lines, the payer's information is
61 // hardcoded with an inflight value of 0 so that we can correctly represent the first hop
62 // in our sliding window of two.
63 let reversed_hops_with_payer = path.iter().rev().skip(1)
64 .map(|hop| hop.pubkey)
65 .chain(core::iter::once(payer_node_id));
66 let mut cumulative_msat = 0;
68 // Taking the reversed vector from above, we zip it with just the reversed hops list to
69 // work "backwards" of the given path, since the last hop's `fee_msat` actually represents
70 // the total amount sent.
71 for (next_hop, prev_hop) in path.iter().rev().zip(reversed_hops_with_payer) {
72 cumulative_msat += next_hop.fee_msat;
74 .entry((next_hop.short_channel_id, NodeId::from_pubkey(&prev_hop) < NodeId::from_pubkey(&next_hop.pubkey)))
75 .and_modify(|used_liquidity_msat| *used_liquidity_msat += cumulative_msat)
76 .or_insert(cumulative_msat);
80 /// Returns liquidity in msat given the public key of the HTLC source, target, and short channel
82 pub fn used_liquidity_msat(&self, source: &NodeId, target: &NodeId, channel_scid: u64) -> Option<u64> {
83 self.0.get(&(channel_scid, source < target)).map(|v| *v)
87 impl Writeable for InFlightHtlcs {
88 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> { self.0.write(writer) }
91 impl Readable for InFlightHtlcs {
92 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
93 let infight_map: HashMap<(u64, bool), u64> = Readable::read(reader)?;
99 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
100 pub struct RouteHop {
101 /// The node_id of the node at this hop.
102 pub pubkey: PublicKey,
103 /// The node_announcement features of the node at this hop. For the last hop, these may be
104 /// amended to match the features present in the invoice this node generated.
105 pub node_features: NodeFeatures,
106 /// The channel that should be used from the previous hop to reach this node.
107 pub short_channel_id: u64,
108 /// The channel_announcement features of the channel that should be used from the previous hop
109 /// to reach this node.
110 pub channel_features: ChannelFeatures,
111 /// The fee taken on this hop (for paying for the use of the *next* channel in the path).
112 /// For the last hop, this should be the full value of the payment (might be more than
113 /// requested if we had to match htlc_minimum_msat).
115 /// The CLTV delta added for this hop. For the last hop, this should be the full CLTV value
116 /// expected at the destination, in excess of the current block height.
117 pub cltv_expiry_delta: u32,
120 impl_writeable_tlv_based!(RouteHop, {
121 (0, pubkey, required),
122 (2, node_features, required),
123 (4, short_channel_id, required),
124 (6, channel_features, required),
125 (8, fee_msat, required),
126 (10, cltv_expiry_delta, required),
129 /// A route directs a payment from the sender (us) to the recipient. If the recipient supports MPP,
130 /// it can take multiple paths. Each path is composed of one or more hops through the network.
131 #[derive(Clone, Hash, PartialEq, Eq)]
133 /// The list of routes taken for a single (potentially-)multi-part payment. The pubkey of the
134 /// last RouteHop in each path must be the same. Each entry represents a list of hops, NOT
135 /// INCLUDING our own, where the last hop is the destination. Thus, this must always be at
136 /// least length one. While the maximum length of any given path is variable, keeping the length
137 /// of any path less or equal to 19 should currently ensure it is viable.
138 pub paths: Vec<Vec<RouteHop>>,
139 /// The `payment_params` parameter passed to [`find_route`].
140 /// This is used by `ChannelManager` to track information which may be required for retries,
141 /// provided back to you via [`Event::PaymentPathFailed`].
143 /// [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed
144 pub payment_params: Option<PaymentParameters>,
147 pub(crate) trait RoutePath {
148 /// Gets the fees for a given path, excluding any excess paid to the recipient.
149 fn get_path_fees(&self) -> u64;
151 impl RoutePath for Vec<RouteHop> {
152 fn get_path_fees(&self) -> u64 {
153 // Do not count last hop of each path since that's the full value of the payment
154 self.split_last().map(|(_, path_prefix)| path_prefix).unwrap_or(&[])
155 .iter().map(|hop| &hop.fee_msat)
161 /// Returns the total amount of fees paid on this [`Route`].
163 /// This doesn't include any extra payment made to the recipient, which can happen in excess of
164 /// the amount passed to [`find_route`]'s `params.final_value_msat`.
165 pub fn get_total_fees(&self) -> u64 {
166 self.paths.iter().map(|path| path.get_path_fees()).sum()
169 /// Returns the total amount paid on this [`Route`], excluding the fees.
170 pub fn get_total_amount(&self) -> u64 {
171 return self.paths.iter()
172 .map(|path| path.split_last().map(|(hop, _)| hop.fee_msat).unwrap_or(0))
177 const SERIALIZATION_VERSION: u8 = 1;
178 const MIN_SERIALIZATION_VERSION: u8 = 1;
180 impl Writeable for Route {
181 fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
182 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
183 (self.paths.len() as u64).write(writer)?;
184 for hops in self.paths.iter() {
185 (hops.len() as u8).write(writer)?;
186 for hop in hops.iter() {
190 write_tlv_fields!(writer, {
191 (1, self.payment_params, option),
197 impl Readable for Route {
198 fn read<R: io::Read>(reader: &mut R) -> Result<Route, DecodeError> {
199 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
200 let path_count: u64 = Readable::read(reader)?;
201 let mut paths = Vec::with_capacity(cmp::min(path_count, 128) as usize);
202 for _ in 0..path_count {
203 let hop_count: u8 = Readable::read(reader)?;
204 let mut hops = Vec::with_capacity(hop_count as usize);
205 for _ in 0..hop_count {
206 hops.push(Readable::read(reader)?);
210 let mut payment_params = None;
211 read_tlv_fields!(reader, {
212 (1, payment_params, option),
214 Ok(Route { paths, payment_params })
218 /// Parameters needed to find a [`Route`].
220 /// Passed to [`find_route`] and [`build_route_from_hops`], but also provided in
221 /// [`Event::PaymentPathFailed`] for retrying a failed payment path.
223 /// [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed
224 #[derive(Clone, Debug)]
225 pub struct RouteParameters {
226 /// The parameters of the failed payment path.
227 pub payment_params: PaymentParameters,
229 /// The amount in msats sent on the failed payment path.
230 pub final_value_msat: u64,
232 /// The CLTV on the final hop of the failed payment path.
233 pub final_cltv_expiry_delta: u32,
236 impl_writeable_tlv_based!(RouteParameters, {
237 (0, payment_params, required),
238 (2, final_value_msat, required),
239 (4, final_cltv_expiry_delta, required),
242 /// Maximum total CTLV difference we allow for a full payment path.
243 pub const DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA: u32 = 1008;
245 /// Maximum number of paths we allow an (MPP) payment to have.
246 // The default limit is currently set rather arbitrary - there aren't any real fundamental path-count
247 // limits, but for now more than 10 paths likely carries too much one-path failure.
248 pub const DEFAULT_MAX_PATH_COUNT: u8 = 10;
250 // The median hop CLTV expiry delta currently seen in the network.
251 const MEDIAN_HOP_CLTV_EXPIRY_DELTA: u32 = 40;
253 // During routing, we only consider paths shorter than our maximum length estimate.
254 // In the TLV onion format, there is no fixed maximum length, but the `hop_payloads`
255 // field is always 1300 bytes. As the `tlv_payload` for each hop may vary in length, we have to
256 // estimate how many hops the route may have so that it actually fits the `hop_payloads` field.
258 // We estimate 3+32 (payload length and HMAC) + 2+8 (amt_to_forward) + 2+4 (outgoing_cltv_value) +
259 // 2+8 (short_channel_id) = 61 bytes for each intermediate hop and 3+32
260 // (payload length and HMAC) + 2+8 (amt_to_forward) + 2+4 (outgoing_cltv_value) + 2+32+8
261 // (payment_secret and total_msat) = 93 bytes for the final hop.
262 // Since the length of the potentially included `payment_metadata` is unknown to us, we round
263 // down from (1300-93) / 61 = 19.78... to arrive at a conservative estimate of 19.
264 const MAX_PATH_LENGTH_ESTIMATE: u8 = 19;
266 /// The recipient of a payment.
267 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
268 pub struct PaymentParameters {
269 /// The node id of the payee.
270 pub payee_pubkey: PublicKey,
272 /// Features supported by the payee.
274 /// May be set from the payee's invoice or via [`for_keysend`]. May be `None` if the invoice
275 /// does not contain any features.
277 /// [`for_keysend`]: Self::for_keysend
278 pub features: Option<InvoiceFeatures>,
280 /// Hints for routing to the payee, containing channels connecting the payee to public nodes.
281 pub route_hints: Vec<RouteHint>,
283 /// Expiration of a payment to the payee, in seconds relative to the UNIX epoch.
284 pub expiry_time: Option<u64>,
286 /// The maximum total CLTV delta we accept for the route.
287 /// Defaults to [`DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA`].
288 pub max_total_cltv_expiry_delta: u32,
290 /// The maximum number of paths that may be used by (MPP) payments.
291 /// Defaults to [`DEFAULT_MAX_PATH_COUNT`].
292 pub max_path_count: u8,
294 /// Selects the maximum share of a channel's total capacity which will be sent over a channel,
295 /// as a power of 1/2. A higher value prefers to send the payment using more MPP parts whereas
296 /// a lower value prefers to send larger MPP parts, potentially saturating channels and
297 /// increasing failure probability for those paths.
299 /// Note that this restriction will be relaxed during pathfinding after paths which meet this
300 /// restriction have been found. While paths which meet this criteria will be searched for, it
301 /// is ultimately up to the scorer to select them over other paths.
303 /// A value of 0 will allow payments up to and including a channel's total announced usable
304 /// capacity, a value of one will only use up to half its capacity, two 1/4, etc.
307 pub max_channel_saturation_power_of_half: u8,
309 /// A list of SCIDs which this payment was previously attempted over and which caused the
310 /// payment to fail. Future attempts for the same payment shouldn't be relayed through any of
312 pub previously_failed_channels: Vec<u64>,
315 impl_writeable_tlv_based!(PaymentParameters, {
316 (0, payee_pubkey, required),
317 (1, max_total_cltv_expiry_delta, (default_value, DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA)),
318 (2, features, option),
319 (3, max_path_count, (default_value, DEFAULT_MAX_PATH_COUNT)),
320 (4, route_hints, vec_type),
321 (5, max_channel_saturation_power_of_half, (default_value, 2)),
322 (6, expiry_time, option),
323 (7, previously_failed_channels, vec_type),
326 impl PaymentParameters {
327 /// Creates a payee with the node id of the given `pubkey`.
328 pub fn from_node_id(payee_pubkey: PublicKey) -> Self {
334 max_total_cltv_expiry_delta: DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA,
335 max_path_count: DEFAULT_MAX_PATH_COUNT,
336 max_channel_saturation_power_of_half: 2,
337 previously_failed_channels: Vec::new(),
341 /// Creates a payee with the node id of the given `pubkey` to use for keysend payments.
342 pub fn for_keysend(payee_pubkey: PublicKey) -> Self {
343 Self::from_node_id(payee_pubkey).with_features(InvoiceFeatures::for_keysend())
346 /// Includes the payee's features.
348 /// (C-not exported) since bindings don't support move semantics
349 pub fn with_features(self, features: InvoiceFeatures) -> Self {
350 Self { features: Some(features), ..self }
353 /// Includes hints for routing to the payee.
355 /// (C-not exported) since bindings don't support move semantics
356 pub fn with_route_hints(self, route_hints: Vec<RouteHint>) -> Self {
357 Self { route_hints, ..self }
360 /// Includes a payment expiration in seconds relative to the UNIX epoch.
362 /// (C-not exported) since bindings don't support move semantics
363 pub fn with_expiry_time(self, expiry_time: u64) -> Self {
364 Self { expiry_time: Some(expiry_time), ..self }
367 /// Includes a limit for the total CLTV expiry delta which is considered during routing
369 /// (C-not exported) since bindings don't support move semantics
370 pub fn with_max_total_cltv_expiry_delta(self, max_total_cltv_expiry_delta: u32) -> Self {
371 Self { max_total_cltv_expiry_delta, ..self }
374 /// Includes a limit for the maximum number of payment paths that may be used.
376 /// (C-not exported) since bindings don't support move semantics
377 pub fn with_max_path_count(self, max_path_count: u8) -> Self {
378 Self { max_path_count, ..self }
381 /// Includes a limit for the maximum number of payment paths that may be used.
383 /// (C-not exported) since bindings don't support move semantics
384 pub fn with_max_channel_saturation_power_of_half(self, max_channel_saturation_power_of_half: u8) -> Self {
385 Self { max_channel_saturation_power_of_half, ..self }
389 /// A list of hops along a payment path terminating with a channel to the recipient.
390 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
391 pub struct RouteHint(pub Vec<RouteHintHop>);
393 impl Writeable for RouteHint {
394 fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
395 (self.0.len() as u64).write(writer)?;
396 for hop in self.0.iter() {
403 impl Readable for RouteHint {
404 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
405 let hop_count: u64 = Readable::read(reader)?;
406 let mut hops = Vec::with_capacity(cmp::min(hop_count, 16) as usize);
407 for _ in 0..hop_count {
408 hops.push(Readable::read(reader)?);
414 /// A channel descriptor for a hop along a payment path.
415 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
416 pub struct RouteHintHop {
417 /// The node_id of the non-target end of the route
418 pub src_node_id: PublicKey,
419 /// The short_channel_id of this channel
420 pub short_channel_id: u64,
421 /// The fees which must be paid to use this channel
422 pub fees: RoutingFees,
423 /// The difference in CLTV values between this node and the next node.
424 pub cltv_expiry_delta: u16,
425 /// The minimum value, in msat, which must be relayed to the next hop.
426 pub htlc_minimum_msat: Option<u64>,
427 /// The maximum value in msat available for routing with a single HTLC.
428 pub htlc_maximum_msat: Option<u64>,
431 impl_writeable_tlv_based!(RouteHintHop, {
432 (0, src_node_id, required),
433 (1, htlc_minimum_msat, option),
434 (2, short_channel_id, required),
435 (3, htlc_maximum_msat, option),
437 (6, cltv_expiry_delta, required),
440 #[derive(Eq, PartialEq)]
441 struct RouteGraphNode {
443 lowest_fee_to_peer_through_node: u64,
444 lowest_fee_to_node: u64,
445 total_cltv_delta: u32,
446 // The maximum value a yet-to-be-constructed payment path might flow through this node.
447 // This value is upper-bounded by us by:
448 // - how much is needed for a path being constructed
449 // - how much value can channels following this node (up to the destination) can contribute,
450 // considering their capacity and fees
451 value_contribution_msat: u64,
452 /// The effective htlc_minimum_msat at this hop. If a later hop on the path had a higher HTLC
453 /// minimum, we use it, plus the fees required at each earlier hop to meet it.
454 path_htlc_minimum_msat: u64,
455 /// All penalties incurred from this hop on the way to the destination, as calculated using
457 path_penalty_msat: u64,
458 /// The number of hops walked up to this node.
459 path_length_to_node: u8,
462 impl cmp::Ord for RouteGraphNode {
463 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
464 let other_score = cmp::max(other.lowest_fee_to_peer_through_node, other.path_htlc_minimum_msat)
465 .saturating_add(other.path_penalty_msat);
466 let self_score = cmp::max(self.lowest_fee_to_peer_through_node, self.path_htlc_minimum_msat)
467 .saturating_add(self.path_penalty_msat);
468 other_score.cmp(&self_score).then_with(|| other.node_id.cmp(&self.node_id))
472 impl cmp::PartialOrd for RouteGraphNode {
473 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
474 Some(self.cmp(other))
478 /// A wrapper around the various hop representations.
480 /// Used to construct a [`PathBuildingHop`] and to estimate [`EffectiveCapacity`].
481 #[derive(Clone, Debug)]
482 enum CandidateRouteHop<'a> {
483 /// A hop from the payer, where the outbound liquidity is known.
485 details: &'a ChannelDetails,
487 /// A hop found in the [`ReadOnlyNetworkGraph`], where the channel capacity may be unknown.
489 info: DirectedChannelInfo<'a>,
490 short_channel_id: u64,
492 /// A hop to the payee found in the payment invoice, though not necessarily a direct channel.
494 hint: &'a RouteHintHop,
498 impl<'a> CandidateRouteHop<'a> {
499 fn short_channel_id(&self) -> u64 {
501 CandidateRouteHop::FirstHop { details } => details.get_outbound_payment_scid().unwrap(),
502 CandidateRouteHop::PublicHop { short_channel_id, .. } => *short_channel_id,
503 CandidateRouteHop::PrivateHop { hint } => hint.short_channel_id,
507 // NOTE: This may alloc memory so avoid calling it in a hot code path.
508 fn features(&self) -> ChannelFeatures {
510 CandidateRouteHop::FirstHop { details } => details.counterparty.features.to_context(),
511 CandidateRouteHop::PublicHop { info, .. } => info.channel().features.clone(),
512 CandidateRouteHop::PrivateHop { .. } => ChannelFeatures::empty(),
516 fn cltv_expiry_delta(&self) -> u32 {
518 CandidateRouteHop::FirstHop { .. } => 0,
519 CandidateRouteHop::PublicHop { info, .. } => info.direction().cltv_expiry_delta as u32,
520 CandidateRouteHop::PrivateHop { hint } => hint.cltv_expiry_delta as u32,
524 fn htlc_minimum_msat(&self) -> u64 {
526 CandidateRouteHop::FirstHop { .. } => 0,
527 CandidateRouteHop::PublicHop { info, .. } => info.direction().htlc_minimum_msat,
528 CandidateRouteHop::PrivateHop { hint } => hint.htlc_minimum_msat.unwrap_or(0),
532 fn fees(&self) -> RoutingFees {
534 CandidateRouteHop::FirstHop { .. } => RoutingFees {
535 base_msat: 0, proportional_millionths: 0,
537 CandidateRouteHop::PublicHop { info, .. } => info.direction().fees,
538 CandidateRouteHop::PrivateHop { hint } => hint.fees,
542 fn effective_capacity(&self) -> EffectiveCapacity {
544 CandidateRouteHop::FirstHop { details } => EffectiveCapacity::ExactLiquidity {
545 liquidity_msat: details.next_outbound_htlc_limit_msat,
547 CandidateRouteHop::PublicHop { info, .. } => info.effective_capacity(),
548 CandidateRouteHop::PrivateHop { .. } => EffectiveCapacity::Infinite,
554 fn max_htlc_from_capacity(capacity: EffectiveCapacity, max_channel_saturation_power_of_half: u8) -> u64 {
555 let saturation_shift: u32 = max_channel_saturation_power_of_half as u32;
557 EffectiveCapacity::ExactLiquidity { liquidity_msat } => liquidity_msat,
558 EffectiveCapacity::Infinite => u64::max_value(),
559 EffectiveCapacity::Unknown => EffectiveCapacity::Unknown.as_msat(),
560 EffectiveCapacity::MaximumHTLC { amount_msat } =>
561 amount_msat.checked_shr(saturation_shift).unwrap_or(0),
562 EffectiveCapacity::Total { capacity_msat, htlc_maximum_msat } =>
563 cmp::min(capacity_msat.checked_shr(saturation_shift).unwrap_or(0), htlc_maximum_msat),
567 fn iter_equal<I1: Iterator, I2: Iterator>(mut iter_a: I1, mut iter_b: I2)
568 -> bool where I1::Item: PartialEq<I2::Item> {
570 let a = iter_a.next();
571 let b = iter_b.next();
572 if a.is_none() && b.is_none() { return true; }
573 if a.is_none() || b.is_none() { return false; }
574 if a.unwrap().ne(&b.unwrap()) { return false; }
578 /// It's useful to keep track of the hops associated with the fees required to use them,
579 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
580 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
581 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
583 struct PathBuildingHop<'a> {
584 // Note that this should be dropped in favor of loading it from CandidateRouteHop, but doing so
585 // is a larger refactor and will require careful performance analysis.
587 candidate: CandidateRouteHop<'a>,
590 /// Minimal fees required to route to the source node of the current hop via any of its inbound channels.
591 src_lowest_inbound_fees: RoutingFees,
592 /// All the fees paid *after* this channel on the way to the destination
593 next_hops_fee_msat: u64,
594 /// Fee paid for the use of the current channel (see candidate.fees()).
595 /// The value will be actually deducted from the counterparty balance on the previous link.
596 hop_use_fee_msat: u64,
597 /// Used to compare channels when choosing the for routing.
598 /// Includes paying for the use of a hop and the following hops, as well as
599 /// an estimated cost of reaching this hop.
600 /// Might get stale when fees are recomputed. Primarily for internal use.
602 /// A mirror of the same field in RouteGraphNode. Note that this is only used during the graph
603 /// walk and may be invalid thereafter.
604 path_htlc_minimum_msat: u64,
605 /// All penalties incurred from this channel on the way to the destination, as calculated using
607 path_penalty_msat: u64,
608 /// If we've already processed a node as the best node, we shouldn't process it again. Normally
609 /// we'd just ignore it if we did as all channels would have a higher new fee, but because we
610 /// may decrease the amounts in use as we walk the graph, the actual calculated fee may
611 /// decrease as well. Thus, we have to explicitly track which nodes have been processed and
612 /// avoid processing them again.
614 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
615 // In tests, we apply further sanity checks on cases where we skip nodes we already processed
616 // to ensure it is specifically in cases where the fee has gone down because of a decrease in
617 // value_contribution_msat, which requires tracking it here. See comments below where it is
618 // used for more info.
619 value_contribution_msat: u64,
622 impl<'a> core::fmt::Debug for PathBuildingHop<'a> {
623 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
624 let mut debug_struct = f.debug_struct("PathBuildingHop");
626 .field("node_id", &self.node_id)
627 .field("short_channel_id", &self.candidate.short_channel_id())
628 .field("total_fee_msat", &self.total_fee_msat)
629 .field("next_hops_fee_msat", &self.next_hops_fee_msat)
630 .field("hop_use_fee_msat", &self.hop_use_fee_msat)
631 .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)))
632 .field("path_penalty_msat", &self.path_penalty_msat)
633 .field("path_htlc_minimum_msat", &self.path_htlc_minimum_msat)
634 .field("cltv_expiry_delta", &self.candidate.cltv_expiry_delta());
635 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
636 let debug_struct = debug_struct
637 .field("value_contribution_msat", &self.value_contribution_msat);
638 debug_struct.finish()
642 // Instantiated with a list of hops with correct data in them collected during path finding,
643 // an instance of this struct should be further modified only via given methods.
645 struct PaymentPath<'a> {
646 hops: Vec<(PathBuildingHop<'a>, NodeFeatures)>,
649 impl<'a> PaymentPath<'a> {
650 // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
651 fn get_value_msat(&self) -> u64 {
652 self.hops.last().unwrap().0.fee_msat
655 fn get_path_penalty_msat(&self) -> u64 {
656 self.hops.first().map(|h| h.0.path_penalty_msat).unwrap_or(u64::max_value())
659 fn get_total_fee_paid_msat(&self) -> u64 {
660 if self.hops.len() < 1 {
664 // Can't use next_hops_fee_msat because it gets outdated.
665 for (i, (hop, _)) in self.hops.iter().enumerate() {
666 if i != self.hops.len() - 1 {
667 result += hop.fee_msat;
673 fn get_cost_msat(&self) -> u64 {
674 self.get_total_fee_paid_msat().saturating_add(self.get_path_penalty_msat())
677 // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
678 // to change fees may result in an inconsistency.
680 // Sometimes we call this function right after constructing a path which is inconsistent in
681 // that it the value being transferred has decreased while we were doing path finding, leading
682 // to the fees being paid not lining up with the actual limits.
684 // Note that this function is not aware of the available_liquidity limit, and thus does not
685 // support increasing the value being transferred beyond what was selected during the initial
687 fn update_value_and_recompute_fees(&mut self, value_msat: u64) {
688 let mut total_fee_paid_msat = 0 as u64;
689 for i in (0..self.hops.len()).rev() {
690 let last_hop = i == self.hops.len() - 1;
692 // For non-last-hop, this value will represent the fees paid on the current hop. It
693 // will consist of the fees for the use of the next hop, and extra fees to match
694 // htlc_minimum_msat of the current channel. Last hop is handled separately.
695 let mut cur_hop_fees_msat = 0;
697 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().0.hop_use_fee_msat;
700 let mut cur_hop = &mut self.hops.get_mut(i).unwrap().0;
701 cur_hop.next_hops_fee_msat = total_fee_paid_msat;
702 // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
703 // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
704 // set it too high just to maliciously take more fees by exploiting this
705 // match htlc_minimum_msat logic.
706 let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
707 if let Some(extra_fees_msat) = cur_hop.candidate.htlc_minimum_msat().checked_sub(cur_hop_transferred_amount_msat) {
708 // Note that there is a risk that *previous hops* (those closer to us, as we go
709 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
711 // This might make us end up with a broken route, although this should be super-rare
712 // in practice, both because of how healthy channels look like, and how we pick
713 // channels in add_entry.
714 // Also, this can't be exploited more heavily than *announce a free path and fail
716 cur_hop_transferred_amount_msat += extra_fees_msat;
717 total_fee_paid_msat += extra_fees_msat;
718 cur_hop_fees_msat += extra_fees_msat;
722 // Final hop is a special case: it usually has just value_msat (by design), but also
723 // it still could overpay for the htlc_minimum_msat.
724 cur_hop.fee_msat = cur_hop_transferred_amount_msat;
726 // Propagate updated fees for the use of the channels to one hop back, where they
727 // will be actually paid (fee_msat). The last hop is handled above separately.
728 cur_hop.fee_msat = cur_hop_fees_msat;
731 // Fee for the use of the current hop which will be deducted on the previous hop.
732 // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
733 // this channel is free for us.
735 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.candidate.fees()) {
736 cur_hop.hop_use_fee_msat = new_fee;
737 total_fee_paid_msat += new_fee;
739 // It should not be possible because this function is called only to reduce the
740 // value. In that case, compute_fee was already called with the same fees for
741 // larger amount and there was no overflow.
749 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
750 let proportional_fee_millions =
751 amount_msat.checked_mul(channel_fees.proportional_millionths as u64);
752 if let Some(new_fee) = proportional_fee_millions.and_then(|part| {
753 (channel_fees.base_msat as u64).checked_add(part / 1_000_000) }) {
757 // This function may be (indirectly) called without any verification,
758 // with channel_fees provided by a caller. We should handle it gracefully.
763 /// The default `features` we assume for a node in a route, when no `features` are known about that
766 /// Default features are:
767 /// * variable_length_onion_optional
768 fn default_node_features() -> NodeFeatures {
769 let mut features = NodeFeatures::empty();
770 features.set_variable_length_onion_optional();
774 /// Finds a route from us (payer) to the given target node (payee).
776 /// If the payee provided features in their invoice, they should be provided via `params.payee`.
777 /// Without this, MPP will only be used if the payee's features are available in the network graph.
779 /// Private routing paths between a public node and the target may be included in `params.payee`.
781 /// If some channels aren't announced, it may be useful to fill in `first_hops` with the results
782 /// from [`ChannelManager::list_usable_channels`]. If it is filled in, the view of these channels
783 /// from `network_graph` will be ignored, and only those in `first_hops` will be used.
785 /// The fees on channels from us to the next hop are ignored as they are assumed to all be equal.
786 /// However, the enabled/disabled bit on such channels as well as the `htlc_minimum_msat` /
787 /// `htlc_maximum_msat` *are* checked as they may change based on the receiving node.
791 /// May be used to re-compute a [`Route`] when handling a [`Event::PaymentPathFailed`]. Any
792 /// adjustments to the [`NetworkGraph`] and channel scores should be made prior to calling this
797 /// Panics if first_hops contains channels without short_channel_ids;
798 /// [`ChannelManager::list_usable_channels`] will never include such channels.
800 /// [`ChannelManager::list_usable_channels`]: crate::ln::channelmanager::ChannelManager::list_usable_channels
801 /// [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed
802 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
803 pub fn find_route<L: Deref, GL: Deref, S: Score>(
804 our_node_pubkey: &PublicKey, route_params: &RouteParameters,
805 network_graph: &NetworkGraph<GL>, first_hops: Option<&[&ChannelDetails]>, logger: L,
806 scorer: &S, random_seed_bytes: &[u8; 32]
807 ) -> Result<Route, LightningError>
808 where L::Target: Logger, GL::Target: Logger {
809 let graph_lock = network_graph.read_only();
810 let mut route = get_route(our_node_pubkey, &route_params.payment_params, &graph_lock, first_hops,
811 route_params.final_value_msat, route_params.final_cltv_expiry_delta, logger, scorer,
813 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
817 pub(crate) fn get_route<L: Deref, S: Score>(
818 our_node_pubkey: &PublicKey, payment_params: &PaymentParameters, network_graph: &ReadOnlyNetworkGraph,
819 first_hops: Option<&[&ChannelDetails]>, final_value_msat: u64, final_cltv_expiry_delta: u32,
820 logger: L, scorer: &S, _random_seed_bytes: &[u8; 32]
821 ) -> Result<Route, LightningError>
822 where L::Target: Logger {
823 let payee_node_id = NodeId::from_pubkey(&payment_params.payee_pubkey);
824 let our_node_id = NodeId::from_pubkey(&our_node_pubkey);
826 if payee_node_id == our_node_id {
827 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
830 if final_value_msat > MAX_VALUE_MSAT {
831 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
834 if final_value_msat == 0 {
835 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
838 for route in payment_params.route_hints.iter() {
839 for hop in &route.0 {
840 if hop.src_node_id == payment_params.payee_pubkey {
841 return Err(LightningError{err: "Route hint cannot have the payee as the source.".to_owned(), action: ErrorAction::IgnoreError});
845 if payment_params.max_total_cltv_expiry_delta <= final_cltv_expiry_delta {
846 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});
849 // The general routing idea is the following:
850 // 1. Fill first/last hops communicated by the caller.
851 // 2. Attempt to construct a path from payer to payee for transferring
852 // any ~sufficient (described later) value.
853 // If succeed, remember which channels were used and how much liquidity they have available,
854 // so that future paths don't rely on the same liquidity.
855 // 3. Proceed to the next step if:
856 // - we hit the recommended target value;
857 // - OR if we could not construct a new path. Any next attempt will fail too.
858 // Otherwise, repeat step 2.
859 // 4. See if we managed to collect paths which aggregately are able to transfer target value
860 // (not recommended value).
861 // 5. If yes, proceed. If not, fail routing.
862 // 6. Select the paths which have the lowest cost (fee plus scorer penalty) per amount
863 // transferred up to the transfer target value.
864 // 7. Reduce the value of the last path until we are sending only the target value.
865 // 8. If our maximum channel saturation limit caused us to pick two identical paths, combine
866 // them so that we're not sending two HTLCs along the same path.
868 // As for the actual search algorithm,
869 // we do a payee-to-payer pseudo-Dijkstra's sorting by each node's distance from the payee
870 // plus the minimum per-HTLC fee to get from it to another node (aka "shitty pseudo-A*").
872 // We are not a faithful Dijkstra's implementation because we can change values which impact
873 // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
874 // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) than
875 // the value we are currently attempting to send over a path, we simply reduce the value being
876 // sent along the path for any hops after that channel. This may imply that later fees (which
877 // we've already tabulated) are lower because a smaller value is passing through the channels
878 // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
879 // channels which were selected earlier (and which may still be used for other paths without a
880 // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
883 // One potentially problematic case for this algorithm would be if there are many
884 // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
885 // graph walking), we may never find a path which is not liquidity-limited and has lower
886 // proportional fee (and only lower absolute fee when considering the ultimate value sent).
887 // Because we only consider paths with at least 5% of the total value being sent, the damage
888 // from such a case should be limited, however this could be further reduced in the future by
889 // calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
890 // limits for the purposes of fee calculation.
892 // Alternatively, we could store more detailed path information in the heap (targets, below)
893 // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
894 // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
895 // and practically (as we would need to store dynamically-allocated path information in heap
896 // objects, increasing malloc traffic and indirect memory access significantly). Further, the
897 // results of such an algorithm would likely be biased towards lower-value paths.
899 // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
900 // outside of our current search value, running a path search more times to gather candidate
901 // paths at different values. While this may be acceptable, further path searches may increase
902 // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
903 // graph for candidate paths, calculating the maximum value which can realistically be sent at
904 // the same time, remaining generic across different payment values.
906 // TODO: There are a few tweaks we could do, including possibly pre-calculating more stuff
907 // to use as the A* heuristic beyond just the cost to get one node further than the current
910 let network_channels = network_graph.channels();
911 let network_nodes = network_graph.nodes();
913 if payment_params.max_path_count == 0 {
914 return Err(LightningError{err: "Can't find a route with no paths allowed.".to_owned(), action: ErrorAction::IgnoreError});
917 // Allow MPP only if we have a features set from somewhere that indicates the payee supports
918 // it. If the payee supports it they're supposed to include it in the invoice, so that should
920 let allow_mpp = if payment_params.max_path_count == 1 {
922 } else if let Some(features) = &payment_params.features {
923 features.supports_basic_mpp()
924 } else if let Some(node) = network_nodes.get(&payee_node_id) {
925 if let Some(node_info) = node.announcement_info.as_ref() {
926 node_info.features.supports_basic_mpp()
930 log_trace!(logger, "Searching for a route from payer {} to payee {} {} MPP and {} first hops {}overriding the network graph", our_node_pubkey,
931 payment_params.payee_pubkey, if allow_mpp { "with" } else { "without" },
932 first_hops.map(|hops| hops.len()).unwrap_or(0), if first_hops.is_some() { "" } else { "not " });
935 // Prepare the data we'll use for payee-to-payer search by
936 // inserting first hops suggested by the caller as targets.
937 // Our search will then attempt to reach them while traversing from the payee node.
938 let mut first_hop_targets: HashMap<_, Vec<&ChannelDetails>> =
939 HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
940 if let Some(hops) = first_hops {
942 if chan.get_outbound_payment_scid().is_none() {
943 panic!("first_hops should be filled in with usable channels, not pending ones");
945 if chan.counterparty.node_id == *our_node_pubkey {
946 return Err(LightningError{err: "First hop cannot have our_node_pubkey as a destination.".to_owned(), action: ErrorAction::IgnoreError});
949 .entry(NodeId::from_pubkey(&chan.counterparty.node_id))
950 .or_insert(Vec::new())
953 if first_hop_targets.is_empty() {
954 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
958 // The main heap containing all candidate next-hops sorted by their score (max(A* fee,
959 // htlc_minimum)). Ideally this would be a heap which allowed cheap score reduction instead of
960 // adding duplicate entries when we find a better path to a given node.
961 let mut targets: BinaryHeap<RouteGraphNode> = BinaryHeap::new();
963 // Map from node_id to information about the best current path to that node, including feerate
965 let mut dist: HashMap<NodeId, PathBuildingHop> = HashMap::with_capacity(network_nodes.len());
967 // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
968 // indicating that we may wish to try again with a higher value, potentially paying to meet an
969 // htlc_minimum with extra fees while still finding a cheaper path.
970 let mut hit_minimum_limit;
972 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
973 // We start with a path_value of the exact amount we want, and if that generates a route we may
974 // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
975 // amount we want in total across paths, selecting the best subset at the end.
976 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
977 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
978 let mut path_value_msat = final_value_msat;
980 // Routing Fragmentation Mitigation heuristic:
982 // Routing fragmentation across many payment paths increases the overall routing
983 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
984 // Taking too many smaller paths also increases the chance of payment failure.
985 // Thus to avoid this effect, we require from our collected links to provide
986 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
987 // This requirement is currently set to be 1/max_path_count of the payment
988 // value to ensure we only ever return routes that do not violate this limit.
989 let minimal_value_contribution_msat: u64 = if allow_mpp {
990 (final_value_msat + (payment_params.max_path_count as u64 - 1)) / payment_params.max_path_count as u64
995 // When we start collecting routes we enforce the max_channel_saturation_power_of_half
996 // requirement strictly. After we've collected enough (or if we fail to find new routes) we
997 // drop the requirement by setting this to 0.
998 let mut channel_saturation_pow_half = payment_params.max_channel_saturation_power_of_half;
1000 // Keep track of how much liquidity has been used in selected channels. Used to determine
1001 // if the channel can be used by additional MPP paths or to inform path finding decisions. It is
1002 // aware of direction *only* to ensure that the correct htlc_maximum_msat value is used. Hence,
1003 // liquidity used in one direction will not offset any used in the opposite direction.
1004 let mut used_channel_liquidities: HashMap<(u64, bool), u64> =
1005 HashMap::with_capacity(network_nodes.len());
1007 // Keeping track of how much value we already collected across other paths. Helps to decide
1008 // when we want to stop looking for new paths.
1009 let mut already_collected_value_msat = 0;
1011 for (_, channels) in first_hop_targets.iter_mut() {
1012 // Sort the first_hops channels to the same node(s) in priority order of which channel we'd
1013 // most like to use.
1015 // First, if channels are below `recommended_value_msat`, sort them in descending order,
1016 // preferring larger channels to avoid splitting the payment into more MPP parts than is
1019 // Second, because simply always sorting in descending order would always use our largest
1020 // available outbound capacity, needlessly fragmenting our available channel capacities,
1021 // sort channels above `recommended_value_msat` in ascending order, preferring channels
1022 // which have enough, but not too much, capacity for the payment.
1023 channels.sort_unstable_by(|chan_a, chan_b| {
1024 if chan_b.next_outbound_htlc_limit_msat < recommended_value_msat || chan_a.next_outbound_htlc_limit_msat < recommended_value_msat {
1025 // Sort in descending order
1026 chan_b.next_outbound_htlc_limit_msat.cmp(&chan_a.next_outbound_htlc_limit_msat)
1028 // Sort in ascending order
1029 chan_a.next_outbound_htlc_limit_msat.cmp(&chan_b.next_outbound_htlc_limit_msat)
1034 log_trace!(logger, "Building path from {} (payee) to {} (us/payer) for value {} msat.", payment_params.payee_pubkey, our_node_pubkey, final_value_msat);
1036 macro_rules! add_entry {
1037 // Adds entry which goes from $src_node_id to $dest_node_id over the $candidate hop.
1038 // $next_hops_fee_msat represents the fees paid for using all the channels *after* this one,
1039 // since that value has to be transferred over this channel.
1040 // Returns whether this channel caused an update to `targets`.
1041 ( $candidate: expr, $src_node_id: expr, $dest_node_id: expr, $next_hops_fee_msat: expr,
1042 $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr,
1043 $next_hops_path_penalty_msat: expr, $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => { {
1044 // We "return" whether we updated the path at the end, via this:
1045 let mut did_add_update_path_to_src_node = false;
1046 // Channels to self should not be used. This is more of belt-and-suspenders, because in
1047 // practice these cases should be caught earlier:
1048 // - for regular channels at channel announcement (TODO)
1049 // - for first and last hops early in get_route
1050 if $src_node_id != $dest_node_id {
1051 let short_channel_id = $candidate.short_channel_id();
1052 let effective_capacity = $candidate.effective_capacity();
1053 let htlc_maximum_msat = max_htlc_from_capacity(effective_capacity, channel_saturation_pow_half);
1055 // It is tricky to subtract $next_hops_fee_msat from available liquidity here.
1056 // It may be misleading because we might later choose to reduce the value transferred
1057 // over these channels, and the channel which was insufficient might become sufficient.
1058 // Worst case: we drop a good channel here because it can't cover the high following
1059 // fees caused by one expensive channel, but then this channel could have been used
1060 // if the amount being transferred over this path is lower.
1061 // We do this for now, but this is a subject for removal.
1062 if let Some(mut available_value_contribution_msat) = htlc_maximum_msat.checked_sub($next_hops_fee_msat) {
1063 let used_liquidity_msat = used_channel_liquidities
1064 .get(&(short_channel_id, $src_node_id < $dest_node_id))
1065 .map_or(0, |used_liquidity_msat| {
1066 available_value_contribution_msat = available_value_contribution_msat
1067 .saturating_sub(*used_liquidity_msat);
1068 *used_liquidity_msat
1071 // Verify the liquidity offered by this channel complies to the minimal contribution.
1072 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
1073 // Do not consider candidate hops that would exceed the maximum path length.
1074 let path_length_to_node = $next_hops_path_length + 1;
1075 let exceeds_max_path_length = path_length_to_node > MAX_PATH_LENGTH_ESTIMATE;
1077 // Do not consider candidates that exceed the maximum total cltv expiry limit.
1078 // In order to already account for some of the privacy enhancing random CLTV
1079 // expiry delta offset we add on top later, we subtract a rough estimate
1080 // (2*MEDIAN_HOP_CLTV_EXPIRY_DELTA) here.
1081 let max_total_cltv_expiry_delta = (payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta)
1082 .checked_sub(2*MEDIAN_HOP_CLTV_EXPIRY_DELTA)
1083 .unwrap_or(payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta);
1084 let hop_total_cltv_delta = ($next_hops_cltv_delta as u32)
1085 .saturating_add($candidate.cltv_expiry_delta());
1086 let exceeds_cltv_delta_limit = hop_total_cltv_delta > max_total_cltv_expiry_delta;
1088 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
1089 // Includes paying fees for the use of the following channels.
1090 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
1091 Some(result) => result,
1092 // Can't overflow due to how the values were computed right above.
1093 None => unreachable!(),
1095 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
1096 let over_path_minimum_msat = amount_to_transfer_over_msat >= $candidate.htlc_minimum_msat() &&
1097 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
1099 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
1100 let may_overpay_to_meet_path_minimum_msat =
1101 ((amount_to_transfer_over_msat < $candidate.htlc_minimum_msat() &&
1102 recommended_value_msat > $candidate.htlc_minimum_msat()) ||
1103 (amount_to_transfer_over_msat < $next_hops_path_htlc_minimum_msat &&
1104 recommended_value_msat > $next_hops_path_htlc_minimum_msat));
1106 let payment_failed_on_this_channel =
1107 payment_params.previously_failed_channels.contains(&short_channel_id);
1109 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
1110 // bother considering this channel. If retrying with recommended_value_msat may
1111 // allow us to hit the HTLC minimum limit, set htlc_minimum_limit so that we go
1112 // around again with a higher amount.
1113 if !contributes_sufficient_value || exceeds_max_path_length ||
1114 exceeds_cltv_delta_limit || payment_failed_on_this_channel {
1115 // Path isn't useful, ignore it and move on.
1116 } else if may_overpay_to_meet_path_minimum_msat {
1117 hit_minimum_limit = true;
1118 } else if over_path_minimum_msat {
1119 // Note that low contribution here (limited by available_liquidity_msat)
1120 // might violate htlc_minimum_msat on the hops which are next along the
1121 // payment path (upstream to the payee). To avoid that, we recompute
1122 // path fees knowing the final path contribution after constructing it.
1123 let path_htlc_minimum_msat = compute_fees($next_hops_path_htlc_minimum_msat, $candidate.fees())
1124 .and_then(|fee_msat| fee_msat.checked_add($next_hops_path_htlc_minimum_msat))
1125 .map(|fee_msat| cmp::max(fee_msat, $candidate.htlc_minimum_msat()))
1126 .unwrap_or_else(|| u64::max_value());
1127 let hm_entry = dist.entry($src_node_id);
1128 let old_entry = hm_entry.or_insert_with(|| {
1129 // If there was previously no known way to access the source node
1130 // (recall it goes payee-to-payer) of short_channel_id, first add a
1131 // semi-dummy record just to compute the fees to reach the source node.
1132 // This will affect our decision on selecting short_channel_id
1133 // as a way to reach the $dest_node_id.
1134 let mut fee_base_msat = 0;
1135 let mut fee_proportional_millionths = 0;
1136 if let Some(Some(fees)) = network_nodes.get(&$src_node_id).map(|node| node.lowest_inbound_channel_fees) {
1137 fee_base_msat = fees.base_msat;
1138 fee_proportional_millionths = fees.proportional_millionths;
1141 node_id: $dest_node_id.clone(),
1142 candidate: $candidate.clone(),
1144 src_lowest_inbound_fees: RoutingFees {
1145 base_msat: fee_base_msat,
1146 proportional_millionths: fee_proportional_millionths,
1148 next_hops_fee_msat: u64::max_value(),
1149 hop_use_fee_msat: u64::max_value(),
1150 total_fee_msat: u64::max_value(),
1151 path_htlc_minimum_msat,
1152 path_penalty_msat: u64::max_value(),
1153 was_processed: false,
1154 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
1155 value_contribution_msat,
1159 #[allow(unused_mut)] // We only use the mut in cfg(test)
1160 let mut should_process = !old_entry.was_processed;
1161 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
1163 // In test/fuzzing builds, we do extra checks to make sure the skipping
1164 // of already-seen nodes only happens in cases we expect (see below).
1165 if !should_process { should_process = true; }
1169 let mut hop_use_fee_msat = 0;
1170 let mut total_fee_msat = $next_hops_fee_msat;
1172 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
1173 // will have the same effective-fee
1174 if $src_node_id != our_node_id {
1175 match compute_fees(amount_to_transfer_over_msat, $candidate.fees()) {
1176 // max_value means we'll always fail
1177 // the old_entry.total_fee_msat > total_fee_msat check
1178 None => total_fee_msat = u64::max_value(),
1180 hop_use_fee_msat = fee_msat;
1181 total_fee_msat += hop_use_fee_msat;
1182 // When calculating the lowest inbound fees to a node, we
1183 // calculate fees here not based on the actual value we think
1184 // will flow over this channel, but on the minimum value that
1185 // we'll accept flowing over it. The minimum accepted value
1186 // is a constant through each path collection run, ensuring
1187 // consistent basis. Otherwise we may later find a
1188 // different path to the source node that is more expensive,
1189 // but which we consider to be cheaper because we are capacity
1190 // constrained and the relative fee becomes lower.
1191 match compute_fees(minimal_value_contribution_msat, old_entry.src_lowest_inbound_fees)
1192 .map(|a| a.checked_add(total_fee_msat)) {
1197 total_fee_msat = u64::max_value();
1204 let channel_usage = ChannelUsage {
1205 amount_msat: amount_to_transfer_over_msat,
1206 inflight_htlc_msat: used_liquidity_msat,
1209 let channel_penalty_msat = scorer.channel_penalty_msat(
1210 short_channel_id, &$src_node_id, &$dest_node_id, channel_usage
1212 let path_penalty_msat = $next_hops_path_penalty_msat
1213 .saturating_add(channel_penalty_msat);
1214 let new_graph_node = RouteGraphNode {
1215 node_id: $src_node_id,
1216 lowest_fee_to_peer_through_node: total_fee_msat,
1217 lowest_fee_to_node: $next_hops_fee_msat as u64 + hop_use_fee_msat,
1218 total_cltv_delta: hop_total_cltv_delta,
1219 value_contribution_msat,
1220 path_htlc_minimum_msat,
1222 path_length_to_node,
1225 // Update the way of reaching $src_node_id with the given short_channel_id (from $dest_node_id),
1226 // if this way is cheaper than the already known
1227 // (considering the cost to "reach" this channel from the route destination,
1228 // the cost of using this channel,
1229 // and the cost of routing to the source node of this channel).
1230 // Also, consider that htlc_minimum_msat_difference, because we might end up
1231 // paying it. Consider the following exploit:
1232 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
1233 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
1234 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
1235 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
1237 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
1238 // but it may require additional tracking - we don't want to double-count
1239 // the fees included in $next_hops_path_htlc_minimum_msat, but also
1240 // can't use something that may decrease on future hops.
1241 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat)
1242 .saturating_add(old_entry.path_penalty_msat);
1243 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat)
1244 .saturating_add(path_penalty_msat);
1246 if !old_entry.was_processed && new_cost < old_cost {
1247 targets.push(new_graph_node);
1248 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
1249 old_entry.hop_use_fee_msat = hop_use_fee_msat;
1250 old_entry.total_fee_msat = total_fee_msat;
1251 old_entry.node_id = $dest_node_id.clone();
1252 old_entry.candidate = $candidate.clone();
1253 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
1254 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
1255 old_entry.path_penalty_msat = path_penalty_msat;
1256 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
1258 old_entry.value_contribution_msat = value_contribution_msat;
1260 did_add_update_path_to_src_node = true;
1261 } else if old_entry.was_processed && new_cost < old_cost {
1262 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
1264 // If we're skipping processing a node which was previously
1265 // processed even though we found another path to it with a
1266 // cheaper fee, check that it was because the second path we
1267 // found (which we are processing now) has a lower value
1268 // contribution due to an HTLC minimum limit.
1270 // e.g. take a graph with two paths from node 1 to node 2, one
1271 // through channel A, and one through channel B. Channel A and
1272 // B are both in the to-process heap, with their scores set by
1273 // a higher htlc_minimum than fee.
1274 // Channel A is processed first, and the channels onwards from
1275 // node 1 are added to the to-process heap. Thereafter, we pop
1276 // Channel B off of the heap, note that it has a much more
1277 // restrictive htlc_maximum_msat, and recalculate the fees for
1278 // all of node 1's channels using the new, reduced, amount.
1280 // This would be bogus - we'd be selecting a higher-fee path
1281 // with a lower htlc_maximum_msat instead of the one we'd
1282 // already decided to use.
1283 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
1285 value_contribution_msat + path_penalty_msat <
1286 old_entry.value_contribution_msat + old_entry.path_penalty_msat
1294 did_add_update_path_to_src_node
1298 let default_node_features = default_node_features();
1300 // Find ways (channels with destination) to reach a given node and store them
1301 // in the corresponding data structures (routing graph etc).
1302 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
1303 // meaning how much will be paid in fees after this node (to the best of our knowledge).
1304 // This data can later be helpful to optimize routing (pay lower fees).
1305 macro_rules! add_entries_to_cheapest_to_target_node {
1306 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr, $next_hops_value_contribution: expr,
1307 $next_hops_path_htlc_minimum_msat: expr, $next_hops_path_penalty_msat: expr,
1308 $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => {
1309 let skip_node = if let Some(elem) = dist.get_mut(&$node_id) {
1310 let was_processed = elem.was_processed;
1311 elem.was_processed = true;
1314 // Entries are added to dist in add_entry!() when there is a channel from a node.
1315 // Because there are no channels from payee, it will not have a dist entry at this point.
1316 // If we're processing any other node, it is always be the result of a channel from it.
1317 assert_eq!($node_id, payee_node_id);
1322 if let Some(first_channels) = first_hop_targets.get(&$node_id) {
1323 for details in first_channels {
1324 let candidate = CandidateRouteHop::FirstHop { details };
1325 add_entry!(candidate, our_node_id, $node_id, $fee_to_target_msat,
1326 $next_hops_value_contribution,
1327 $next_hops_path_htlc_minimum_msat, $next_hops_path_penalty_msat,
1328 $next_hops_cltv_delta, $next_hops_path_length);
1332 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
1335 &default_node_features
1338 if !features.requires_unknown_bits() {
1339 for chan_id in $node.channels.iter() {
1340 let chan = network_channels.get(chan_id).unwrap();
1341 if !chan.features.requires_unknown_bits() {
1342 if let Some((directed_channel, source)) = chan.as_directed_to(&$node_id) {
1343 if first_hops.is_none() || *source != our_node_id {
1344 if directed_channel.direction().enabled {
1345 let candidate = CandidateRouteHop::PublicHop {
1346 info: directed_channel,
1347 short_channel_id: *chan_id,
1349 add_entry!(candidate, *source, $node_id,
1350 $fee_to_target_msat,
1351 $next_hops_value_contribution,
1352 $next_hops_path_htlc_minimum_msat,
1353 $next_hops_path_penalty_msat,
1354 $next_hops_cltv_delta, $next_hops_path_length);
1365 let mut payment_paths = Vec::<PaymentPath>::new();
1367 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
1368 'paths_collection: loop {
1369 // For every new path, start from scratch, except for used_channel_liquidities, which
1370 // helps to avoid reusing previously selected paths in future iterations.
1373 hit_minimum_limit = false;
1375 // If first hop is a private channel and the only way to reach the payee, this is the only
1376 // place where it could be added.
1377 if let Some(first_channels) = first_hop_targets.get(&payee_node_id) {
1378 for details in first_channels {
1379 let candidate = CandidateRouteHop::FirstHop { details };
1380 let added = add_entry!(candidate, our_node_id, payee_node_id, 0, path_value_msat,
1382 log_trace!(logger, "{} direct route to payee via SCID {}",
1383 if added { "Added" } else { "Skipped" }, candidate.short_channel_id());
1387 // Add the payee as a target, so that the payee-to-payer
1388 // search algorithm knows what to start with.
1389 match network_nodes.get(&payee_node_id) {
1390 // The payee is not in our network graph, so nothing to add here.
1391 // There is still a chance of reaching them via last_hops though,
1392 // so don't yet fail the payment here.
1393 // If not, targets.pop() will not even let us enter the loop in step 2.
1396 add_entries_to_cheapest_to_target_node!(node, payee_node_id, 0, path_value_msat, 0, 0u64, 0, 0);
1401 // If a caller provided us with last hops, add them to routing targets. Since this happens
1402 // earlier than general path finding, they will be somewhat prioritized, although currently
1403 // it matters only if the fees are exactly the same.
1404 for route in payment_params.route_hints.iter().filter(|route| !route.0.is_empty()) {
1405 let first_hop_in_route = &(route.0)[0];
1406 let have_hop_src_in_graph =
1407 // Only add the hops in this route to our candidate set if either
1408 // we have a direct channel to the first hop or the first hop is
1409 // in the regular network graph.
1410 first_hop_targets.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some() ||
1411 network_nodes.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some();
1412 if have_hop_src_in_graph {
1413 // We start building the path from reverse, i.e., from payee
1414 // to the first RouteHintHop in the path.
1415 let hop_iter = route.0.iter().rev();
1416 let prev_hop_iter = core::iter::once(&payment_params.payee_pubkey).chain(
1417 route.0.iter().skip(1).rev().map(|hop| &hop.src_node_id));
1418 let mut hop_used = true;
1419 let mut aggregate_next_hops_fee_msat: u64 = 0;
1420 let mut aggregate_next_hops_path_htlc_minimum_msat: u64 = 0;
1421 let mut aggregate_next_hops_path_penalty_msat: u64 = 0;
1422 let mut aggregate_next_hops_cltv_delta: u32 = 0;
1423 let mut aggregate_next_hops_path_length: u8 = 0;
1425 for (idx, (hop, prev_hop_id)) in hop_iter.zip(prev_hop_iter).enumerate() {
1426 let source = NodeId::from_pubkey(&hop.src_node_id);
1427 let target = NodeId::from_pubkey(&prev_hop_id);
1428 let candidate = network_channels
1429 .get(&hop.short_channel_id)
1430 .and_then(|channel| channel.as_directed_to(&target))
1431 .map(|(info, _)| CandidateRouteHop::PublicHop {
1433 short_channel_id: hop.short_channel_id,
1435 .unwrap_or_else(|| CandidateRouteHop::PrivateHop { hint: hop });
1437 if !add_entry!(candidate, source, target, aggregate_next_hops_fee_msat,
1438 path_value_msat, aggregate_next_hops_path_htlc_minimum_msat,
1439 aggregate_next_hops_path_penalty_msat,
1440 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length) {
1441 // If this hop was not used then there is no use checking the preceding
1442 // hops in the RouteHint. We can break by just searching for a direct
1443 // channel between last checked hop and first_hop_targets.
1447 let used_liquidity_msat = used_channel_liquidities
1448 .get(&(hop.short_channel_id, source < target)).copied().unwrap_or(0);
1449 let channel_usage = ChannelUsage {
1450 amount_msat: final_value_msat + aggregate_next_hops_fee_msat,
1451 inflight_htlc_msat: used_liquidity_msat,
1452 effective_capacity: candidate.effective_capacity(),
1454 let channel_penalty_msat = scorer.channel_penalty_msat(
1455 hop.short_channel_id, &source, &target, channel_usage
1457 aggregate_next_hops_path_penalty_msat = aggregate_next_hops_path_penalty_msat
1458 .saturating_add(channel_penalty_msat);
1460 aggregate_next_hops_cltv_delta = aggregate_next_hops_cltv_delta
1461 .saturating_add(hop.cltv_expiry_delta as u32);
1463 aggregate_next_hops_path_length = aggregate_next_hops_path_length
1466 // Searching for a direct channel between last checked hop and first_hop_targets
1467 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&prev_hop_id)) {
1468 for details in first_channels {
1469 let candidate = CandidateRouteHop::FirstHop { details };
1470 add_entry!(candidate, our_node_id, NodeId::from_pubkey(&prev_hop_id),
1471 aggregate_next_hops_fee_msat, path_value_msat,
1472 aggregate_next_hops_path_htlc_minimum_msat,
1473 aggregate_next_hops_path_penalty_msat, aggregate_next_hops_cltv_delta,
1474 aggregate_next_hops_path_length);
1482 // In the next values of the iterator, the aggregate fees already reflects
1483 // the sum of value sent from payer (final_value_msat) and routing fees
1484 // for the last node in the RouteHint. We need to just add the fees to
1485 // route through the current node so that the preceding node (next iteration)
1487 let hops_fee = compute_fees(aggregate_next_hops_fee_msat + final_value_msat, hop.fees)
1488 .map_or(None, |inc| inc.checked_add(aggregate_next_hops_fee_msat));
1489 aggregate_next_hops_fee_msat = if let Some(val) = hops_fee { val } else { break; };
1491 let hop_htlc_minimum_msat = candidate.htlc_minimum_msat();
1492 let hop_htlc_minimum_msat_inc = if let Some(val) = compute_fees(aggregate_next_hops_path_htlc_minimum_msat, hop.fees) { val } else { break; };
1493 let hops_path_htlc_minimum = aggregate_next_hops_path_htlc_minimum_msat
1494 .checked_add(hop_htlc_minimum_msat_inc);
1495 aggregate_next_hops_path_htlc_minimum_msat = if let Some(val) = hops_path_htlc_minimum { cmp::max(hop_htlc_minimum_msat, val) } else { break; };
1497 if idx == route.0.len() - 1 {
1498 // The last hop in this iterator is the first hop in
1499 // overall RouteHint.
1500 // If this hop connects to a node with which we have a direct channel,
1501 // ignore the network graph and, if the last hop was added, add our
1502 // direct channel to the candidate set.
1504 // Note that we *must* check if the last hop was added as `add_entry`
1505 // always assumes that the third argument is a node to which we have a
1507 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&hop.src_node_id)) {
1508 for details in first_channels {
1509 let candidate = CandidateRouteHop::FirstHop { details };
1510 add_entry!(candidate, our_node_id,
1511 NodeId::from_pubkey(&hop.src_node_id),
1512 aggregate_next_hops_fee_msat, path_value_msat,
1513 aggregate_next_hops_path_htlc_minimum_msat,
1514 aggregate_next_hops_path_penalty_msat,
1515 aggregate_next_hops_cltv_delta,
1516 aggregate_next_hops_path_length);
1524 log_trace!(logger, "Starting main path collection loop with {} nodes pre-filled from first/last hops.", targets.len());
1526 // At this point, targets are filled with the data from first and
1527 // last hops communicated by the caller, and the payment receiver.
1528 let mut found_new_path = false;
1531 // If this loop terminates due the exhaustion of targets, two situations are possible:
1532 // - not enough outgoing liquidity:
1533 // 0 < already_collected_value_msat < final_value_msat
1534 // - enough outgoing liquidity:
1535 // final_value_msat <= already_collected_value_msat < recommended_value_msat
1536 // Both these cases (and other cases except reaching recommended_value_msat) mean that
1537 // paths_collection will be stopped because found_new_path==false.
1538 // This is not necessarily a routing failure.
1539 '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() {
1541 // Since we're going payee-to-payer, hitting our node as a target means we should stop
1542 // traversing the graph and arrange the path out of what we found.
1543 if node_id == our_node_id {
1544 let mut new_entry = dist.remove(&our_node_id).unwrap();
1545 let mut ordered_hops: Vec<(PathBuildingHop, NodeFeatures)> = vec!((new_entry.clone(), default_node_features.clone()));
1548 let mut features_set = false;
1549 if let Some(first_channels) = first_hop_targets.get(&ordered_hops.last().unwrap().0.node_id) {
1550 for details in first_channels {
1551 if details.get_outbound_payment_scid().unwrap() == ordered_hops.last().unwrap().0.candidate.short_channel_id() {
1552 ordered_hops.last_mut().unwrap().1 = details.counterparty.features.to_context();
1553 features_set = true;
1559 if let Some(node) = network_nodes.get(&ordered_hops.last().unwrap().0.node_id) {
1560 if let Some(node_info) = node.announcement_info.as_ref() {
1561 ordered_hops.last_mut().unwrap().1 = node_info.features.clone();
1563 ordered_hops.last_mut().unwrap().1 = default_node_features.clone();
1566 // We can fill in features for everything except hops which were
1567 // provided via the invoice we're paying. We could guess based on the
1568 // recipient's features but for now we simply avoid guessing at all.
1572 // Means we succesfully traversed from the payer to the payee, now
1573 // save this path for the payment route. Also, update the liquidity
1574 // remaining on the used hops, so that we take them into account
1575 // while looking for more paths.
1576 if ordered_hops.last().unwrap().0.node_id == payee_node_id {
1580 new_entry = match dist.remove(&ordered_hops.last().unwrap().0.node_id) {
1581 Some(payment_hop) => payment_hop,
1582 // We can't arrive at None because, if we ever add an entry to targets,
1583 // we also fill in the entry in dist (see add_entry!).
1584 None => unreachable!(),
1586 // We "propagate" the fees one hop backward (topologically) here,
1587 // so that fees paid for a HTLC forwarding on the current channel are
1588 // associated with the previous channel (where they will be subtracted).
1589 ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
1590 ordered_hops.push((new_entry.clone(), default_node_features.clone()));
1592 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
1593 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
1595 log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: \n {:#?}",
1596 ordered_hops.len(), value_contribution_msat, ordered_hops.iter().map(|h| &(h.0)).collect::<Vec<&PathBuildingHop>>());
1598 let mut payment_path = PaymentPath {hops: ordered_hops};
1600 // We could have possibly constructed a slightly inconsistent path: since we reduce
1601 // value being transferred along the way, we could have violated htlc_minimum_msat
1602 // on some channels we already passed (assuming dest->source direction). Here, we
1603 // recompute the fees again, so that if that's the case, we match the currently
1604 // underpaid htlc_minimum_msat with fees.
1605 debug_assert_eq!(payment_path.get_value_msat(), value_contribution_msat);
1606 value_contribution_msat = cmp::min(value_contribution_msat, final_value_msat);
1607 payment_path.update_value_and_recompute_fees(value_contribution_msat);
1609 // Since a path allows to transfer as much value as
1610 // the smallest channel it has ("bottleneck"), we should recompute
1611 // the fees so sender HTLC don't overpay fees when traversing
1612 // larger channels than the bottleneck. This may happen because
1613 // when we were selecting those channels we were not aware how much value
1614 // this path will transfer, and the relative fee for them
1615 // might have been computed considering a larger value.
1616 // Remember that we used these channels so that we don't rely
1617 // on the same liquidity in future paths.
1618 let mut prevented_redundant_path_selection = false;
1619 let prev_hop_iter = core::iter::once(&our_node_id)
1620 .chain(payment_path.hops.iter().map(|(hop, _)| &hop.node_id));
1621 for (prev_hop, (hop, _)) in prev_hop_iter.zip(payment_path.hops.iter()) {
1622 let spent_on_hop_msat = value_contribution_msat + hop.next_hops_fee_msat;
1623 let used_liquidity_msat = used_channel_liquidities
1624 .entry((hop.candidate.short_channel_id(), *prev_hop < hop.node_id))
1625 .and_modify(|used_liquidity_msat| *used_liquidity_msat += spent_on_hop_msat)
1626 .or_insert(spent_on_hop_msat);
1627 let hop_capacity = hop.candidate.effective_capacity();
1628 let hop_max_msat = max_htlc_from_capacity(hop_capacity, channel_saturation_pow_half);
1629 if *used_liquidity_msat == hop_max_msat {
1630 // If this path used all of this channel's available liquidity, we know
1631 // this path will not be selected again in the next loop iteration.
1632 prevented_redundant_path_selection = true;
1634 debug_assert!(*used_liquidity_msat <= hop_max_msat);
1636 if !prevented_redundant_path_selection {
1637 // If we weren't capped by hitting a liquidity limit on a channel in the path,
1638 // we'll probably end up picking the same path again on the next iteration.
1639 // Decrease the available liquidity of a hop in the middle of the path.
1640 let victim_scid = payment_path.hops[(payment_path.hops.len()) / 2].0.candidate.short_channel_id();
1641 let exhausted = u64::max_value();
1642 log_trace!(logger, "Disabling channel {} for future path building iterations to avoid duplicates.", victim_scid);
1643 *used_channel_liquidities.entry((victim_scid, false)).or_default() = exhausted;
1644 *used_channel_liquidities.entry((victim_scid, true)).or_default() = exhausted;
1647 // Track the total amount all our collected paths allow to send so that we know
1648 // when to stop looking for more paths
1649 already_collected_value_msat += value_contribution_msat;
1651 payment_paths.push(payment_path);
1652 found_new_path = true;
1653 break 'path_construction;
1656 // If we found a path back to the payee, we shouldn't try to process it again. This is
1657 // the equivalent of the `elem.was_processed` check in
1658 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
1659 if node_id == payee_node_id { continue 'path_construction; }
1661 // Otherwise, since the current target node is not us,
1662 // keep "unrolling" the payment graph from payee to payer by
1663 // finding a way to reach the current target from the payer side.
1664 match network_nodes.get(&node_id) {
1667 add_entries_to_cheapest_to_target_node!(node, node_id, lowest_fee_to_node,
1668 value_contribution_msat, path_htlc_minimum_msat, path_penalty_msat,
1669 total_cltv_delta, path_length_to_node);
1675 if !found_new_path && channel_saturation_pow_half != 0 {
1676 channel_saturation_pow_half = 0;
1677 continue 'paths_collection;
1679 // If we don't support MPP, no use trying to gather more value ever.
1680 break 'paths_collection;
1684 // Stop either when the recommended value is reached or if no new path was found in this
1686 // In the latter case, making another path finding attempt won't help,
1687 // because we deterministically terminated the search due to low liquidity.
1688 if !found_new_path && channel_saturation_pow_half != 0 {
1689 channel_saturation_pow_half = 0;
1690 } else if already_collected_value_msat >= recommended_value_msat || !found_new_path {
1691 log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
1692 already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
1693 break 'paths_collection;
1694 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
1695 // Further, if this was our first walk of the graph, and we weren't limited by an
1696 // htlc_minimum_msat, return immediately because this path should suffice. If we were
1697 // limited by an htlc_minimum_msat value, find another path with a higher value,
1698 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
1699 // still keeping a lower total fee than this path.
1700 if !hit_minimum_limit {
1701 log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
1702 break 'paths_collection;
1704 log_trace!(logger, "Collected our payment amount on the first pass, but running again to collect extra paths with a potentially higher limit.");
1705 path_value_msat = recommended_value_msat;
1710 if payment_paths.len() == 0 {
1711 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1714 if already_collected_value_msat < final_value_msat {
1715 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1719 let mut selected_route = payment_paths;
1721 debug_assert_eq!(selected_route.iter().map(|p| p.get_value_msat()).sum::<u64>(), already_collected_value_msat);
1722 let mut overpaid_value_msat = already_collected_value_msat - final_value_msat;
1724 // First, sort by the cost-per-value of the path, dropping the paths that cost the most for
1725 // the value they contribute towards the payment amount.
1726 // We sort in descending order as we will remove from the front in `retain`, next.
1727 selected_route.sort_unstable_by(|a, b|
1728 (((b.get_cost_msat() as u128) << 64) / (b.get_value_msat() as u128))
1729 .cmp(&(((a.get_cost_msat() as u128) << 64) / (a.get_value_msat() as u128)))
1732 // We should make sure that at least 1 path left.
1733 let mut paths_left = selected_route.len();
1734 selected_route.retain(|path| {
1735 if paths_left == 1 {
1738 let path_value_msat = path.get_value_msat();
1739 if path_value_msat <= overpaid_value_msat {
1740 overpaid_value_msat -= path_value_msat;
1746 debug_assert!(selected_route.len() > 0);
1748 if overpaid_value_msat != 0 {
1750 // Now, subtract the remaining overpaid value from the most-expensive path.
1751 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1752 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1753 selected_route.sort_unstable_by(|a, b| {
1754 let a_f = a.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
1755 let b_f = b.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
1756 a_f.cmp(&b_f).then_with(|| b.get_cost_msat().cmp(&a.get_cost_msat()))
1758 let expensive_payment_path = selected_route.first_mut().unwrap();
1760 // We already dropped all the paths with value below `overpaid_value_msat` above, thus this
1761 // can't go negative.
1762 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
1763 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
1767 // Sort by the path itself and combine redundant paths.
1768 // Note that we sort by SCIDs alone as its simpler but when combining we have to ensure we
1769 // compare both SCIDs and NodeIds as individual nodes may use random aliases causing collisions
1771 selected_route.sort_unstable_by_key(|path| {
1772 let mut key = [0u64; MAX_PATH_LENGTH_ESTIMATE as usize];
1773 debug_assert!(path.hops.len() <= key.len());
1774 for (scid, key) in path.hops.iter().map(|h| h.0.candidate.short_channel_id()).zip(key.iter_mut()) {
1779 for idx in 0..(selected_route.len() - 1) {
1780 if idx + 1 >= selected_route.len() { break; }
1781 if iter_equal(selected_route[idx ].hops.iter().map(|h| (h.0.candidate.short_channel_id(), h.0.node_id)),
1782 selected_route[idx + 1].hops.iter().map(|h| (h.0.candidate.short_channel_id(), h.0.node_id))) {
1783 let new_value = selected_route[idx].get_value_msat() + selected_route[idx + 1].get_value_msat();
1784 selected_route[idx].update_value_and_recompute_fees(new_value);
1785 selected_route.remove(idx + 1);
1789 let mut selected_paths = Vec::<Vec<Result<RouteHop, LightningError>>>::new();
1790 for payment_path in selected_route {
1791 let mut path = payment_path.hops.iter().map(|(payment_hop, node_features)| {
1793 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)})?,
1794 node_features: node_features.clone(),
1795 short_channel_id: payment_hop.candidate.short_channel_id(),
1796 channel_features: payment_hop.candidate.features(),
1797 fee_msat: payment_hop.fee_msat,
1798 cltv_expiry_delta: payment_hop.candidate.cltv_expiry_delta(),
1800 }).collect::<Vec<_>>();
1801 // Propagate the cltv_expiry_delta one hop backwards since the delta from the current hop is
1802 // applicable for the previous hop.
1803 path.iter_mut().rev().fold(final_cltv_expiry_delta, |prev_cltv_expiry_delta, hop| {
1804 core::mem::replace(&mut hop.as_mut().unwrap().cltv_expiry_delta, prev_cltv_expiry_delta)
1806 selected_paths.push(path);
1808 // Make sure we would never create a route with more paths than we allow.
1809 debug_assert!(selected_paths.len() <= payment_params.max_path_count.into());
1811 if let Some(features) = &payment_params.features {
1812 for path in selected_paths.iter_mut() {
1813 if let Ok(route_hop) = path.last_mut().unwrap() {
1814 route_hop.node_features = features.to_context();
1820 paths: selected_paths.into_iter().map(|path| path.into_iter().collect()).collect::<Result<Vec<_>, _>>()?,
1821 payment_params: Some(payment_params.clone()),
1823 log_info!(logger, "Got route to {}: {}", payment_params.payee_pubkey, log_route!(route));
1827 // When an adversarial intermediary node observes a payment, it may be able to infer its
1828 // destination, if the remaining CLTV expiry delta exactly matches a feasible path in the network
1829 // graph. In order to improve privacy, this method obfuscates the CLTV expiry deltas along the
1830 // payment path by adding a randomized 'shadow route' offset to the final hop.
1831 fn add_random_cltv_offset(route: &mut Route, payment_params: &PaymentParameters,
1832 network_graph: &ReadOnlyNetworkGraph, random_seed_bytes: &[u8; 32]
1834 let network_channels = network_graph.channels();
1835 let network_nodes = network_graph.nodes();
1837 for path in route.paths.iter_mut() {
1838 let mut shadow_ctlv_expiry_delta_offset: u32 = 0;
1840 // Remember the last three nodes of the random walk and avoid looping back on them.
1841 // Init with the last three nodes from the actual path, if possible.
1842 let mut nodes_to_avoid: [NodeId; 3] = [NodeId::from_pubkey(&path.last().unwrap().pubkey),
1843 NodeId::from_pubkey(&path.get(path.len().saturating_sub(2)).unwrap().pubkey),
1844 NodeId::from_pubkey(&path.get(path.len().saturating_sub(3)).unwrap().pubkey)];
1846 // Choose the last publicly known node as the starting point for the random walk.
1847 let mut cur_hop: Option<NodeId> = None;
1848 let mut path_nonce = [0u8; 12];
1849 if let Some(starting_hop) = path.iter().rev()
1850 .find(|h| network_nodes.contains_key(&NodeId::from_pubkey(&h.pubkey))) {
1851 cur_hop = Some(NodeId::from_pubkey(&starting_hop.pubkey));
1852 path_nonce.copy_from_slice(&cur_hop.unwrap().as_slice()[..12]);
1855 // Init PRNG with the path-dependant nonce, which is static for private paths.
1856 let mut prng = ChaCha20::new(random_seed_bytes, &path_nonce);
1857 let mut random_path_bytes = [0u8; ::core::mem::size_of::<usize>()];
1859 // Pick a random path length in [1 .. 3]
1860 prng.process_in_place(&mut random_path_bytes);
1861 let random_walk_length = usize::from_be_bytes(random_path_bytes).wrapping_rem(3).wrapping_add(1);
1863 for random_hop in 0..random_walk_length {
1864 // If we don't find a suitable offset in the public network graph, we default to
1865 // MEDIAN_HOP_CLTV_EXPIRY_DELTA.
1866 let mut random_hop_offset = MEDIAN_HOP_CLTV_EXPIRY_DELTA;
1868 if let Some(cur_node_id) = cur_hop {
1869 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
1870 // Randomly choose the next unvisited hop.
1871 prng.process_in_place(&mut random_path_bytes);
1872 if let Some(random_channel) = usize::from_be_bytes(random_path_bytes)
1873 .checked_rem(cur_node.channels.len())
1874 .and_then(|index| cur_node.channels.get(index))
1875 .and_then(|id| network_channels.get(id)) {
1876 random_channel.as_directed_from(&cur_node_id).map(|(dir_info, next_id)| {
1877 if !nodes_to_avoid.iter().any(|x| x == next_id) {
1878 nodes_to_avoid[random_hop] = *next_id;
1879 random_hop_offset = dir_info.direction().cltv_expiry_delta.into();
1880 cur_hop = Some(*next_id);
1887 shadow_ctlv_expiry_delta_offset = shadow_ctlv_expiry_delta_offset
1888 .checked_add(random_hop_offset)
1889 .unwrap_or(shadow_ctlv_expiry_delta_offset);
1892 // Limit the total offset to reduce the worst-case locked liquidity timevalue
1893 const MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET: u32 = 3*144;
1894 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET);
1896 // Limit the offset so we never exceed the max_total_cltv_expiry_delta. To improve plausibility,
1897 // we choose the limit to be the largest possible multiple of MEDIAN_HOP_CLTV_EXPIRY_DELTA.
1898 let path_total_cltv_expiry_delta: u32 = path.iter().map(|h| h.cltv_expiry_delta).sum();
1899 let mut max_path_offset = payment_params.max_total_cltv_expiry_delta - path_total_cltv_expiry_delta;
1900 max_path_offset = cmp::max(
1901 max_path_offset - (max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA),
1902 max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA);
1903 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, max_path_offset);
1905 // Add 'shadow' CLTV offset to the final hop
1906 if let Some(last_hop) = path.last_mut() {
1907 last_hop.cltv_expiry_delta = last_hop.cltv_expiry_delta
1908 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(last_hop.cltv_expiry_delta);
1913 /// Construct a route from us (payer) to the target node (payee) via the given hops (which should
1914 /// exclude the payer, but include the payee). This may be useful, e.g., for probing the chosen path.
1916 /// Re-uses logic from `find_route`, so the restrictions described there also apply here.
1917 pub fn build_route_from_hops<L: Deref, GL: Deref>(
1918 our_node_pubkey: &PublicKey, hops: &[PublicKey], route_params: &RouteParameters,
1919 network_graph: &NetworkGraph<GL>, logger: L, random_seed_bytes: &[u8; 32]
1920 ) -> Result<Route, LightningError>
1921 where L::Target: Logger, GL::Target: Logger {
1922 let graph_lock = network_graph.read_only();
1923 let mut route = build_route_from_hops_internal(
1924 our_node_pubkey, hops, &route_params.payment_params, &graph_lock,
1925 route_params.final_value_msat, route_params.final_cltv_expiry_delta, logger, random_seed_bytes)?;
1926 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
1930 fn build_route_from_hops_internal<L: Deref>(
1931 our_node_pubkey: &PublicKey, hops: &[PublicKey], payment_params: &PaymentParameters,
1932 network_graph: &ReadOnlyNetworkGraph, final_value_msat: u64, final_cltv_expiry_delta: u32,
1933 logger: L, random_seed_bytes: &[u8; 32]
1934 ) -> Result<Route, LightningError> where L::Target: Logger {
1937 our_node_id: NodeId,
1938 hop_ids: [Option<NodeId>; MAX_PATH_LENGTH_ESTIMATE as usize],
1941 impl Score for HopScorer {
1942 fn channel_penalty_msat(&self, _short_channel_id: u64, source: &NodeId, target: &NodeId,
1943 _usage: ChannelUsage) -> u64
1945 let mut cur_id = self.our_node_id;
1946 for i in 0..self.hop_ids.len() {
1947 if let Some(next_id) = self.hop_ids[i] {
1948 if cur_id == *source && next_id == *target {
1959 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
1961 fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
1963 fn probe_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
1965 fn probe_successful(&mut self, _path: &[&RouteHop]) {}
1968 impl<'a> Writeable for HopScorer {
1970 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), io::Error> {
1975 if hops.len() > MAX_PATH_LENGTH_ESTIMATE.into() {
1976 return Err(LightningError{err: "Cannot build a route exceeding the maximum path length.".to_owned(), action: ErrorAction::IgnoreError});
1979 let our_node_id = NodeId::from_pubkey(our_node_pubkey);
1980 let mut hop_ids = [None; MAX_PATH_LENGTH_ESTIMATE as usize];
1981 for i in 0..hops.len() {
1982 hop_ids[i] = Some(NodeId::from_pubkey(&hops[i]));
1985 let scorer = HopScorer { our_node_id, hop_ids };
1987 get_route(our_node_pubkey, payment_params, network_graph, None, final_value_msat,
1988 final_cltv_expiry_delta, logger, &scorer, random_seed_bytes)
1993 use crate::routing::gossip::{NetworkGraph, P2PGossipSync, NodeId, EffectiveCapacity};
1994 use crate::routing::router::{get_route, build_route_from_hops_internal, add_random_cltv_offset, default_node_features,
1995 PaymentParameters, Route, RouteHint, RouteHintHop, RouteHop, RoutingFees,
1996 DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA, MAX_PATH_LENGTH_ESTIMATE};
1997 use crate::routing::scoring::{ChannelUsage, Score, ProbabilisticScorer, ProbabilisticScoringParameters};
1998 use crate::routing::test_utils::{add_channel, add_or_update_node, build_graph, build_line_graph, id_to_feature_flags, get_nodes, update_channel};
1999 use crate::chain::transaction::OutPoint;
2000 use crate::chain::keysinterface::KeysInterface;
2001 use crate::ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
2002 use crate::ln::msgs::{ErrorAction, LightningError, UnsignedChannelUpdate, MAX_VALUE_MSAT};
2003 use crate::ln::channelmanager;
2004 use crate::util::test_utils as ln_test_utils;
2005 use crate::util::chacha20::ChaCha20;
2007 use crate::util::ser::{Writeable, Writer};
2009 use bitcoin::hashes::Hash;
2010 use bitcoin::network::constants::Network;
2011 use bitcoin::blockdata::constants::genesis_block;
2012 use bitcoin::blockdata::script::Builder;
2013 use bitcoin::blockdata::opcodes;
2014 use bitcoin::blockdata::transaction::TxOut;
2018 use bitcoin::secp256k1::{PublicKey,SecretKey};
2019 use bitcoin::secp256k1::Secp256k1;
2021 use crate::prelude::*;
2022 use crate::sync::Arc;
2024 use core::convert::TryInto;
2026 fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
2027 features: InitFeatures, outbound_capacity_msat: u64) -> channelmanager::ChannelDetails {
2028 channelmanager::ChannelDetails {
2029 channel_id: [0; 32],
2030 counterparty: channelmanager::ChannelCounterparty {
2033 unspendable_punishment_reserve: 0,
2034 forwarding_info: None,
2035 outbound_htlc_minimum_msat: None,
2036 outbound_htlc_maximum_msat: None,
2038 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
2041 outbound_scid_alias: None,
2042 inbound_scid_alias: None,
2043 channel_value_satoshis: 0,
2046 outbound_capacity_msat,
2047 next_outbound_htlc_limit_msat: outbound_capacity_msat,
2048 inbound_capacity_msat: 42,
2049 unspendable_punishment_reserve: None,
2050 confirmations_required: None,
2051 force_close_spend_delay: None,
2052 is_outbound: true, is_channel_ready: true,
2053 is_usable: true, is_public: true,
2054 inbound_htlc_minimum_msat: None,
2055 inbound_htlc_maximum_msat: None,
2061 fn simple_route_test() {
2062 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2063 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2064 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2065 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2066 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2067 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2069 // Simple route to 2 via 1
2071 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) {
2072 assert_eq!(err, "Cannot send a payment of 0 msat");
2073 } else { panic!(); }
2075 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2076 assert_eq!(route.paths[0].len(), 2);
2078 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2079 assert_eq!(route.paths[0][0].short_channel_id, 2);
2080 assert_eq!(route.paths[0][0].fee_msat, 100);
2081 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2082 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2083 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2085 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2086 assert_eq!(route.paths[0][1].short_channel_id, 4);
2087 assert_eq!(route.paths[0][1].fee_msat, 100);
2088 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2089 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2090 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2094 fn invalid_first_hop_test() {
2095 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2096 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2097 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2098 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2099 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2100 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2102 // Simple route to 2 via 1
2104 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
2106 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) =
2107 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) {
2108 assert_eq!(err, "First hop cannot have our_node_pubkey as a destination.");
2109 } else { panic!(); }
2111 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2112 assert_eq!(route.paths[0].len(), 2);
2116 fn htlc_minimum_test() {
2117 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2118 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2119 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2120 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2121 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2122 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2124 // Simple route to 2 via 1
2126 // Disable other paths
2127 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2128 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2129 short_channel_id: 12,
2131 flags: 2, // to disable
2132 cltv_expiry_delta: 0,
2133 htlc_minimum_msat: 0,
2134 htlc_maximum_msat: MAX_VALUE_MSAT,
2136 fee_proportional_millionths: 0,
2137 excess_data: Vec::new()
2139 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2140 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2141 short_channel_id: 3,
2143 flags: 2, // to disable
2144 cltv_expiry_delta: 0,
2145 htlc_minimum_msat: 0,
2146 htlc_maximum_msat: MAX_VALUE_MSAT,
2148 fee_proportional_millionths: 0,
2149 excess_data: Vec::new()
2151 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2152 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2153 short_channel_id: 13,
2155 flags: 2, // to disable
2156 cltv_expiry_delta: 0,
2157 htlc_minimum_msat: 0,
2158 htlc_maximum_msat: MAX_VALUE_MSAT,
2160 fee_proportional_millionths: 0,
2161 excess_data: Vec::new()
2163 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2164 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2165 short_channel_id: 6,
2167 flags: 2, // to disable
2168 cltv_expiry_delta: 0,
2169 htlc_minimum_msat: 0,
2170 htlc_maximum_msat: MAX_VALUE_MSAT,
2172 fee_proportional_millionths: 0,
2173 excess_data: Vec::new()
2175 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2176 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2177 short_channel_id: 7,
2179 flags: 2, // to disable
2180 cltv_expiry_delta: 0,
2181 htlc_minimum_msat: 0,
2182 htlc_maximum_msat: MAX_VALUE_MSAT,
2184 fee_proportional_millionths: 0,
2185 excess_data: Vec::new()
2188 // Check against amount_to_transfer_over_msat.
2189 // Set minimal HTLC of 200_000_000 msat.
2190 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2191 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2192 short_channel_id: 2,
2195 cltv_expiry_delta: 0,
2196 htlc_minimum_msat: 200_000_000,
2197 htlc_maximum_msat: MAX_VALUE_MSAT,
2199 fee_proportional_millionths: 0,
2200 excess_data: Vec::new()
2203 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
2205 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2206 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2207 short_channel_id: 4,
2210 cltv_expiry_delta: 0,
2211 htlc_minimum_msat: 0,
2212 htlc_maximum_msat: 199_999_999,
2214 fee_proportional_millionths: 0,
2215 excess_data: Vec::new()
2218 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
2219 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) {
2220 assert_eq!(err, "Failed to find a path to the given destination");
2221 } else { panic!(); }
2223 // Lift the restriction on the first hop.
2224 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2225 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2226 short_channel_id: 2,
2229 cltv_expiry_delta: 0,
2230 htlc_minimum_msat: 0,
2231 htlc_maximum_msat: MAX_VALUE_MSAT,
2233 fee_proportional_millionths: 0,
2234 excess_data: Vec::new()
2237 // A payment above the minimum should pass
2238 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();
2239 assert_eq!(route.paths[0].len(), 2);
2243 fn htlc_minimum_overpay_test() {
2244 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2245 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2246 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(channelmanager::provided_invoice_features());
2247 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2248 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2249 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2251 // A route to node#2 via two paths.
2252 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
2253 // Thus, they can't send 60 without overpaying.
2254 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2255 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2256 short_channel_id: 2,
2259 cltv_expiry_delta: 0,
2260 htlc_minimum_msat: 35_000,
2261 htlc_maximum_msat: 40_000,
2263 fee_proportional_millionths: 0,
2264 excess_data: Vec::new()
2266 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2267 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2268 short_channel_id: 12,
2271 cltv_expiry_delta: 0,
2272 htlc_minimum_msat: 35_000,
2273 htlc_maximum_msat: 40_000,
2275 fee_proportional_millionths: 0,
2276 excess_data: Vec::new()
2280 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2281 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2282 short_channel_id: 13,
2285 cltv_expiry_delta: 0,
2286 htlc_minimum_msat: 0,
2287 htlc_maximum_msat: MAX_VALUE_MSAT,
2289 fee_proportional_millionths: 0,
2290 excess_data: Vec::new()
2292 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2293 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2294 short_channel_id: 4,
2297 cltv_expiry_delta: 0,
2298 htlc_minimum_msat: 0,
2299 htlc_maximum_msat: MAX_VALUE_MSAT,
2301 fee_proportional_millionths: 0,
2302 excess_data: Vec::new()
2305 // Disable other paths
2306 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2307 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2308 short_channel_id: 1,
2310 flags: 2, // to disable
2311 cltv_expiry_delta: 0,
2312 htlc_minimum_msat: 0,
2313 htlc_maximum_msat: MAX_VALUE_MSAT,
2315 fee_proportional_millionths: 0,
2316 excess_data: Vec::new()
2319 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 60_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2320 // Overpay fees to hit htlc_minimum_msat.
2321 let overpaid_fees = route.paths[0][0].fee_msat + route.paths[1][0].fee_msat;
2322 // TODO: this could be better balanced to overpay 10k and not 15k.
2323 assert_eq!(overpaid_fees, 15_000);
2325 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
2326 // while taking even more fee to match htlc_minimum_msat.
2327 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2328 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2329 short_channel_id: 12,
2332 cltv_expiry_delta: 0,
2333 htlc_minimum_msat: 65_000,
2334 htlc_maximum_msat: 80_000,
2336 fee_proportional_millionths: 0,
2337 excess_data: Vec::new()
2339 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2340 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2341 short_channel_id: 2,
2344 cltv_expiry_delta: 0,
2345 htlc_minimum_msat: 0,
2346 htlc_maximum_msat: MAX_VALUE_MSAT,
2348 fee_proportional_millionths: 0,
2349 excess_data: Vec::new()
2351 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2352 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2353 short_channel_id: 4,
2356 cltv_expiry_delta: 0,
2357 htlc_minimum_msat: 0,
2358 htlc_maximum_msat: MAX_VALUE_MSAT,
2360 fee_proportional_millionths: 100_000,
2361 excess_data: Vec::new()
2364 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 60_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2365 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
2366 assert_eq!(route.paths.len(), 1);
2367 assert_eq!(route.paths[0][0].short_channel_id, 12);
2368 let fees = route.paths[0][0].fee_msat;
2369 assert_eq!(fees, 5_000);
2371 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2372 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
2373 // the other channel.
2374 assert_eq!(route.paths.len(), 1);
2375 assert_eq!(route.paths[0][0].short_channel_id, 2);
2376 let fees = route.paths[0][0].fee_msat;
2377 assert_eq!(fees, 5_000);
2381 fn disable_channels_test() {
2382 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2383 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2384 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2385 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2386 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2387 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2389 // // Disable channels 4 and 12 by flags=2
2390 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2391 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2392 short_channel_id: 4,
2394 flags: 2, // to disable
2395 cltv_expiry_delta: 0,
2396 htlc_minimum_msat: 0,
2397 htlc_maximum_msat: MAX_VALUE_MSAT,
2399 fee_proportional_millionths: 0,
2400 excess_data: Vec::new()
2402 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2403 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2404 short_channel_id: 12,
2406 flags: 2, // to disable
2407 cltv_expiry_delta: 0,
2408 htlc_minimum_msat: 0,
2409 htlc_maximum_msat: MAX_VALUE_MSAT,
2411 fee_proportional_millionths: 0,
2412 excess_data: Vec::new()
2415 // If all the channels require some features we don't understand, route should fail
2416 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) {
2417 assert_eq!(err, "Failed to find a path to the given destination");
2418 } else { panic!(); }
2420 // If we specify a channel to node7, that overrides our local channel view and that gets used
2421 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2422 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();
2423 assert_eq!(route.paths[0].len(), 2);
2425 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2426 assert_eq!(route.paths[0][0].short_channel_id, 42);
2427 assert_eq!(route.paths[0][0].fee_msat, 200);
2428 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2429 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2430 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2432 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2433 assert_eq!(route.paths[0][1].short_channel_id, 13);
2434 assert_eq!(route.paths[0][1].fee_msat, 100);
2435 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2436 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2437 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2441 fn disable_node_test() {
2442 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2443 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2444 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2445 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2446 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2447 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2449 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
2450 let mut unknown_features = NodeFeatures::empty();
2451 unknown_features.set_unknown_feature_required();
2452 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
2453 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
2454 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
2456 // If all nodes require some features we don't understand, route should fail
2457 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) {
2458 assert_eq!(err, "Failed to find a path to the given destination");
2459 } else { panic!(); }
2461 // If we specify a channel to node7, that overrides our local channel view and that gets used
2462 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2463 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();
2464 assert_eq!(route.paths[0].len(), 2);
2466 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2467 assert_eq!(route.paths[0][0].short_channel_id, 42);
2468 assert_eq!(route.paths[0][0].fee_msat, 200);
2469 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2470 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2471 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2473 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2474 assert_eq!(route.paths[0][1].short_channel_id, 13);
2475 assert_eq!(route.paths[0][1].fee_msat, 100);
2476 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2477 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2478 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2480 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
2481 // naively) assume that the user checked the feature bits on the invoice, which override
2482 // the node_announcement.
2486 fn our_chans_test() {
2487 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2488 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2489 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2490 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2491 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2493 // Route to 1 via 2 and 3 because our channel to 1 is disabled
2494 let payment_params = PaymentParameters::from_node_id(nodes[0]);
2495 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2496 assert_eq!(route.paths[0].len(), 3);
2498 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2499 assert_eq!(route.paths[0][0].short_channel_id, 2);
2500 assert_eq!(route.paths[0][0].fee_msat, 200);
2501 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2502 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2503 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2505 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2506 assert_eq!(route.paths[0][1].short_channel_id, 4);
2507 assert_eq!(route.paths[0][1].fee_msat, 100);
2508 assert_eq!(route.paths[0][1].cltv_expiry_delta, (3 << 4) | 2);
2509 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2510 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2512 assert_eq!(route.paths[0][2].pubkey, nodes[0]);
2513 assert_eq!(route.paths[0][2].short_channel_id, 3);
2514 assert_eq!(route.paths[0][2].fee_msat, 100);
2515 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
2516 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(1));
2517 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(3));
2519 // If we specify a channel to node7, that overrides our local channel view and that gets used
2520 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2521 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2522 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();
2523 assert_eq!(route.paths[0].len(), 2);
2525 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2526 assert_eq!(route.paths[0][0].short_channel_id, 42);
2527 assert_eq!(route.paths[0][0].fee_msat, 200);
2528 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2529 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2530 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2532 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2533 assert_eq!(route.paths[0][1].short_channel_id, 13);
2534 assert_eq!(route.paths[0][1].fee_msat, 100);
2535 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2536 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2537 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2540 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2541 let zero_fees = RoutingFees {
2543 proportional_millionths: 0,
2545 vec![RouteHint(vec![RouteHintHop {
2546 src_node_id: nodes[3],
2547 short_channel_id: 8,
2549 cltv_expiry_delta: (8 << 4) | 1,
2550 htlc_minimum_msat: None,
2551 htlc_maximum_msat: None,
2553 ]), RouteHint(vec![RouteHintHop {
2554 src_node_id: nodes[4],
2555 short_channel_id: 9,
2558 proportional_millionths: 0,
2560 cltv_expiry_delta: (9 << 4) | 1,
2561 htlc_minimum_msat: None,
2562 htlc_maximum_msat: None,
2563 }]), RouteHint(vec![RouteHintHop {
2564 src_node_id: nodes[5],
2565 short_channel_id: 10,
2567 cltv_expiry_delta: (10 << 4) | 1,
2568 htlc_minimum_msat: None,
2569 htlc_maximum_msat: None,
2573 fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2574 let zero_fees = RoutingFees {
2576 proportional_millionths: 0,
2578 vec![RouteHint(vec![RouteHintHop {
2579 src_node_id: nodes[2],
2580 short_channel_id: 5,
2583 proportional_millionths: 0,
2585 cltv_expiry_delta: (5 << 4) | 1,
2586 htlc_minimum_msat: None,
2587 htlc_maximum_msat: None,
2589 src_node_id: nodes[3],
2590 short_channel_id: 8,
2592 cltv_expiry_delta: (8 << 4) | 1,
2593 htlc_minimum_msat: None,
2594 htlc_maximum_msat: None,
2596 ]), RouteHint(vec![RouteHintHop {
2597 src_node_id: nodes[4],
2598 short_channel_id: 9,
2601 proportional_millionths: 0,
2603 cltv_expiry_delta: (9 << 4) | 1,
2604 htlc_minimum_msat: None,
2605 htlc_maximum_msat: None,
2606 }]), RouteHint(vec![RouteHintHop {
2607 src_node_id: nodes[5],
2608 short_channel_id: 10,
2610 cltv_expiry_delta: (10 << 4) | 1,
2611 htlc_minimum_msat: None,
2612 htlc_maximum_msat: None,
2617 fn partial_route_hint_test() {
2618 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2619 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2620 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2621 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2622 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2624 // Simple test across 2, 3, 5, and 4 via a last_hop channel
2625 // Tests the behaviour when the RouteHint contains a suboptimal hop.
2626 // RouteHint may be partially used by the algo to build the best path.
2628 // First check that last hop can't have its source as the payee.
2629 let invalid_last_hop = RouteHint(vec![RouteHintHop {
2630 src_node_id: nodes[6],
2631 short_channel_id: 8,
2634 proportional_millionths: 0,
2636 cltv_expiry_delta: (8 << 4) | 1,
2637 htlc_minimum_msat: None,
2638 htlc_maximum_msat: None,
2641 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
2642 invalid_last_hops.push(invalid_last_hop);
2644 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(invalid_last_hops);
2645 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) {
2646 assert_eq!(err, "Route hint cannot have the payee as the source.");
2647 } else { panic!(); }
2650 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops_multi_private_channels(&nodes));
2651 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2652 assert_eq!(route.paths[0].len(), 5);
2654 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2655 assert_eq!(route.paths[0][0].short_channel_id, 2);
2656 assert_eq!(route.paths[0][0].fee_msat, 100);
2657 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2658 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2659 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2661 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2662 assert_eq!(route.paths[0][1].short_channel_id, 4);
2663 assert_eq!(route.paths[0][1].fee_msat, 0);
2664 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
2665 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2666 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2668 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2669 assert_eq!(route.paths[0][2].short_channel_id, 6);
2670 assert_eq!(route.paths[0][2].fee_msat, 0);
2671 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
2672 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2673 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2675 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2676 assert_eq!(route.paths[0][3].short_channel_id, 11);
2677 assert_eq!(route.paths[0][3].fee_msat, 0);
2678 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
2679 // If we have a peer in the node map, we'll use their features here since we don't have
2680 // a way of figuring out their features from the invoice:
2681 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2682 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2684 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2685 assert_eq!(route.paths[0][4].short_channel_id, 8);
2686 assert_eq!(route.paths[0][4].fee_msat, 100);
2687 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2688 assert_eq!(route.paths[0][4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
2689 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2692 fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2693 let zero_fees = RoutingFees {
2695 proportional_millionths: 0,
2697 vec![RouteHint(vec![RouteHintHop {
2698 src_node_id: nodes[3],
2699 short_channel_id: 8,
2701 cltv_expiry_delta: (8 << 4) | 1,
2702 htlc_minimum_msat: None,
2703 htlc_maximum_msat: None,
2704 }]), RouteHint(vec![
2706 ]), RouteHint(vec![RouteHintHop {
2707 src_node_id: nodes[5],
2708 short_channel_id: 10,
2710 cltv_expiry_delta: (10 << 4) | 1,
2711 htlc_minimum_msat: None,
2712 htlc_maximum_msat: None,
2717 fn ignores_empty_last_hops_test() {
2718 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2719 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2720 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(empty_last_hop(&nodes));
2721 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2722 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2723 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2725 // Test handling of an empty RouteHint passed in Invoice.
2727 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2728 assert_eq!(route.paths[0].len(), 5);
2730 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2731 assert_eq!(route.paths[0][0].short_channel_id, 2);
2732 assert_eq!(route.paths[0][0].fee_msat, 100);
2733 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2734 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2735 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2737 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2738 assert_eq!(route.paths[0][1].short_channel_id, 4);
2739 assert_eq!(route.paths[0][1].fee_msat, 0);
2740 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
2741 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2742 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2744 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2745 assert_eq!(route.paths[0][2].short_channel_id, 6);
2746 assert_eq!(route.paths[0][2].fee_msat, 0);
2747 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
2748 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2749 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2751 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2752 assert_eq!(route.paths[0][3].short_channel_id, 11);
2753 assert_eq!(route.paths[0][3].fee_msat, 0);
2754 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
2755 // If we have a peer in the node map, we'll use their features here since we don't have
2756 // a way of figuring out their features from the invoice:
2757 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2758 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2760 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2761 assert_eq!(route.paths[0][4].short_channel_id, 8);
2762 assert_eq!(route.paths[0][4].fee_msat, 100);
2763 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2764 assert_eq!(route.paths[0][4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
2765 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2768 /// Builds a trivial last-hop hint that passes through the two nodes given, with channel 0xff00
2770 fn multi_hop_last_hops_hint(hint_hops: [PublicKey; 2]) -> Vec<RouteHint> {
2771 let zero_fees = RoutingFees {
2773 proportional_millionths: 0,
2775 vec![RouteHint(vec![RouteHintHop {
2776 src_node_id: hint_hops[0],
2777 short_channel_id: 0xff00,
2780 proportional_millionths: 0,
2782 cltv_expiry_delta: (5 << 4) | 1,
2783 htlc_minimum_msat: None,
2784 htlc_maximum_msat: None,
2786 src_node_id: hint_hops[1],
2787 short_channel_id: 0xff01,
2789 cltv_expiry_delta: (8 << 4) | 1,
2790 htlc_minimum_msat: None,
2791 htlc_maximum_msat: None,
2796 fn multi_hint_last_hops_test() {
2797 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2798 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2799 let last_hops = multi_hop_last_hops_hint([nodes[2], nodes[3]]);
2800 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops.clone());
2801 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2802 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2803 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2804 // Test through channels 2, 3, 0xff00, 0xff01.
2805 // Test shows that multiple hop hints are considered.
2807 // Disabling channels 6 & 7 by flags=2
2808 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2809 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2810 short_channel_id: 6,
2812 flags: 2, // to disable
2813 cltv_expiry_delta: 0,
2814 htlc_minimum_msat: 0,
2815 htlc_maximum_msat: MAX_VALUE_MSAT,
2817 fee_proportional_millionths: 0,
2818 excess_data: Vec::new()
2820 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2821 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2822 short_channel_id: 7,
2824 flags: 2, // to disable
2825 cltv_expiry_delta: 0,
2826 htlc_minimum_msat: 0,
2827 htlc_maximum_msat: MAX_VALUE_MSAT,
2829 fee_proportional_millionths: 0,
2830 excess_data: Vec::new()
2833 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2834 assert_eq!(route.paths[0].len(), 4);
2836 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2837 assert_eq!(route.paths[0][0].short_channel_id, 2);
2838 assert_eq!(route.paths[0][0].fee_msat, 200);
2839 assert_eq!(route.paths[0][0].cltv_expiry_delta, 65);
2840 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2841 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2843 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2844 assert_eq!(route.paths[0][1].short_channel_id, 4);
2845 assert_eq!(route.paths[0][1].fee_msat, 100);
2846 assert_eq!(route.paths[0][1].cltv_expiry_delta, 81);
2847 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2848 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2850 assert_eq!(route.paths[0][2].pubkey, nodes[3]);
2851 assert_eq!(route.paths[0][2].short_channel_id, last_hops[0].0[0].short_channel_id);
2852 assert_eq!(route.paths[0][2].fee_msat, 0);
2853 assert_eq!(route.paths[0][2].cltv_expiry_delta, 129);
2854 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(4));
2855 assert_eq!(route.paths[0][2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2857 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2858 assert_eq!(route.paths[0][3].short_channel_id, last_hops[0].0[1].short_channel_id);
2859 assert_eq!(route.paths[0][3].fee_msat, 100);
2860 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2861 assert_eq!(route.paths[0][3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
2862 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2866 fn private_multi_hint_last_hops_test() {
2867 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2868 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2870 let non_announced_privkey = SecretKey::from_slice(&hex::decode(format!("{:02x}", 0xf0).repeat(32)).unwrap()[..]).unwrap();
2871 let non_announced_pubkey = PublicKey::from_secret_key(&secp_ctx, &non_announced_privkey);
2873 let last_hops = multi_hop_last_hops_hint([nodes[2], non_announced_pubkey]);
2874 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops.clone());
2875 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2876 // Test through channels 2, 3, 0xff00, 0xff01.
2877 // Test shows that multiple hop hints are considered.
2879 // Disabling channels 6 & 7 by flags=2
2880 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2881 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2882 short_channel_id: 6,
2884 flags: 2, // to disable
2885 cltv_expiry_delta: 0,
2886 htlc_minimum_msat: 0,
2887 htlc_maximum_msat: MAX_VALUE_MSAT,
2889 fee_proportional_millionths: 0,
2890 excess_data: Vec::new()
2892 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2893 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2894 short_channel_id: 7,
2896 flags: 2, // to disable
2897 cltv_expiry_delta: 0,
2898 htlc_minimum_msat: 0,
2899 htlc_maximum_msat: MAX_VALUE_MSAT,
2901 fee_proportional_millionths: 0,
2902 excess_data: Vec::new()
2905 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &[42u8; 32]).unwrap();
2906 assert_eq!(route.paths[0].len(), 4);
2908 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2909 assert_eq!(route.paths[0][0].short_channel_id, 2);
2910 assert_eq!(route.paths[0][0].fee_msat, 200);
2911 assert_eq!(route.paths[0][0].cltv_expiry_delta, 65);
2912 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2913 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2915 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2916 assert_eq!(route.paths[0][1].short_channel_id, 4);
2917 assert_eq!(route.paths[0][1].fee_msat, 100);
2918 assert_eq!(route.paths[0][1].cltv_expiry_delta, 81);
2919 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2920 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2922 assert_eq!(route.paths[0][2].pubkey, non_announced_pubkey);
2923 assert_eq!(route.paths[0][2].short_channel_id, last_hops[0].0[0].short_channel_id);
2924 assert_eq!(route.paths[0][2].fee_msat, 0);
2925 assert_eq!(route.paths[0][2].cltv_expiry_delta, 129);
2926 assert_eq!(route.paths[0][2].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
2927 assert_eq!(route.paths[0][2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2929 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2930 assert_eq!(route.paths[0][3].short_channel_id, last_hops[0].0[1].short_channel_id);
2931 assert_eq!(route.paths[0][3].fee_msat, 100);
2932 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2933 assert_eq!(route.paths[0][3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
2934 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2937 fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2938 let zero_fees = RoutingFees {
2940 proportional_millionths: 0,
2942 vec![RouteHint(vec![RouteHintHop {
2943 src_node_id: nodes[4],
2944 short_channel_id: 11,
2946 cltv_expiry_delta: (11 << 4) | 1,
2947 htlc_minimum_msat: None,
2948 htlc_maximum_msat: None,
2950 src_node_id: nodes[3],
2951 short_channel_id: 8,
2953 cltv_expiry_delta: (8 << 4) | 1,
2954 htlc_minimum_msat: None,
2955 htlc_maximum_msat: None,
2956 }]), RouteHint(vec![RouteHintHop {
2957 src_node_id: nodes[4],
2958 short_channel_id: 9,
2961 proportional_millionths: 0,
2963 cltv_expiry_delta: (9 << 4) | 1,
2964 htlc_minimum_msat: None,
2965 htlc_maximum_msat: None,
2966 }]), RouteHint(vec![RouteHintHop {
2967 src_node_id: nodes[5],
2968 short_channel_id: 10,
2970 cltv_expiry_delta: (10 << 4) | 1,
2971 htlc_minimum_msat: None,
2972 htlc_maximum_msat: None,
2977 fn last_hops_with_public_channel_test() {
2978 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2979 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2980 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops_with_public_channel(&nodes));
2981 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2982 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2983 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2984 // This test shows that public routes can be present in the invoice
2985 // which would be handled in the same manner.
2987 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2988 assert_eq!(route.paths[0].len(), 5);
2990 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2991 assert_eq!(route.paths[0][0].short_channel_id, 2);
2992 assert_eq!(route.paths[0][0].fee_msat, 100);
2993 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2994 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2995 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2997 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2998 assert_eq!(route.paths[0][1].short_channel_id, 4);
2999 assert_eq!(route.paths[0][1].fee_msat, 0);
3000 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
3001 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3002 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3004 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
3005 assert_eq!(route.paths[0][2].short_channel_id, 6);
3006 assert_eq!(route.paths[0][2].fee_msat, 0);
3007 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
3008 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
3009 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
3011 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
3012 assert_eq!(route.paths[0][3].short_channel_id, 11);
3013 assert_eq!(route.paths[0][3].fee_msat, 0);
3014 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
3015 // If we have a peer in the node map, we'll use their features here since we don't have
3016 // a way of figuring out their features from the invoice:
3017 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
3018 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
3020 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
3021 assert_eq!(route.paths[0][4].short_channel_id, 8);
3022 assert_eq!(route.paths[0][4].fee_msat, 100);
3023 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
3024 assert_eq!(route.paths[0][4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3025 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3029 fn our_chans_last_hop_connect_test() {
3030 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3031 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3032 let scorer = ln_test_utils::TestScorer::with_penalty(0);
3033 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3034 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3036 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
3037 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3038 let mut last_hops = last_hops(&nodes);
3039 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops.clone());
3040 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();
3041 assert_eq!(route.paths[0].len(), 2);
3043 assert_eq!(route.paths[0][0].pubkey, nodes[3]);
3044 assert_eq!(route.paths[0][0].short_channel_id, 42);
3045 assert_eq!(route.paths[0][0].fee_msat, 0);
3046 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 4) | 1);
3047 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
3048 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3050 assert_eq!(route.paths[0][1].pubkey, nodes[6]);
3051 assert_eq!(route.paths[0][1].short_channel_id, 8);
3052 assert_eq!(route.paths[0][1].fee_msat, 100);
3053 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
3054 assert_eq!(route.paths[0][1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3055 assert_eq!(route.paths[0][1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3057 last_hops[0].0[0].fees.base_msat = 1000;
3059 // Revert to via 6 as the fee on 8 goes up
3060 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops);
3061 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3062 assert_eq!(route.paths[0].len(), 4);
3064 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3065 assert_eq!(route.paths[0][0].short_channel_id, 2);
3066 assert_eq!(route.paths[0][0].fee_msat, 200); // fee increased as its % of value transferred across node
3067 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
3068 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3069 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3071 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3072 assert_eq!(route.paths[0][1].short_channel_id, 4);
3073 assert_eq!(route.paths[0][1].fee_msat, 100);
3074 assert_eq!(route.paths[0][1].cltv_expiry_delta, (7 << 4) | 1);
3075 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3076 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3078 assert_eq!(route.paths[0][2].pubkey, nodes[5]);
3079 assert_eq!(route.paths[0][2].short_channel_id, 7);
3080 assert_eq!(route.paths[0][2].fee_msat, 0);
3081 assert_eq!(route.paths[0][2].cltv_expiry_delta, (10 << 4) | 1);
3082 // If we have a peer in the node map, we'll use their features here since we don't have
3083 // a way of figuring out their features from the invoice:
3084 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
3085 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(7));
3087 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
3088 assert_eq!(route.paths[0][3].short_channel_id, 10);
3089 assert_eq!(route.paths[0][3].fee_msat, 100);
3090 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
3091 assert_eq!(route.paths[0][3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3092 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3094 // ...but still use 8 for larger payments as 6 has a variable feerate
3095 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 2000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3096 assert_eq!(route.paths[0].len(), 5);
3098 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3099 assert_eq!(route.paths[0][0].short_channel_id, 2);
3100 assert_eq!(route.paths[0][0].fee_msat, 3000);
3101 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
3102 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3103 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3105 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3106 assert_eq!(route.paths[0][1].short_channel_id, 4);
3107 assert_eq!(route.paths[0][1].fee_msat, 0);
3108 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
3109 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3110 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3112 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
3113 assert_eq!(route.paths[0][2].short_channel_id, 6);
3114 assert_eq!(route.paths[0][2].fee_msat, 0);
3115 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
3116 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
3117 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
3119 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
3120 assert_eq!(route.paths[0][3].short_channel_id, 11);
3121 assert_eq!(route.paths[0][3].fee_msat, 1000);
3122 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
3123 // If we have a peer in the node map, we'll use their features here since we don't have
3124 // a way of figuring out their features from the invoice:
3125 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
3126 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
3128 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
3129 assert_eq!(route.paths[0][4].short_channel_id, 8);
3130 assert_eq!(route.paths[0][4].fee_msat, 2000);
3131 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
3132 assert_eq!(route.paths[0][4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3133 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3136 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> {
3137 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
3138 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3139 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3141 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
3142 let last_hops = RouteHint(vec![RouteHintHop {
3143 src_node_id: middle_node_id,
3144 short_channel_id: 8,
3147 proportional_millionths: last_hop_fee_prop,
3149 cltv_expiry_delta: (8 << 4) | 1,
3150 htlc_minimum_msat: None,
3151 htlc_maximum_msat: last_hop_htlc_max,
3153 let payment_params = PaymentParameters::from_node_id(target_node_id).with_route_hints(vec![last_hops]);
3154 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
3155 let scorer = ln_test_utils::TestScorer::with_penalty(0);
3156 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3157 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3158 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
3159 let logger = ln_test_utils::TestLogger::new();
3160 let network_graph = NetworkGraph::new(genesis_hash, &logger);
3161 let route = get_route(&source_node_id, &payment_params, &network_graph.read_only(),
3162 Some(&our_chans.iter().collect::<Vec<_>>()), route_val, 42, &logger, &scorer, &random_seed_bytes);
3167 fn unannounced_path_test() {
3168 // We should be able to send a payment to a destination without any help of a routing graph
3169 // if we have a channel with a common counterparty that appears in the first and last hop
3171 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
3173 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3174 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3175 assert_eq!(route.paths[0].len(), 2);
3177 assert_eq!(route.paths[0][0].pubkey, middle_node_id);
3178 assert_eq!(route.paths[0][0].short_channel_id, 42);
3179 assert_eq!(route.paths[0][0].fee_msat, 1001);
3180 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 4) | 1);
3181 assert_eq!(route.paths[0][0].node_features.le_flags(), &[0b11]);
3182 assert_eq!(route.paths[0][0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3184 assert_eq!(route.paths[0][1].pubkey, target_node_id);
3185 assert_eq!(route.paths[0][1].short_channel_id, 8);
3186 assert_eq!(route.paths[0][1].fee_msat, 1000000);
3187 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
3188 assert_eq!(route.paths[0][1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3189 assert_eq!(route.paths[0][1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3193 fn overflow_unannounced_path_test_liquidity_underflow() {
3194 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
3195 // the last-hop had a fee which overflowed a u64, we'd panic.
3196 // This was due to us adding the first-hop from us unconditionally, causing us to think
3197 // we'd built a path (as our node is in the "best candidate" set), when we had not.
3198 // In this test, we previously hit a subtraction underflow due to having less available
3199 // liquidity at the last hop than 0.
3200 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());
3204 fn overflow_unannounced_path_test_feerate_overflow() {
3205 // This tests for the same case as above, except instead of hitting a subtraction
3206 // underflow, we hit a case where the fee charged at a hop overflowed.
3207 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());
3211 fn available_amount_while_routing_test() {
3212 // Tests whether we choose the correct available channel amount while routing.
3214 let (secp_ctx, network_graph, mut gossip_sync, chain_monitor, logger) = build_graph();
3215 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3216 let scorer = ln_test_utils::TestScorer::with_penalty(0);
3217 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3218 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3219 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(channelmanager::provided_invoice_features());
3221 // We will use a simple single-path route from
3222 // our node to node2 via node0: channels {1, 3}.
3224 // First disable all other paths.
3225 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3226 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3227 short_channel_id: 2,
3230 cltv_expiry_delta: 0,
3231 htlc_minimum_msat: 0,
3232 htlc_maximum_msat: 100_000,
3234 fee_proportional_millionths: 0,
3235 excess_data: Vec::new()
3237 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3238 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3239 short_channel_id: 12,
3242 cltv_expiry_delta: 0,
3243 htlc_minimum_msat: 0,
3244 htlc_maximum_msat: 100_000,
3246 fee_proportional_millionths: 0,
3247 excess_data: Vec::new()
3250 // Make the first channel (#1) very permissive,
3251 // and we will be testing all limits on the second channel.
3252 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3253 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3254 short_channel_id: 1,
3257 cltv_expiry_delta: 0,
3258 htlc_minimum_msat: 0,
3259 htlc_maximum_msat: 1_000_000_000,
3261 fee_proportional_millionths: 0,
3262 excess_data: Vec::new()
3265 // First, let's see if routing works if we have absolutely no idea about the available amount.
3266 // In this case, it should be set to 250_000 sats.
3267 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3268 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3269 short_channel_id: 3,
3272 cltv_expiry_delta: 0,
3273 htlc_minimum_msat: 0,
3274 htlc_maximum_msat: 250_000_000,
3276 fee_proportional_millionths: 0,
3277 excess_data: Vec::new()
3281 // Attempt to route more than available results in a failure.
3282 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3283 &our_id, &payment_params, &network_graph.read_only(), None, 250_000_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3284 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3285 } else { panic!(); }
3289 // Now, attempt to route an exact amount we have should be fine.
3290 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();
3291 assert_eq!(route.paths.len(), 1);
3292 let path = route.paths.last().unwrap();
3293 assert_eq!(path.len(), 2);
3294 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3295 assert_eq!(path.last().unwrap().fee_msat, 250_000_000);
3298 // Check that setting next_outbound_htlc_limit_msat in first_hops limits the channels.
3299 // Disable channel #1 and use another first hop.
3300 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3301 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3302 short_channel_id: 1,
3305 cltv_expiry_delta: 0,
3306 htlc_minimum_msat: 0,
3307 htlc_maximum_msat: 1_000_000_000,
3309 fee_proportional_millionths: 0,
3310 excess_data: Vec::new()
3313 // Now, limit the first_hop by the next_outbound_htlc_limit_msat of 200_000 sats.
3314 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
3317 // Attempt to route more than available results in a failure.
3318 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3319 &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) {
3320 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3321 } else { panic!(); }
3325 // Now, attempt to route an exact amount we have should be fine.
3326 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();
3327 assert_eq!(route.paths.len(), 1);
3328 let path = route.paths.last().unwrap();
3329 assert_eq!(path.len(), 2);
3330 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3331 assert_eq!(path.last().unwrap().fee_msat, 200_000_000);
3334 // Enable channel #1 back.
3335 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3336 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3337 short_channel_id: 1,
3340 cltv_expiry_delta: 0,
3341 htlc_minimum_msat: 0,
3342 htlc_maximum_msat: 1_000_000_000,
3344 fee_proportional_millionths: 0,
3345 excess_data: Vec::new()
3349 // Now let's see if routing works if we know only htlc_maximum_msat.
3350 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3351 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3352 short_channel_id: 3,
3355 cltv_expiry_delta: 0,
3356 htlc_minimum_msat: 0,
3357 htlc_maximum_msat: 15_000,
3359 fee_proportional_millionths: 0,
3360 excess_data: Vec::new()
3364 // Attempt to route more than available results in a failure.
3365 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3366 &our_id, &payment_params, &network_graph.read_only(), None, 15_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3367 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3368 } else { panic!(); }
3372 // Now, attempt to route an exact amount we have should be fine.
3373 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 15_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3374 assert_eq!(route.paths.len(), 1);
3375 let path = route.paths.last().unwrap();
3376 assert_eq!(path.len(), 2);
3377 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3378 assert_eq!(path.last().unwrap().fee_msat, 15_000);
3381 // Now let's see if routing works if we know only capacity from the UTXO.
3383 // We can't change UTXO capacity on the fly, so we'll disable
3384 // the existing channel and add another one with the capacity we need.
3385 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3386 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3387 short_channel_id: 3,
3390 cltv_expiry_delta: 0,
3391 htlc_minimum_msat: 0,
3392 htlc_maximum_msat: MAX_VALUE_MSAT,
3394 fee_proportional_millionths: 0,
3395 excess_data: Vec::new()
3398 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
3399 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
3400 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
3401 .push_opcode(opcodes::all::OP_PUSHNUM_2)
3402 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
3404 *chain_monitor.utxo_ret.lock().unwrap() = Ok(TxOut { value: 15, script_pubkey: good_script.clone() });
3405 gossip_sync.add_chain_access(Some(chain_monitor));
3407 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
3408 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3409 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3410 short_channel_id: 333,
3413 cltv_expiry_delta: (3 << 4) | 1,
3414 htlc_minimum_msat: 0,
3415 htlc_maximum_msat: 15_000,
3417 fee_proportional_millionths: 0,
3418 excess_data: Vec::new()
3420 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3421 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3422 short_channel_id: 333,
3425 cltv_expiry_delta: (3 << 4) | 2,
3426 htlc_minimum_msat: 0,
3427 htlc_maximum_msat: 15_000,
3429 fee_proportional_millionths: 0,
3430 excess_data: Vec::new()
3434 // Attempt to route more than available results in a failure.
3435 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3436 &our_id, &payment_params, &network_graph.read_only(), None, 15_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3437 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3438 } else { panic!(); }
3442 // Now, attempt to route an exact amount we have should be fine.
3443 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 15_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3444 assert_eq!(route.paths.len(), 1);
3445 let path = route.paths.last().unwrap();
3446 assert_eq!(path.len(), 2);
3447 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3448 assert_eq!(path.last().unwrap().fee_msat, 15_000);
3451 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
3452 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3453 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3454 short_channel_id: 333,
3457 cltv_expiry_delta: 0,
3458 htlc_minimum_msat: 0,
3459 htlc_maximum_msat: 10_000,
3461 fee_proportional_millionths: 0,
3462 excess_data: Vec::new()
3466 // Attempt to route more than available results in a failure.
3467 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3468 &our_id, &payment_params, &network_graph.read_only(), None, 10_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3469 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3470 } else { panic!(); }
3474 // Now, attempt to route an exact amount we have should be fine.
3475 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 10_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3476 assert_eq!(route.paths.len(), 1);
3477 let path = route.paths.last().unwrap();
3478 assert_eq!(path.len(), 2);
3479 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3480 assert_eq!(path.last().unwrap().fee_msat, 10_000);
3485 fn available_liquidity_last_hop_test() {
3486 // Check that available liquidity properly limits the path even when only
3487 // one of the latter hops is limited.
3488 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3489 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3490 let scorer = ln_test_utils::TestScorer::with_penalty(0);
3491 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3492 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3493 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(channelmanager::provided_invoice_features());
3495 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3496 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
3497 // Total capacity: 50 sats.
3499 // Disable other potential paths.
3500 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3501 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3502 short_channel_id: 2,
3505 cltv_expiry_delta: 0,
3506 htlc_minimum_msat: 0,
3507 htlc_maximum_msat: 100_000,
3509 fee_proportional_millionths: 0,
3510 excess_data: Vec::new()
3512 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3513 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3514 short_channel_id: 7,
3517 cltv_expiry_delta: 0,
3518 htlc_minimum_msat: 0,
3519 htlc_maximum_msat: 100_000,
3521 fee_proportional_millionths: 0,
3522 excess_data: Vec::new()
3527 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3528 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3529 short_channel_id: 12,
3532 cltv_expiry_delta: 0,
3533 htlc_minimum_msat: 0,
3534 htlc_maximum_msat: 100_000,
3536 fee_proportional_millionths: 0,
3537 excess_data: Vec::new()
3539 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3540 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3541 short_channel_id: 13,
3544 cltv_expiry_delta: 0,
3545 htlc_minimum_msat: 0,
3546 htlc_maximum_msat: 100_000,
3548 fee_proportional_millionths: 0,
3549 excess_data: Vec::new()
3552 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3553 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3554 short_channel_id: 6,
3557 cltv_expiry_delta: 0,
3558 htlc_minimum_msat: 0,
3559 htlc_maximum_msat: 50_000,
3561 fee_proportional_millionths: 0,
3562 excess_data: Vec::new()
3564 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3565 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3566 short_channel_id: 11,
3569 cltv_expiry_delta: 0,
3570 htlc_minimum_msat: 0,
3571 htlc_maximum_msat: 100_000,
3573 fee_proportional_millionths: 0,
3574 excess_data: Vec::new()
3577 // Attempt to route more than available results in a failure.
3578 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3579 &our_id, &payment_params, &network_graph.read_only(), None, 60_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3580 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3581 } else { panic!(); }
3585 // Now, attempt to route 49 sats (just a bit below the capacity).
3586 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 49_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3587 assert_eq!(route.paths.len(), 1);
3588 let mut total_amount_paid_msat = 0;
3589 for path in &route.paths {
3590 assert_eq!(path.len(), 4);
3591 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3592 total_amount_paid_msat += path.last().unwrap().fee_msat;
3594 assert_eq!(total_amount_paid_msat, 49_000);
3598 // Attempt to route an exact amount is also fine
3599 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3600 assert_eq!(route.paths.len(), 1);
3601 let mut total_amount_paid_msat = 0;
3602 for path in &route.paths {
3603 assert_eq!(path.len(), 4);
3604 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3605 total_amount_paid_msat += path.last().unwrap().fee_msat;
3607 assert_eq!(total_amount_paid_msat, 50_000);
3612 fn ignore_fee_first_hop_test() {
3613 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3614 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3615 let scorer = ln_test_utils::TestScorer::with_penalty(0);
3616 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3617 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3618 let payment_params = PaymentParameters::from_node_id(nodes[2]);
3620 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3621 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3622 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3623 short_channel_id: 1,
3626 cltv_expiry_delta: 0,
3627 htlc_minimum_msat: 0,
3628 htlc_maximum_msat: 100_000,
3629 fee_base_msat: 1_000_000,
3630 fee_proportional_millionths: 0,
3631 excess_data: Vec::new()
3633 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3634 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3635 short_channel_id: 3,
3638 cltv_expiry_delta: 0,
3639 htlc_minimum_msat: 0,
3640 htlc_maximum_msat: 50_000,
3642 fee_proportional_millionths: 0,
3643 excess_data: Vec::new()
3647 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3648 assert_eq!(route.paths.len(), 1);
3649 let mut total_amount_paid_msat = 0;
3650 for path in &route.paths {
3651 assert_eq!(path.len(), 2);
3652 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3653 total_amount_paid_msat += path.last().unwrap().fee_msat;
3655 assert_eq!(total_amount_paid_msat, 50_000);
3660 fn simple_mpp_route_test() {
3661 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3662 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3663 let scorer = ln_test_utils::TestScorer::with_penalty(0);
3664 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3665 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3666 let payment_params = PaymentParameters::from_node_id(nodes[2])
3667 .with_features(channelmanager::provided_invoice_features());
3669 // We need a route consisting of 3 paths:
3670 // From our node to node2 via node0, node7, node1 (three paths one hop each).
3671 // To achieve this, the amount being transferred should be around
3672 // the total capacity of these 3 paths.
3674 // First, we set limits on these (previously unlimited) channels.
3675 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
3677 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3678 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3679 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3680 short_channel_id: 1,
3683 cltv_expiry_delta: 0,
3684 htlc_minimum_msat: 0,
3685 htlc_maximum_msat: 100_000,
3687 fee_proportional_millionths: 0,
3688 excess_data: Vec::new()
3690 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3691 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3692 short_channel_id: 3,
3695 cltv_expiry_delta: 0,
3696 htlc_minimum_msat: 0,
3697 htlc_maximum_msat: 50_000,
3699 fee_proportional_millionths: 0,
3700 excess_data: Vec::new()
3703 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
3704 // (total limit 60).
3705 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3706 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3707 short_channel_id: 12,
3710 cltv_expiry_delta: 0,
3711 htlc_minimum_msat: 0,
3712 htlc_maximum_msat: 60_000,
3714 fee_proportional_millionths: 0,
3715 excess_data: Vec::new()
3717 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3718 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3719 short_channel_id: 13,
3722 cltv_expiry_delta: 0,
3723 htlc_minimum_msat: 0,
3724 htlc_maximum_msat: 60_000,
3726 fee_proportional_millionths: 0,
3727 excess_data: Vec::new()
3730 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
3731 // (total capacity 180 sats).
3732 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3733 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3734 short_channel_id: 2,
3737 cltv_expiry_delta: 0,
3738 htlc_minimum_msat: 0,
3739 htlc_maximum_msat: 200_000,
3741 fee_proportional_millionths: 0,
3742 excess_data: Vec::new()
3744 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3745 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3746 short_channel_id: 4,
3749 cltv_expiry_delta: 0,
3750 htlc_minimum_msat: 0,
3751 htlc_maximum_msat: 180_000,
3753 fee_proportional_millionths: 0,
3754 excess_data: Vec::new()
3758 // Attempt to route more than available results in a failure.
3759 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3760 &our_id, &payment_params, &network_graph.read_only(), None, 300_000, 42,
3761 Arc::clone(&logger), &scorer, &random_seed_bytes) {
3762 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3763 } else { panic!(); }
3767 // Attempt to route while setting max_path_count to 0 results in a failure.
3768 let zero_payment_params = payment_params.clone().with_max_path_count(0);
3769 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3770 &our_id, &zero_payment_params, &network_graph.read_only(), None, 100, 42,
3771 Arc::clone(&logger), &scorer, &random_seed_bytes) {
3772 assert_eq!(err, "Can't find a route with no paths allowed.");
3773 } else { panic!(); }
3777 // Attempt to route while setting max_path_count to 3 results in a failure.
3778 // This is the case because the minimal_value_contribution_msat would require each path
3779 // to account for 1/3 of the total value, which is violated by 2 out of 3 paths.
3780 let fail_payment_params = payment_params.clone().with_max_path_count(3);
3781 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3782 &our_id, &fail_payment_params, &network_graph.read_only(), None, 250_000, 42,
3783 Arc::clone(&logger), &scorer, &random_seed_bytes) {
3784 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3785 } else { panic!(); }
3789 // Now, attempt to route 250 sats (just a bit below the capacity).
3790 // Our algorithm should provide us with these 3 paths.
3791 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None,
3792 250_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3793 assert_eq!(route.paths.len(), 3);
3794 let mut total_amount_paid_msat = 0;
3795 for path in &route.paths {
3796 assert_eq!(path.len(), 2);
3797 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3798 total_amount_paid_msat += path.last().unwrap().fee_msat;
3800 assert_eq!(total_amount_paid_msat, 250_000);
3804 // Attempt to route an exact amount is also fine
3805 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None,
3806 290_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3807 assert_eq!(route.paths.len(), 3);
3808 let mut total_amount_paid_msat = 0;
3809 for path in &route.paths {
3810 assert_eq!(path.len(), 2);
3811 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3812 total_amount_paid_msat += path.last().unwrap().fee_msat;
3814 assert_eq!(total_amount_paid_msat, 290_000);
3819 fn long_mpp_route_test() {
3820 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3821 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3822 let scorer = ln_test_utils::TestScorer::with_penalty(0);
3823 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3824 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3825 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(channelmanager::provided_invoice_features());
3827 // We need a route consisting of 3 paths:
3828 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3829 // Note that these paths overlap (channels 5, 12, 13).
3830 // We will route 300 sats.
3831 // Each path will have 100 sats capacity, those channels which
3832 // are used twice will have 200 sats capacity.
3834 // Disable other potential paths.
3835 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3836 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3837 short_channel_id: 2,
3840 cltv_expiry_delta: 0,
3841 htlc_minimum_msat: 0,
3842 htlc_maximum_msat: 100_000,
3844 fee_proportional_millionths: 0,
3845 excess_data: Vec::new()
3847 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3848 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3849 short_channel_id: 7,
3852 cltv_expiry_delta: 0,
3853 htlc_minimum_msat: 0,
3854 htlc_maximum_msat: 100_000,
3856 fee_proportional_millionths: 0,
3857 excess_data: Vec::new()
3860 // Path via {node0, node2} is channels {1, 3, 5}.
3861 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3862 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3863 short_channel_id: 1,
3866 cltv_expiry_delta: 0,
3867 htlc_minimum_msat: 0,
3868 htlc_maximum_msat: 100_000,
3870 fee_proportional_millionths: 0,
3871 excess_data: Vec::new()
3873 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3874 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3875 short_channel_id: 3,
3878 cltv_expiry_delta: 0,
3879 htlc_minimum_msat: 0,
3880 htlc_maximum_msat: 100_000,
3882 fee_proportional_millionths: 0,
3883 excess_data: Vec::new()
3886 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3887 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3888 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3889 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3890 short_channel_id: 5,
3893 cltv_expiry_delta: 0,
3894 htlc_minimum_msat: 0,
3895 htlc_maximum_msat: 200_000,
3897 fee_proportional_millionths: 0,
3898 excess_data: Vec::new()
3901 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3902 // Add 100 sats to the capacities of {12, 13}, because these channels
3903 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3904 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3905 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3906 short_channel_id: 12,
3909 cltv_expiry_delta: 0,
3910 htlc_minimum_msat: 0,
3911 htlc_maximum_msat: 200_000,
3913 fee_proportional_millionths: 0,
3914 excess_data: Vec::new()
3916 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3917 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3918 short_channel_id: 13,
3921 cltv_expiry_delta: 0,
3922 htlc_minimum_msat: 0,
3923 htlc_maximum_msat: 200_000,
3925 fee_proportional_millionths: 0,
3926 excess_data: Vec::new()
3929 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3930 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3931 short_channel_id: 6,
3934 cltv_expiry_delta: 0,
3935 htlc_minimum_msat: 0,
3936 htlc_maximum_msat: 100_000,
3938 fee_proportional_millionths: 0,
3939 excess_data: Vec::new()
3941 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3942 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3943 short_channel_id: 11,
3946 cltv_expiry_delta: 0,
3947 htlc_minimum_msat: 0,
3948 htlc_maximum_msat: 100_000,
3950 fee_proportional_millionths: 0,
3951 excess_data: Vec::new()
3954 // Path via {node7, node2} is channels {12, 13, 5}.
3955 // We already limited them to 200 sats (they are used twice for 100 sats).
3956 // Nothing to do here.
3959 // Attempt to route more than available results in a failure.
3960 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3961 &our_id, &payment_params, &network_graph.read_only(), None, 350_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3962 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3963 } else { panic!(); }
3967 // Now, attempt to route 300 sats (exact amount we can route).
3968 // Our algorithm should provide us with these 3 paths, 100 sats each.
3969 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 300_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3970 assert_eq!(route.paths.len(), 3);
3972 let mut total_amount_paid_msat = 0;
3973 for path in &route.paths {
3974 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3975 total_amount_paid_msat += path.last().unwrap().fee_msat;
3977 assert_eq!(total_amount_paid_msat, 300_000);
3983 fn mpp_cheaper_route_test() {
3984 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3985 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3986 let scorer = ln_test_utils::TestScorer::with_penalty(0);
3987 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3988 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3989 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(channelmanager::provided_invoice_features());
3991 // This test checks that if we have two cheaper paths and one more expensive path,
3992 // so that liquidity-wise any 2 of 3 combination is sufficient,
3993 // two cheaper paths will be taken.
3994 // These paths have equal available liquidity.
3996 // We need a combination of 3 paths:
3997 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3998 // Note that these paths overlap (channels 5, 12, 13).
3999 // Each path will have 100 sats capacity, those channels which
4000 // are used twice will have 200 sats capacity.
4002 // Disable other potential paths.
4003 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4004 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4005 short_channel_id: 2,
4008 cltv_expiry_delta: 0,
4009 htlc_minimum_msat: 0,
4010 htlc_maximum_msat: 100_000,
4012 fee_proportional_millionths: 0,
4013 excess_data: Vec::new()
4015 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4016 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4017 short_channel_id: 7,
4020 cltv_expiry_delta: 0,
4021 htlc_minimum_msat: 0,
4022 htlc_maximum_msat: 100_000,
4024 fee_proportional_millionths: 0,
4025 excess_data: Vec::new()
4028 // Path via {node0, node2} is channels {1, 3, 5}.
4029 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4030 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4031 short_channel_id: 1,
4034 cltv_expiry_delta: 0,
4035 htlc_minimum_msat: 0,
4036 htlc_maximum_msat: 100_000,
4038 fee_proportional_millionths: 0,
4039 excess_data: Vec::new()
4041 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4042 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4043 short_channel_id: 3,
4046 cltv_expiry_delta: 0,
4047 htlc_minimum_msat: 0,
4048 htlc_maximum_msat: 100_000,
4050 fee_proportional_millionths: 0,
4051 excess_data: Vec::new()
4054 // Capacity of 200 sats because this channel will be used by 3rd path as well.
4055 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4056 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4057 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4058 short_channel_id: 5,
4061 cltv_expiry_delta: 0,
4062 htlc_minimum_msat: 0,
4063 htlc_maximum_msat: 200_000,
4065 fee_proportional_millionths: 0,
4066 excess_data: Vec::new()
4069 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4070 // Add 100 sats to the capacities of {12, 13}, because these channels
4071 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
4072 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4073 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4074 short_channel_id: 12,
4077 cltv_expiry_delta: 0,
4078 htlc_minimum_msat: 0,
4079 htlc_maximum_msat: 200_000,
4081 fee_proportional_millionths: 0,
4082 excess_data: Vec::new()
4084 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4085 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4086 short_channel_id: 13,
4089 cltv_expiry_delta: 0,
4090 htlc_minimum_msat: 0,
4091 htlc_maximum_msat: 200_000,
4093 fee_proportional_millionths: 0,
4094 excess_data: Vec::new()
4097 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4098 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4099 short_channel_id: 6,
4102 cltv_expiry_delta: 0,
4103 htlc_minimum_msat: 0,
4104 htlc_maximum_msat: 100_000,
4105 fee_base_msat: 1_000,
4106 fee_proportional_millionths: 0,
4107 excess_data: Vec::new()
4109 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4110 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4111 short_channel_id: 11,
4114 cltv_expiry_delta: 0,
4115 htlc_minimum_msat: 0,
4116 htlc_maximum_msat: 100_000,
4118 fee_proportional_millionths: 0,
4119 excess_data: Vec::new()
4122 // Path via {node7, node2} is channels {12, 13, 5}.
4123 // We already limited them to 200 sats (they are used twice for 100 sats).
4124 // Nothing to do here.
4127 // Now, attempt to route 180 sats.
4128 // Our algorithm should provide us with these 2 paths.
4129 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 180_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4130 assert_eq!(route.paths.len(), 2);
4132 let mut total_value_transferred_msat = 0;
4133 let mut total_paid_msat = 0;
4134 for path in &route.paths {
4135 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
4136 total_value_transferred_msat += path.last().unwrap().fee_msat;
4138 total_paid_msat += hop.fee_msat;
4141 // If we paid fee, this would be higher.
4142 assert_eq!(total_value_transferred_msat, 180_000);
4143 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
4144 assert_eq!(total_fees_paid, 0);
4149 fn fees_on_mpp_route_test() {
4150 // This test makes sure that MPP algorithm properly takes into account
4151 // fees charged on the channels, by making the fees impactful:
4152 // if the fee is not properly accounted for, the behavior is different.
4153 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4154 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4155 let scorer = ln_test_utils::TestScorer::with_penalty(0);
4156 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4157 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4158 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(channelmanager::provided_invoice_features());
4160 // We need a route consisting of 2 paths:
4161 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
4162 // We will route 200 sats, Each path will have 100 sats capacity.
4164 // This test is not particularly stable: e.g.,
4165 // there's a way to route via {node0, node2, node4}.
4166 // It works while pathfinding is deterministic, but can be broken otherwise.
4167 // It's fine to ignore this concern for now.
4169 // Disable other potential paths.
4170 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4171 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4172 short_channel_id: 2,
4175 cltv_expiry_delta: 0,
4176 htlc_minimum_msat: 0,
4177 htlc_maximum_msat: 100_000,
4179 fee_proportional_millionths: 0,
4180 excess_data: Vec::new()
4183 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4184 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4185 short_channel_id: 7,
4188 cltv_expiry_delta: 0,
4189 htlc_minimum_msat: 0,
4190 htlc_maximum_msat: 100_000,
4192 fee_proportional_millionths: 0,
4193 excess_data: Vec::new()
4196 // Path via {node0, node2} is channels {1, 3, 5}.
4197 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4198 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4199 short_channel_id: 1,
4202 cltv_expiry_delta: 0,
4203 htlc_minimum_msat: 0,
4204 htlc_maximum_msat: 100_000,
4206 fee_proportional_millionths: 0,
4207 excess_data: Vec::new()
4209 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4210 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4211 short_channel_id: 3,
4214 cltv_expiry_delta: 0,
4215 htlc_minimum_msat: 0,
4216 htlc_maximum_msat: 100_000,
4218 fee_proportional_millionths: 0,
4219 excess_data: Vec::new()
4222 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4223 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4224 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4225 short_channel_id: 5,
4228 cltv_expiry_delta: 0,
4229 htlc_minimum_msat: 0,
4230 htlc_maximum_msat: 100_000,
4232 fee_proportional_millionths: 0,
4233 excess_data: Vec::new()
4236 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4237 // All channels should be 100 sats capacity. But for the fee experiment,
4238 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
4239 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
4240 // 100 sats (and pay 150 sats in fees for the use of channel 6),
4241 // so no matter how large are other channels,
4242 // the whole path will be limited by 100 sats with just these 2 conditions:
4243 // - channel 12 capacity is 250 sats
4244 // - fee for channel 6 is 150 sats
4245 // Let's test this by enforcing these 2 conditions and removing other limits.
4246 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4247 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4248 short_channel_id: 12,
4251 cltv_expiry_delta: 0,
4252 htlc_minimum_msat: 0,
4253 htlc_maximum_msat: 250_000,
4255 fee_proportional_millionths: 0,
4256 excess_data: Vec::new()
4258 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4259 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4260 short_channel_id: 13,
4263 cltv_expiry_delta: 0,
4264 htlc_minimum_msat: 0,
4265 htlc_maximum_msat: MAX_VALUE_MSAT,
4267 fee_proportional_millionths: 0,
4268 excess_data: Vec::new()
4271 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4272 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4273 short_channel_id: 6,
4276 cltv_expiry_delta: 0,
4277 htlc_minimum_msat: 0,
4278 htlc_maximum_msat: MAX_VALUE_MSAT,
4279 fee_base_msat: 150_000,
4280 fee_proportional_millionths: 0,
4281 excess_data: Vec::new()
4283 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4284 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4285 short_channel_id: 11,
4288 cltv_expiry_delta: 0,
4289 htlc_minimum_msat: 0,
4290 htlc_maximum_msat: MAX_VALUE_MSAT,
4292 fee_proportional_millionths: 0,
4293 excess_data: Vec::new()
4297 // Attempt to route more than available results in a failure.
4298 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4299 &our_id, &payment_params, &network_graph.read_only(), None, 210_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
4300 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4301 } else { panic!(); }
4305 // Now, attempt to route 200 sats (exact amount we can route).
4306 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 200_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4307 assert_eq!(route.paths.len(), 2);
4309 let mut total_amount_paid_msat = 0;
4310 for path in &route.paths {
4311 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
4312 total_amount_paid_msat += path.last().unwrap().fee_msat;
4314 assert_eq!(total_amount_paid_msat, 200_000);
4315 assert_eq!(route.get_total_fees(), 150_000);
4320 fn mpp_with_last_hops() {
4321 // Previously, if we tried to send an MPP payment to a destination which was only reachable
4322 // via a single last-hop route hint, we'd fail to route if we first collected routes
4323 // totaling close but not quite enough to fund the full payment.
4325 // This was because we considered last-hop hints to have exactly the sought payment amount
4326 // instead of the amount we were trying to collect, needlessly limiting our path searching
4327 // at the very first hop.
4329 // Specifically, this interacted with our "all paths must fund at least 5% of total target"
4330 // criterion to cause us to refuse all routes at the last hop hint which would be considered
4331 // to only have the remaining to-collect amount in available liquidity.
4333 // This bug appeared in production in some specific channel configurations.
4334 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4335 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4336 let scorer = ln_test_utils::TestScorer::with_penalty(0);
4337 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4338 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4339 let payment_params = PaymentParameters::from_node_id(PublicKey::from_slice(&[02; 33]).unwrap()).with_features(channelmanager::provided_invoice_features())
4340 .with_route_hints(vec![RouteHint(vec![RouteHintHop {
4341 src_node_id: nodes[2],
4342 short_channel_id: 42,
4343 fees: RoutingFees { base_msat: 0, proportional_millionths: 0 },
4344 cltv_expiry_delta: 42,
4345 htlc_minimum_msat: None,
4346 htlc_maximum_msat: None,
4347 }])]).with_max_channel_saturation_power_of_half(0);
4349 // Keep only two paths from us to nodes[2], both with a 99sat HTLC maximum, with one with
4350 // no fee and one with a 1msat fee. Previously, trying to route 100 sats to nodes[2] here
4351 // would first use the no-fee route and then fail to find a path along the second route as
4352 // we think we can only send up to 1 additional sat over the last-hop but refuse to as its
4353 // under 5% of our payment amount.
4354 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4355 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4356 short_channel_id: 1,
4359 cltv_expiry_delta: (5 << 4) | 5,
4360 htlc_minimum_msat: 0,
4361 htlc_maximum_msat: 99_000,
4362 fee_base_msat: u32::max_value(),
4363 fee_proportional_millionths: u32::max_value(),
4364 excess_data: Vec::new()
4366 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4367 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4368 short_channel_id: 2,
4371 cltv_expiry_delta: (5 << 4) | 3,
4372 htlc_minimum_msat: 0,
4373 htlc_maximum_msat: 99_000,
4374 fee_base_msat: u32::max_value(),
4375 fee_proportional_millionths: u32::max_value(),
4376 excess_data: Vec::new()
4378 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4379 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4380 short_channel_id: 4,
4383 cltv_expiry_delta: (4 << 4) | 1,
4384 htlc_minimum_msat: 0,
4385 htlc_maximum_msat: MAX_VALUE_MSAT,
4387 fee_proportional_millionths: 0,
4388 excess_data: Vec::new()
4390 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4391 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4392 short_channel_id: 13,
4394 flags: 0|2, // Channel disabled
4395 cltv_expiry_delta: (13 << 4) | 1,
4396 htlc_minimum_msat: 0,
4397 htlc_maximum_msat: MAX_VALUE_MSAT,
4399 fee_proportional_millionths: 2000000,
4400 excess_data: Vec::new()
4403 // Get a route for 100 sats and check that we found the MPP route no problem and didn't
4405 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();
4406 assert_eq!(route.paths.len(), 2);
4407 route.paths.sort_by_key(|path| path[0].short_channel_id);
4408 // Paths are manually ordered ordered by SCID, so:
4409 // * the first is channel 1 (0 fee, but 99 sat maximum) -> channel 3 -> channel 42
4410 // * the second is channel 2 (1 msat fee) -> channel 4 -> channel 42
4411 assert_eq!(route.paths[0][0].short_channel_id, 1);
4412 assert_eq!(route.paths[0][0].fee_msat, 0);
4413 assert_eq!(route.paths[0][2].fee_msat, 99_000);
4414 assert_eq!(route.paths[1][0].short_channel_id, 2);
4415 assert_eq!(route.paths[1][0].fee_msat, 1);
4416 assert_eq!(route.paths[1][2].fee_msat, 1_000);
4417 assert_eq!(route.get_total_fees(), 1);
4418 assert_eq!(route.get_total_amount(), 100_000);
4422 fn drop_lowest_channel_mpp_route_test() {
4423 // This test checks that low-capacity channel is dropped when after
4424 // path finding we realize that we found more capacity than we need.
4425 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4426 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4427 let scorer = ln_test_utils::TestScorer::with_penalty(0);
4428 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4429 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4430 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(channelmanager::provided_invoice_features())
4431 .with_max_channel_saturation_power_of_half(0);
4433 // We need a route consisting of 3 paths:
4434 // From our node to node2 via node0, node7, node1 (three paths one hop each).
4436 // The first and the second paths should be sufficient, but the third should be
4437 // cheaper, so that we select it but drop later.
4439 // First, we set limits on these (previously unlimited) channels.
4440 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
4442 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
4443 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4444 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4445 short_channel_id: 1,
4448 cltv_expiry_delta: 0,
4449 htlc_minimum_msat: 0,
4450 htlc_maximum_msat: 100_000,
4452 fee_proportional_millionths: 0,
4453 excess_data: Vec::new()
4455 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4456 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4457 short_channel_id: 3,
4460 cltv_expiry_delta: 0,
4461 htlc_minimum_msat: 0,
4462 htlc_maximum_msat: 50_000,
4464 fee_proportional_millionths: 0,
4465 excess_data: Vec::new()
4468 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
4469 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4470 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4471 short_channel_id: 12,
4474 cltv_expiry_delta: 0,
4475 htlc_minimum_msat: 0,
4476 htlc_maximum_msat: 60_000,
4478 fee_proportional_millionths: 0,
4479 excess_data: Vec::new()
4481 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4482 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4483 short_channel_id: 13,
4486 cltv_expiry_delta: 0,
4487 htlc_minimum_msat: 0,
4488 htlc_maximum_msat: 60_000,
4490 fee_proportional_millionths: 0,
4491 excess_data: Vec::new()
4494 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
4495 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4496 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4497 short_channel_id: 2,
4500 cltv_expiry_delta: 0,
4501 htlc_minimum_msat: 0,
4502 htlc_maximum_msat: 20_000,
4504 fee_proportional_millionths: 0,
4505 excess_data: Vec::new()
4507 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4508 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4509 short_channel_id: 4,
4512 cltv_expiry_delta: 0,
4513 htlc_minimum_msat: 0,
4514 htlc_maximum_msat: 20_000,
4516 fee_proportional_millionths: 0,
4517 excess_data: Vec::new()
4521 // Attempt to route more than available results in a failure.
4522 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4523 &our_id, &payment_params, &network_graph.read_only(), None, 150_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
4524 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4525 } else { panic!(); }
4529 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
4530 // Our algorithm should provide us with these 3 paths.
4531 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 125_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4532 assert_eq!(route.paths.len(), 3);
4533 let mut total_amount_paid_msat = 0;
4534 for path in &route.paths {
4535 assert_eq!(path.len(), 2);
4536 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4537 total_amount_paid_msat += path.last().unwrap().fee_msat;
4539 assert_eq!(total_amount_paid_msat, 125_000);
4543 // Attempt to route without the last small cheap channel
4544 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4545 assert_eq!(route.paths.len(), 2);
4546 let mut total_amount_paid_msat = 0;
4547 for path in &route.paths {
4548 assert_eq!(path.len(), 2);
4549 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4550 total_amount_paid_msat += path.last().unwrap().fee_msat;
4552 assert_eq!(total_amount_paid_msat, 90_000);
4557 fn min_criteria_consistency() {
4558 // Test that we don't use an inconsistent metric between updating and walking nodes during
4559 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
4560 // was updated with a different criterion from the heap sorting, resulting in loops in
4561 // calculated paths. We test for that specific case here.
4563 // We construct a network that looks like this:
4565 // node2 -1(3)2- node3
4569 // node1 -1(5)2- node4 -1(1)2- node6
4575 // We create a loop on the side of our real path - our destination is node 6, with a
4576 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
4577 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
4578 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
4579 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
4580 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
4581 // "previous hop" being set to node 3, creating a loop in the path.
4582 let secp_ctx = Secp256k1::new();
4583 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
4584 let logger = Arc::new(ln_test_utils::TestLogger::new());
4585 let network = Arc::new(NetworkGraph::new(genesis_hash, Arc::clone(&logger)));
4586 let gossip_sync = P2PGossipSync::new(Arc::clone(&network), None, Arc::clone(&logger));
4587 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4588 let scorer = ln_test_utils::TestScorer::with_penalty(0);
4589 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4590 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4591 let payment_params = PaymentParameters::from_node_id(nodes[6]);
4593 add_channel(&gossip_sync, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
4594 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4595 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4596 short_channel_id: 6,
4599 cltv_expiry_delta: (6 << 4) | 0,
4600 htlc_minimum_msat: 0,
4601 htlc_maximum_msat: MAX_VALUE_MSAT,
4603 fee_proportional_millionths: 0,
4604 excess_data: Vec::new()
4606 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
4608 add_channel(&gossip_sync, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4609 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4610 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4611 short_channel_id: 5,
4614 cltv_expiry_delta: (5 << 4) | 0,
4615 htlc_minimum_msat: 0,
4616 htlc_maximum_msat: MAX_VALUE_MSAT,
4618 fee_proportional_millionths: 0,
4619 excess_data: Vec::new()
4621 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
4623 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
4624 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4625 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4626 short_channel_id: 4,
4629 cltv_expiry_delta: (4 << 4) | 0,
4630 htlc_minimum_msat: 0,
4631 htlc_maximum_msat: MAX_VALUE_MSAT,
4633 fee_proportional_millionths: 0,
4634 excess_data: Vec::new()
4636 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
4638 add_channel(&gossip_sync, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
4639 update_channel(&gossip_sync, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
4640 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4641 short_channel_id: 3,
4644 cltv_expiry_delta: (3 << 4) | 0,
4645 htlc_minimum_msat: 0,
4646 htlc_maximum_msat: MAX_VALUE_MSAT,
4648 fee_proportional_millionths: 0,
4649 excess_data: Vec::new()
4651 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
4653 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
4654 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4655 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4656 short_channel_id: 2,
4659 cltv_expiry_delta: (2 << 4) | 0,
4660 htlc_minimum_msat: 0,
4661 htlc_maximum_msat: MAX_VALUE_MSAT,
4663 fee_proportional_millionths: 0,
4664 excess_data: Vec::new()
4667 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
4668 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4669 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4670 short_channel_id: 1,
4673 cltv_expiry_delta: (1 << 4) | 0,
4674 htlc_minimum_msat: 100,
4675 htlc_maximum_msat: MAX_VALUE_MSAT,
4677 fee_proportional_millionths: 0,
4678 excess_data: Vec::new()
4680 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
4683 // Now ensure the route flows simply over nodes 1 and 4 to 6.
4684 let route = get_route(&our_id, &payment_params, &network.read_only(), None, 10_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4685 assert_eq!(route.paths.len(), 1);
4686 assert_eq!(route.paths[0].len(), 3);
4688 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
4689 assert_eq!(route.paths[0][0].short_channel_id, 6);
4690 assert_eq!(route.paths[0][0].fee_msat, 100);
4691 assert_eq!(route.paths[0][0].cltv_expiry_delta, (5 << 4) | 0);
4692 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(1));
4693 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(6));
4695 assert_eq!(route.paths[0][1].pubkey, nodes[4]);
4696 assert_eq!(route.paths[0][1].short_channel_id, 5);
4697 assert_eq!(route.paths[0][1].fee_msat, 0);
4698 assert_eq!(route.paths[0][1].cltv_expiry_delta, (1 << 4) | 0);
4699 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(4));
4700 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(5));
4702 assert_eq!(route.paths[0][2].pubkey, nodes[6]);
4703 assert_eq!(route.paths[0][2].short_channel_id, 1);
4704 assert_eq!(route.paths[0][2].fee_msat, 10_000);
4705 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
4706 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
4707 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(1));
4713 fn exact_fee_liquidity_limit() {
4714 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
4715 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
4716 // we calculated fees on a higher value, resulting in us ignoring such paths.
4717 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4718 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
4719 let scorer = ln_test_utils::TestScorer::with_penalty(0);
4720 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4721 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4722 let payment_params = PaymentParameters::from_node_id(nodes[2]);
4724 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
4726 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4727 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4728 short_channel_id: 2,
4731 cltv_expiry_delta: 0,
4732 htlc_minimum_msat: 0,
4733 htlc_maximum_msat: 85_000,
4735 fee_proportional_millionths: 0,
4736 excess_data: Vec::new()
4739 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4740 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4741 short_channel_id: 12,
4744 cltv_expiry_delta: (4 << 4) | 1,
4745 htlc_minimum_msat: 0,
4746 htlc_maximum_msat: 270_000,
4748 fee_proportional_millionths: 1000000,
4749 excess_data: Vec::new()
4753 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
4754 // 200% fee charged channel 13 in the 1-to-2 direction.
4755 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4756 assert_eq!(route.paths.len(), 1);
4757 assert_eq!(route.paths[0].len(), 2);
4759 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
4760 assert_eq!(route.paths[0][0].short_channel_id, 12);
4761 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
4762 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
4763 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
4764 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
4766 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
4767 assert_eq!(route.paths[0][1].short_channel_id, 13);
4768 assert_eq!(route.paths[0][1].fee_msat, 90_000);
4769 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
4770 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
4771 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
4776 fn htlc_max_reduction_below_min() {
4777 // Test that if, while walking the graph, we reduce the value being sent to meet an
4778 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
4779 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
4780 // resulting in us thinking there is no possible path, even if other paths exist.
4781 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4782 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4783 let scorer = ln_test_utils::TestScorer::with_penalty(0);
4784 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4785 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4786 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(channelmanager::provided_invoice_features());
4788 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
4789 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
4790 // then try to send 90_000.
4791 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4792 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4793 short_channel_id: 2,
4796 cltv_expiry_delta: 0,
4797 htlc_minimum_msat: 0,
4798 htlc_maximum_msat: 80_000,
4800 fee_proportional_millionths: 0,
4801 excess_data: Vec::new()
4803 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4804 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4805 short_channel_id: 4,
4808 cltv_expiry_delta: (4 << 4) | 1,
4809 htlc_minimum_msat: 90_000,
4810 htlc_maximum_msat: MAX_VALUE_MSAT,
4812 fee_proportional_millionths: 0,
4813 excess_data: Vec::new()
4817 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
4818 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
4819 // expensive) channels 12-13 path.
4820 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4821 assert_eq!(route.paths.len(), 1);
4822 assert_eq!(route.paths[0].len(), 2);
4824 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
4825 assert_eq!(route.paths[0][0].short_channel_id, 12);
4826 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
4827 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
4828 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
4829 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
4831 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
4832 assert_eq!(route.paths[0][1].short_channel_id, 13);
4833 assert_eq!(route.paths[0][1].fee_msat, 90_000);
4834 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
4835 assert_eq!(route.paths[0][1].node_features.le_flags(), channelmanager::provided_invoice_features().le_flags());
4836 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
4841 fn multiple_direct_first_hops() {
4842 // Previously we'd only ever considered one first hop path per counterparty.
4843 // However, as we don't restrict users to one channel per peer, we really need to support
4844 // looking at all first hop paths.
4845 // Here we test that we do not ignore all-but-the-last first hop paths per counterparty (as
4846 // we used to do by overwriting the `first_hop_targets` hashmap entry) and that we can MPP
4847 // route over multiple channels with the same first hop.
4848 let secp_ctx = Secp256k1::new();
4849 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4850 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
4851 let logger = Arc::new(ln_test_utils::TestLogger::new());
4852 let network_graph = NetworkGraph::new(genesis_hash, Arc::clone(&logger));
4853 let scorer = ln_test_utils::TestScorer::with_penalty(0);
4854 let payment_params = PaymentParameters::from_node_id(nodes[0]).with_features(channelmanager::provided_invoice_features());
4855 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4856 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4859 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
4860 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(), 200_000),
4861 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(), 10_000),
4862 ]), 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4863 assert_eq!(route.paths.len(), 1);
4864 assert_eq!(route.paths[0].len(), 1);
4866 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
4867 assert_eq!(route.paths[0][0].short_channel_id, 3);
4868 assert_eq!(route.paths[0][0].fee_msat, 100_000);
4871 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
4872 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(), 50_000),
4873 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(), 50_000),
4874 ]), 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4875 assert_eq!(route.paths.len(), 2);
4876 assert_eq!(route.paths[0].len(), 1);
4877 assert_eq!(route.paths[1].len(), 1);
4879 assert!((route.paths[0][0].short_channel_id == 3 && route.paths[1][0].short_channel_id == 2) ||
4880 (route.paths[0][0].short_channel_id == 2 && route.paths[1][0].short_channel_id == 3));
4882 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
4883 assert_eq!(route.paths[0][0].fee_msat, 50_000);
4885 assert_eq!(route.paths[1][0].pubkey, nodes[0]);
4886 assert_eq!(route.paths[1][0].fee_msat, 50_000);
4890 // If we have a bunch of outbound channels to the same node, where most are not
4891 // sufficient to pay the full payment, but one is, we should default to just using the
4892 // one single channel that has sufficient balance, avoiding MPP.
4894 // If we have several options above the 3xpayment value threshold, we should pick the
4895 // smallest of them, avoiding further fragmenting our available outbound balance to
4897 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
4898 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(), 50_000),
4899 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(), 50_000),
4900 &get_channel_details(Some(5), nodes[0], channelmanager::provided_init_features(), 50_000),
4901 &get_channel_details(Some(6), nodes[0], channelmanager::provided_init_features(), 300_000),
4902 &get_channel_details(Some(7), nodes[0], channelmanager::provided_init_features(), 50_000),
4903 &get_channel_details(Some(8), nodes[0], channelmanager::provided_init_features(), 50_000),
4904 &get_channel_details(Some(9), nodes[0], channelmanager::provided_init_features(), 50_000),
4905 &get_channel_details(Some(4), nodes[0], channelmanager::provided_init_features(), 1_000_000),
4906 ]), 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4907 assert_eq!(route.paths.len(), 1);
4908 assert_eq!(route.paths[0].len(), 1);
4910 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
4911 assert_eq!(route.paths[0][0].short_channel_id, 6);
4912 assert_eq!(route.paths[0][0].fee_msat, 100_000);
4917 fn prefers_shorter_route_with_higher_fees() {
4918 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4919 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4920 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
4922 // Without penalizing each hop 100 msats, a longer path with lower fees is chosen.
4923 let scorer = ln_test_utils::TestScorer::with_penalty(0);
4924 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4925 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4926 let route = get_route(
4927 &our_id, &payment_params, &network_graph.read_only(), None, 100, 42,
4928 Arc::clone(&logger), &scorer, &random_seed_bytes
4930 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4932 assert_eq!(route.get_total_fees(), 100);
4933 assert_eq!(route.get_total_amount(), 100);
4934 assert_eq!(path, vec![2, 4, 6, 11, 8]);
4936 // Applying a 100 msat penalty to each hop results in taking channels 7 and 10 to nodes[6]
4937 // from nodes[2] rather than channel 6, 11, and 8, even though the longer path is cheaper.
4938 let scorer = ln_test_utils::TestScorer::with_penalty(100);
4939 let route = get_route(
4940 &our_id, &payment_params, &network_graph.read_only(), None, 100, 42,
4941 Arc::clone(&logger), &scorer, &random_seed_bytes
4943 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4945 assert_eq!(route.get_total_fees(), 300);
4946 assert_eq!(route.get_total_amount(), 100);
4947 assert_eq!(path, vec![2, 4, 7, 10]);
4950 struct BadChannelScorer {
4951 short_channel_id: u64,
4955 impl Writeable for BadChannelScorer {
4956 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
4958 impl Score for BadChannelScorer {
4959 fn channel_penalty_msat(&self, short_channel_id: u64, _: &NodeId, _: &NodeId, _: ChannelUsage) -> u64 {
4960 if short_channel_id == self.short_channel_id { u64::max_value() } else { 0 }
4963 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
4964 fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
4965 fn probe_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
4966 fn probe_successful(&mut self, _path: &[&RouteHop]) {}
4969 struct BadNodeScorer {
4974 impl Writeable for BadNodeScorer {
4975 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
4978 impl Score for BadNodeScorer {
4979 fn channel_penalty_msat(&self, _: u64, _: &NodeId, target: &NodeId, _: ChannelUsage) -> u64 {
4980 if *target == self.node_id { u64::max_value() } else { 0 }
4983 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
4984 fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
4985 fn probe_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
4986 fn probe_successful(&mut self, _path: &[&RouteHop]) {}
4990 fn avoids_routing_through_bad_channels_and_nodes() {
4991 let (secp_ctx, network, _, _, logger) = build_graph();
4992 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4993 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
4994 let network_graph = network.read_only();
4996 // A path to nodes[6] exists when no penalties are applied to any channel.
4997 let scorer = ln_test_utils::TestScorer::with_penalty(0);
4998 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4999 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5000 let route = get_route(
5001 &our_id, &payment_params, &network_graph, None, 100, 42,
5002 Arc::clone(&logger), &scorer, &random_seed_bytes
5004 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5006 assert_eq!(route.get_total_fees(), 100);
5007 assert_eq!(route.get_total_amount(), 100);
5008 assert_eq!(path, vec![2, 4, 6, 11, 8]);
5010 // A different path to nodes[6] exists if channel 6 cannot be routed over.
5011 let scorer = BadChannelScorer { short_channel_id: 6 };
5012 let route = get_route(
5013 &our_id, &payment_params, &network_graph, None, 100, 42,
5014 Arc::clone(&logger), &scorer, &random_seed_bytes
5016 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5018 assert_eq!(route.get_total_fees(), 300);
5019 assert_eq!(route.get_total_amount(), 100);
5020 assert_eq!(path, vec![2, 4, 7, 10]);
5022 // A path to nodes[6] does not exist if nodes[2] cannot be routed through.
5023 let scorer = BadNodeScorer { node_id: NodeId::from_pubkey(&nodes[2]) };
5025 &our_id, &payment_params, &network_graph, None, 100, 42,
5026 Arc::clone(&logger), &scorer, &random_seed_bytes
5028 Err(LightningError { err, .. } ) => {
5029 assert_eq!(err, "Failed to find a path to the given destination");
5031 Ok(_) => panic!("Expected error"),
5036 fn total_fees_single_path() {
5040 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5041 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5042 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5045 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5046 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5047 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5050 pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
5051 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5052 short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0
5055 payment_params: None,
5058 assert_eq!(route.get_total_fees(), 250);
5059 assert_eq!(route.get_total_amount(), 225);
5063 fn total_fees_multi_path() {
5067 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5068 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5069 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5072 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5073 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5074 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5078 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5079 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5080 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5083 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5084 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5085 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5088 payment_params: None,
5091 assert_eq!(route.get_total_fees(), 200);
5092 assert_eq!(route.get_total_amount(), 300);
5096 fn total_empty_route_no_panic() {
5097 // In an earlier version of `Route::get_total_fees` and `Route::get_total_amount`, they
5098 // would both panic if the route was completely empty. We test to ensure they return 0
5099 // here, even though its somewhat nonsensical as a route.
5100 let route = Route { paths: Vec::new(), payment_params: None };
5102 assert_eq!(route.get_total_fees(), 0);
5103 assert_eq!(route.get_total_amount(), 0);
5107 fn limits_total_cltv_delta() {
5108 let (secp_ctx, network, _, _, logger) = build_graph();
5109 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5110 let network_graph = network.read_only();
5112 let scorer = ln_test_utils::TestScorer::with_penalty(0);
5114 // Make sure that generally there is at least one route available
5115 let feasible_max_total_cltv_delta = 1008;
5116 let feasible_payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes))
5117 .with_max_total_cltv_expiry_delta(feasible_max_total_cltv_delta);
5118 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5119 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5120 let route = get_route(&our_id, &feasible_payment_params, &network_graph, None, 100, 0, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5121 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5122 assert_ne!(path.len(), 0);
5124 // But not if we exclude all paths on the basis of their accumulated CLTV delta
5125 let fail_max_total_cltv_delta = 23;
5126 let fail_payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes))
5127 .with_max_total_cltv_expiry_delta(fail_max_total_cltv_delta);
5128 match get_route(&our_id, &fail_payment_params, &network_graph, None, 100, 0, Arc::clone(&logger), &scorer, &random_seed_bytes)
5130 Err(LightningError { err, .. } ) => {
5131 assert_eq!(err, "Failed to find a path to the given destination");
5133 Ok(_) => panic!("Expected error"),
5138 fn avoids_recently_failed_paths() {
5139 // Ensure that the router always avoids all of the `previously_failed_channels` channels by
5140 // randomly inserting channels into it until we can't find a route anymore.
5141 let (secp_ctx, network, _, _, logger) = build_graph();
5142 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5143 let network_graph = network.read_only();
5145 let scorer = ln_test_utils::TestScorer::with_penalty(0);
5146 let mut payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes))
5147 .with_max_path_count(1);
5148 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5149 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5151 // We should be able to find a route initially, and then after we fail a few random
5152 // channels eventually we won't be able to any longer.
5153 assert!(get_route(&our_id, &payment_params, &network_graph, None, 100, 0, Arc::clone(&logger), &scorer, &random_seed_bytes).is_ok());
5155 if let Ok(route) = get_route(&our_id, &payment_params, &network_graph, None, 100, 0, Arc::clone(&logger), &scorer, &random_seed_bytes) {
5156 for chan in route.paths[0].iter() {
5157 assert!(!payment_params.previously_failed_channels.contains(&chan.short_channel_id));
5159 let victim = (u64::from_ne_bytes(random_seed_bytes[0..8].try_into().unwrap()) as usize)
5160 % route.paths[0].len();
5161 payment_params.previously_failed_channels.push(route.paths[0][victim].short_channel_id);
5167 fn limits_path_length() {
5168 let (secp_ctx, network, _, _, logger) = build_line_graph();
5169 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5170 let network_graph = network.read_only();
5172 let scorer = ln_test_utils::TestScorer::with_penalty(0);
5173 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5174 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5176 // First check we can actually create a long route on this graph.
5177 let feasible_payment_params = PaymentParameters::from_node_id(nodes[18]);
5178 let route = get_route(&our_id, &feasible_payment_params, &network_graph, None, 100, 0,
5179 Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5180 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5181 assert!(path.len() == MAX_PATH_LENGTH_ESTIMATE.into());
5183 // But we can't create a path surpassing the MAX_PATH_LENGTH_ESTIMATE limit.
5184 let fail_payment_params = PaymentParameters::from_node_id(nodes[19]);
5185 match get_route(&our_id, &fail_payment_params, &network_graph, None, 100, 0,
5186 Arc::clone(&logger), &scorer, &random_seed_bytes)
5188 Err(LightningError { err, .. } ) => {
5189 assert_eq!(err, "Failed to find a path to the given destination");
5191 Ok(_) => panic!("Expected error"),
5196 fn adds_and_limits_cltv_offset() {
5197 let (secp_ctx, network_graph, _, _, logger) = build_graph();
5198 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5200 let scorer = ln_test_utils::TestScorer::with_penalty(0);
5202 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
5203 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5204 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5205 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5206 assert_eq!(route.paths.len(), 1);
5208 let cltv_expiry_deltas_before = route.paths[0].iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5210 // Check whether the offset added to the last hop by default is in [1 .. DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA]
5211 let mut route_default = route.clone();
5212 add_random_cltv_offset(&mut route_default, &payment_params, &network_graph.read_only(), &random_seed_bytes);
5213 let cltv_expiry_deltas_default = route_default.paths[0].iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5214 assert_eq!(cltv_expiry_deltas_before.split_last().unwrap().1, cltv_expiry_deltas_default.split_last().unwrap().1);
5215 assert!(cltv_expiry_deltas_default.last() > cltv_expiry_deltas_before.last());
5216 assert!(cltv_expiry_deltas_default.last().unwrap() <= &DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA);
5218 // Check that no offset is added when we restrict the max_total_cltv_expiry_delta
5219 let mut route_limited = route.clone();
5220 let limited_max_total_cltv_expiry_delta = cltv_expiry_deltas_before.iter().sum();
5221 let limited_payment_params = payment_params.with_max_total_cltv_expiry_delta(limited_max_total_cltv_expiry_delta);
5222 add_random_cltv_offset(&mut route_limited, &limited_payment_params, &network_graph.read_only(), &random_seed_bytes);
5223 let cltv_expiry_deltas_limited = route_limited.paths[0].iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5224 assert_eq!(cltv_expiry_deltas_before, cltv_expiry_deltas_limited);
5228 fn adds_plausible_cltv_offset() {
5229 let (secp_ctx, network, _, _, logger) = build_graph();
5230 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5231 let network_graph = network.read_only();
5232 let network_nodes = network_graph.nodes();
5233 let network_channels = network_graph.channels();
5234 let scorer = ln_test_utils::TestScorer::with_penalty(0);
5235 let payment_params = PaymentParameters::from_node_id(nodes[3]);
5236 let keys_manager = ln_test_utils::TestKeysInterface::new(&[4u8; 32], Network::Testnet);
5237 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5239 let mut route = get_route(&our_id, &payment_params, &network_graph, None, 100, 0,
5240 Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5241 add_random_cltv_offset(&mut route, &payment_params, &network_graph, &random_seed_bytes);
5243 let mut path_plausibility = vec![];
5245 for p in route.paths {
5246 // 1. Select random observation point
5247 let mut prng = ChaCha20::new(&random_seed_bytes, &[0u8; 12]);
5248 let mut random_bytes = [0u8; ::core::mem::size_of::<usize>()];
5250 prng.process_in_place(&mut random_bytes);
5251 let random_path_index = usize::from_be_bytes(random_bytes).wrapping_rem(p.len());
5252 let observation_point = NodeId::from_pubkey(&p.get(random_path_index).unwrap().pubkey);
5254 // 2. Calculate what CLTV expiry delta we would observe there
5255 let observed_cltv_expiry_delta: u32 = p[random_path_index..].iter().map(|h| h.cltv_expiry_delta).sum();
5257 // 3. Starting from the observation point, find candidate paths
5258 let mut candidates: VecDeque<(NodeId, Vec<u32>)> = VecDeque::new();
5259 candidates.push_back((observation_point, vec![]));
5261 let mut found_plausible_candidate = false;
5263 'candidate_loop: while let Some((cur_node_id, cur_path_cltv_deltas)) = candidates.pop_front() {
5264 if let Some(remaining) = observed_cltv_expiry_delta.checked_sub(cur_path_cltv_deltas.iter().sum::<u32>()) {
5265 if remaining == 0 || remaining.wrapping_rem(40) == 0 || remaining.wrapping_rem(144) == 0 {
5266 found_plausible_candidate = true;
5267 break 'candidate_loop;
5271 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
5272 for channel_id in &cur_node.channels {
5273 if let Some(channel_info) = network_channels.get(&channel_id) {
5274 if let Some((dir_info, next_id)) = channel_info.as_directed_from(&cur_node_id) {
5275 let next_cltv_expiry_delta = dir_info.direction().cltv_expiry_delta as u32;
5276 if cur_path_cltv_deltas.iter().sum::<u32>()
5277 .saturating_add(next_cltv_expiry_delta) <= observed_cltv_expiry_delta {
5278 let mut new_path_cltv_deltas = cur_path_cltv_deltas.clone();
5279 new_path_cltv_deltas.push(next_cltv_expiry_delta);
5280 candidates.push_back((*next_id, new_path_cltv_deltas));
5288 path_plausibility.push(found_plausible_candidate);
5290 assert!(path_plausibility.iter().all(|x| *x));
5294 fn builds_correct_path_from_hops() {
5295 let (secp_ctx, network, _, _, logger) = build_graph();
5296 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5297 let network_graph = network.read_only();
5299 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5300 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5302 let payment_params = PaymentParameters::from_node_id(nodes[3]);
5303 let hops = [nodes[1], nodes[2], nodes[4], nodes[3]];
5304 let route = build_route_from_hops_internal(&our_id, &hops, &payment_params,
5305 &network_graph, 100, 0, Arc::clone(&logger), &random_seed_bytes).unwrap();
5306 let route_hop_pubkeys = route.paths[0].iter().map(|hop| hop.pubkey).collect::<Vec<_>>();
5307 assert_eq!(hops.len(), route.paths[0].len());
5308 for (idx, hop_pubkey) in hops.iter().enumerate() {
5309 assert!(*hop_pubkey == route_hop_pubkeys[idx]);
5314 fn avoids_saturating_channels() {
5315 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5316 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5318 let scorer = ProbabilisticScorer::new(Default::default(), &*network_graph, Arc::clone(&logger));
5320 // Set the fee on channel 13 to 100% to match channel 4 giving us two equivalent paths (us
5321 // -> node 7 -> node2 and us -> node 1 -> node 2) which we should balance over.
5322 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5323 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5324 short_channel_id: 4,
5327 cltv_expiry_delta: (4 << 4) | 1,
5328 htlc_minimum_msat: 0,
5329 htlc_maximum_msat: 250_000_000,
5331 fee_proportional_millionths: 0,
5332 excess_data: Vec::new()
5334 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5335 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5336 short_channel_id: 13,
5339 cltv_expiry_delta: (13 << 4) | 1,
5340 htlc_minimum_msat: 0,
5341 htlc_maximum_msat: 250_000_000,
5343 fee_proportional_millionths: 0,
5344 excess_data: Vec::new()
5347 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(channelmanager::provided_invoice_features());
5348 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5349 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5350 // 100,000 sats is less than the available liquidity on each channel, set above.
5351 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();
5352 assert_eq!(route.paths.len(), 2);
5353 assert!((route.paths[0][1].short_channel_id == 4 && route.paths[1][1].short_channel_id == 13) ||
5354 (route.paths[1][1].short_channel_id == 4 && route.paths[0][1].short_channel_id == 13));
5357 #[cfg(not(feature = "no-std"))]
5358 pub(super) fn random_init_seed() -> u64 {
5359 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
5360 use core::hash::{BuildHasher, Hasher};
5361 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
5362 println!("Using seed of {}", seed);
5365 #[cfg(not(feature = "no-std"))]
5366 use crate::util::ser::ReadableArgs;
5369 #[cfg(not(feature = "no-std"))]
5370 fn generate_routes() {
5371 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringParameters};
5373 let mut d = match super::bench_utils::get_route_file() {
5380 let logger = ln_test_utils::TestLogger::new();
5381 let graph = NetworkGraph::read(&mut d, &logger).unwrap();
5382 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5383 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5385 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
5386 let mut seed = random_init_seed() as usize;
5387 let nodes = graph.read_only().nodes().clone();
5388 'load_endpoints: for _ in 0..10 {
5390 seed = seed.overflowing_mul(0xdeadbeef).0;
5391 let src = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5392 seed = seed.overflowing_mul(0xdeadbeef).0;
5393 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5394 let payment_params = PaymentParameters::from_node_id(dst);
5395 let amt = seed as u64 % 200_000_000;
5396 let params = ProbabilisticScoringParameters::default();
5397 let scorer = ProbabilisticScorer::new(params, &graph, &logger);
5398 if get_route(src, &payment_params, &graph.read_only(), None, amt, 42, &logger, &scorer, &random_seed_bytes).is_ok() {
5399 continue 'load_endpoints;
5406 #[cfg(not(feature = "no-std"))]
5407 fn generate_routes_mpp() {
5408 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringParameters};
5410 let mut d = match super::bench_utils::get_route_file() {
5417 let logger = ln_test_utils::TestLogger::new();
5418 let graph = NetworkGraph::read(&mut d, &logger).unwrap();
5419 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5420 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5422 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
5423 let mut seed = random_init_seed() as usize;
5424 let nodes = graph.read_only().nodes().clone();
5425 'load_endpoints: for _ in 0..10 {
5427 seed = seed.overflowing_mul(0xdeadbeef).0;
5428 let src = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5429 seed = seed.overflowing_mul(0xdeadbeef).0;
5430 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5431 let payment_params = PaymentParameters::from_node_id(dst).with_features(channelmanager::provided_invoice_features());
5432 let amt = seed as u64 % 200_000_000;
5433 let params = ProbabilisticScoringParameters::default();
5434 let scorer = ProbabilisticScorer::new(params, &graph, &logger);
5435 if get_route(src, &payment_params, &graph.read_only(), None, amt, 42, &logger, &scorer, &random_seed_bytes).is_ok() {
5436 continue 'load_endpoints;
5443 fn honors_manual_penalties() {
5444 let (secp_ctx, network_graph, _, _, logger) = build_line_graph();
5445 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5447 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5448 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5450 let scorer_params = ProbabilisticScoringParameters::default();
5451 let mut scorer = ProbabilisticScorer::new(scorer_params, Arc::clone(&network_graph), Arc::clone(&logger));
5453 // First check set manual penalties are returned by the scorer.
5454 let usage = ChannelUsage {
5456 inflight_htlc_msat: 0,
5457 effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_024_000, htlc_maximum_msat: 1_000 },
5459 scorer.set_manual_penalty(&NodeId::from_pubkey(&nodes[3]), 123);
5460 scorer.set_manual_penalty(&NodeId::from_pubkey(&nodes[4]), 456);
5461 assert_eq!(scorer.channel_penalty_msat(42, &NodeId::from_pubkey(&nodes[3]), &NodeId::from_pubkey(&nodes[4]), usage), 456);
5463 // Then check we can get a normal route
5464 let payment_params = PaymentParameters::from_node_id(nodes[10]);
5465 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes);
5466 assert!(route.is_ok());
5468 // Then check that we can't get a route if we ban an intermediate node.
5469 scorer.add_banned(&NodeId::from_pubkey(&nodes[3]));
5470 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes);
5471 assert!(route.is_err());
5473 // Finally make sure we can route again, when we remove the ban.
5474 scorer.remove_banned(&NodeId::from_pubkey(&nodes[3]));
5475 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes);
5476 assert!(route.is_ok());
5480 #[cfg(all(test, not(feature = "no-std")))]
5481 pub(crate) mod bench_utils {
5483 /// Tries to open a network graph file, or panics with a URL to fetch it.
5484 pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
5485 let res = File::open("net_graph-2021-05-31.bin") // By default we're run in RL/lightning
5486 .or_else(|_| File::open("lightning/net_graph-2021-05-31.bin")) // We may be run manually in RL/
5487 .or_else(|_| { // Fall back to guessing based on the binary location
5488 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
5489 let mut path = std::env::current_exe().unwrap();
5490 path.pop(); // lightning-...
5492 path.pop(); // debug
5493 path.pop(); // target
5494 path.push("lightning");
5495 path.push("net_graph-2021-05-31.bin");
5496 eprintln!("{}", path.to_str().unwrap());
5499 .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");
5500 #[cfg(require_route_graph_test)]
5501 return Ok(res.unwrap());
5502 #[cfg(not(require_route_graph_test))]
5507 #[cfg(all(test, feature = "_bench_unstable", not(feature = "no-std")))]
5510 use bitcoin::hashes::Hash;
5511 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
5512 use crate::chain::transaction::OutPoint;
5513 use crate::chain::keysinterface::{KeysManager,KeysInterface};
5514 use crate::ln::channelmanager::{self, ChannelCounterparty, ChannelDetails};
5515 use crate::ln::features::InvoiceFeatures;
5516 use crate::routing::gossip::NetworkGraph;
5517 use crate::routing::scoring::{FixedPenaltyScorer, ProbabilisticScorer, ProbabilisticScoringParameters};
5518 use crate::util::logger::{Logger, Record};
5519 use crate::util::ser::ReadableArgs;
5523 struct DummyLogger {}
5524 impl Logger for DummyLogger {
5525 fn log(&self, _record: &Record) {}
5528 fn read_network_graph(logger: &DummyLogger) -> NetworkGraph<&DummyLogger> {
5529 let mut d = bench_utils::get_route_file().unwrap();
5530 NetworkGraph::read(&mut d, logger).unwrap()
5533 fn payer_pubkey() -> PublicKey {
5534 let secp_ctx = Secp256k1::new();
5535 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
5539 fn first_hop(node_id: PublicKey) -> ChannelDetails {
5541 channel_id: [0; 32],
5542 counterparty: ChannelCounterparty {
5543 features: channelmanager::provided_init_features(),
5545 unspendable_punishment_reserve: 0,
5546 forwarding_info: None,
5547 outbound_htlc_minimum_msat: None,
5548 outbound_htlc_maximum_msat: None,
5550 funding_txo: Some(OutPoint {
5551 txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0
5554 short_channel_id: Some(1),
5555 inbound_scid_alias: None,
5556 outbound_scid_alias: None,
5557 channel_value_satoshis: 10_000_000,
5559 balance_msat: 10_000_000,
5560 outbound_capacity_msat: 10_000_000,
5561 next_outbound_htlc_limit_msat: 10_000_000,
5562 inbound_capacity_msat: 0,
5563 unspendable_punishment_reserve: None,
5564 confirmations_required: None,
5565 force_close_spend_delay: None,
5567 is_channel_ready: true,
5570 inbound_htlc_minimum_msat: None,
5571 inbound_htlc_maximum_msat: None,
5577 fn generate_routes_with_zero_penalty_scorer(bench: &mut Bencher) {
5578 let logger = DummyLogger {};
5579 let network_graph = read_network_graph(&logger);
5580 let scorer = FixedPenaltyScorer::with_penalty(0);
5581 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::empty());
5585 fn generate_mpp_routes_with_zero_penalty_scorer(bench: &mut Bencher) {
5586 let logger = DummyLogger {};
5587 let network_graph = read_network_graph(&logger);
5588 let scorer = FixedPenaltyScorer::with_penalty(0);
5589 generate_routes(bench, &network_graph, scorer, channelmanager::provided_invoice_features());
5593 fn generate_routes_with_probabilistic_scorer(bench: &mut Bencher) {
5594 let logger = DummyLogger {};
5595 let network_graph = read_network_graph(&logger);
5596 let params = ProbabilisticScoringParameters::default();
5597 let scorer = ProbabilisticScorer::new(params, &network_graph, &logger);
5598 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::empty());
5602 fn generate_mpp_routes_with_probabilistic_scorer(bench: &mut Bencher) {
5603 let logger = DummyLogger {};
5604 let network_graph = read_network_graph(&logger);
5605 let params = ProbabilisticScoringParameters::default();
5606 let scorer = ProbabilisticScorer::new(params, &network_graph, &logger);
5607 generate_routes(bench, &network_graph, scorer, channelmanager::provided_invoice_features());
5610 fn generate_routes<S: Score>(
5611 bench: &mut Bencher, graph: &NetworkGraph<&DummyLogger>, mut scorer: S,
5612 features: InvoiceFeatures
5614 let nodes = graph.read_only().nodes().clone();
5615 let payer = payer_pubkey();
5616 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
5617 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5619 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
5620 let mut routes = Vec::new();
5621 let mut route_endpoints = Vec::new();
5622 let mut seed: usize = 0xdeadbeef;
5623 'load_endpoints: for _ in 0..150 {
5626 let src = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5628 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5629 let params = PaymentParameters::from_node_id(dst).with_features(features.clone());
5630 let first_hop = first_hop(src);
5631 let amt = seed as u64 % 1_000_000;
5632 if let Ok(route) = get_route(&payer, ¶ms, &graph.read_only(), Some(&[&first_hop]), amt, 42, &DummyLogger{}, &scorer, &random_seed_bytes) {
5634 route_endpoints.push((first_hop, params, amt));
5635 continue 'load_endpoints;
5640 // ...and seed the scorer with success and failure data...
5641 for route in routes {
5642 let amount = route.get_total_amount();
5643 if amount < 250_000 {
5644 for path in route.paths {
5645 scorer.payment_path_successful(&path.iter().collect::<Vec<_>>());
5647 } else if amount > 750_000 {
5648 for path in route.paths {
5649 let short_channel_id = path[path.len() / 2].short_channel_id;
5650 scorer.payment_path_failed(&path.iter().collect::<Vec<_>>(), short_channel_id);
5655 // Because we've changed channel scores, its possible we'll take different routes to the
5656 // selected destinations, possibly causing us to fail because, eg, the newly-selected path
5657 // requires a too-high CLTV delta.
5658 route_endpoints.retain(|(first_hop, params, amt)| {
5659 get_route(&payer, params, &graph.read_only(), Some(&[first_hop]), *amt, 42, &DummyLogger{}, &scorer, &random_seed_bytes).is_ok()
5661 route_endpoints.truncate(100);
5662 assert_eq!(route_endpoints.len(), 100);
5664 // ...then benchmark finding paths between the nodes we learned.
5667 let (first_hop, params, amt) = &route_endpoints[idx % route_endpoints.len()];
5668 assert!(get_route(&payer, params, &graph.read_only(), Some(&[first_hop]), *amt, 42, &DummyLogger{}, &scorer, &random_seed_bytes).is_ok());