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 confirmations: None,
2052 force_close_spend_delay: None,
2053 is_outbound: true, is_channel_ready: true,
2054 is_usable: true, is_public: true,
2055 inbound_htlc_minimum_msat: None,
2056 inbound_htlc_maximum_msat: None,
2062 fn simple_route_test() {
2063 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2064 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2065 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2066 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2067 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2068 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2070 // Simple route to 2 via 1
2072 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) {
2073 assert_eq!(err, "Cannot send a payment of 0 msat");
2074 } else { panic!(); }
2076 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2077 assert_eq!(route.paths[0].len(), 2);
2079 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2080 assert_eq!(route.paths[0][0].short_channel_id, 2);
2081 assert_eq!(route.paths[0][0].fee_msat, 100);
2082 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2083 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2084 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2086 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2087 assert_eq!(route.paths[0][1].short_channel_id, 4);
2088 assert_eq!(route.paths[0][1].fee_msat, 100);
2089 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2090 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2091 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2095 fn invalid_first_hop_test() {
2096 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2097 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2098 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2099 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2100 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2101 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2103 // Simple route to 2 via 1
2105 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
2107 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) =
2108 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) {
2109 assert_eq!(err, "First hop cannot have our_node_pubkey as a destination.");
2110 } else { panic!(); }
2112 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2113 assert_eq!(route.paths[0].len(), 2);
2117 fn htlc_minimum_test() {
2118 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2119 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2120 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2121 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2122 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2123 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2125 // Simple route to 2 via 1
2127 // Disable other paths
2128 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2129 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2130 short_channel_id: 12,
2132 flags: 2, // to disable
2133 cltv_expiry_delta: 0,
2134 htlc_minimum_msat: 0,
2135 htlc_maximum_msat: MAX_VALUE_MSAT,
2137 fee_proportional_millionths: 0,
2138 excess_data: Vec::new()
2140 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2141 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2142 short_channel_id: 3,
2144 flags: 2, // to disable
2145 cltv_expiry_delta: 0,
2146 htlc_minimum_msat: 0,
2147 htlc_maximum_msat: MAX_VALUE_MSAT,
2149 fee_proportional_millionths: 0,
2150 excess_data: Vec::new()
2152 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2153 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2154 short_channel_id: 13,
2156 flags: 2, // to disable
2157 cltv_expiry_delta: 0,
2158 htlc_minimum_msat: 0,
2159 htlc_maximum_msat: MAX_VALUE_MSAT,
2161 fee_proportional_millionths: 0,
2162 excess_data: Vec::new()
2164 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2165 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2166 short_channel_id: 6,
2168 flags: 2, // to disable
2169 cltv_expiry_delta: 0,
2170 htlc_minimum_msat: 0,
2171 htlc_maximum_msat: MAX_VALUE_MSAT,
2173 fee_proportional_millionths: 0,
2174 excess_data: Vec::new()
2176 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2177 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2178 short_channel_id: 7,
2180 flags: 2, // to disable
2181 cltv_expiry_delta: 0,
2182 htlc_minimum_msat: 0,
2183 htlc_maximum_msat: MAX_VALUE_MSAT,
2185 fee_proportional_millionths: 0,
2186 excess_data: Vec::new()
2189 // Check against amount_to_transfer_over_msat.
2190 // Set minimal HTLC of 200_000_000 msat.
2191 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2192 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2193 short_channel_id: 2,
2196 cltv_expiry_delta: 0,
2197 htlc_minimum_msat: 200_000_000,
2198 htlc_maximum_msat: MAX_VALUE_MSAT,
2200 fee_proportional_millionths: 0,
2201 excess_data: Vec::new()
2204 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
2206 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2207 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2208 short_channel_id: 4,
2211 cltv_expiry_delta: 0,
2212 htlc_minimum_msat: 0,
2213 htlc_maximum_msat: 199_999_999,
2215 fee_proportional_millionths: 0,
2216 excess_data: Vec::new()
2219 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
2220 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) {
2221 assert_eq!(err, "Failed to find a path to the given destination");
2222 } else { panic!(); }
2224 // Lift the restriction on the first hop.
2225 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2226 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2227 short_channel_id: 2,
2230 cltv_expiry_delta: 0,
2231 htlc_minimum_msat: 0,
2232 htlc_maximum_msat: MAX_VALUE_MSAT,
2234 fee_proportional_millionths: 0,
2235 excess_data: Vec::new()
2238 // A payment above the minimum should pass
2239 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();
2240 assert_eq!(route.paths[0].len(), 2);
2244 fn htlc_minimum_overpay_test() {
2245 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2246 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2247 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(channelmanager::provided_invoice_features());
2248 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2249 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2250 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2252 // A route to node#2 via two paths.
2253 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
2254 // Thus, they can't send 60 without overpaying.
2255 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2256 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2257 short_channel_id: 2,
2260 cltv_expiry_delta: 0,
2261 htlc_minimum_msat: 35_000,
2262 htlc_maximum_msat: 40_000,
2264 fee_proportional_millionths: 0,
2265 excess_data: Vec::new()
2267 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2268 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2269 short_channel_id: 12,
2272 cltv_expiry_delta: 0,
2273 htlc_minimum_msat: 35_000,
2274 htlc_maximum_msat: 40_000,
2276 fee_proportional_millionths: 0,
2277 excess_data: Vec::new()
2281 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2282 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2283 short_channel_id: 13,
2286 cltv_expiry_delta: 0,
2287 htlc_minimum_msat: 0,
2288 htlc_maximum_msat: MAX_VALUE_MSAT,
2290 fee_proportional_millionths: 0,
2291 excess_data: Vec::new()
2293 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2294 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2295 short_channel_id: 4,
2298 cltv_expiry_delta: 0,
2299 htlc_minimum_msat: 0,
2300 htlc_maximum_msat: MAX_VALUE_MSAT,
2302 fee_proportional_millionths: 0,
2303 excess_data: Vec::new()
2306 // Disable other paths
2307 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2308 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2309 short_channel_id: 1,
2311 flags: 2, // to disable
2312 cltv_expiry_delta: 0,
2313 htlc_minimum_msat: 0,
2314 htlc_maximum_msat: MAX_VALUE_MSAT,
2316 fee_proportional_millionths: 0,
2317 excess_data: Vec::new()
2320 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 60_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2321 // Overpay fees to hit htlc_minimum_msat.
2322 let overpaid_fees = route.paths[0][0].fee_msat + route.paths[1][0].fee_msat;
2323 // TODO: this could be better balanced to overpay 10k and not 15k.
2324 assert_eq!(overpaid_fees, 15_000);
2326 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
2327 // while taking even more fee to match htlc_minimum_msat.
2328 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2329 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2330 short_channel_id: 12,
2333 cltv_expiry_delta: 0,
2334 htlc_minimum_msat: 65_000,
2335 htlc_maximum_msat: 80_000,
2337 fee_proportional_millionths: 0,
2338 excess_data: Vec::new()
2340 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2341 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2342 short_channel_id: 2,
2345 cltv_expiry_delta: 0,
2346 htlc_minimum_msat: 0,
2347 htlc_maximum_msat: MAX_VALUE_MSAT,
2349 fee_proportional_millionths: 0,
2350 excess_data: Vec::new()
2352 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2353 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2354 short_channel_id: 4,
2357 cltv_expiry_delta: 0,
2358 htlc_minimum_msat: 0,
2359 htlc_maximum_msat: MAX_VALUE_MSAT,
2361 fee_proportional_millionths: 100_000,
2362 excess_data: Vec::new()
2365 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 60_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2366 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
2367 assert_eq!(route.paths.len(), 1);
2368 assert_eq!(route.paths[0][0].short_channel_id, 12);
2369 let fees = route.paths[0][0].fee_msat;
2370 assert_eq!(fees, 5_000);
2372 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2373 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
2374 // the other channel.
2375 assert_eq!(route.paths.len(), 1);
2376 assert_eq!(route.paths[0][0].short_channel_id, 2);
2377 let fees = route.paths[0][0].fee_msat;
2378 assert_eq!(fees, 5_000);
2382 fn disable_channels_test() {
2383 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2384 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2385 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2386 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2387 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2388 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2390 // // Disable channels 4 and 12 by flags=2
2391 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2392 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2393 short_channel_id: 4,
2395 flags: 2, // to disable
2396 cltv_expiry_delta: 0,
2397 htlc_minimum_msat: 0,
2398 htlc_maximum_msat: MAX_VALUE_MSAT,
2400 fee_proportional_millionths: 0,
2401 excess_data: Vec::new()
2403 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2404 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2405 short_channel_id: 12,
2407 flags: 2, // to disable
2408 cltv_expiry_delta: 0,
2409 htlc_minimum_msat: 0,
2410 htlc_maximum_msat: MAX_VALUE_MSAT,
2412 fee_proportional_millionths: 0,
2413 excess_data: Vec::new()
2416 // If all the channels require some features we don't understand, route should fail
2417 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) {
2418 assert_eq!(err, "Failed to find a path to the given destination");
2419 } else { panic!(); }
2421 // If we specify a channel to node7, that overrides our local channel view and that gets used
2422 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2423 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();
2424 assert_eq!(route.paths[0].len(), 2);
2426 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2427 assert_eq!(route.paths[0][0].short_channel_id, 42);
2428 assert_eq!(route.paths[0][0].fee_msat, 200);
2429 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2430 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2431 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2433 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2434 assert_eq!(route.paths[0][1].short_channel_id, 13);
2435 assert_eq!(route.paths[0][1].fee_msat, 100);
2436 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2437 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2438 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2442 fn disable_node_test() {
2443 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2444 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2445 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2446 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2447 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2448 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2450 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
2451 let mut unknown_features = NodeFeatures::empty();
2452 unknown_features.set_unknown_feature_required();
2453 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
2454 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
2455 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
2457 // If all nodes require some features we don't understand, route should fail
2458 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) {
2459 assert_eq!(err, "Failed to find a path to the given destination");
2460 } else { panic!(); }
2462 // If we specify a channel to node7, that overrides our local channel view and that gets used
2463 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2464 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();
2465 assert_eq!(route.paths[0].len(), 2);
2467 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2468 assert_eq!(route.paths[0][0].short_channel_id, 42);
2469 assert_eq!(route.paths[0][0].fee_msat, 200);
2470 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2471 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2472 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2474 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2475 assert_eq!(route.paths[0][1].short_channel_id, 13);
2476 assert_eq!(route.paths[0][1].fee_msat, 100);
2477 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2478 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2479 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2481 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
2482 // naively) assume that the user checked the feature bits on the invoice, which override
2483 // the node_announcement.
2487 fn our_chans_test() {
2488 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2489 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2490 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2491 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2492 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2494 // Route to 1 via 2 and 3 because our channel to 1 is disabled
2495 let payment_params = PaymentParameters::from_node_id(nodes[0]);
2496 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2497 assert_eq!(route.paths[0].len(), 3);
2499 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2500 assert_eq!(route.paths[0][0].short_channel_id, 2);
2501 assert_eq!(route.paths[0][0].fee_msat, 200);
2502 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2503 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2504 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2506 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2507 assert_eq!(route.paths[0][1].short_channel_id, 4);
2508 assert_eq!(route.paths[0][1].fee_msat, 100);
2509 assert_eq!(route.paths[0][1].cltv_expiry_delta, (3 << 4) | 2);
2510 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2511 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2513 assert_eq!(route.paths[0][2].pubkey, nodes[0]);
2514 assert_eq!(route.paths[0][2].short_channel_id, 3);
2515 assert_eq!(route.paths[0][2].fee_msat, 100);
2516 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
2517 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(1));
2518 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(3));
2520 // If we specify a channel to node7, that overrides our local channel view and that gets used
2521 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2522 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2523 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();
2524 assert_eq!(route.paths[0].len(), 2);
2526 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2527 assert_eq!(route.paths[0][0].short_channel_id, 42);
2528 assert_eq!(route.paths[0][0].fee_msat, 200);
2529 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2530 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2531 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2533 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2534 assert_eq!(route.paths[0][1].short_channel_id, 13);
2535 assert_eq!(route.paths[0][1].fee_msat, 100);
2536 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2537 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2538 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2541 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2542 let zero_fees = RoutingFees {
2544 proportional_millionths: 0,
2546 vec![RouteHint(vec![RouteHintHop {
2547 src_node_id: nodes[3],
2548 short_channel_id: 8,
2550 cltv_expiry_delta: (8 << 4) | 1,
2551 htlc_minimum_msat: None,
2552 htlc_maximum_msat: None,
2554 ]), RouteHint(vec![RouteHintHop {
2555 src_node_id: nodes[4],
2556 short_channel_id: 9,
2559 proportional_millionths: 0,
2561 cltv_expiry_delta: (9 << 4) | 1,
2562 htlc_minimum_msat: None,
2563 htlc_maximum_msat: None,
2564 }]), RouteHint(vec![RouteHintHop {
2565 src_node_id: nodes[5],
2566 short_channel_id: 10,
2568 cltv_expiry_delta: (10 << 4) | 1,
2569 htlc_minimum_msat: None,
2570 htlc_maximum_msat: None,
2574 fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2575 let zero_fees = RoutingFees {
2577 proportional_millionths: 0,
2579 vec![RouteHint(vec![RouteHintHop {
2580 src_node_id: nodes[2],
2581 short_channel_id: 5,
2584 proportional_millionths: 0,
2586 cltv_expiry_delta: (5 << 4) | 1,
2587 htlc_minimum_msat: None,
2588 htlc_maximum_msat: None,
2590 src_node_id: nodes[3],
2591 short_channel_id: 8,
2593 cltv_expiry_delta: (8 << 4) | 1,
2594 htlc_minimum_msat: None,
2595 htlc_maximum_msat: None,
2597 ]), RouteHint(vec![RouteHintHop {
2598 src_node_id: nodes[4],
2599 short_channel_id: 9,
2602 proportional_millionths: 0,
2604 cltv_expiry_delta: (9 << 4) | 1,
2605 htlc_minimum_msat: None,
2606 htlc_maximum_msat: None,
2607 }]), RouteHint(vec![RouteHintHop {
2608 src_node_id: nodes[5],
2609 short_channel_id: 10,
2611 cltv_expiry_delta: (10 << 4) | 1,
2612 htlc_minimum_msat: None,
2613 htlc_maximum_msat: None,
2618 fn partial_route_hint_test() {
2619 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2620 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2621 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2622 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2623 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2625 // Simple test across 2, 3, 5, and 4 via a last_hop channel
2626 // Tests the behaviour when the RouteHint contains a suboptimal hop.
2627 // RouteHint may be partially used by the algo to build the best path.
2629 // First check that last hop can't have its source as the payee.
2630 let invalid_last_hop = RouteHint(vec![RouteHintHop {
2631 src_node_id: nodes[6],
2632 short_channel_id: 8,
2635 proportional_millionths: 0,
2637 cltv_expiry_delta: (8 << 4) | 1,
2638 htlc_minimum_msat: None,
2639 htlc_maximum_msat: None,
2642 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
2643 invalid_last_hops.push(invalid_last_hop);
2645 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(invalid_last_hops);
2646 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) {
2647 assert_eq!(err, "Route hint cannot have the payee as the source.");
2648 } else { panic!(); }
2651 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops_multi_private_channels(&nodes));
2652 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2653 assert_eq!(route.paths[0].len(), 5);
2655 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2656 assert_eq!(route.paths[0][0].short_channel_id, 2);
2657 assert_eq!(route.paths[0][0].fee_msat, 100);
2658 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2659 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2660 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2662 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2663 assert_eq!(route.paths[0][1].short_channel_id, 4);
2664 assert_eq!(route.paths[0][1].fee_msat, 0);
2665 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
2666 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2667 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2669 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2670 assert_eq!(route.paths[0][2].short_channel_id, 6);
2671 assert_eq!(route.paths[0][2].fee_msat, 0);
2672 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
2673 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2674 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2676 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2677 assert_eq!(route.paths[0][3].short_channel_id, 11);
2678 assert_eq!(route.paths[0][3].fee_msat, 0);
2679 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
2680 // If we have a peer in the node map, we'll use their features here since we don't have
2681 // a way of figuring out their features from the invoice:
2682 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2683 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2685 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2686 assert_eq!(route.paths[0][4].short_channel_id, 8);
2687 assert_eq!(route.paths[0][4].fee_msat, 100);
2688 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2689 assert_eq!(route.paths[0][4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
2690 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2693 fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2694 let zero_fees = RoutingFees {
2696 proportional_millionths: 0,
2698 vec![RouteHint(vec![RouteHintHop {
2699 src_node_id: nodes[3],
2700 short_channel_id: 8,
2702 cltv_expiry_delta: (8 << 4) | 1,
2703 htlc_minimum_msat: None,
2704 htlc_maximum_msat: None,
2705 }]), RouteHint(vec![
2707 ]), RouteHint(vec![RouteHintHop {
2708 src_node_id: nodes[5],
2709 short_channel_id: 10,
2711 cltv_expiry_delta: (10 << 4) | 1,
2712 htlc_minimum_msat: None,
2713 htlc_maximum_msat: None,
2718 fn ignores_empty_last_hops_test() {
2719 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2720 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2721 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(empty_last_hop(&nodes));
2722 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2723 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2724 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2726 // Test handling of an empty RouteHint passed in Invoice.
2728 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2729 assert_eq!(route.paths[0].len(), 5);
2731 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2732 assert_eq!(route.paths[0][0].short_channel_id, 2);
2733 assert_eq!(route.paths[0][0].fee_msat, 100);
2734 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2735 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2736 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2738 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2739 assert_eq!(route.paths[0][1].short_channel_id, 4);
2740 assert_eq!(route.paths[0][1].fee_msat, 0);
2741 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
2742 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2743 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2745 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2746 assert_eq!(route.paths[0][2].short_channel_id, 6);
2747 assert_eq!(route.paths[0][2].fee_msat, 0);
2748 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
2749 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2750 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2752 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2753 assert_eq!(route.paths[0][3].short_channel_id, 11);
2754 assert_eq!(route.paths[0][3].fee_msat, 0);
2755 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
2756 // If we have a peer in the node map, we'll use their features here since we don't have
2757 // a way of figuring out their features from the invoice:
2758 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2759 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2761 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2762 assert_eq!(route.paths[0][4].short_channel_id, 8);
2763 assert_eq!(route.paths[0][4].fee_msat, 100);
2764 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2765 assert_eq!(route.paths[0][4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
2766 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2769 /// Builds a trivial last-hop hint that passes through the two nodes given, with channel 0xff00
2771 fn multi_hop_last_hops_hint(hint_hops: [PublicKey; 2]) -> Vec<RouteHint> {
2772 let zero_fees = RoutingFees {
2774 proportional_millionths: 0,
2776 vec![RouteHint(vec![RouteHintHop {
2777 src_node_id: hint_hops[0],
2778 short_channel_id: 0xff00,
2781 proportional_millionths: 0,
2783 cltv_expiry_delta: (5 << 4) | 1,
2784 htlc_minimum_msat: None,
2785 htlc_maximum_msat: None,
2787 src_node_id: hint_hops[1],
2788 short_channel_id: 0xff01,
2790 cltv_expiry_delta: (8 << 4) | 1,
2791 htlc_minimum_msat: None,
2792 htlc_maximum_msat: None,
2797 fn multi_hint_last_hops_test() {
2798 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2799 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2800 let last_hops = multi_hop_last_hops_hint([nodes[2], nodes[3]]);
2801 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops.clone());
2802 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2803 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2804 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2805 // Test through channels 2, 3, 0xff00, 0xff01.
2806 // Test shows that multiple hop hints are considered.
2808 // Disabling channels 6 & 7 by flags=2
2809 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2810 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2811 short_channel_id: 6,
2813 flags: 2, // to disable
2814 cltv_expiry_delta: 0,
2815 htlc_minimum_msat: 0,
2816 htlc_maximum_msat: MAX_VALUE_MSAT,
2818 fee_proportional_millionths: 0,
2819 excess_data: Vec::new()
2821 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2822 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2823 short_channel_id: 7,
2825 flags: 2, // to disable
2826 cltv_expiry_delta: 0,
2827 htlc_minimum_msat: 0,
2828 htlc_maximum_msat: MAX_VALUE_MSAT,
2830 fee_proportional_millionths: 0,
2831 excess_data: Vec::new()
2834 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2835 assert_eq!(route.paths[0].len(), 4);
2837 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2838 assert_eq!(route.paths[0][0].short_channel_id, 2);
2839 assert_eq!(route.paths[0][0].fee_msat, 200);
2840 assert_eq!(route.paths[0][0].cltv_expiry_delta, 65);
2841 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2842 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2844 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2845 assert_eq!(route.paths[0][1].short_channel_id, 4);
2846 assert_eq!(route.paths[0][1].fee_msat, 100);
2847 assert_eq!(route.paths[0][1].cltv_expiry_delta, 81);
2848 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2849 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2851 assert_eq!(route.paths[0][2].pubkey, nodes[3]);
2852 assert_eq!(route.paths[0][2].short_channel_id, last_hops[0].0[0].short_channel_id);
2853 assert_eq!(route.paths[0][2].fee_msat, 0);
2854 assert_eq!(route.paths[0][2].cltv_expiry_delta, 129);
2855 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(4));
2856 assert_eq!(route.paths[0][2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2858 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2859 assert_eq!(route.paths[0][3].short_channel_id, last_hops[0].0[1].short_channel_id);
2860 assert_eq!(route.paths[0][3].fee_msat, 100);
2861 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2862 assert_eq!(route.paths[0][3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
2863 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2867 fn private_multi_hint_last_hops_test() {
2868 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2869 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2871 let non_announced_privkey = SecretKey::from_slice(&hex::decode(format!("{:02x}", 0xf0).repeat(32)).unwrap()[..]).unwrap();
2872 let non_announced_pubkey = PublicKey::from_secret_key(&secp_ctx, &non_announced_privkey);
2874 let last_hops = multi_hop_last_hops_hint([nodes[2], non_announced_pubkey]);
2875 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops.clone());
2876 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2877 // Test through channels 2, 3, 0xff00, 0xff01.
2878 // Test shows that multiple hop hints are considered.
2880 // Disabling channels 6 & 7 by flags=2
2881 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2882 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2883 short_channel_id: 6,
2885 flags: 2, // to disable
2886 cltv_expiry_delta: 0,
2887 htlc_minimum_msat: 0,
2888 htlc_maximum_msat: MAX_VALUE_MSAT,
2890 fee_proportional_millionths: 0,
2891 excess_data: Vec::new()
2893 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2894 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2895 short_channel_id: 7,
2897 flags: 2, // to disable
2898 cltv_expiry_delta: 0,
2899 htlc_minimum_msat: 0,
2900 htlc_maximum_msat: MAX_VALUE_MSAT,
2902 fee_proportional_millionths: 0,
2903 excess_data: Vec::new()
2906 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &[42u8; 32]).unwrap();
2907 assert_eq!(route.paths[0].len(), 4);
2909 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2910 assert_eq!(route.paths[0][0].short_channel_id, 2);
2911 assert_eq!(route.paths[0][0].fee_msat, 200);
2912 assert_eq!(route.paths[0][0].cltv_expiry_delta, 65);
2913 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2914 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2916 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2917 assert_eq!(route.paths[0][1].short_channel_id, 4);
2918 assert_eq!(route.paths[0][1].fee_msat, 100);
2919 assert_eq!(route.paths[0][1].cltv_expiry_delta, 81);
2920 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2921 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2923 assert_eq!(route.paths[0][2].pubkey, non_announced_pubkey);
2924 assert_eq!(route.paths[0][2].short_channel_id, last_hops[0].0[0].short_channel_id);
2925 assert_eq!(route.paths[0][2].fee_msat, 0);
2926 assert_eq!(route.paths[0][2].cltv_expiry_delta, 129);
2927 assert_eq!(route.paths[0][2].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
2928 assert_eq!(route.paths[0][2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2930 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2931 assert_eq!(route.paths[0][3].short_channel_id, last_hops[0].0[1].short_channel_id);
2932 assert_eq!(route.paths[0][3].fee_msat, 100);
2933 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2934 assert_eq!(route.paths[0][3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
2935 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2938 fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2939 let zero_fees = RoutingFees {
2941 proportional_millionths: 0,
2943 vec![RouteHint(vec![RouteHintHop {
2944 src_node_id: nodes[4],
2945 short_channel_id: 11,
2947 cltv_expiry_delta: (11 << 4) | 1,
2948 htlc_minimum_msat: None,
2949 htlc_maximum_msat: None,
2951 src_node_id: nodes[3],
2952 short_channel_id: 8,
2954 cltv_expiry_delta: (8 << 4) | 1,
2955 htlc_minimum_msat: None,
2956 htlc_maximum_msat: None,
2957 }]), RouteHint(vec![RouteHintHop {
2958 src_node_id: nodes[4],
2959 short_channel_id: 9,
2962 proportional_millionths: 0,
2964 cltv_expiry_delta: (9 << 4) | 1,
2965 htlc_minimum_msat: None,
2966 htlc_maximum_msat: None,
2967 }]), RouteHint(vec![RouteHintHop {
2968 src_node_id: nodes[5],
2969 short_channel_id: 10,
2971 cltv_expiry_delta: (10 << 4) | 1,
2972 htlc_minimum_msat: None,
2973 htlc_maximum_msat: None,
2978 fn last_hops_with_public_channel_test() {
2979 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2980 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2981 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops_with_public_channel(&nodes));
2982 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2983 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2984 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2985 // This test shows that public routes can be present in the invoice
2986 // which would be handled in the same manner.
2988 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2989 assert_eq!(route.paths[0].len(), 5);
2991 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2992 assert_eq!(route.paths[0][0].short_channel_id, 2);
2993 assert_eq!(route.paths[0][0].fee_msat, 100);
2994 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2995 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2996 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2998 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2999 assert_eq!(route.paths[0][1].short_channel_id, 4);
3000 assert_eq!(route.paths[0][1].fee_msat, 0);
3001 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
3002 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3003 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3005 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
3006 assert_eq!(route.paths[0][2].short_channel_id, 6);
3007 assert_eq!(route.paths[0][2].fee_msat, 0);
3008 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
3009 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
3010 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
3012 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
3013 assert_eq!(route.paths[0][3].short_channel_id, 11);
3014 assert_eq!(route.paths[0][3].fee_msat, 0);
3015 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
3016 // If we have a peer in the node map, we'll use their features here since we don't have
3017 // a way of figuring out their features from the invoice:
3018 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
3019 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
3021 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
3022 assert_eq!(route.paths[0][4].short_channel_id, 8);
3023 assert_eq!(route.paths[0][4].fee_msat, 100);
3024 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
3025 assert_eq!(route.paths[0][4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3026 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3030 fn our_chans_last_hop_connect_test() {
3031 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3032 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3033 let scorer = ln_test_utils::TestScorer::with_penalty(0);
3034 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3035 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3037 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
3038 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3039 let mut last_hops = last_hops(&nodes);
3040 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops.clone());
3041 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();
3042 assert_eq!(route.paths[0].len(), 2);
3044 assert_eq!(route.paths[0][0].pubkey, nodes[3]);
3045 assert_eq!(route.paths[0][0].short_channel_id, 42);
3046 assert_eq!(route.paths[0][0].fee_msat, 0);
3047 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 4) | 1);
3048 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
3049 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3051 assert_eq!(route.paths[0][1].pubkey, nodes[6]);
3052 assert_eq!(route.paths[0][1].short_channel_id, 8);
3053 assert_eq!(route.paths[0][1].fee_msat, 100);
3054 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
3055 assert_eq!(route.paths[0][1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3056 assert_eq!(route.paths[0][1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3058 last_hops[0].0[0].fees.base_msat = 1000;
3060 // Revert to via 6 as the fee on 8 goes up
3061 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops);
3062 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3063 assert_eq!(route.paths[0].len(), 4);
3065 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3066 assert_eq!(route.paths[0][0].short_channel_id, 2);
3067 assert_eq!(route.paths[0][0].fee_msat, 200); // fee increased as its % of value transferred across node
3068 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
3069 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3070 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3072 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3073 assert_eq!(route.paths[0][1].short_channel_id, 4);
3074 assert_eq!(route.paths[0][1].fee_msat, 100);
3075 assert_eq!(route.paths[0][1].cltv_expiry_delta, (7 << 4) | 1);
3076 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3077 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3079 assert_eq!(route.paths[0][2].pubkey, nodes[5]);
3080 assert_eq!(route.paths[0][2].short_channel_id, 7);
3081 assert_eq!(route.paths[0][2].fee_msat, 0);
3082 assert_eq!(route.paths[0][2].cltv_expiry_delta, (10 << 4) | 1);
3083 // If we have a peer in the node map, we'll use their features here since we don't have
3084 // a way of figuring out their features from the invoice:
3085 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
3086 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(7));
3088 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
3089 assert_eq!(route.paths[0][3].short_channel_id, 10);
3090 assert_eq!(route.paths[0][3].fee_msat, 100);
3091 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
3092 assert_eq!(route.paths[0][3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3093 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3095 // ...but still use 8 for larger payments as 6 has a variable feerate
3096 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 2000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3097 assert_eq!(route.paths[0].len(), 5);
3099 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3100 assert_eq!(route.paths[0][0].short_channel_id, 2);
3101 assert_eq!(route.paths[0][0].fee_msat, 3000);
3102 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
3103 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3104 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3106 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3107 assert_eq!(route.paths[0][1].short_channel_id, 4);
3108 assert_eq!(route.paths[0][1].fee_msat, 0);
3109 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
3110 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3111 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3113 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
3114 assert_eq!(route.paths[0][2].short_channel_id, 6);
3115 assert_eq!(route.paths[0][2].fee_msat, 0);
3116 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
3117 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
3118 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
3120 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
3121 assert_eq!(route.paths[0][3].short_channel_id, 11);
3122 assert_eq!(route.paths[0][3].fee_msat, 1000);
3123 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
3124 // If we have a peer in the node map, we'll use their features here since we don't have
3125 // a way of figuring out their features from the invoice:
3126 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
3127 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
3129 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
3130 assert_eq!(route.paths[0][4].short_channel_id, 8);
3131 assert_eq!(route.paths[0][4].fee_msat, 2000);
3132 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
3133 assert_eq!(route.paths[0][4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3134 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3137 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> {
3138 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
3139 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3140 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3142 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
3143 let last_hops = RouteHint(vec![RouteHintHop {
3144 src_node_id: middle_node_id,
3145 short_channel_id: 8,
3148 proportional_millionths: last_hop_fee_prop,
3150 cltv_expiry_delta: (8 << 4) | 1,
3151 htlc_minimum_msat: None,
3152 htlc_maximum_msat: last_hop_htlc_max,
3154 let payment_params = PaymentParameters::from_node_id(target_node_id).with_route_hints(vec![last_hops]);
3155 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
3156 let scorer = ln_test_utils::TestScorer::with_penalty(0);
3157 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3158 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3159 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
3160 let logger = ln_test_utils::TestLogger::new();
3161 let network_graph = NetworkGraph::new(genesis_hash, &logger);
3162 let route = get_route(&source_node_id, &payment_params, &network_graph.read_only(),
3163 Some(&our_chans.iter().collect::<Vec<_>>()), route_val, 42, &logger, &scorer, &random_seed_bytes);
3168 fn unannounced_path_test() {
3169 // We should be able to send a payment to a destination without any help of a routing graph
3170 // if we have a channel with a common counterparty that appears in the first and last hop
3172 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
3174 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3175 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3176 assert_eq!(route.paths[0].len(), 2);
3178 assert_eq!(route.paths[0][0].pubkey, middle_node_id);
3179 assert_eq!(route.paths[0][0].short_channel_id, 42);
3180 assert_eq!(route.paths[0][0].fee_msat, 1001);
3181 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 4) | 1);
3182 assert_eq!(route.paths[0][0].node_features.le_flags(), &[0b11]);
3183 assert_eq!(route.paths[0][0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3185 assert_eq!(route.paths[0][1].pubkey, target_node_id);
3186 assert_eq!(route.paths[0][1].short_channel_id, 8);
3187 assert_eq!(route.paths[0][1].fee_msat, 1000000);
3188 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
3189 assert_eq!(route.paths[0][1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3190 assert_eq!(route.paths[0][1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3194 fn overflow_unannounced_path_test_liquidity_underflow() {
3195 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
3196 // the last-hop had a fee which overflowed a u64, we'd panic.
3197 // This was due to us adding the first-hop from us unconditionally, causing us to think
3198 // we'd built a path (as our node is in the "best candidate" set), when we had not.
3199 // In this test, we previously hit a subtraction underflow due to having less available
3200 // liquidity at the last hop than 0.
3201 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());
3205 fn overflow_unannounced_path_test_feerate_overflow() {
3206 // This tests for the same case as above, except instead of hitting a subtraction
3207 // underflow, we hit a case where the fee charged at a hop overflowed.
3208 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());
3212 fn available_amount_while_routing_test() {
3213 // Tests whether we choose the correct available channel amount while routing.
3215 let (secp_ctx, network_graph, mut gossip_sync, chain_monitor, logger) = build_graph();
3216 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3217 let scorer = ln_test_utils::TestScorer::with_penalty(0);
3218 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3219 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3220 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(channelmanager::provided_invoice_features());
3222 // We will use a simple single-path route from
3223 // our node to node2 via node0: channels {1, 3}.
3225 // First disable all other paths.
3226 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3227 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3228 short_channel_id: 2,
3231 cltv_expiry_delta: 0,
3232 htlc_minimum_msat: 0,
3233 htlc_maximum_msat: 100_000,
3235 fee_proportional_millionths: 0,
3236 excess_data: Vec::new()
3238 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3239 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3240 short_channel_id: 12,
3243 cltv_expiry_delta: 0,
3244 htlc_minimum_msat: 0,
3245 htlc_maximum_msat: 100_000,
3247 fee_proportional_millionths: 0,
3248 excess_data: Vec::new()
3251 // Make the first channel (#1) very permissive,
3252 // and we will be testing all limits on the second channel.
3253 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3254 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3255 short_channel_id: 1,
3258 cltv_expiry_delta: 0,
3259 htlc_minimum_msat: 0,
3260 htlc_maximum_msat: 1_000_000_000,
3262 fee_proportional_millionths: 0,
3263 excess_data: Vec::new()
3266 // First, let's see if routing works if we have absolutely no idea about the available amount.
3267 // In this case, it should be set to 250_000 sats.
3268 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3269 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3270 short_channel_id: 3,
3273 cltv_expiry_delta: 0,
3274 htlc_minimum_msat: 0,
3275 htlc_maximum_msat: 250_000_000,
3277 fee_proportional_millionths: 0,
3278 excess_data: Vec::new()
3282 // Attempt to route more than available results in a failure.
3283 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3284 &our_id, &payment_params, &network_graph.read_only(), None, 250_000_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3285 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3286 } else { panic!(); }
3290 // Now, attempt to route an exact amount we have should be fine.
3291 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();
3292 assert_eq!(route.paths.len(), 1);
3293 let path = route.paths.last().unwrap();
3294 assert_eq!(path.len(), 2);
3295 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3296 assert_eq!(path.last().unwrap().fee_msat, 250_000_000);
3299 // Check that setting next_outbound_htlc_limit_msat in first_hops limits the channels.
3300 // Disable channel #1 and use another first hop.
3301 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3302 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3303 short_channel_id: 1,
3306 cltv_expiry_delta: 0,
3307 htlc_minimum_msat: 0,
3308 htlc_maximum_msat: 1_000_000_000,
3310 fee_proportional_millionths: 0,
3311 excess_data: Vec::new()
3314 // Now, limit the first_hop by the next_outbound_htlc_limit_msat of 200_000 sats.
3315 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
3318 // Attempt to route more than available results in a failure.
3319 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3320 &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) {
3321 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3322 } else { panic!(); }
3326 // Now, attempt to route an exact amount we have should be fine.
3327 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();
3328 assert_eq!(route.paths.len(), 1);
3329 let path = route.paths.last().unwrap();
3330 assert_eq!(path.len(), 2);
3331 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3332 assert_eq!(path.last().unwrap().fee_msat, 200_000_000);
3335 // Enable channel #1 back.
3336 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3337 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3338 short_channel_id: 1,
3341 cltv_expiry_delta: 0,
3342 htlc_minimum_msat: 0,
3343 htlc_maximum_msat: 1_000_000_000,
3345 fee_proportional_millionths: 0,
3346 excess_data: Vec::new()
3350 // Now let's see if routing works if we know only htlc_maximum_msat.
3351 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3352 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3353 short_channel_id: 3,
3356 cltv_expiry_delta: 0,
3357 htlc_minimum_msat: 0,
3358 htlc_maximum_msat: 15_000,
3360 fee_proportional_millionths: 0,
3361 excess_data: Vec::new()
3365 // Attempt to route more than available results in a failure.
3366 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3367 &our_id, &payment_params, &network_graph.read_only(), None, 15_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3368 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3369 } else { panic!(); }
3373 // Now, attempt to route an exact amount we have should be fine.
3374 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 15_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3375 assert_eq!(route.paths.len(), 1);
3376 let path = route.paths.last().unwrap();
3377 assert_eq!(path.len(), 2);
3378 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3379 assert_eq!(path.last().unwrap().fee_msat, 15_000);
3382 // Now let's see if routing works if we know only capacity from the UTXO.
3384 // We can't change UTXO capacity on the fly, so we'll disable
3385 // the existing channel and add another one with the capacity we need.
3386 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3387 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3388 short_channel_id: 3,
3391 cltv_expiry_delta: 0,
3392 htlc_minimum_msat: 0,
3393 htlc_maximum_msat: MAX_VALUE_MSAT,
3395 fee_proportional_millionths: 0,
3396 excess_data: Vec::new()
3399 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
3400 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
3401 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
3402 .push_opcode(opcodes::all::OP_PUSHNUM_2)
3403 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
3405 *chain_monitor.utxo_ret.lock().unwrap() = Ok(TxOut { value: 15, script_pubkey: good_script.clone() });
3406 gossip_sync.add_chain_access(Some(chain_monitor));
3408 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
3409 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3410 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3411 short_channel_id: 333,
3414 cltv_expiry_delta: (3 << 4) | 1,
3415 htlc_minimum_msat: 0,
3416 htlc_maximum_msat: 15_000,
3418 fee_proportional_millionths: 0,
3419 excess_data: Vec::new()
3421 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3422 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3423 short_channel_id: 333,
3426 cltv_expiry_delta: (3 << 4) | 2,
3427 htlc_minimum_msat: 0,
3428 htlc_maximum_msat: 15_000,
3430 fee_proportional_millionths: 0,
3431 excess_data: Vec::new()
3435 // Attempt to route more than available results in a failure.
3436 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3437 &our_id, &payment_params, &network_graph.read_only(), None, 15_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3438 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3439 } else { panic!(); }
3443 // Now, attempt to route an exact amount we have should be fine.
3444 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 15_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3445 assert_eq!(route.paths.len(), 1);
3446 let path = route.paths.last().unwrap();
3447 assert_eq!(path.len(), 2);
3448 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3449 assert_eq!(path.last().unwrap().fee_msat, 15_000);
3452 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
3453 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3454 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3455 short_channel_id: 333,
3458 cltv_expiry_delta: 0,
3459 htlc_minimum_msat: 0,
3460 htlc_maximum_msat: 10_000,
3462 fee_proportional_millionths: 0,
3463 excess_data: Vec::new()
3467 // Attempt to route more than available results in a failure.
3468 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3469 &our_id, &payment_params, &network_graph.read_only(), None, 10_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3470 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3471 } else { panic!(); }
3475 // Now, attempt to route an exact amount we have should be fine.
3476 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 10_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3477 assert_eq!(route.paths.len(), 1);
3478 let path = route.paths.last().unwrap();
3479 assert_eq!(path.len(), 2);
3480 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3481 assert_eq!(path.last().unwrap().fee_msat, 10_000);
3486 fn available_liquidity_last_hop_test() {
3487 // Check that available liquidity properly limits the path even when only
3488 // one of the latter hops is limited.
3489 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3490 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3491 let scorer = ln_test_utils::TestScorer::with_penalty(0);
3492 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3493 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3494 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(channelmanager::provided_invoice_features());
3496 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3497 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
3498 // Total capacity: 50 sats.
3500 // Disable other potential paths.
3501 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3502 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3503 short_channel_id: 2,
3506 cltv_expiry_delta: 0,
3507 htlc_minimum_msat: 0,
3508 htlc_maximum_msat: 100_000,
3510 fee_proportional_millionths: 0,
3511 excess_data: Vec::new()
3513 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3514 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3515 short_channel_id: 7,
3518 cltv_expiry_delta: 0,
3519 htlc_minimum_msat: 0,
3520 htlc_maximum_msat: 100_000,
3522 fee_proportional_millionths: 0,
3523 excess_data: Vec::new()
3528 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3529 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3530 short_channel_id: 12,
3533 cltv_expiry_delta: 0,
3534 htlc_minimum_msat: 0,
3535 htlc_maximum_msat: 100_000,
3537 fee_proportional_millionths: 0,
3538 excess_data: Vec::new()
3540 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3541 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3542 short_channel_id: 13,
3545 cltv_expiry_delta: 0,
3546 htlc_minimum_msat: 0,
3547 htlc_maximum_msat: 100_000,
3549 fee_proportional_millionths: 0,
3550 excess_data: Vec::new()
3553 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3554 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3555 short_channel_id: 6,
3558 cltv_expiry_delta: 0,
3559 htlc_minimum_msat: 0,
3560 htlc_maximum_msat: 50_000,
3562 fee_proportional_millionths: 0,
3563 excess_data: Vec::new()
3565 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3566 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3567 short_channel_id: 11,
3570 cltv_expiry_delta: 0,
3571 htlc_minimum_msat: 0,
3572 htlc_maximum_msat: 100_000,
3574 fee_proportional_millionths: 0,
3575 excess_data: Vec::new()
3578 // Attempt to route more than available results in a failure.
3579 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3580 &our_id, &payment_params, &network_graph.read_only(), None, 60_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3581 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3582 } else { panic!(); }
3586 // Now, attempt to route 49 sats (just a bit below the capacity).
3587 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 49_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3588 assert_eq!(route.paths.len(), 1);
3589 let mut total_amount_paid_msat = 0;
3590 for path in &route.paths {
3591 assert_eq!(path.len(), 4);
3592 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3593 total_amount_paid_msat += path.last().unwrap().fee_msat;
3595 assert_eq!(total_amount_paid_msat, 49_000);
3599 // Attempt to route an exact amount is also fine
3600 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3601 assert_eq!(route.paths.len(), 1);
3602 let mut total_amount_paid_msat = 0;
3603 for path in &route.paths {
3604 assert_eq!(path.len(), 4);
3605 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3606 total_amount_paid_msat += path.last().unwrap().fee_msat;
3608 assert_eq!(total_amount_paid_msat, 50_000);
3613 fn ignore_fee_first_hop_test() {
3614 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3615 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3616 let scorer = ln_test_utils::TestScorer::with_penalty(0);
3617 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3618 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3619 let payment_params = PaymentParameters::from_node_id(nodes[2]);
3621 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3622 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3623 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3624 short_channel_id: 1,
3627 cltv_expiry_delta: 0,
3628 htlc_minimum_msat: 0,
3629 htlc_maximum_msat: 100_000,
3630 fee_base_msat: 1_000_000,
3631 fee_proportional_millionths: 0,
3632 excess_data: Vec::new()
3634 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3635 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3636 short_channel_id: 3,
3639 cltv_expiry_delta: 0,
3640 htlc_minimum_msat: 0,
3641 htlc_maximum_msat: 50_000,
3643 fee_proportional_millionths: 0,
3644 excess_data: Vec::new()
3648 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3649 assert_eq!(route.paths.len(), 1);
3650 let mut total_amount_paid_msat = 0;
3651 for path in &route.paths {
3652 assert_eq!(path.len(), 2);
3653 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3654 total_amount_paid_msat += path.last().unwrap().fee_msat;
3656 assert_eq!(total_amount_paid_msat, 50_000);
3661 fn simple_mpp_route_test() {
3662 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3663 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3664 let scorer = ln_test_utils::TestScorer::with_penalty(0);
3665 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3666 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3667 let payment_params = PaymentParameters::from_node_id(nodes[2])
3668 .with_features(channelmanager::provided_invoice_features());
3670 // We need a route consisting of 3 paths:
3671 // From our node to node2 via node0, node7, node1 (three paths one hop each).
3672 // To achieve this, the amount being transferred should be around
3673 // the total capacity of these 3 paths.
3675 // First, we set limits on these (previously unlimited) channels.
3676 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
3678 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3679 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3680 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3681 short_channel_id: 1,
3684 cltv_expiry_delta: 0,
3685 htlc_minimum_msat: 0,
3686 htlc_maximum_msat: 100_000,
3688 fee_proportional_millionths: 0,
3689 excess_data: Vec::new()
3691 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3692 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3693 short_channel_id: 3,
3696 cltv_expiry_delta: 0,
3697 htlc_minimum_msat: 0,
3698 htlc_maximum_msat: 50_000,
3700 fee_proportional_millionths: 0,
3701 excess_data: Vec::new()
3704 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
3705 // (total limit 60).
3706 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3707 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3708 short_channel_id: 12,
3711 cltv_expiry_delta: 0,
3712 htlc_minimum_msat: 0,
3713 htlc_maximum_msat: 60_000,
3715 fee_proportional_millionths: 0,
3716 excess_data: Vec::new()
3718 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3719 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3720 short_channel_id: 13,
3723 cltv_expiry_delta: 0,
3724 htlc_minimum_msat: 0,
3725 htlc_maximum_msat: 60_000,
3727 fee_proportional_millionths: 0,
3728 excess_data: Vec::new()
3731 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
3732 // (total capacity 180 sats).
3733 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3734 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3735 short_channel_id: 2,
3738 cltv_expiry_delta: 0,
3739 htlc_minimum_msat: 0,
3740 htlc_maximum_msat: 200_000,
3742 fee_proportional_millionths: 0,
3743 excess_data: Vec::new()
3745 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3746 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3747 short_channel_id: 4,
3750 cltv_expiry_delta: 0,
3751 htlc_minimum_msat: 0,
3752 htlc_maximum_msat: 180_000,
3754 fee_proportional_millionths: 0,
3755 excess_data: Vec::new()
3759 // Attempt to route more than available results in a failure.
3760 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3761 &our_id, &payment_params, &network_graph.read_only(), None, 300_000, 42,
3762 Arc::clone(&logger), &scorer, &random_seed_bytes) {
3763 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3764 } else { panic!(); }
3768 // Attempt to route while setting max_path_count to 0 results in a failure.
3769 let zero_payment_params = payment_params.clone().with_max_path_count(0);
3770 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3771 &our_id, &zero_payment_params, &network_graph.read_only(), None, 100, 42,
3772 Arc::clone(&logger), &scorer, &random_seed_bytes) {
3773 assert_eq!(err, "Can't find a route with no paths allowed.");
3774 } else { panic!(); }
3778 // Attempt to route while setting max_path_count to 3 results in a failure.
3779 // This is the case because the minimal_value_contribution_msat would require each path
3780 // to account for 1/3 of the total value, which is violated by 2 out of 3 paths.
3781 let fail_payment_params = payment_params.clone().with_max_path_count(3);
3782 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3783 &our_id, &fail_payment_params, &network_graph.read_only(), None, 250_000, 42,
3784 Arc::clone(&logger), &scorer, &random_seed_bytes) {
3785 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3786 } else { panic!(); }
3790 // Now, attempt to route 250 sats (just a bit below the capacity).
3791 // Our algorithm should provide us with these 3 paths.
3792 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None,
3793 250_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3794 assert_eq!(route.paths.len(), 3);
3795 let mut total_amount_paid_msat = 0;
3796 for path in &route.paths {
3797 assert_eq!(path.len(), 2);
3798 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3799 total_amount_paid_msat += path.last().unwrap().fee_msat;
3801 assert_eq!(total_amount_paid_msat, 250_000);
3805 // Attempt to route an exact amount is also fine
3806 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None,
3807 290_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3808 assert_eq!(route.paths.len(), 3);
3809 let mut total_amount_paid_msat = 0;
3810 for path in &route.paths {
3811 assert_eq!(path.len(), 2);
3812 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3813 total_amount_paid_msat += path.last().unwrap().fee_msat;
3815 assert_eq!(total_amount_paid_msat, 290_000);
3820 fn long_mpp_route_test() {
3821 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3822 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3823 let scorer = ln_test_utils::TestScorer::with_penalty(0);
3824 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3825 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3826 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(channelmanager::provided_invoice_features());
3828 // We need a route consisting of 3 paths:
3829 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3830 // Note that these paths overlap (channels 5, 12, 13).
3831 // We will route 300 sats.
3832 // Each path will have 100 sats capacity, those channels which
3833 // are used twice will have 200 sats capacity.
3835 // Disable other potential paths.
3836 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3837 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3838 short_channel_id: 2,
3841 cltv_expiry_delta: 0,
3842 htlc_minimum_msat: 0,
3843 htlc_maximum_msat: 100_000,
3845 fee_proportional_millionths: 0,
3846 excess_data: Vec::new()
3848 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3849 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3850 short_channel_id: 7,
3853 cltv_expiry_delta: 0,
3854 htlc_minimum_msat: 0,
3855 htlc_maximum_msat: 100_000,
3857 fee_proportional_millionths: 0,
3858 excess_data: Vec::new()
3861 // Path via {node0, node2} is channels {1, 3, 5}.
3862 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3863 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3864 short_channel_id: 1,
3867 cltv_expiry_delta: 0,
3868 htlc_minimum_msat: 0,
3869 htlc_maximum_msat: 100_000,
3871 fee_proportional_millionths: 0,
3872 excess_data: Vec::new()
3874 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3875 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3876 short_channel_id: 3,
3879 cltv_expiry_delta: 0,
3880 htlc_minimum_msat: 0,
3881 htlc_maximum_msat: 100_000,
3883 fee_proportional_millionths: 0,
3884 excess_data: Vec::new()
3887 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3888 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3889 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3890 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3891 short_channel_id: 5,
3894 cltv_expiry_delta: 0,
3895 htlc_minimum_msat: 0,
3896 htlc_maximum_msat: 200_000,
3898 fee_proportional_millionths: 0,
3899 excess_data: Vec::new()
3902 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3903 // Add 100 sats to the capacities of {12, 13}, because these channels
3904 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3905 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3906 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3907 short_channel_id: 12,
3910 cltv_expiry_delta: 0,
3911 htlc_minimum_msat: 0,
3912 htlc_maximum_msat: 200_000,
3914 fee_proportional_millionths: 0,
3915 excess_data: Vec::new()
3917 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3918 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3919 short_channel_id: 13,
3922 cltv_expiry_delta: 0,
3923 htlc_minimum_msat: 0,
3924 htlc_maximum_msat: 200_000,
3926 fee_proportional_millionths: 0,
3927 excess_data: Vec::new()
3930 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3931 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3932 short_channel_id: 6,
3935 cltv_expiry_delta: 0,
3936 htlc_minimum_msat: 0,
3937 htlc_maximum_msat: 100_000,
3939 fee_proportional_millionths: 0,
3940 excess_data: Vec::new()
3942 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3943 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3944 short_channel_id: 11,
3947 cltv_expiry_delta: 0,
3948 htlc_minimum_msat: 0,
3949 htlc_maximum_msat: 100_000,
3951 fee_proportional_millionths: 0,
3952 excess_data: Vec::new()
3955 // Path via {node7, node2} is channels {12, 13, 5}.
3956 // We already limited them to 200 sats (they are used twice for 100 sats).
3957 // Nothing to do here.
3960 // Attempt to route more than available results in a failure.
3961 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3962 &our_id, &payment_params, &network_graph.read_only(), None, 350_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3963 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3964 } else { panic!(); }
3968 // Now, attempt to route 300 sats (exact amount we can route).
3969 // Our algorithm should provide us with these 3 paths, 100 sats each.
3970 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 300_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3971 assert_eq!(route.paths.len(), 3);
3973 let mut total_amount_paid_msat = 0;
3974 for path in &route.paths {
3975 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3976 total_amount_paid_msat += path.last().unwrap().fee_msat;
3978 assert_eq!(total_amount_paid_msat, 300_000);
3984 fn mpp_cheaper_route_test() {
3985 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3986 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3987 let scorer = ln_test_utils::TestScorer::with_penalty(0);
3988 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3989 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3990 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(channelmanager::provided_invoice_features());
3992 // This test checks that if we have two cheaper paths and one more expensive path,
3993 // so that liquidity-wise any 2 of 3 combination is sufficient,
3994 // two cheaper paths will be taken.
3995 // These paths have equal available liquidity.
3997 // We need a combination of 3 paths:
3998 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3999 // Note that these paths overlap (channels 5, 12, 13).
4000 // Each path will have 100 sats capacity, those channels which
4001 // are used twice will have 200 sats capacity.
4003 // Disable other potential paths.
4004 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4005 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4006 short_channel_id: 2,
4009 cltv_expiry_delta: 0,
4010 htlc_minimum_msat: 0,
4011 htlc_maximum_msat: 100_000,
4013 fee_proportional_millionths: 0,
4014 excess_data: Vec::new()
4016 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4017 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4018 short_channel_id: 7,
4021 cltv_expiry_delta: 0,
4022 htlc_minimum_msat: 0,
4023 htlc_maximum_msat: 100_000,
4025 fee_proportional_millionths: 0,
4026 excess_data: Vec::new()
4029 // Path via {node0, node2} is channels {1, 3, 5}.
4030 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4031 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4032 short_channel_id: 1,
4035 cltv_expiry_delta: 0,
4036 htlc_minimum_msat: 0,
4037 htlc_maximum_msat: 100_000,
4039 fee_proportional_millionths: 0,
4040 excess_data: Vec::new()
4042 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4043 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4044 short_channel_id: 3,
4047 cltv_expiry_delta: 0,
4048 htlc_minimum_msat: 0,
4049 htlc_maximum_msat: 100_000,
4051 fee_proportional_millionths: 0,
4052 excess_data: Vec::new()
4055 // Capacity of 200 sats because this channel will be used by 3rd path as well.
4056 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4057 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4058 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4059 short_channel_id: 5,
4062 cltv_expiry_delta: 0,
4063 htlc_minimum_msat: 0,
4064 htlc_maximum_msat: 200_000,
4066 fee_proportional_millionths: 0,
4067 excess_data: Vec::new()
4070 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4071 // Add 100 sats to the capacities of {12, 13}, because these channels
4072 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
4073 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4074 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4075 short_channel_id: 12,
4078 cltv_expiry_delta: 0,
4079 htlc_minimum_msat: 0,
4080 htlc_maximum_msat: 200_000,
4082 fee_proportional_millionths: 0,
4083 excess_data: Vec::new()
4085 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4086 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4087 short_channel_id: 13,
4090 cltv_expiry_delta: 0,
4091 htlc_minimum_msat: 0,
4092 htlc_maximum_msat: 200_000,
4094 fee_proportional_millionths: 0,
4095 excess_data: Vec::new()
4098 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4099 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4100 short_channel_id: 6,
4103 cltv_expiry_delta: 0,
4104 htlc_minimum_msat: 0,
4105 htlc_maximum_msat: 100_000,
4106 fee_base_msat: 1_000,
4107 fee_proportional_millionths: 0,
4108 excess_data: Vec::new()
4110 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4111 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4112 short_channel_id: 11,
4115 cltv_expiry_delta: 0,
4116 htlc_minimum_msat: 0,
4117 htlc_maximum_msat: 100_000,
4119 fee_proportional_millionths: 0,
4120 excess_data: Vec::new()
4123 // Path via {node7, node2} is channels {12, 13, 5}.
4124 // We already limited them to 200 sats (they are used twice for 100 sats).
4125 // Nothing to do here.
4128 // Now, attempt to route 180 sats.
4129 // Our algorithm should provide us with these 2 paths.
4130 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 180_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4131 assert_eq!(route.paths.len(), 2);
4133 let mut total_value_transferred_msat = 0;
4134 let mut total_paid_msat = 0;
4135 for path in &route.paths {
4136 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
4137 total_value_transferred_msat += path.last().unwrap().fee_msat;
4139 total_paid_msat += hop.fee_msat;
4142 // If we paid fee, this would be higher.
4143 assert_eq!(total_value_transferred_msat, 180_000);
4144 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
4145 assert_eq!(total_fees_paid, 0);
4150 fn fees_on_mpp_route_test() {
4151 // This test makes sure that MPP algorithm properly takes into account
4152 // fees charged on the channels, by making the fees impactful:
4153 // if the fee is not properly accounted for, the behavior is different.
4154 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4155 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4156 let scorer = ln_test_utils::TestScorer::with_penalty(0);
4157 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4158 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4159 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(channelmanager::provided_invoice_features());
4161 // We need a route consisting of 2 paths:
4162 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
4163 // We will route 200 sats, Each path will have 100 sats capacity.
4165 // This test is not particularly stable: e.g.,
4166 // there's a way to route via {node0, node2, node4}.
4167 // It works while pathfinding is deterministic, but can be broken otherwise.
4168 // It's fine to ignore this concern for now.
4170 // Disable other potential paths.
4171 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4172 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4173 short_channel_id: 2,
4176 cltv_expiry_delta: 0,
4177 htlc_minimum_msat: 0,
4178 htlc_maximum_msat: 100_000,
4180 fee_proportional_millionths: 0,
4181 excess_data: Vec::new()
4184 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4185 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4186 short_channel_id: 7,
4189 cltv_expiry_delta: 0,
4190 htlc_minimum_msat: 0,
4191 htlc_maximum_msat: 100_000,
4193 fee_proportional_millionths: 0,
4194 excess_data: Vec::new()
4197 // Path via {node0, node2} is channels {1, 3, 5}.
4198 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4199 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4200 short_channel_id: 1,
4203 cltv_expiry_delta: 0,
4204 htlc_minimum_msat: 0,
4205 htlc_maximum_msat: 100_000,
4207 fee_proportional_millionths: 0,
4208 excess_data: Vec::new()
4210 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4211 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4212 short_channel_id: 3,
4215 cltv_expiry_delta: 0,
4216 htlc_minimum_msat: 0,
4217 htlc_maximum_msat: 100_000,
4219 fee_proportional_millionths: 0,
4220 excess_data: Vec::new()
4223 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4224 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4225 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4226 short_channel_id: 5,
4229 cltv_expiry_delta: 0,
4230 htlc_minimum_msat: 0,
4231 htlc_maximum_msat: 100_000,
4233 fee_proportional_millionths: 0,
4234 excess_data: Vec::new()
4237 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4238 // All channels should be 100 sats capacity. But for the fee experiment,
4239 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
4240 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
4241 // 100 sats (and pay 150 sats in fees for the use of channel 6),
4242 // so no matter how large are other channels,
4243 // the whole path will be limited by 100 sats with just these 2 conditions:
4244 // - channel 12 capacity is 250 sats
4245 // - fee for channel 6 is 150 sats
4246 // Let's test this by enforcing these 2 conditions and removing other limits.
4247 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4248 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4249 short_channel_id: 12,
4252 cltv_expiry_delta: 0,
4253 htlc_minimum_msat: 0,
4254 htlc_maximum_msat: 250_000,
4256 fee_proportional_millionths: 0,
4257 excess_data: Vec::new()
4259 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4260 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4261 short_channel_id: 13,
4264 cltv_expiry_delta: 0,
4265 htlc_minimum_msat: 0,
4266 htlc_maximum_msat: MAX_VALUE_MSAT,
4268 fee_proportional_millionths: 0,
4269 excess_data: Vec::new()
4272 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4273 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4274 short_channel_id: 6,
4277 cltv_expiry_delta: 0,
4278 htlc_minimum_msat: 0,
4279 htlc_maximum_msat: MAX_VALUE_MSAT,
4280 fee_base_msat: 150_000,
4281 fee_proportional_millionths: 0,
4282 excess_data: Vec::new()
4284 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4285 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4286 short_channel_id: 11,
4289 cltv_expiry_delta: 0,
4290 htlc_minimum_msat: 0,
4291 htlc_maximum_msat: MAX_VALUE_MSAT,
4293 fee_proportional_millionths: 0,
4294 excess_data: Vec::new()
4298 // Attempt to route more than available results in a failure.
4299 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4300 &our_id, &payment_params, &network_graph.read_only(), None, 210_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
4301 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4302 } else { panic!(); }
4306 // Now, attempt to route 200 sats (exact amount we can route).
4307 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 200_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4308 assert_eq!(route.paths.len(), 2);
4310 let mut total_amount_paid_msat = 0;
4311 for path in &route.paths {
4312 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
4313 total_amount_paid_msat += path.last().unwrap().fee_msat;
4315 assert_eq!(total_amount_paid_msat, 200_000);
4316 assert_eq!(route.get_total_fees(), 150_000);
4321 fn mpp_with_last_hops() {
4322 // Previously, if we tried to send an MPP payment to a destination which was only reachable
4323 // via a single last-hop route hint, we'd fail to route if we first collected routes
4324 // totaling close but not quite enough to fund the full payment.
4326 // This was because we considered last-hop hints to have exactly the sought payment amount
4327 // instead of the amount we were trying to collect, needlessly limiting our path searching
4328 // at the very first hop.
4330 // Specifically, this interacted with our "all paths must fund at least 5% of total target"
4331 // criterion to cause us to refuse all routes at the last hop hint which would be considered
4332 // to only have the remaining to-collect amount in available liquidity.
4334 // This bug appeared in production in some specific channel configurations.
4335 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4336 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4337 let scorer = ln_test_utils::TestScorer::with_penalty(0);
4338 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4339 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4340 let payment_params = PaymentParameters::from_node_id(PublicKey::from_slice(&[02; 33]).unwrap()).with_features(channelmanager::provided_invoice_features())
4341 .with_route_hints(vec![RouteHint(vec![RouteHintHop {
4342 src_node_id: nodes[2],
4343 short_channel_id: 42,
4344 fees: RoutingFees { base_msat: 0, proportional_millionths: 0 },
4345 cltv_expiry_delta: 42,
4346 htlc_minimum_msat: None,
4347 htlc_maximum_msat: None,
4348 }])]).with_max_channel_saturation_power_of_half(0);
4350 // Keep only two paths from us to nodes[2], both with a 99sat HTLC maximum, with one with
4351 // no fee and one with a 1msat fee. Previously, trying to route 100 sats to nodes[2] here
4352 // would first use the no-fee route and then fail to find a path along the second route as
4353 // we think we can only send up to 1 additional sat over the last-hop but refuse to as its
4354 // under 5% of our payment amount.
4355 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4356 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4357 short_channel_id: 1,
4360 cltv_expiry_delta: (5 << 4) | 5,
4361 htlc_minimum_msat: 0,
4362 htlc_maximum_msat: 99_000,
4363 fee_base_msat: u32::max_value(),
4364 fee_proportional_millionths: u32::max_value(),
4365 excess_data: Vec::new()
4367 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4368 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4369 short_channel_id: 2,
4372 cltv_expiry_delta: (5 << 4) | 3,
4373 htlc_minimum_msat: 0,
4374 htlc_maximum_msat: 99_000,
4375 fee_base_msat: u32::max_value(),
4376 fee_proportional_millionths: u32::max_value(),
4377 excess_data: Vec::new()
4379 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4380 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4381 short_channel_id: 4,
4384 cltv_expiry_delta: (4 << 4) | 1,
4385 htlc_minimum_msat: 0,
4386 htlc_maximum_msat: MAX_VALUE_MSAT,
4388 fee_proportional_millionths: 0,
4389 excess_data: Vec::new()
4391 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4392 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4393 short_channel_id: 13,
4395 flags: 0|2, // Channel disabled
4396 cltv_expiry_delta: (13 << 4) | 1,
4397 htlc_minimum_msat: 0,
4398 htlc_maximum_msat: MAX_VALUE_MSAT,
4400 fee_proportional_millionths: 2000000,
4401 excess_data: Vec::new()
4404 // Get a route for 100 sats and check that we found the MPP route no problem and didn't
4406 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();
4407 assert_eq!(route.paths.len(), 2);
4408 route.paths.sort_by_key(|path| path[0].short_channel_id);
4409 // Paths are manually ordered ordered by SCID, so:
4410 // * the first is channel 1 (0 fee, but 99 sat maximum) -> channel 3 -> channel 42
4411 // * the second is channel 2 (1 msat fee) -> channel 4 -> channel 42
4412 assert_eq!(route.paths[0][0].short_channel_id, 1);
4413 assert_eq!(route.paths[0][0].fee_msat, 0);
4414 assert_eq!(route.paths[0][2].fee_msat, 99_000);
4415 assert_eq!(route.paths[1][0].short_channel_id, 2);
4416 assert_eq!(route.paths[1][0].fee_msat, 1);
4417 assert_eq!(route.paths[1][2].fee_msat, 1_000);
4418 assert_eq!(route.get_total_fees(), 1);
4419 assert_eq!(route.get_total_amount(), 100_000);
4423 fn drop_lowest_channel_mpp_route_test() {
4424 // This test checks that low-capacity channel is dropped when after
4425 // path finding we realize that we found more capacity than we need.
4426 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4427 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4428 let scorer = ln_test_utils::TestScorer::with_penalty(0);
4429 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4430 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4431 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(channelmanager::provided_invoice_features())
4432 .with_max_channel_saturation_power_of_half(0);
4434 // We need a route consisting of 3 paths:
4435 // From our node to node2 via node0, node7, node1 (three paths one hop each).
4437 // The first and the second paths should be sufficient, but the third should be
4438 // cheaper, so that we select it but drop later.
4440 // First, we set limits on these (previously unlimited) channels.
4441 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
4443 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
4444 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4445 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4446 short_channel_id: 1,
4449 cltv_expiry_delta: 0,
4450 htlc_minimum_msat: 0,
4451 htlc_maximum_msat: 100_000,
4453 fee_proportional_millionths: 0,
4454 excess_data: Vec::new()
4456 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4457 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4458 short_channel_id: 3,
4461 cltv_expiry_delta: 0,
4462 htlc_minimum_msat: 0,
4463 htlc_maximum_msat: 50_000,
4465 fee_proportional_millionths: 0,
4466 excess_data: Vec::new()
4469 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
4470 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4471 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4472 short_channel_id: 12,
4475 cltv_expiry_delta: 0,
4476 htlc_minimum_msat: 0,
4477 htlc_maximum_msat: 60_000,
4479 fee_proportional_millionths: 0,
4480 excess_data: Vec::new()
4482 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4483 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4484 short_channel_id: 13,
4487 cltv_expiry_delta: 0,
4488 htlc_minimum_msat: 0,
4489 htlc_maximum_msat: 60_000,
4491 fee_proportional_millionths: 0,
4492 excess_data: Vec::new()
4495 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
4496 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4497 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4498 short_channel_id: 2,
4501 cltv_expiry_delta: 0,
4502 htlc_minimum_msat: 0,
4503 htlc_maximum_msat: 20_000,
4505 fee_proportional_millionths: 0,
4506 excess_data: Vec::new()
4508 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4509 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4510 short_channel_id: 4,
4513 cltv_expiry_delta: 0,
4514 htlc_minimum_msat: 0,
4515 htlc_maximum_msat: 20_000,
4517 fee_proportional_millionths: 0,
4518 excess_data: Vec::new()
4522 // Attempt to route more than available results in a failure.
4523 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4524 &our_id, &payment_params, &network_graph.read_only(), None, 150_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
4525 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4526 } else { panic!(); }
4530 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
4531 // Our algorithm should provide us with these 3 paths.
4532 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 125_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4533 assert_eq!(route.paths.len(), 3);
4534 let mut total_amount_paid_msat = 0;
4535 for path in &route.paths {
4536 assert_eq!(path.len(), 2);
4537 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4538 total_amount_paid_msat += path.last().unwrap().fee_msat;
4540 assert_eq!(total_amount_paid_msat, 125_000);
4544 // Attempt to route without the last small cheap channel
4545 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4546 assert_eq!(route.paths.len(), 2);
4547 let mut total_amount_paid_msat = 0;
4548 for path in &route.paths {
4549 assert_eq!(path.len(), 2);
4550 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4551 total_amount_paid_msat += path.last().unwrap().fee_msat;
4553 assert_eq!(total_amount_paid_msat, 90_000);
4558 fn min_criteria_consistency() {
4559 // Test that we don't use an inconsistent metric between updating and walking nodes during
4560 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
4561 // was updated with a different criterion from the heap sorting, resulting in loops in
4562 // calculated paths. We test for that specific case here.
4564 // We construct a network that looks like this:
4566 // node2 -1(3)2- node3
4570 // node1 -1(5)2- node4 -1(1)2- node6
4576 // We create a loop on the side of our real path - our destination is node 6, with a
4577 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
4578 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
4579 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
4580 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
4581 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
4582 // "previous hop" being set to node 3, creating a loop in the path.
4583 let secp_ctx = Secp256k1::new();
4584 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
4585 let logger = Arc::new(ln_test_utils::TestLogger::new());
4586 let network = Arc::new(NetworkGraph::new(genesis_hash, Arc::clone(&logger)));
4587 let gossip_sync = P2PGossipSync::new(Arc::clone(&network), None, Arc::clone(&logger));
4588 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4589 let scorer = ln_test_utils::TestScorer::with_penalty(0);
4590 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4591 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4592 let payment_params = PaymentParameters::from_node_id(nodes[6]);
4594 add_channel(&gossip_sync, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
4595 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4596 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4597 short_channel_id: 6,
4600 cltv_expiry_delta: (6 << 4) | 0,
4601 htlc_minimum_msat: 0,
4602 htlc_maximum_msat: MAX_VALUE_MSAT,
4604 fee_proportional_millionths: 0,
4605 excess_data: Vec::new()
4607 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
4609 add_channel(&gossip_sync, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4610 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4611 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4612 short_channel_id: 5,
4615 cltv_expiry_delta: (5 << 4) | 0,
4616 htlc_minimum_msat: 0,
4617 htlc_maximum_msat: MAX_VALUE_MSAT,
4619 fee_proportional_millionths: 0,
4620 excess_data: Vec::new()
4622 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
4624 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
4625 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4626 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4627 short_channel_id: 4,
4630 cltv_expiry_delta: (4 << 4) | 0,
4631 htlc_minimum_msat: 0,
4632 htlc_maximum_msat: MAX_VALUE_MSAT,
4634 fee_proportional_millionths: 0,
4635 excess_data: Vec::new()
4637 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
4639 add_channel(&gossip_sync, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
4640 update_channel(&gossip_sync, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
4641 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4642 short_channel_id: 3,
4645 cltv_expiry_delta: (3 << 4) | 0,
4646 htlc_minimum_msat: 0,
4647 htlc_maximum_msat: MAX_VALUE_MSAT,
4649 fee_proportional_millionths: 0,
4650 excess_data: Vec::new()
4652 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
4654 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
4655 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4656 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4657 short_channel_id: 2,
4660 cltv_expiry_delta: (2 << 4) | 0,
4661 htlc_minimum_msat: 0,
4662 htlc_maximum_msat: MAX_VALUE_MSAT,
4664 fee_proportional_millionths: 0,
4665 excess_data: Vec::new()
4668 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
4669 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4670 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4671 short_channel_id: 1,
4674 cltv_expiry_delta: (1 << 4) | 0,
4675 htlc_minimum_msat: 100,
4676 htlc_maximum_msat: MAX_VALUE_MSAT,
4678 fee_proportional_millionths: 0,
4679 excess_data: Vec::new()
4681 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
4684 // Now ensure the route flows simply over nodes 1 and 4 to 6.
4685 let route = get_route(&our_id, &payment_params, &network.read_only(), None, 10_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4686 assert_eq!(route.paths.len(), 1);
4687 assert_eq!(route.paths[0].len(), 3);
4689 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
4690 assert_eq!(route.paths[0][0].short_channel_id, 6);
4691 assert_eq!(route.paths[0][0].fee_msat, 100);
4692 assert_eq!(route.paths[0][0].cltv_expiry_delta, (5 << 4) | 0);
4693 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(1));
4694 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(6));
4696 assert_eq!(route.paths[0][1].pubkey, nodes[4]);
4697 assert_eq!(route.paths[0][1].short_channel_id, 5);
4698 assert_eq!(route.paths[0][1].fee_msat, 0);
4699 assert_eq!(route.paths[0][1].cltv_expiry_delta, (1 << 4) | 0);
4700 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(4));
4701 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(5));
4703 assert_eq!(route.paths[0][2].pubkey, nodes[6]);
4704 assert_eq!(route.paths[0][2].short_channel_id, 1);
4705 assert_eq!(route.paths[0][2].fee_msat, 10_000);
4706 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
4707 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
4708 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(1));
4714 fn exact_fee_liquidity_limit() {
4715 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
4716 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
4717 // we calculated fees on a higher value, resulting in us ignoring such paths.
4718 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4719 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
4720 let scorer = ln_test_utils::TestScorer::with_penalty(0);
4721 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4722 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4723 let payment_params = PaymentParameters::from_node_id(nodes[2]);
4725 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
4727 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4728 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4729 short_channel_id: 2,
4732 cltv_expiry_delta: 0,
4733 htlc_minimum_msat: 0,
4734 htlc_maximum_msat: 85_000,
4736 fee_proportional_millionths: 0,
4737 excess_data: Vec::new()
4740 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4741 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4742 short_channel_id: 12,
4745 cltv_expiry_delta: (4 << 4) | 1,
4746 htlc_minimum_msat: 0,
4747 htlc_maximum_msat: 270_000,
4749 fee_proportional_millionths: 1000000,
4750 excess_data: Vec::new()
4754 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
4755 // 200% fee charged channel 13 in the 1-to-2 direction.
4756 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4757 assert_eq!(route.paths.len(), 1);
4758 assert_eq!(route.paths[0].len(), 2);
4760 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
4761 assert_eq!(route.paths[0][0].short_channel_id, 12);
4762 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
4763 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
4764 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
4765 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
4767 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
4768 assert_eq!(route.paths[0][1].short_channel_id, 13);
4769 assert_eq!(route.paths[0][1].fee_msat, 90_000);
4770 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
4771 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
4772 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
4777 fn htlc_max_reduction_below_min() {
4778 // Test that if, while walking the graph, we reduce the value being sent to meet an
4779 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
4780 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
4781 // resulting in us thinking there is no possible path, even if other paths exist.
4782 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4783 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4784 let scorer = ln_test_utils::TestScorer::with_penalty(0);
4785 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4786 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4787 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(channelmanager::provided_invoice_features());
4789 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
4790 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
4791 // then try to send 90_000.
4792 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4793 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4794 short_channel_id: 2,
4797 cltv_expiry_delta: 0,
4798 htlc_minimum_msat: 0,
4799 htlc_maximum_msat: 80_000,
4801 fee_proportional_millionths: 0,
4802 excess_data: Vec::new()
4804 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4805 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4806 short_channel_id: 4,
4809 cltv_expiry_delta: (4 << 4) | 1,
4810 htlc_minimum_msat: 90_000,
4811 htlc_maximum_msat: MAX_VALUE_MSAT,
4813 fee_proportional_millionths: 0,
4814 excess_data: Vec::new()
4818 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
4819 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
4820 // expensive) channels 12-13 path.
4821 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4822 assert_eq!(route.paths.len(), 1);
4823 assert_eq!(route.paths[0].len(), 2);
4825 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
4826 assert_eq!(route.paths[0][0].short_channel_id, 12);
4827 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
4828 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
4829 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
4830 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
4832 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
4833 assert_eq!(route.paths[0][1].short_channel_id, 13);
4834 assert_eq!(route.paths[0][1].fee_msat, 90_000);
4835 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
4836 assert_eq!(route.paths[0][1].node_features.le_flags(), channelmanager::provided_invoice_features().le_flags());
4837 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
4842 fn multiple_direct_first_hops() {
4843 // Previously we'd only ever considered one first hop path per counterparty.
4844 // However, as we don't restrict users to one channel per peer, we really need to support
4845 // looking at all first hop paths.
4846 // Here we test that we do not ignore all-but-the-last first hop paths per counterparty (as
4847 // we used to do by overwriting the `first_hop_targets` hashmap entry) and that we can MPP
4848 // route over multiple channels with the same first hop.
4849 let secp_ctx = Secp256k1::new();
4850 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4851 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
4852 let logger = Arc::new(ln_test_utils::TestLogger::new());
4853 let network_graph = NetworkGraph::new(genesis_hash, Arc::clone(&logger));
4854 let scorer = ln_test_utils::TestScorer::with_penalty(0);
4855 let payment_params = PaymentParameters::from_node_id(nodes[0]).with_features(channelmanager::provided_invoice_features());
4856 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4857 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4860 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
4861 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(), 200_000),
4862 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(), 10_000),
4863 ]), 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4864 assert_eq!(route.paths.len(), 1);
4865 assert_eq!(route.paths[0].len(), 1);
4867 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
4868 assert_eq!(route.paths[0][0].short_channel_id, 3);
4869 assert_eq!(route.paths[0][0].fee_msat, 100_000);
4872 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
4873 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(), 50_000),
4874 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(), 50_000),
4875 ]), 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4876 assert_eq!(route.paths.len(), 2);
4877 assert_eq!(route.paths[0].len(), 1);
4878 assert_eq!(route.paths[1].len(), 1);
4880 assert!((route.paths[0][0].short_channel_id == 3 && route.paths[1][0].short_channel_id == 2) ||
4881 (route.paths[0][0].short_channel_id == 2 && route.paths[1][0].short_channel_id == 3));
4883 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
4884 assert_eq!(route.paths[0][0].fee_msat, 50_000);
4886 assert_eq!(route.paths[1][0].pubkey, nodes[0]);
4887 assert_eq!(route.paths[1][0].fee_msat, 50_000);
4891 // If we have a bunch of outbound channels to the same node, where most are not
4892 // sufficient to pay the full payment, but one is, we should default to just using the
4893 // one single channel that has sufficient balance, avoiding MPP.
4895 // If we have several options above the 3xpayment value threshold, we should pick the
4896 // smallest of them, avoiding further fragmenting our available outbound balance to
4898 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
4899 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(), 50_000),
4900 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(), 50_000),
4901 &get_channel_details(Some(5), nodes[0], channelmanager::provided_init_features(), 50_000),
4902 &get_channel_details(Some(6), nodes[0], channelmanager::provided_init_features(), 300_000),
4903 &get_channel_details(Some(7), nodes[0], channelmanager::provided_init_features(), 50_000),
4904 &get_channel_details(Some(8), nodes[0], channelmanager::provided_init_features(), 50_000),
4905 &get_channel_details(Some(9), nodes[0], channelmanager::provided_init_features(), 50_000),
4906 &get_channel_details(Some(4), nodes[0], channelmanager::provided_init_features(), 1_000_000),
4907 ]), 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4908 assert_eq!(route.paths.len(), 1);
4909 assert_eq!(route.paths[0].len(), 1);
4911 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
4912 assert_eq!(route.paths[0][0].short_channel_id, 6);
4913 assert_eq!(route.paths[0][0].fee_msat, 100_000);
4918 fn prefers_shorter_route_with_higher_fees() {
4919 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4920 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4921 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
4923 // Without penalizing each hop 100 msats, a longer path with lower fees is chosen.
4924 let scorer = ln_test_utils::TestScorer::with_penalty(0);
4925 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4926 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4927 let route = get_route(
4928 &our_id, &payment_params, &network_graph.read_only(), None, 100, 42,
4929 Arc::clone(&logger), &scorer, &random_seed_bytes
4931 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4933 assert_eq!(route.get_total_fees(), 100);
4934 assert_eq!(route.get_total_amount(), 100);
4935 assert_eq!(path, vec![2, 4, 6, 11, 8]);
4937 // Applying a 100 msat penalty to each hop results in taking channels 7 and 10 to nodes[6]
4938 // from nodes[2] rather than channel 6, 11, and 8, even though the longer path is cheaper.
4939 let scorer = ln_test_utils::TestScorer::with_penalty(100);
4940 let route = get_route(
4941 &our_id, &payment_params, &network_graph.read_only(), None, 100, 42,
4942 Arc::clone(&logger), &scorer, &random_seed_bytes
4944 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4946 assert_eq!(route.get_total_fees(), 300);
4947 assert_eq!(route.get_total_amount(), 100);
4948 assert_eq!(path, vec![2, 4, 7, 10]);
4951 struct BadChannelScorer {
4952 short_channel_id: u64,
4956 impl Writeable for BadChannelScorer {
4957 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
4959 impl Score for BadChannelScorer {
4960 fn channel_penalty_msat(&self, short_channel_id: u64, _: &NodeId, _: &NodeId, _: ChannelUsage) -> u64 {
4961 if short_channel_id == self.short_channel_id { u64::max_value() } else { 0 }
4964 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
4965 fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
4966 fn probe_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
4967 fn probe_successful(&mut self, _path: &[&RouteHop]) {}
4970 struct BadNodeScorer {
4975 impl Writeable for BadNodeScorer {
4976 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
4979 impl Score for BadNodeScorer {
4980 fn channel_penalty_msat(&self, _: u64, _: &NodeId, target: &NodeId, _: ChannelUsage) -> u64 {
4981 if *target == self.node_id { u64::max_value() } else { 0 }
4984 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
4985 fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
4986 fn probe_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
4987 fn probe_successful(&mut self, _path: &[&RouteHop]) {}
4991 fn avoids_routing_through_bad_channels_and_nodes() {
4992 let (secp_ctx, network, _, _, logger) = build_graph();
4993 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4994 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
4995 let network_graph = network.read_only();
4997 // A path to nodes[6] exists when no penalties are applied to any channel.
4998 let scorer = ln_test_utils::TestScorer::with_penalty(0);
4999 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5000 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5001 let route = get_route(
5002 &our_id, &payment_params, &network_graph, None, 100, 42,
5003 Arc::clone(&logger), &scorer, &random_seed_bytes
5005 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5007 assert_eq!(route.get_total_fees(), 100);
5008 assert_eq!(route.get_total_amount(), 100);
5009 assert_eq!(path, vec![2, 4, 6, 11, 8]);
5011 // A different path to nodes[6] exists if channel 6 cannot be routed over.
5012 let scorer = BadChannelScorer { short_channel_id: 6 };
5013 let route = get_route(
5014 &our_id, &payment_params, &network_graph, None, 100, 42,
5015 Arc::clone(&logger), &scorer, &random_seed_bytes
5017 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5019 assert_eq!(route.get_total_fees(), 300);
5020 assert_eq!(route.get_total_amount(), 100);
5021 assert_eq!(path, vec![2, 4, 7, 10]);
5023 // A path to nodes[6] does not exist if nodes[2] cannot be routed through.
5024 let scorer = BadNodeScorer { node_id: NodeId::from_pubkey(&nodes[2]) };
5026 &our_id, &payment_params, &network_graph, None, 100, 42,
5027 Arc::clone(&logger), &scorer, &random_seed_bytes
5029 Err(LightningError { err, .. } ) => {
5030 assert_eq!(err, "Failed to find a path to the given destination");
5032 Ok(_) => panic!("Expected error"),
5037 fn total_fees_single_path() {
5041 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5042 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5043 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5046 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5047 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5048 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5051 pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
5052 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5053 short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0
5056 payment_params: None,
5059 assert_eq!(route.get_total_fees(), 250);
5060 assert_eq!(route.get_total_amount(), 225);
5064 fn total_fees_multi_path() {
5068 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5069 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5070 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5073 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5074 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5075 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5079 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5080 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5081 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5084 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5085 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5086 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5089 payment_params: None,
5092 assert_eq!(route.get_total_fees(), 200);
5093 assert_eq!(route.get_total_amount(), 300);
5097 fn total_empty_route_no_panic() {
5098 // In an earlier version of `Route::get_total_fees` and `Route::get_total_amount`, they
5099 // would both panic if the route was completely empty. We test to ensure they return 0
5100 // here, even though its somewhat nonsensical as a route.
5101 let route = Route { paths: Vec::new(), payment_params: None };
5103 assert_eq!(route.get_total_fees(), 0);
5104 assert_eq!(route.get_total_amount(), 0);
5108 fn limits_total_cltv_delta() {
5109 let (secp_ctx, network, _, _, logger) = build_graph();
5110 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5111 let network_graph = network.read_only();
5113 let scorer = ln_test_utils::TestScorer::with_penalty(0);
5115 // Make sure that generally there is at least one route available
5116 let feasible_max_total_cltv_delta = 1008;
5117 let feasible_payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes))
5118 .with_max_total_cltv_expiry_delta(feasible_max_total_cltv_delta);
5119 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5120 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5121 let route = get_route(&our_id, &feasible_payment_params, &network_graph, None, 100, 0, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5122 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5123 assert_ne!(path.len(), 0);
5125 // But not if we exclude all paths on the basis of their accumulated CLTV delta
5126 let fail_max_total_cltv_delta = 23;
5127 let fail_payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes))
5128 .with_max_total_cltv_expiry_delta(fail_max_total_cltv_delta);
5129 match get_route(&our_id, &fail_payment_params, &network_graph, None, 100, 0, Arc::clone(&logger), &scorer, &random_seed_bytes)
5131 Err(LightningError { err, .. } ) => {
5132 assert_eq!(err, "Failed to find a path to the given destination");
5134 Ok(_) => panic!("Expected error"),
5139 fn avoids_recently_failed_paths() {
5140 // Ensure that the router always avoids all of the `previously_failed_channels` channels by
5141 // randomly inserting channels into it until we can't find a route anymore.
5142 let (secp_ctx, network, _, _, logger) = build_graph();
5143 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5144 let network_graph = network.read_only();
5146 let scorer = ln_test_utils::TestScorer::with_penalty(0);
5147 let mut payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes))
5148 .with_max_path_count(1);
5149 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5150 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5152 // We should be able to find a route initially, and then after we fail a few random
5153 // channels eventually we won't be able to any longer.
5154 assert!(get_route(&our_id, &payment_params, &network_graph, None, 100, 0, Arc::clone(&logger), &scorer, &random_seed_bytes).is_ok());
5156 if let Ok(route) = get_route(&our_id, &payment_params, &network_graph, None, 100, 0, Arc::clone(&logger), &scorer, &random_seed_bytes) {
5157 for chan in route.paths[0].iter() {
5158 assert!(!payment_params.previously_failed_channels.contains(&chan.short_channel_id));
5160 let victim = (u64::from_ne_bytes(random_seed_bytes[0..8].try_into().unwrap()) as usize)
5161 % route.paths[0].len();
5162 payment_params.previously_failed_channels.push(route.paths[0][victim].short_channel_id);
5168 fn limits_path_length() {
5169 let (secp_ctx, network, _, _, logger) = build_line_graph();
5170 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5171 let network_graph = network.read_only();
5173 let scorer = ln_test_utils::TestScorer::with_penalty(0);
5174 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5175 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5177 // First check we can actually create a long route on this graph.
5178 let feasible_payment_params = PaymentParameters::from_node_id(nodes[18]);
5179 let route = get_route(&our_id, &feasible_payment_params, &network_graph, None, 100, 0,
5180 Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5181 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5182 assert!(path.len() == MAX_PATH_LENGTH_ESTIMATE.into());
5184 // But we can't create a path surpassing the MAX_PATH_LENGTH_ESTIMATE limit.
5185 let fail_payment_params = PaymentParameters::from_node_id(nodes[19]);
5186 match get_route(&our_id, &fail_payment_params, &network_graph, None, 100, 0,
5187 Arc::clone(&logger), &scorer, &random_seed_bytes)
5189 Err(LightningError { err, .. } ) => {
5190 assert_eq!(err, "Failed to find a path to the given destination");
5192 Ok(_) => panic!("Expected error"),
5197 fn adds_and_limits_cltv_offset() {
5198 let (secp_ctx, network_graph, _, _, logger) = build_graph();
5199 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5201 let scorer = ln_test_utils::TestScorer::with_penalty(0);
5203 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
5204 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5205 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5206 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5207 assert_eq!(route.paths.len(), 1);
5209 let cltv_expiry_deltas_before = route.paths[0].iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5211 // Check whether the offset added to the last hop by default is in [1 .. DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA]
5212 let mut route_default = route.clone();
5213 add_random_cltv_offset(&mut route_default, &payment_params, &network_graph.read_only(), &random_seed_bytes);
5214 let cltv_expiry_deltas_default = route_default.paths[0].iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5215 assert_eq!(cltv_expiry_deltas_before.split_last().unwrap().1, cltv_expiry_deltas_default.split_last().unwrap().1);
5216 assert!(cltv_expiry_deltas_default.last() > cltv_expiry_deltas_before.last());
5217 assert!(cltv_expiry_deltas_default.last().unwrap() <= &DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA);
5219 // Check that no offset is added when we restrict the max_total_cltv_expiry_delta
5220 let mut route_limited = route.clone();
5221 let limited_max_total_cltv_expiry_delta = cltv_expiry_deltas_before.iter().sum();
5222 let limited_payment_params = payment_params.with_max_total_cltv_expiry_delta(limited_max_total_cltv_expiry_delta);
5223 add_random_cltv_offset(&mut route_limited, &limited_payment_params, &network_graph.read_only(), &random_seed_bytes);
5224 let cltv_expiry_deltas_limited = route_limited.paths[0].iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5225 assert_eq!(cltv_expiry_deltas_before, cltv_expiry_deltas_limited);
5229 fn adds_plausible_cltv_offset() {
5230 let (secp_ctx, network, _, _, logger) = build_graph();
5231 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5232 let network_graph = network.read_only();
5233 let network_nodes = network_graph.nodes();
5234 let network_channels = network_graph.channels();
5235 let scorer = ln_test_utils::TestScorer::with_penalty(0);
5236 let payment_params = PaymentParameters::from_node_id(nodes[3]);
5237 let keys_manager = ln_test_utils::TestKeysInterface::new(&[4u8; 32], Network::Testnet);
5238 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5240 let mut route = get_route(&our_id, &payment_params, &network_graph, None, 100, 0,
5241 Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5242 add_random_cltv_offset(&mut route, &payment_params, &network_graph, &random_seed_bytes);
5244 let mut path_plausibility = vec![];
5246 for p in route.paths {
5247 // 1. Select random observation point
5248 let mut prng = ChaCha20::new(&random_seed_bytes, &[0u8; 12]);
5249 let mut random_bytes = [0u8; ::core::mem::size_of::<usize>()];
5251 prng.process_in_place(&mut random_bytes);
5252 let random_path_index = usize::from_be_bytes(random_bytes).wrapping_rem(p.len());
5253 let observation_point = NodeId::from_pubkey(&p.get(random_path_index).unwrap().pubkey);
5255 // 2. Calculate what CLTV expiry delta we would observe there
5256 let observed_cltv_expiry_delta: u32 = p[random_path_index..].iter().map(|h| h.cltv_expiry_delta).sum();
5258 // 3. Starting from the observation point, find candidate paths
5259 let mut candidates: VecDeque<(NodeId, Vec<u32>)> = VecDeque::new();
5260 candidates.push_back((observation_point, vec![]));
5262 let mut found_plausible_candidate = false;
5264 'candidate_loop: while let Some((cur_node_id, cur_path_cltv_deltas)) = candidates.pop_front() {
5265 if let Some(remaining) = observed_cltv_expiry_delta.checked_sub(cur_path_cltv_deltas.iter().sum::<u32>()) {
5266 if remaining == 0 || remaining.wrapping_rem(40) == 0 || remaining.wrapping_rem(144) == 0 {
5267 found_plausible_candidate = true;
5268 break 'candidate_loop;
5272 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
5273 for channel_id in &cur_node.channels {
5274 if let Some(channel_info) = network_channels.get(&channel_id) {
5275 if let Some((dir_info, next_id)) = channel_info.as_directed_from(&cur_node_id) {
5276 let next_cltv_expiry_delta = dir_info.direction().cltv_expiry_delta as u32;
5277 if cur_path_cltv_deltas.iter().sum::<u32>()
5278 .saturating_add(next_cltv_expiry_delta) <= observed_cltv_expiry_delta {
5279 let mut new_path_cltv_deltas = cur_path_cltv_deltas.clone();
5280 new_path_cltv_deltas.push(next_cltv_expiry_delta);
5281 candidates.push_back((*next_id, new_path_cltv_deltas));
5289 path_plausibility.push(found_plausible_candidate);
5291 assert!(path_plausibility.iter().all(|x| *x));
5295 fn builds_correct_path_from_hops() {
5296 let (secp_ctx, network, _, _, logger) = build_graph();
5297 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5298 let network_graph = network.read_only();
5300 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5301 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5303 let payment_params = PaymentParameters::from_node_id(nodes[3]);
5304 let hops = [nodes[1], nodes[2], nodes[4], nodes[3]];
5305 let route = build_route_from_hops_internal(&our_id, &hops, &payment_params,
5306 &network_graph, 100, 0, Arc::clone(&logger), &random_seed_bytes).unwrap();
5307 let route_hop_pubkeys = route.paths[0].iter().map(|hop| hop.pubkey).collect::<Vec<_>>();
5308 assert_eq!(hops.len(), route.paths[0].len());
5309 for (idx, hop_pubkey) in hops.iter().enumerate() {
5310 assert!(*hop_pubkey == route_hop_pubkeys[idx]);
5315 fn avoids_saturating_channels() {
5316 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5317 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5319 let scorer = ProbabilisticScorer::new(Default::default(), &*network_graph, Arc::clone(&logger));
5321 // Set the fee on channel 13 to 100% to match channel 4 giving us two equivalent paths (us
5322 // -> node 7 -> node2 and us -> node 1 -> node 2) which we should balance over.
5323 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5324 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5325 short_channel_id: 4,
5328 cltv_expiry_delta: (4 << 4) | 1,
5329 htlc_minimum_msat: 0,
5330 htlc_maximum_msat: 250_000_000,
5332 fee_proportional_millionths: 0,
5333 excess_data: Vec::new()
5335 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5336 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5337 short_channel_id: 13,
5340 cltv_expiry_delta: (13 << 4) | 1,
5341 htlc_minimum_msat: 0,
5342 htlc_maximum_msat: 250_000_000,
5344 fee_proportional_millionths: 0,
5345 excess_data: Vec::new()
5348 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(channelmanager::provided_invoice_features());
5349 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5350 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5351 // 100,000 sats is less than the available liquidity on each channel, set above.
5352 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();
5353 assert_eq!(route.paths.len(), 2);
5354 assert!((route.paths[0][1].short_channel_id == 4 && route.paths[1][1].short_channel_id == 13) ||
5355 (route.paths[1][1].short_channel_id == 4 && route.paths[0][1].short_channel_id == 13));
5358 #[cfg(not(feature = "no-std"))]
5359 pub(super) fn random_init_seed() -> u64 {
5360 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
5361 use core::hash::{BuildHasher, Hasher};
5362 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
5363 println!("Using seed of {}", seed);
5366 #[cfg(not(feature = "no-std"))]
5367 use crate::util::ser::ReadableArgs;
5370 #[cfg(not(feature = "no-std"))]
5371 fn generate_routes() {
5372 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringParameters};
5374 let mut d = match super::bench_utils::get_route_file() {
5381 let logger = ln_test_utils::TestLogger::new();
5382 let graph = NetworkGraph::read(&mut d, &logger).unwrap();
5383 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5384 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5386 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
5387 let mut seed = random_init_seed() as usize;
5388 let nodes = graph.read_only().nodes().clone();
5389 'load_endpoints: for _ in 0..10 {
5391 seed = seed.overflowing_mul(0xdeadbeef).0;
5392 let src = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5393 seed = seed.overflowing_mul(0xdeadbeef).0;
5394 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5395 let payment_params = PaymentParameters::from_node_id(dst);
5396 let amt = seed as u64 % 200_000_000;
5397 let params = ProbabilisticScoringParameters::default();
5398 let scorer = ProbabilisticScorer::new(params, &graph, &logger);
5399 if get_route(src, &payment_params, &graph.read_only(), None, amt, 42, &logger, &scorer, &random_seed_bytes).is_ok() {
5400 continue 'load_endpoints;
5407 #[cfg(not(feature = "no-std"))]
5408 fn generate_routes_mpp() {
5409 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringParameters};
5411 let mut d = match super::bench_utils::get_route_file() {
5418 let logger = ln_test_utils::TestLogger::new();
5419 let graph = NetworkGraph::read(&mut d, &logger).unwrap();
5420 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5421 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5423 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
5424 let mut seed = random_init_seed() as usize;
5425 let nodes = graph.read_only().nodes().clone();
5426 'load_endpoints: for _ in 0..10 {
5428 seed = seed.overflowing_mul(0xdeadbeef).0;
5429 let src = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5430 seed = seed.overflowing_mul(0xdeadbeef).0;
5431 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5432 let payment_params = PaymentParameters::from_node_id(dst).with_features(channelmanager::provided_invoice_features());
5433 let amt = seed as u64 % 200_000_000;
5434 let params = ProbabilisticScoringParameters::default();
5435 let scorer = ProbabilisticScorer::new(params, &graph, &logger);
5436 if get_route(src, &payment_params, &graph.read_only(), None, amt, 42, &logger, &scorer, &random_seed_bytes).is_ok() {
5437 continue 'load_endpoints;
5444 fn honors_manual_penalties() {
5445 let (secp_ctx, network_graph, _, _, logger) = build_line_graph();
5446 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5448 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5449 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5451 let scorer_params = ProbabilisticScoringParameters::default();
5452 let mut scorer = ProbabilisticScorer::new(scorer_params, Arc::clone(&network_graph), Arc::clone(&logger));
5454 // First check set manual penalties are returned by the scorer.
5455 let usage = ChannelUsage {
5457 inflight_htlc_msat: 0,
5458 effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_024_000, htlc_maximum_msat: 1_000 },
5460 scorer.set_manual_penalty(&NodeId::from_pubkey(&nodes[3]), 123);
5461 scorer.set_manual_penalty(&NodeId::from_pubkey(&nodes[4]), 456);
5462 assert_eq!(scorer.channel_penalty_msat(42, &NodeId::from_pubkey(&nodes[3]), &NodeId::from_pubkey(&nodes[4]), usage), 456);
5464 // Then check we can get a normal route
5465 let payment_params = PaymentParameters::from_node_id(nodes[10]);
5466 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes);
5467 assert!(route.is_ok());
5469 // Then check that we can't get a route if we ban an intermediate node.
5470 scorer.add_banned(&NodeId::from_pubkey(&nodes[3]));
5471 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes);
5472 assert!(route.is_err());
5474 // Finally make sure we can route again, when we remove the ban.
5475 scorer.remove_banned(&NodeId::from_pubkey(&nodes[3]));
5476 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes);
5477 assert!(route.is_ok());
5481 #[cfg(all(test, not(feature = "no-std")))]
5482 pub(crate) mod bench_utils {
5484 /// Tries to open a network graph file, or panics with a URL to fetch it.
5485 pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
5486 let res = File::open("net_graph-2021-05-31.bin") // By default we're run in RL/lightning
5487 .or_else(|_| File::open("lightning/net_graph-2021-05-31.bin")) // We may be run manually in RL/
5488 .or_else(|_| { // Fall back to guessing based on the binary location
5489 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
5490 let mut path = std::env::current_exe().unwrap();
5491 path.pop(); // lightning-...
5493 path.pop(); // debug
5494 path.pop(); // target
5495 path.push("lightning");
5496 path.push("net_graph-2021-05-31.bin");
5497 eprintln!("{}", path.to_str().unwrap());
5500 .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");
5501 #[cfg(require_route_graph_test)]
5502 return Ok(res.unwrap());
5503 #[cfg(not(require_route_graph_test))]
5508 #[cfg(all(test, feature = "_bench_unstable", not(feature = "no-std")))]
5511 use bitcoin::hashes::Hash;
5512 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
5513 use crate::chain::transaction::OutPoint;
5514 use crate::chain::keysinterface::{KeysManager,KeysInterface};
5515 use crate::ln::channelmanager::{self, ChannelCounterparty, ChannelDetails};
5516 use crate::ln::features::InvoiceFeatures;
5517 use crate::routing::gossip::NetworkGraph;
5518 use crate::routing::scoring::{FixedPenaltyScorer, ProbabilisticScorer, ProbabilisticScoringParameters};
5519 use crate::util::logger::{Logger, Record};
5520 use crate::util::ser::ReadableArgs;
5524 struct DummyLogger {}
5525 impl Logger for DummyLogger {
5526 fn log(&self, _record: &Record) {}
5529 fn read_network_graph(logger: &DummyLogger) -> NetworkGraph<&DummyLogger> {
5530 let mut d = bench_utils::get_route_file().unwrap();
5531 NetworkGraph::read(&mut d, logger).unwrap()
5534 fn payer_pubkey() -> PublicKey {
5535 let secp_ctx = Secp256k1::new();
5536 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
5540 fn first_hop(node_id: PublicKey) -> ChannelDetails {
5542 channel_id: [0; 32],
5543 counterparty: ChannelCounterparty {
5544 features: channelmanager::provided_init_features(),
5546 unspendable_punishment_reserve: 0,
5547 forwarding_info: None,
5548 outbound_htlc_minimum_msat: None,
5549 outbound_htlc_maximum_msat: None,
5551 funding_txo: Some(OutPoint {
5552 txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0
5555 short_channel_id: Some(1),
5556 inbound_scid_alias: None,
5557 outbound_scid_alias: None,
5558 channel_value_satoshis: 10_000_000,
5560 balance_msat: 10_000_000,
5561 outbound_capacity_msat: 10_000_000,
5562 next_outbound_htlc_limit_msat: 10_000_000,
5563 inbound_capacity_msat: 0,
5564 unspendable_punishment_reserve: None,
5565 confirmations_required: None,
5566 confirmations: None,
5567 force_close_spend_delay: None,
5569 is_channel_ready: true,
5572 inbound_htlc_minimum_msat: None,
5573 inbound_htlc_maximum_msat: None,
5579 fn generate_routes_with_zero_penalty_scorer(bench: &mut Bencher) {
5580 let logger = DummyLogger {};
5581 let network_graph = read_network_graph(&logger);
5582 let scorer = FixedPenaltyScorer::with_penalty(0);
5583 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::empty());
5587 fn generate_mpp_routes_with_zero_penalty_scorer(bench: &mut Bencher) {
5588 let logger = DummyLogger {};
5589 let network_graph = read_network_graph(&logger);
5590 let scorer = FixedPenaltyScorer::with_penalty(0);
5591 generate_routes(bench, &network_graph, scorer, channelmanager::provided_invoice_features());
5595 fn generate_routes_with_probabilistic_scorer(bench: &mut Bencher) {
5596 let logger = DummyLogger {};
5597 let network_graph = read_network_graph(&logger);
5598 let params = ProbabilisticScoringParameters::default();
5599 let scorer = ProbabilisticScorer::new(params, &network_graph, &logger);
5600 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::empty());
5604 fn generate_mpp_routes_with_probabilistic_scorer(bench: &mut Bencher) {
5605 let logger = DummyLogger {};
5606 let network_graph = read_network_graph(&logger);
5607 let params = ProbabilisticScoringParameters::default();
5608 let scorer = ProbabilisticScorer::new(params, &network_graph, &logger);
5609 generate_routes(bench, &network_graph, scorer, channelmanager::provided_invoice_features());
5612 fn generate_routes<S: Score>(
5613 bench: &mut Bencher, graph: &NetworkGraph<&DummyLogger>, mut scorer: S,
5614 features: InvoiceFeatures
5616 let nodes = graph.read_only().nodes().clone();
5617 let payer = payer_pubkey();
5618 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
5619 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5621 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
5622 let mut routes = Vec::new();
5623 let mut route_endpoints = Vec::new();
5624 let mut seed: usize = 0xdeadbeef;
5625 'load_endpoints: for _ in 0..150 {
5628 let src = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5630 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5631 let params = PaymentParameters::from_node_id(dst).with_features(features.clone());
5632 let first_hop = first_hop(src);
5633 let amt = seed as u64 % 1_000_000;
5634 if let Ok(route) = get_route(&payer, ¶ms, &graph.read_only(), Some(&[&first_hop]), amt, 42, &DummyLogger{}, &scorer, &random_seed_bytes) {
5636 route_endpoints.push((first_hop, params, amt));
5637 continue 'load_endpoints;
5642 // ...and seed the scorer with success and failure data...
5643 for route in routes {
5644 let amount = route.get_total_amount();
5645 if amount < 250_000 {
5646 for path in route.paths {
5647 scorer.payment_path_successful(&path.iter().collect::<Vec<_>>());
5649 } else if amount > 750_000 {
5650 for path in route.paths {
5651 let short_channel_id = path[path.len() / 2].short_channel_id;
5652 scorer.payment_path_failed(&path.iter().collect::<Vec<_>>(), short_channel_id);
5657 // Because we've changed channel scores, its possible we'll take different routes to the
5658 // selected destinations, possibly causing us to fail because, eg, the newly-selected path
5659 // requires a too-high CLTV delta.
5660 route_endpoints.retain(|(first_hop, params, amt)| {
5661 get_route(&payer, params, &graph.read_only(), Some(&[first_hop]), *amt, 42, &DummyLogger{}, &scorer, &random_seed_bytes).is_ok()
5663 route_endpoints.truncate(100);
5664 assert_eq!(route_endpoints.len(), 100);
5666 // ...then benchmark finding paths between the nodes we learned.
5669 let (first_hop, params, amt) = &route_endpoints[idx % route_endpoints.len()];
5670 assert!(get_route(&payer, params, &graph.read_only(), Some(&[first_hop]), *amt, 42, &DummyLogger{}, &scorer, &random_seed_bytes).is_ok());