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::{DirectedChannelInfoWithUpdate, 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;
33 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
35 /// The node_id of the node at this hop.
36 pub pubkey: PublicKey,
37 /// The node_announcement features of the node at this hop. For the last hop, these may be
38 /// amended to match the features present in the invoice this node generated.
39 pub node_features: NodeFeatures,
40 /// The channel that should be used from the previous hop to reach this node.
41 pub short_channel_id: u64,
42 /// The channel_announcement features of the channel that should be used from the previous hop
43 /// to reach this node.
44 pub channel_features: ChannelFeatures,
45 /// The fee taken on this hop (for paying for the use of the *next* channel in the path).
46 /// For the last hop, this should be the full value of the payment (might be more than
47 /// requested if we had to match htlc_minimum_msat).
49 /// The CLTV delta added for this hop. For the last hop, this should be the full CLTV value
50 /// expected at the destination, in excess of the current block height.
51 pub cltv_expiry_delta: u32,
54 impl_writeable_tlv_based!(RouteHop, {
55 (0, pubkey, required),
56 (2, node_features, required),
57 (4, short_channel_id, required),
58 (6, channel_features, required),
59 (8, fee_msat, required),
60 (10, cltv_expiry_delta, required),
63 /// A route directs a payment from the sender (us) to the recipient. If the recipient supports MPP,
64 /// it can take multiple paths. Each path is composed of one or more hops through the network.
65 #[derive(Clone, Hash, PartialEq, Eq)]
67 /// The list of routes taken for a single (potentially-)multi-part payment. The pubkey of the
68 /// last RouteHop in each path must be the same. Each entry represents a list of hops, NOT
69 /// INCLUDING our own, where the last hop is the destination. Thus, this must always be at
70 /// least length one. While the maximum length of any given path is variable, keeping the length
71 /// of any path less or equal to 19 should currently ensure it is viable.
72 pub paths: Vec<Vec<RouteHop>>,
73 /// The `payment_params` parameter passed to [`find_route`].
74 /// This is used by `ChannelManager` to track information which may be required for retries,
75 /// provided back to you via [`Event::PaymentPathFailed`].
77 /// [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed
78 pub payment_params: Option<PaymentParameters>,
81 pub(crate) trait RoutePath {
82 /// Gets the fees for a given path, excluding any excess paid to the recipient.
83 fn get_path_fees(&self) -> u64;
85 impl RoutePath for Vec<RouteHop> {
86 fn get_path_fees(&self) -> u64 {
87 // Do not count last hop of each path since that's the full value of the payment
88 self.split_last().map(|(_, path_prefix)| path_prefix).unwrap_or(&[])
89 .iter().map(|hop| &hop.fee_msat)
95 /// Returns the total amount of fees paid on this [`Route`].
97 /// This doesn't include any extra payment made to the recipient, which can happen in excess of
98 /// the amount passed to [`find_route`]'s `params.final_value_msat`.
99 pub fn get_total_fees(&self) -> u64 {
100 self.paths.iter().map(|path| path.get_path_fees()).sum()
103 /// Returns the total amount paid on this [`Route`], excluding the fees.
104 pub fn get_total_amount(&self) -> u64 {
105 return self.paths.iter()
106 .map(|path| path.split_last().map(|(hop, _)| hop.fee_msat).unwrap_or(0))
111 const SERIALIZATION_VERSION: u8 = 1;
112 const MIN_SERIALIZATION_VERSION: u8 = 1;
114 impl Writeable for Route {
115 fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
116 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
117 (self.paths.len() as u64).write(writer)?;
118 for hops in self.paths.iter() {
119 (hops.len() as u8).write(writer)?;
120 for hop in hops.iter() {
124 write_tlv_fields!(writer, {
125 (1, self.payment_params, option),
131 impl Readable for Route {
132 fn read<R: io::Read>(reader: &mut R) -> Result<Route, DecodeError> {
133 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
134 let path_count: u64 = Readable::read(reader)?;
135 let mut paths = Vec::with_capacity(cmp::min(path_count, 128) as usize);
136 for _ in 0..path_count {
137 let hop_count: u8 = Readable::read(reader)?;
138 let mut hops = Vec::with_capacity(hop_count as usize);
139 for _ in 0..hop_count {
140 hops.push(Readable::read(reader)?);
144 let mut payment_params = None;
145 read_tlv_fields!(reader, {
146 (1, payment_params, option),
148 Ok(Route { paths, payment_params })
152 /// Parameters needed to find a [`Route`].
154 /// Passed to [`find_route`] and [`build_route_from_hops`], but also provided in
155 /// [`Event::PaymentPathFailed`] for retrying a failed payment path.
157 /// [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed
158 #[derive(Clone, Debug)]
159 pub struct RouteParameters {
160 /// The parameters of the failed payment path.
161 pub payment_params: PaymentParameters,
163 /// The amount in msats sent on the failed payment path.
164 pub final_value_msat: u64,
166 /// The CLTV on the final hop of the failed payment path.
167 pub final_cltv_expiry_delta: u32,
170 impl_writeable_tlv_based!(RouteParameters, {
171 (0, payment_params, required),
172 (2, final_value_msat, required),
173 (4, final_cltv_expiry_delta, required),
176 /// Maximum total CTLV difference we allow for a full payment path.
177 pub const DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA: u32 = 1008;
179 /// Maximum number of paths we allow an (MPP) payment to have.
180 // The default limit is currently set rather arbitrary - there aren't any real fundamental path-count
181 // limits, but for now more than 10 paths likely carries too much one-path failure.
182 pub const DEFAULT_MAX_PATH_COUNT: u8 = 10;
184 // The median hop CLTV expiry delta currently seen in the network.
185 const MEDIAN_HOP_CLTV_EXPIRY_DELTA: u32 = 40;
187 // During routing, we only consider paths shorter than our maximum length estimate.
188 // In the TLV onion format, there is no fixed maximum length, but the `hop_payloads`
189 // field is always 1300 bytes. As the `tlv_payload` for each hop may vary in length, we have to
190 // estimate how many hops the route may have so that it actually fits the `hop_payloads` field.
192 // We estimate 3+32 (payload length and HMAC) + 2+8 (amt_to_forward) + 2+4 (outgoing_cltv_value) +
193 // 2+8 (short_channel_id) = 61 bytes for each intermediate hop and 3+32
194 // (payload length and HMAC) + 2+8 (amt_to_forward) + 2+4 (outgoing_cltv_value) + 2+32+8
195 // (payment_secret and total_msat) = 93 bytes for the final hop.
196 // Since the length of the potentially included `payment_metadata` is unknown to us, we round
197 // down from (1300-93) / 61 = 19.78... to arrive at a conservative estimate of 19.
198 const MAX_PATH_LENGTH_ESTIMATE: u8 = 19;
200 /// The recipient of a payment.
201 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
202 pub struct PaymentParameters {
203 /// The node id of the payee.
204 pub payee_pubkey: PublicKey,
206 /// Features supported by the payee.
208 /// May be set from the payee's invoice or via [`for_keysend`]. May be `None` if the invoice
209 /// does not contain any features.
211 /// [`for_keysend`]: Self::for_keysend
212 pub features: Option<InvoiceFeatures>,
214 /// Hints for routing to the payee, containing channels connecting the payee to public nodes.
215 pub route_hints: Vec<RouteHint>,
217 /// Expiration of a payment to the payee, in seconds relative to the UNIX epoch.
218 pub expiry_time: Option<u64>,
220 /// The maximum total CLTV delta we accept for the route.
221 /// Defaults to [`DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA`].
222 pub max_total_cltv_expiry_delta: u32,
224 /// The maximum number of paths that may be used by (MPP) payments.
225 /// Defaults to [`DEFAULT_MAX_PATH_COUNT`].
226 pub max_path_count: u8,
228 /// Selects the maximum share of a channel's total capacity which will be sent over a channel,
229 /// as a power of 1/2. A higher value prefers to send the payment using more MPP parts whereas
230 /// a lower value prefers to send larger MPP parts, potentially saturating channels and
231 /// increasing failure probability for those paths.
233 /// Note that this restriction will be relaxed during pathfinding after paths which meet this
234 /// restriction have been found. While paths which meet this criteria will be searched for, it
235 /// is ultimately up to the scorer to select them over other paths.
237 /// A value of 0 will allow payments up to and including a channel's total announced usable
238 /// capacity, a value of one will only use up to half its capacity, two 1/4, etc.
241 pub max_channel_saturation_power_of_half: u8,
243 /// A list of SCIDs which this payment was previously attempted over and which caused the
244 /// payment to fail. Future attempts for the same payment shouldn't be relayed through any of
246 pub previously_failed_channels: Vec<u64>,
249 impl_writeable_tlv_based!(PaymentParameters, {
250 (0, payee_pubkey, required),
251 (1, max_total_cltv_expiry_delta, (default_value, DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA)),
252 (2, features, option),
253 (3, max_path_count, (default_value, DEFAULT_MAX_PATH_COUNT)),
254 (4, route_hints, vec_type),
255 (5, max_channel_saturation_power_of_half, (default_value, 2)),
256 (6, expiry_time, option),
257 (7, previously_failed_channels, vec_type),
260 impl PaymentParameters {
261 /// Creates a payee with the node id of the given `pubkey`.
262 pub fn from_node_id(payee_pubkey: PublicKey) -> Self {
268 max_total_cltv_expiry_delta: DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA,
269 max_path_count: DEFAULT_MAX_PATH_COUNT,
270 max_channel_saturation_power_of_half: 2,
271 previously_failed_channels: Vec::new(),
275 /// Creates a payee with the node id of the given `pubkey` to use for keysend payments.
276 pub fn for_keysend(payee_pubkey: PublicKey) -> Self {
277 Self::from_node_id(payee_pubkey).with_features(InvoiceFeatures::for_keysend())
280 /// Includes the payee's features.
282 /// (C-not exported) since bindings don't support move semantics
283 pub fn with_features(self, features: InvoiceFeatures) -> Self {
284 Self { features: Some(features), ..self }
287 /// Includes hints for routing to the payee.
289 /// (C-not exported) since bindings don't support move semantics
290 pub fn with_route_hints(self, route_hints: Vec<RouteHint>) -> Self {
291 Self { route_hints, ..self }
294 /// Includes a payment expiration in seconds relative to the UNIX epoch.
296 /// (C-not exported) since bindings don't support move semantics
297 pub fn with_expiry_time(self, expiry_time: u64) -> Self {
298 Self { expiry_time: Some(expiry_time), ..self }
301 /// Includes a limit for the total CLTV expiry delta which is considered during routing
303 /// (C-not exported) since bindings don't support move semantics
304 pub fn with_max_total_cltv_expiry_delta(self, max_total_cltv_expiry_delta: u32) -> Self {
305 Self { max_total_cltv_expiry_delta, ..self }
308 /// Includes a limit for the maximum number of payment paths that may be used.
310 /// (C-not exported) since bindings don't support move semantics
311 pub fn with_max_path_count(self, max_path_count: u8) -> Self {
312 Self { max_path_count, ..self }
315 /// Includes a limit for the maximum number of payment paths that may be used.
317 /// (C-not exported) since bindings don't support move semantics
318 pub fn with_max_channel_saturation_power_of_half(self, max_channel_saturation_power_of_half: u8) -> Self {
319 Self { max_channel_saturation_power_of_half, ..self }
323 /// A list of hops along a payment path terminating with a channel to the recipient.
324 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
325 pub struct RouteHint(pub Vec<RouteHintHop>);
327 impl Writeable for RouteHint {
328 fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
329 (self.0.len() as u64).write(writer)?;
330 for hop in self.0.iter() {
337 impl Readable for RouteHint {
338 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
339 let hop_count: u64 = Readable::read(reader)?;
340 let mut hops = Vec::with_capacity(cmp::min(hop_count, 16) as usize);
341 for _ in 0..hop_count {
342 hops.push(Readable::read(reader)?);
348 /// A channel descriptor for a hop along a payment path.
349 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
350 pub struct RouteHintHop {
351 /// The node_id of the non-target end of the route
352 pub src_node_id: PublicKey,
353 /// The short_channel_id of this channel
354 pub short_channel_id: u64,
355 /// The fees which must be paid to use this channel
356 pub fees: RoutingFees,
357 /// The difference in CLTV values between this node and the next node.
358 pub cltv_expiry_delta: u16,
359 /// The minimum value, in msat, which must be relayed to the next hop.
360 pub htlc_minimum_msat: Option<u64>,
361 /// The maximum value in msat available for routing with a single HTLC.
362 pub htlc_maximum_msat: Option<u64>,
365 impl_writeable_tlv_based!(RouteHintHop, {
366 (0, src_node_id, required),
367 (1, htlc_minimum_msat, option),
368 (2, short_channel_id, required),
369 (3, htlc_maximum_msat, option),
371 (6, cltv_expiry_delta, required),
374 #[derive(Eq, PartialEq)]
375 struct RouteGraphNode {
377 lowest_fee_to_peer_through_node: u64,
378 lowest_fee_to_node: u64,
379 total_cltv_delta: u32,
380 // The maximum value a yet-to-be-constructed payment path might flow through this node.
381 // This value is upper-bounded by us by:
382 // - how much is needed for a path being constructed
383 // - how much value can channels following this node (up to the destination) can contribute,
384 // considering their capacity and fees
385 value_contribution_msat: u64,
386 /// The effective htlc_minimum_msat at this hop. If a later hop on the path had a higher HTLC
387 /// minimum, we use it, plus the fees required at each earlier hop to meet it.
388 path_htlc_minimum_msat: u64,
389 /// All penalties incurred from this hop on the way to the destination, as calculated using
391 path_penalty_msat: u64,
392 /// The number of hops walked up to this node.
393 path_length_to_node: u8,
396 impl cmp::Ord for RouteGraphNode {
397 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
398 let other_score = cmp::max(other.lowest_fee_to_peer_through_node, other.path_htlc_minimum_msat)
399 .saturating_add(other.path_penalty_msat);
400 let self_score = cmp::max(self.lowest_fee_to_peer_through_node, self.path_htlc_minimum_msat)
401 .saturating_add(self.path_penalty_msat);
402 other_score.cmp(&self_score).then_with(|| other.node_id.cmp(&self.node_id))
406 impl cmp::PartialOrd for RouteGraphNode {
407 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
408 Some(self.cmp(other))
412 /// A wrapper around the various hop representations.
414 /// Used to construct a [`PathBuildingHop`] and to estimate [`EffectiveCapacity`].
415 #[derive(Clone, Debug)]
416 enum CandidateRouteHop<'a> {
417 /// A hop from the payer, where the outbound liquidity is known.
419 details: &'a ChannelDetails,
421 /// A hop found in the [`ReadOnlyNetworkGraph`], where the channel capacity may be unknown.
423 info: DirectedChannelInfoWithUpdate<'a>,
424 short_channel_id: u64,
426 /// A hop to the payee found in the payment invoice, though not necessarily a direct channel.
428 hint: &'a RouteHintHop,
432 impl<'a> CandidateRouteHop<'a> {
433 fn short_channel_id(&self) -> u64 {
435 CandidateRouteHop::FirstHop { details } => details.get_outbound_payment_scid().unwrap(),
436 CandidateRouteHop::PublicHop { short_channel_id, .. } => *short_channel_id,
437 CandidateRouteHop::PrivateHop { hint } => hint.short_channel_id,
441 // NOTE: This may alloc memory so avoid calling it in a hot code path.
442 fn features(&self) -> ChannelFeatures {
444 CandidateRouteHop::FirstHop { details } => details.counterparty.features.to_context(),
445 CandidateRouteHop::PublicHop { info, .. } => info.channel().features.clone(),
446 CandidateRouteHop::PrivateHop { .. } => ChannelFeatures::empty(),
450 fn cltv_expiry_delta(&self) -> u32 {
452 CandidateRouteHop::FirstHop { .. } => 0,
453 CandidateRouteHop::PublicHop { info, .. } => info.direction().cltv_expiry_delta as u32,
454 CandidateRouteHop::PrivateHop { hint } => hint.cltv_expiry_delta as u32,
458 fn htlc_minimum_msat(&self) -> u64 {
460 CandidateRouteHop::FirstHop { .. } => 0,
461 CandidateRouteHop::PublicHop { info, .. } => info.direction().htlc_minimum_msat,
462 CandidateRouteHop::PrivateHop { hint } => hint.htlc_minimum_msat.unwrap_or(0),
466 fn fees(&self) -> RoutingFees {
468 CandidateRouteHop::FirstHop { .. } => RoutingFees {
469 base_msat: 0, proportional_millionths: 0,
471 CandidateRouteHop::PublicHop { info, .. } => info.direction().fees,
472 CandidateRouteHop::PrivateHop { hint } => hint.fees,
476 fn effective_capacity(&self) -> EffectiveCapacity {
478 CandidateRouteHop::FirstHop { details } => EffectiveCapacity::ExactLiquidity {
479 liquidity_msat: details.next_outbound_htlc_limit_msat,
481 CandidateRouteHop::PublicHop { info, .. } => info.effective_capacity(),
482 CandidateRouteHop::PrivateHop { .. } => EffectiveCapacity::Infinite,
488 fn max_htlc_from_capacity(capacity: EffectiveCapacity, max_channel_saturation_power_of_half: u8) -> u64 {
489 let saturation_shift: u32 = max_channel_saturation_power_of_half as u32;
491 EffectiveCapacity::ExactLiquidity { liquidity_msat } => liquidity_msat,
492 EffectiveCapacity::Infinite => u64::max_value(),
493 EffectiveCapacity::Unknown => EffectiveCapacity::Unknown.as_msat(),
494 EffectiveCapacity::MaximumHTLC { amount_msat } =>
495 amount_msat.checked_shr(saturation_shift).unwrap_or(0),
496 EffectiveCapacity::Total { capacity_msat, htlc_maximum_msat: None } =>
497 capacity_msat.checked_shr(saturation_shift).unwrap_or(0),
498 EffectiveCapacity::Total { capacity_msat, htlc_maximum_msat: Some(htlc_max) } =>
499 cmp::min(capacity_msat.checked_shr(saturation_shift).unwrap_or(0), htlc_max),
503 fn iter_equal<I1: Iterator, I2: Iterator>(mut iter_a: I1, mut iter_b: I2)
504 -> bool where I1::Item: PartialEq<I2::Item> {
506 let a = iter_a.next();
507 let b = iter_b.next();
508 if a.is_none() && b.is_none() { return true; }
509 if a.is_none() || b.is_none() { return false; }
510 if a.unwrap().ne(&b.unwrap()) { return false; }
514 /// It's useful to keep track of the hops associated with the fees required to use them,
515 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
516 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
517 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
519 struct PathBuildingHop<'a> {
520 // Note that this should be dropped in favor of loading it from CandidateRouteHop, but doing so
521 // is a larger refactor and will require careful performance analysis.
523 candidate: CandidateRouteHop<'a>,
526 /// Minimal fees required to route to the source node of the current hop via any of its inbound channels.
527 src_lowest_inbound_fees: RoutingFees,
528 /// All the fees paid *after* this channel on the way to the destination
529 next_hops_fee_msat: u64,
530 /// Fee paid for the use of the current channel (see candidate.fees()).
531 /// The value will be actually deducted from the counterparty balance on the previous link.
532 hop_use_fee_msat: u64,
533 /// Used to compare channels when choosing the for routing.
534 /// Includes paying for the use of a hop and the following hops, as well as
535 /// an estimated cost of reaching this hop.
536 /// Might get stale when fees are recomputed. Primarily for internal use.
538 /// A mirror of the same field in RouteGraphNode. Note that this is only used during the graph
539 /// walk and may be invalid thereafter.
540 path_htlc_minimum_msat: u64,
541 /// All penalties incurred from this channel on the way to the destination, as calculated using
543 path_penalty_msat: u64,
544 /// If we've already processed a node as the best node, we shouldn't process it again. Normally
545 /// we'd just ignore it if we did as all channels would have a higher new fee, but because we
546 /// may decrease the amounts in use as we walk the graph, the actual calculated fee may
547 /// decrease as well. Thus, we have to explicitly track which nodes have been processed and
548 /// avoid processing them again.
550 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
551 // In tests, we apply further sanity checks on cases where we skip nodes we already processed
552 // to ensure it is specifically in cases where the fee has gone down because of a decrease in
553 // value_contribution_msat, which requires tracking it here. See comments below where it is
554 // used for more info.
555 value_contribution_msat: u64,
558 impl<'a> core::fmt::Debug for PathBuildingHop<'a> {
559 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
560 let mut debug_struct = f.debug_struct("PathBuildingHop");
562 .field("node_id", &self.node_id)
563 .field("short_channel_id", &self.candidate.short_channel_id())
564 .field("total_fee_msat", &self.total_fee_msat)
565 .field("next_hops_fee_msat", &self.next_hops_fee_msat)
566 .field("hop_use_fee_msat", &self.hop_use_fee_msat)
567 .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)))
568 .field("path_penalty_msat", &self.path_penalty_msat)
569 .field("path_htlc_minimum_msat", &self.path_htlc_minimum_msat)
570 .field("cltv_expiry_delta", &self.candidate.cltv_expiry_delta());
571 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
572 let debug_struct = debug_struct
573 .field("value_contribution_msat", &self.value_contribution_msat);
574 debug_struct.finish()
578 // Instantiated with a list of hops with correct data in them collected during path finding,
579 // an instance of this struct should be further modified only via given methods.
581 struct PaymentPath<'a> {
582 hops: Vec<(PathBuildingHop<'a>, NodeFeatures)>,
585 impl<'a> PaymentPath<'a> {
586 // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
587 fn get_value_msat(&self) -> u64 {
588 self.hops.last().unwrap().0.fee_msat
591 fn get_path_penalty_msat(&self) -> u64 {
592 self.hops.first().map(|h| h.0.path_penalty_msat).unwrap_or(u64::max_value())
595 fn get_total_fee_paid_msat(&self) -> u64 {
596 if self.hops.len() < 1 {
600 // Can't use next_hops_fee_msat because it gets outdated.
601 for (i, (hop, _)) in self.hops.iter().enumerate() {
602 if i != self.hops.len() - 1 {
603 result += hop.fee_msat;
609 fn get_cost_msat(&self) -> u64 {
610 self.get_total_fee_paid_msat().saturating_add(self.get_path_penalty_msat())
613 // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
614 // to change fees may result in an inconsistency.
616 // Sometimes we call this function right after constructing a path which is inconsistent in
617 // that it the value being transferred has decreased while we were doing path finding, leading
618 // to the fees being paid not lining up with the actual limits.
620 // Note that this function is not aware of the available_liquidity limit, and thus does not
621 // support increasing the value being transferred beyond what was selected during the initial
623 fn update_value_and_recompute_fees(&mut self, value_msat: u64) {
624 let mut total_fee_paid_msat = 0 as u64;
625 for i in (0..self.hops.len()).rev() {
626 let last_hop = i == self.hops.len() - 1;
628 // For non-last-hop, this value will represent the fees paid on the current hop. It
629 // will consist of the fees for the use of the next hop, and extra fees to match
630 // htlc_minimum_msat of the current channel. Last hop is handled separately.
631 let mut cur_hop_fees_msat = 0;
633 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().0.hop_use_fee_msat;
636 let mut cur_hop = &mut self.hops.get_mut(i).unwrap().0;
637 cur_hop.next_hops_fee_msat = total_fee_paid_msat;
638 // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
639 // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
640 // set it too high just to maliciously take more fees by exploiting this
641 // match htlc_minimum_msat logic.
642 let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
643 if let Some(extra_fees_msat) = cur_hop.candidate.htlc_minimum_msat().checked_sub(cur_hop_transferred_amount_msat) {
644 // Note that there is a risk that *previous hops* (those closer to us, as we go
645 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
647 // This might make us end up with a broken route, although this should be super-rare
648 // in practice, both because of how healthy channels look like, and how we pick
649 // channels in add_entry.
650 // Also, this can't be exploited more heavily than *announce a free path and fail
652 cur_hop_transferred_amount_msat += extra_fees_msat;
653 total_fee_paid_msat += extra_fees_msat;
654 cur_hop_fees_msat += extra_fees_msat;
658 // Final hop is a special case: it usually has just value_msat (by design), but also
659 // it still could overpay for the htlc_minimum_msat.
660 cur_hop.fee_msat = cur_hop_transferred_amount_msat;
662 // Propagate updated fees for the use of the channels to one hop back, where they
663 // will be actually paid (fee_msat). The last hop is handled above separately.
664 cur_hop.fee_msat = cur_hop_fees_msat;
667 // Fee for the use of the current hop which will be deducted on the previous hop.
668 // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
669 // this channel is free for us.
671 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.candidate.fees()) {
672 cur_hop.hop_use_fee_msat = new_fee;
673 total_fee_paid_msat += new_fee;
675 // It should not be possible because this function is called only to reduce the
676 // value. In that case, compute_fee was already called with the same fees for
677 // larger amount and there was no overflow.
685 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
686 let proportional_fee_millions =
687 amount_msat.checked_mul(channel_fees.proportional_millionths as u64);
688 if let Some(new_fee) = proportional_fee_millions.and_then(|part| {
689 (channel_fees.base_msat as u64).checked_add(part / 1_000_000) }) {
693 // This function may be (indirectly) called without any verification,
694 // with channel_fees provided by a caller. We should handle it gracefully.
699 /// The default `features` we assume for a node in a route, when no `features` are known about that
702 /// Default features are:
703 /// * variable_length_onion_optional
704 fn default_node_features() -> NodeFeatures {
705 let mut features = NodeFeatures::empty();
706 features.set_variable_length_onion_optional();
710 /// Finds a route from us (payer) to the given target node (payee).
712 /// If the payee provided features in their invoice, they should be provided via `params.payee`.
713 /// Without this, MPP will only be used if the payee's features are available in the network graph.
715 /// Private routing paths between a public node and the target may be included in `params.payee`.
717 /// If some channels aren't announced, it may be useful to fill in `first_hops` with the results
718 /// from [`ChannelManager::list_usable_channels`]. If it is filled in, the view of these channels
719 /// from `network_graph` will be ignored, and only those in `first_hops` will be used.
721 /// The fees on channels from us to the next hop are ignored as they are assumed to all be equal.
722 /// However, the enabled/disabled bit on such channels as well as the `htlc_minimum_msat` /
723 /// `htlc_maximum_msat` *are* checked as they may change based on the receiving node.
727 /// May be used to re-compute a [`Route`] when handling a [`Event::PaymentPathFailed`]. Any
728 /// adjustments to the [`NetworkGraph`] and channel scores should be made prior to calling this
733 /// Panics if first_hops contains channels without short_channel_ids;
734 /// [`ChannelManager::list_usable_channels`] will never include such channels.
736 /// [`ChannelManager::list_usable_channels`]: crate::ln::channelmanager::ChannelManager::list_usable_channels
737 /// [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed
738 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
739 pub fn find_route<L: Deref, GL: Deref, S: Score>(
740 our_node_pubkey: &PublicKey, route_params: &RouteParameters,
741 network_graph: &NetworkGraph<GL>, first_hops: Option<&[&ChannelDetails]>, logger: L,
742 scorer: &S, random_seed_bytes: &[u8; 32]
743 ) -> Result<Route, LightningError>
744 where L::Target: Logger, GL::Target: Logger {
745 let graph_lock = network_graph.read_only();
746 let mut route = get_route(our_node_pubkey, &route_params.payment_params, &graph_lock, first_hops,
747 route_params.final_value_msat, route_params.final_cltv_expiry_delta, logger, scorer,
749 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
753 pub(crate) fn get_route<L: Deref, S: Score>(
754 our_node_pubkey: &PublicKey, payment_params: &PaymentParameters, network_graph: &ReadOnlyNetworkGraph,
755 first_hops: Option<&[&ChannelDetails]>, final_value_msat: u64, final_cltv_expiry_delta: u32,
756 logger: L, scorer: &S, _random_seed_bytes: &[u8; 32]
757 ) -> Result<Route, LightningError>
758 where L::Target: Logger {
759 let payee_node_id = NodeId::from_pubkey(&payment_params.payee_pubkey);
760 let our_node_id = NodeId::from_pubkey(&our_node_pubkey);
762 if payee_node_id == our_node_id {
763 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
766 if final_value_msat > MAX_VALUE_MSAT {
767 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
770 if final_value_msat == 0 {
771 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
774 for route in payment_params.route_hints.iter() {
775 for hop in &route.0 {
776 if hop.src_node_id == payment_params.payee_pubkey {
777 return Err(LightningError{err: "Route hint cannot have the payee as the source.".to_owned(), action: ErrorAction::IgnoreError});
781 if payment_params.max_total_cltv_expiry_delta <= final_cltv_expiry_delta {
782 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});
785 // The general routing idea is the following:
786 // 1. Fill first/last hops communicated by the caller.
787 // 2. Attempt to construct a path from payer to payee for transferring
788 // any ~sufficient (described later) value.
789 // If succeed, remember which channels were used and how much liquidity they have available,
790 // so that future paths don't rely on the same liquidity.
791 // 3. Proceed to the next step if:
792 // - we hit the recommended target value;
793 // - OR if we could not construct a new path. Any next attempt will fail too.
794 // Otherwise, repeat step 2.
795 // 4. See if we managed to collect paths which aggregately are able to transfer target value
796 // (not recommended value).
797 // 5. If yes, proceed. If not, fail routing.
798 // 6. Select the paths which have the lowest cost (fee plus scorer penalty) per amount
799 // transferred up to the transfer target value.
800 // 7. Reduce the value of the last path until we are sending only the target value.
801 // 8. If our maximum channel saturation limit caused us to pick two identical paths, combine
802 // them so that we're not sending two HTLCs along the same path.
804 // As for the actual search algorithm,
805 // we do a payee-to-payer pseudo-Dijkstra's sorting by each node's distance from the payee
806 // plus the minimum per-HTLC fee to get from it to another node (aka "shitty pseudo-A*").
808 // We are not a faithful Dijkstra's implementation because we can change values which impact
809 // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
810 // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) than
811 // the value we are currently attempting to send over a path, we simply reduce the value being
812 // sent along the path for any hops after that channel. This may imply that later fees (which
813 // we've already tabulated) are lower because a smaller value is passing through the channels
814 // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
815 // channels which were selected earlier (and which may still be used for other paths without a
816 // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
819 // One potentially problematic case for this algorithm would be if there are many
820 // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
821 // graph walking), we may never find a path which is not liquidity-limited and has lower
822 // proportional fee (and only lower absolute fee when considering the ultimate value sent).
823 // Because we only consider paths with at least 5% of the total value being sent, the damage
824 // from such a case should be limited, however this could be further reduced in the future by
825 // calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
826 // limits for the purposes of fee calculation.
828 // Alternatively, we could store more detailed path information in the heap (targets, below)
829 // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
830 // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
831 // and practically (as we would need to store dynamically-allocated path information in heap
832 // objects, increasing malloc traffic and indirect memory access significantly). Further, the
833 // results of such an algorithm would likely be biased towards lower-value paths.
835 // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
836 // outside of our current search value, running a path search more times to gather candidate
837 // paths at different values. While this may be acceptable, further path searches may increase
838 // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
839 // graph for candidate paths, calculating the maximum value which can realistically be sent at
840 // the same time, remaining generic across different payment values.
842 // TODO: There are a few tweaks we could do, including possibly pre-calculating more stuff
843 // to use as the A* heuristic beyond just the cost to get one node further than the current
846 let network_channels = network_graph.channels();
847 let network_nodes = network_graph.nodes();
849 if payment_params.max_path_count == 0 {
850 return Err(LightningError{err: "Can't find a route with no paths allowed.".to_owned(), action: ErrorAction::IgnoreError});
853 // Allow MPP only if we have a features set from somewhere that indicates the payee supports
854 // it. If the payee supports it they're supposed to include it in the invoice, so that should
856 let allow_mpp = if payment_params.max_path_count == 1 {
858 } else if let Some(features) = &payment_params.features {
859 features.supports_basic_mpp()
860 } else if let Some(node) = network_nodes.get(&payee_node_id) {
861 if let Some(node_info) = node.announcement_info.as_ref() {
862 node_info.features.supports_basic_mpp()
866 log_trace!(logger, "Searching for a route from payer {} to payee {} {} MPP and {} first hops {}overriding the network graph", our_node_pubkey,
867 payment_params.payee_pubkey, if allow_mpp { "with" } else { "without" },
868 first_hops.map(|hops| hops.len()).unwrap_or(0), if first_hops.is_some() { "" } else { "not " });
871 // Prepare the data we'll use for payee-to-payer search by
872 // inserting first hops suggested by the caller as targets.
873 // Our search will then attempt to reach them while traversing from the payee node.
874 let mut first_hop_targets: HashMap<_, Vec<&ChannelDetails>> =
875 HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
876 if let Some(hops) = first_hops {
878 if chan.get_outbound_payment_scid().is_none() {
879 panic!("first_hops should be filled in with usable channels, not pending ones");
881 if chan.counterparty.node_id == *our_node_pubkey {
882 return Err(LightningError{err: "First hop cannot have our_node_pubkey as a destination.".to_owned(), action: ErrorAction::IgnoreError});
885 .entry(NodeId::from_pubkey(&chan.counterparty.node_id))
886 .or_insert(Vec::new())
889 if first_hop_targets.is_empty() {
890 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
894 // The main heap containing all candidate next-hops sorted by their score (max(A* fee,
895 // htlc_minimum)). Ideally this would be a heap which allowed cheap score reduction instead of
896 // adding duplicate entries when we find a better path to a given node.
897 let mut targets: BinaryHeap<RouteGraphNode> = BinaryHeap::new();
899 // Map from node_id to information about the best current path to that node, including feerate
901 let mut dist: HashMap<NodeId, PathBuildingHop> = HashMap::with_capacity(network_nodes.len());
903 // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
904 // indicating that we may wish to try again with a higher value, potentially paying to meet an
905 // htlc_minimum with extra fees while still finding a cheaper path.
906 let mut hit_minimum_limit;
908 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
909 // We start with a path_value of the exact amount we want, and if that generates a route we may
910 // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
911 // amount we want in total across paths, selecting the best subset at the end.
912 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
913 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
914 let mut path_value_msat = final_value_msat;
916 // Routing Fragmentation Mitigation heuristic:
918 // Routing fragmentation across many payment paths increases the overall routing
919 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
920 // Taking too many smaller paths also increases the chance of payment failure.
921 // Thus to avoid this effect, we require from our collected links to provide
922 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
923 // This requirement is currently set to be 1/max_path_count of the payment
924 // value to ensure we only ever return routes that do not violate this limit.
925 let minimal_value_contribution_msat: u64 = if allow_mpp {
926 (final_value_msat + (payment_params.max_path_count as u64 - 1)) / payment_params.max_path_count as u64
931 // When we start collecting routes we enforce the max_channel_saturation_power_of_half
932 // requirement strictly. After we've collected enough (or if we fail to find new routes) we
933 // drop the requirement by setting this to 0.
934 let mut channel_saturation_pow_half = payment_params.max_channel_saturation_power_of_half;
936 // Keep track of how much liquidity has been used in selected channels. Used to determine
937 // if the channel can be used by additional MPP paths or to inform path finding decisions. It is
938 // aware of direction *only* to ensure that the correct htlc_maximum_msat value is used. Hence,
939 // liquidity used in one direction will not offset any used in the opposite direction.
940 let mut used_channel_liquidities: HashMap<(u64, bool), u64> =
941 HashMap::with_capacity(network_nodes.len());
943 // Keeping track of how much value we already collected across other paths. Helps to decide
944 // when we want to stop looking for new paths.
945 let mut already_collected_value_msat = 0;
947 for (_, channels) in first_hop_targets.iter_mut() {
948 // Sort the first_hops channels to the same node(s) in priority order of which channel we'd
951 // First, if channels are below `recommended_value_msat`, sort them in descending order,
952 // preferring larger channels to avoid splitting the payment into more MPP parts than is
955 // Second, because simply always sorting in descending order would always use our largest
956 // available outbound capacity, needlessly fragmenting our available channel capacities,
957 // sort channels above `recommended_value_msat` in ascending order, preferring channels
958 // which have enough, but not too much, capacity for the payment.
959 channels.sort_unstable_by(|chan_a, chan_b| {
960 if chan_b.next_outbound_htlc_limit_msat < recommended_value_msat || chan_a.next_outbound_htlc_limit_msat < recommended_value_msat {
961 // Sort in descending order
962 chan_b.next_outbound_htlc_limit_msat.cmp(&chan_a.next_outbound_htlc_limit_msat)
964 // Sort in ascending order
965 chan_a.next_outbound_htlc_limit_msat.cmp(&chan_b.next_outbound_htlc_limit_msat)
970 log_trace!(logger, "Building path from {} (payee) to {} (us/payer) for value {} msat.", payment_params.payee_pubkey, our_node_pubkey, final_value_msat);
972 macro_rules! add_entry {
973 // Adds entry which goes from $src_node_id to $dest_node_id over the $candidate hop.
974 // $next_hops_fee_msat represents the fees paid for using all the channels *after* this one,
975 // since that value has to be transferred over this channel.
976 // Returns whether this channel caused an update to `targets`.
977 ( $candidate: expr, $src_node_id: expr, $dest_node_id: expr, $next_hops_fee_msat: expr,
978 $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr,
979 $next_hops_path_penalty_msat: expr, $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => { {
980 // We "return" whether we updated the path at the end, via this:
981 let mut did_add_update_path_to_src_node = false;
982 // Channels to self should not be used. This is more of belt-and-suspenders, because in
983 // practice these cases should be caught earlier:
984 // - for regular channels at channel announcement (TODO)
985 // - for first and last hops early in get_route
986 if $src_node_id != $dest_node_id {
987 let short_channel_id = $candidate.short_channel_id();
988 let effective_capacity = $candidate.effective_capacity();
989 let htlc_maximum_msat = max_htlc_from_capacity(effective_capacity, channel_saturation_pow_half);
991 // It is tricky to subtract $next_hops_fee_msat from available liquidity here.
992 // It may be misleading because we might later choose to reduce the value transferred
993 // over these channels, and the channel which was insufficient might become sufficient.
994 // Worst case: we drop a good channel here because it can't cover the high following
995 // fees caused by one expensive channel, but then this channel could have been used
996 // if the amount being transferred over this path is lower.
997 // We do this for now, but this is a subject for removal.
998 if let Some(mut available_value_contribution_msat) = htlc_maximum_msat.checked_sub($next_hops_fee_msat) {
999 let used_liquidity_msat = used_channel_liquidities
1000 .get(&(short_channel_id, $src_node_id < $dest_node_id))
1001 .map_or(0, |used_liquidity_msat| {
1002 available_value_contribution_msat = available_value_contribution_msat
1003 .saturating_sub(*used_liquidity_msat);
1004 *used_liquidity_msat
1007 // Verify the liquidity offered by this channel complies to the minimal contribution.
1008 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
1009 // Do not consider candidate hops that would exceed the maximum path length.
1010 let path_length_to_node = $next_hops_path_length + 1;
1011 let exceeds_max_path_length = path_length_to_node > MAX_PATH_LENGTH_ESTIMATE;
1013 // Do not consider candidates that exceed the maximum total cltv expiry limit.
1014 // In order to already account for some of the privacy enhancing random CLTV
1015 // expiry delta offset we add on top later, we subtract a rough estimate
1016 // (2*MEDIAN_HOP_CLTV_EXPIRY_DELTA) here.
1017 let max_total_cltv_expiry_delta = (payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta)
1018 .checked_sub(2*MEDIAN_HOP_CLTV_EXPIRY_DELTA)
1019 .unwrap_or(payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta);
1020 let hop_total_cltv_delta = ($next_hops_cltv_delta as u32)
1021 .saturating_add($candidate.cltv_expiry_delta());
1022 let exceeds_cltv_delta_limit = hop_total_cltv_delta > max_total_cltv_expiry_delta;
1024 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
1025 // Includes paying fees for the use of the following channels.
1026 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
1027 Some(result) => result,
1028 // Can't overflow due to how the values were computed right above.
1029 None => unreachable!(),
1031 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
1032 let over_path_minimum_msat = amount_to_transfer_over_msat >= $candidate.htlc_minimum_msat() &&
1033 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
1035 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
1036 let may_overpay_to_meet_path_minimum_msat =
1037 ((amount_to_transfer_over_msat < $candidate.htlc_minimum_msat() &&
1038 recommended_value_msat > $candidate.htlc_minimum_msat()) ||
1039 (amount_to_transfer_over_msat < $next_hops_path_htlc_minimum_msat &&
1040 recommended_value_msat > $next_hops_path_htlc_minimum_msat));
1042 let payment_failed_on_this_channel =
1043 payment_params.previously_failed_channels.contains(&short_channel_id);
1045 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
1046 // bother considering this channel. If retrying with recommended_value_msat may
1047 // allow us to hit the HTLC minimum limit, set htlc_minimum_limit so that we go
1048 // around again with a higher amount.
1049 if !contributes_sufficient_value || exceeds_max_path_length ||
1050 exceeds_cltv_delta_limit || payment_failed_on_this_channel {
1051 // Path isn't useful, ignore it and move on.
1052 } else if may_overpay_to_meet_path_minimum_msat {
1053 hit_minimum_limit = true;
1054 } else if over_path_minimum_msat {
1055 // Note that low contribution here (limited by available_liquidity_msat)
1056 // might violate htlc_minimum_msat on the hops which are next along the
1057 // payment path (upstream to the payee). To avoid that, we recompute
1058 // path fees knowing the final path contribution after constructing it.
1059 let path_htlc_minimum_msat = compute_fees($next_hops_path_htlc_minimum_msat, $candidate.fees())
1060 .and_then(|fee_msat| fee_msat.checked_add($next_hops_path_htlc_minimum_msat))
1061 .map(|fee_msat| cmp::max(fee_msat, $candidate.htlc_minimum_msat()))
1062 .unwrap_or_else(|| u64::max_value());
1063 let hm_entry = dist.entry($src_node_id);
1064 let old_entry = hm_entry.or_insert_with(|| {
1065 // If there was previously no known way to access the source node
1066 // (recall it goes payee-to-payer) of short_channel_id, first add a
1067 // semi-dummy record just to compute the fees to reach the source node.
1068 // This will affect our decision on selecting short_channel_id
1069 // as a way to reach the $dest_node_id.
1070 let mut fee_base_msat = 0;
1071 let mut fee_proportional_millionths = 0;
1072 if let Some(Some(fees)) = network_nodes.get(&$src_node_id).map(|node| node.lowest_inbound_channel_fees) {
1073 fee_base_msat = fees.base_msat;
1074 fee_proportional_millionths = fees.proportional_millionths;
1077 node_id: $dest_node_id.clone(),
1078 candidate: $candidate.clone(),
1080 src_lowest_inbound_fees: RoutingFees {
1081 base_msat: fee_base_msat,
1082 proportional_millionths: fee_proportional_millionths,
1084 next_hops_fee_msat: u64::max_value(),
1085 hop_use_fee_msat: u64::max_value(),
1086 total_fee_msat: u64::max_value(),
1087 path_htlc_minimum_msat,
1088 path_penalty_msat: u64::max_value(),
1089 was_processed: false,
1090 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
1091 value_contribution_msat,
1095 #[allow(unused_mut)] // We only use the mut in cfg(test)
1096 let mut should_process = !old_entry.was_processed;
1097 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
1099 // In test/fuzzing builds, we do extra checks to make sure the skipping
1100 // of already-seen nodes only happens in cases we expect (see below).
1101 if !should_process { should_process = true; }
1105 let mut hop_use_fee_msat = 0;
1106 let mut total_fee_msat = $next_hops_fee_msat;
1108 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
1109 // will have the same effective-fee
1110 if $src_node_id != our_node_id {
1111 match compute_fees(amount_to_transfer_over_msat, $candidate.fees()) {
1112 // max_value means we'll always fail
1113 // the old_entry.total_fee_msat > total_fee_msat check
1114 None => total_fee_msat = u64::max_value(),
1116 hop_use_fee_msat = fee_msat;
1117 total_fee_msat += hop_use_fee_msat;
1118 // When calculating the lowest inbound fees to a node, we
1119 // calculate fees here not based on the actual value we think
1120 // will flow over this channel, but on the minimum value that
1121 // we'll accept flowing over it. The minimum accepted value
1122 // is a constant through each path collection run, ensuring
1123 // consistent basis. Otherwise we may later find a
1124 // different path to the source node that is more expensive,
1125 // but which we consider to be cheaper because we are capacity
1126 // constrained and the relative fee becomes lower.
1127 match compute_fees(minimal_value_contribution_msat, old_entry.src_lowest_inbound_fees)
1128 .map(|a| a.checked_add(total_fee_msat)) {
1133 total_fee_msat = u64::max_value();
1140 let channel_usage = ChannelUsage {
1141 amount_msat: amount_to_transfer_over_msat,
1142 inflight_htlc_msat: used_liquidity_msat,
1145 let channel_penalty_msat = scorer.channel_penalty_msat(
1146 short_channel_id, &$src_node_id, &$dest_node_id, channel_usage
1148 let path_penalty_msat = $next_hops_path_penalty_msat
1149 .saturating_add(channel_penalty_msat);
1150 let new_graph_node = RouteGraphNode {
1151 node_id: $src_node_id,
1152 lowest_fee_to_peer_through_node: total_fee_msat,
1153 lowest_fee_to_node: $next_hops_fee_msat as u64 + hop_use_fee_msat,
1154 total_cltv_delta: hop_total_cltv_delta,
1155 value_contribution_msat,
1156 path_htlc_minimum_msat,
1158 path_length_to_node,
1161 // Update the way of reaching $src_node_id with the given short_channel_id (from $dest_node_id),
1162 // if this way is cheaper than the already known
1163 // (considering the cost to "reach" this channel from the route destination,
1164 // the cost of using this channel,
1165 // and the cost of routing to the source node of this channel).
1166 // Also, consider that htlc_minimum_msat_difference, because we might end up
1167 // paying it. Consider the following exploit:
1168 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
1169 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
1170 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
1171 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
1173 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
1174 // but it may require additional tracking - we don't want to double-count
1175 // the fees included in $next_hops_path_htlc_minimum_msat, but also
1176 // can't use something that may decrease on future hops.
1177 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat)
1178 .saturating_add(old_entry.path_penalty_msat);
1179 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat)
1180 .saturating_add(path_penalty_msat);
1182 if !old_entry.was_processed && new_cost < old_cost {
1183 targets.push(new_graph_node);
1184 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
1185 old_entry.hop_use_fee_msat = hop_use_fee_msat;
1186 old_entry.total_fee_msat = total_fee_msat;
1187 old_entry.node_id = $dest_node_id.clone();
1188 old_entry.candidate = $candidate.clone();
1189 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
1190 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
1191 old_entry.path_penalty_msat = path_penalty_msat;
1192 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
1194 old_entry.value_contribution_msat = value_contribution_msat;
1196 did_add_update_path_to_src_node = true;
1197 } else if old_entry.was_processed && new_cost < old_cost {
1198 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
1200 // If we're skipping processing a node which was previously
1201 // processed even though we found another path to it with a
1202 // cheaper fee, check that it was because the second path we
1203 // found (which we are processing now) has a lower value
1204 // contribution due to an HTLC minimum limit.
1206 // e.g. take a graph with two paths from node 1 to node 2, one
1207 // through channel A, and one through channel B. Channel A and
1208 // B are both in the to-process heap, with their scores set by
1209 // a higher htlc_minimum than fee.
1210 // Channel A is processed first, and the channels onwards from
1211 // node 1 are added to the to-process heap. Thereafter, we pop
1212 // Channel B off of the heap, note that it has a much more
1213 // restrictive htlc_maximum_msat, and recalculate the fees for
1214 // all of node 1's channels using the new, reduced, amount.
1216 // This would be bogus - we'd be selecting a higher-fee path
1217 // with a lower htlc_maximum_msat instead of the one we'd
1218 // already decided to use.
1219 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
1221 value_contribution_msat + path_penalty_msat <
1222 old_entry.value_contribution_msat + old_entry.path_penalty_msat
1230 did_add_update_path_to_src_node
1234 let default_node_features = default_node_features();
1236 // Find ways (channels with destination) to reach a given node and store them
1237 // in the corresponding data structures (routing graph etc).
1238 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
1239 // meaning how much will be paid in fees after this node (to the best of our knowledge).
1240 // This data can later be helpful to optimize routing (pay lower fees).
1241 macro_rules! add_entries_to_cheapest_to_target_node {
1242 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr, $next_hops_value_contribution: expr,
1243 $next_hops_path_htlc_minimum_msat: expr, $next_hops_path_penalty_msat: expr,
1244 $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => {
1245 let skip_node = if let Some(elem) = dist.get_mut(&$node_id) {
1246 let was_processed = elem.was_processed;
1247 elem.was_processed = true;
1250 // Entries are added to dist in add_entry!() when there is a channel from a node.
1251 // Because there are no channels from payee, it will not have a dist entry at this point.
1252 // If we're processing any other node, it is always be the result of a channel from it.
1253 assert_eq!($node_id, payee_node_id);
1258 if let Some(first_channels) = first_hop_targets.get(&$node_id) {
1259 for details in first_channels {
1260 let candidate = CandidateRouteHop::FirstHop { details };
1261 add_entry!(candidate, our_node_id, $node_id, $fee_to_target_msat,
1262 $next_hops_value_contribution,
1263 $next_hops_path_htlc_minimum_msat, $next_hops_path_penalty_msat,
1264 $next_hops_cltv_delta, $next_hops_path_length);
1268 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
1271 &default_node_features
1274 if !features.requires_unknown_bits() {
1275 for chan_id in $node.channels.iter() {
1276 let chan = network_channels.get(chan_id).unwrap();
1277 if !chan.features.requires_unknown_bits() {
1278 let (directed_channel, source) =
1279 chan.as_directed_to(&$node_id).expect("inconsistent NetworkGraph");
1280 if first_hops.is_none() || *source != our_node_id {
1281 if let Some(direction) = directed_channel.direction() {
1282 if direction.enabled {
1283 let candidate = CandidateRouteHop::PublicHop {
1284 info: directed_channel.with_update().unwrap(),
1285 short_channel_id: *chan_id,
1287 add_entry!(candidate, *source, $node_id,
1288 $fee_to_target_msat,
1289 $next_hops_value_contribution,
1290 $next_hops_path_htlc_minimum_msat,
1291 $next_hops_path_penalty_msat,
1292 $next_hops_cltv_delta, $next_hops_path_length);
1303 let mut payment_paths = Vec::<PaymentPath>::new();
1305 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
1306 'paths_collection: loop {
1307 // For every new path, start from scratch, except for used_channel_liquidities, which
1308 // helps to avoid reusing previously selected paths in future iterations.
1311 hit_minimum_limit = false;
1313 // If first hop is a private channel and the only way to reach the payee, this is the only
1314 // place where it could be added.
1315 if let Some(first_channels) = first_hop_targets.get(&payee_node_id) {
1316 for details in first_channels {
1317 let candidate = CandidateRouteHop::FirstHop { details };
1318 let added = add_entry!(candidate, our_node_id, payee_node_id, 0, path_value_msat,
1320 log_trace!(logger, "{} direct route to payee via SCID {}",
1321 if added { "Added" } else { "Skipped" }, candidate.short_channel_id());
1325 // Add the payee as a target, so that the payee-to-payer
1326 // search algorithm knows what to start with.
1327 match network_nodes.get(&payee_node_id) {
1328 // The payee is not in our network graph, so nothing to add here.
1329 // There is still a chance of reaching them via last_hops though,
1330 // so don't yet fail the payment here.
1331 // If not, targets.pop() will not even let us enter the loop in step 2.
1334 add_entries_to_cheapest_to_target_node!(node, payee_node_id, 0, path_value_msat, 0, 0u64, 0, 0);
1339 // If a caller provided us with last hops, add them to routing targets. Since this happens
1340 // earlier than general path finding, they will be somewhat prioritized, although currently
1341 // it matters only if the fees are exactly the same.
1342 for route in payment_params.route_hints.iter().filter(|route| !route.0.is_empty()) {
1343 let first_hop_in_route = &(route.0)[0];
1344 let have_hop_src_in_graph =
1345 // Only add the hops in this route to our candidate set if either
1346 // we have a direct channel to the first hop or the first hop is
1347 // in the regular network graph.
1348 first_hop_targets.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some() ||
1349 network_nodes.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some();
1350 if have_hop_src_in_graph {
1351 // We start building the path from reverse, i.e., from payee
1352 // to the first RouteHintHop in the path.
1353 let hop_iter = route.0.iter().rev();
1354 let prev_hop_iter = core::iter::once(&payment_params.payee_pubkey).chain(
1355 route.0.iter().skip(1).rev().map(|hop| &hop.src_node_id));
1356 let mut hop_used = true;
1357 let mut aggregate_next_hops_fee_msat: u64 = 0;
1358 let mut aggregate_next_hops_path_htlc_minimum_msat: u64 = 0;
1359 let mut aggregate_next_hops_path_penalty_msat: u64 = 0;
1360 let mut aggregate_next_hops_cltv_delta: u32 = 0;
1361 let mut aggregate_next_hops_path_length: u8 = 0;
1363 for (idx, (hop, prev_hop_id)) in hop_iter.zip(prev_hop_iter).enumerate() {
1364 let source = NodeId::from_pubkey(&hop.src_node_id);
1365 let target = NodeId::from_pubkey(&prev_hop_id);
1366 let candidate = network_channels
1367 .get(&hop.short_channel_id)
1368 .and_then(|channel| channel.as_directed_to(&target))
1369 .and_then(|(channel, _)| channel.with_update())
1370 .map(|info| CandidateRouteHop::PublicHop {
1372 short_channel_id: hop.short_channel_id,
1374 .unwrap_or_else(|| CandidateRouteHop::PrivateHop { hint: hop });
1376 if !add_entry!(candidate, source, target, aggregate_next_hops_fee_msat,
1377 path_value_msat, aggregate_next_hops_path_htlc_minimum_msat,
1378 aggregate_next_hops_path_penalty_msat,
1379 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length) {
1380 // If this hop was not used then there is no use checking the preceding
1381 // hops in the RouteHint. We can break by just searching for a direct
1382 // channel between last checked hop and first_hop_targets.
1386 let used_liquidity_msat = used_channel_liquidities
1387 .get(&(hop.short_channel_id, source < target)).copied().unwrap_or(0);
1388 let channel_usage = ChannelUsage {
1389 amount_msat: final_value_msat + aggregate_next_hops_fee_msat,
1390 inflight_htlc_msat: used_liquidity_msat,
1391 effective_capacity: candidate.effective_capacity(),
1393 let channel_penalty_msat = scorer.channel_penalty_msat(
1394 hop.short_channel_id, &source, &target, channel_usage
1396 aggregate_next_hops_path_penalty_msat = aggregate_next_hops_path_penalty_msat
1397 .saturating_add(channel_penalty_msat);
1399 aggregate_next_hops_cltv_delta = aggregate_next_hops_cltv_delta
1400 .saturating_add(hop.cltv_expiry_delta as u32);
1402 aggregate_next_hops_path_length = aggregate_next_hops_path_length
1405 // Searching for a direct channel between last checked hop and first_hop_targets
1406 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&prev_hop_id)) {
1407 for details in first_channels {
1408 let candidate = CandidateRouteHop::FirstHop { details };
1409 add_entry!(candidate, our_node_id, NodeId::from_pubkey(&prev_hop_id),
1410 aggregate_next_hops_fee_msat, path_value_msat,
1411 aggregate_next_hops_path_htlc_minimum_msat,
1412 aggregate_next_hops_path_penalty_msat, aggregate_next_hops_cltv_delta,
1413 aggregate_next_hops_path_length);
1421 // In the next values of the iterator, the aggregate fees already reflects
1422 // the sum of value sent from payer (final_value_msat) and routing fees
1423 // for the last node in the RouteHint. We need to just add the fees to
1424 // route through the current node so that the preceding node (next iteration)
1426 let hops_fee = compute_fees(aggregate_next_hops_fee_msat + final_value_msat, hop.fees)
1427 .map_or(None, |inc| inc.checked_add(aggregate_next_hops_fee_msat));
1428 aggregate_next_hops_fee_msat = if let Some(val) = hops_fee { val } else { break; };
1430 let hop_htlc_minimum_msat = candidate.htlc_minimum_msat();
1431 let hop_htlc_minimum_msat_inc = if let Some(val) = compute_fees(aggregate_next_hops_path_htlc_minimum_msat, hop.fees) { val } else { break; };
1432 let hops_path_htlc_minimum = aggregate_next_hops_path_htlc_minimum_msat
1433 .checked_add(hop_htlc_minimum_msat_inc);
1434 aggregate_next_hops_path_htlc_minimum_msat = if let Some(val) = hops_path_htlc_minimum { cmp::max(hop_htlc_minimum_msat, val) } else { break; };
1436 if idx == route.0.len() - 1 {
1437 // The last hop in this iterator is the first hop in
1438 // overall RouteHint.
1439 // If this hop connects to a node with which we have a direct channel,
1440 // ignore the network graph and, if the last hop was added, add our
1441 // direct channel to the candidate set.
1443 // Note that we *must* check if the last hop was added as `add_entry`
1444 // always assumes that the third argument is a node to which we have a
1446 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&hop.src_node_id)) {
1447 for details in first_channels {
1448 let candidate = CandidateRouteHop::FirstHop { details };
1449 add_entry!(candidate, our_node_id,
1450 NodeId::from_pubkey(&hop.src_node_id),
1451 aggregate_next_hops_fee_msat, path_value_msat,
1452 aggregate_next_hops_path_htlc_minimum_msat,
1453 aggregate_next_hops_path_penalty_msat,
1454 aggregate_next_hops_cltv_delta,
1455 aggregate_next_hops_path_length);
1463 log_trace!(logger, "Starting main path collection loop with {} nodes pre-filled from first/last hops.", targets.len());
1465 // At this point, targets are filled with the data from first and
1466 // last hops communicated by the caller, and the payment receiver.
1467 let mut found_new_path = false;
1470 // If this loop terminates due the exhaustion of targets, two situations are possible:
1471 // - not enough outgoing liquidity:
1472 // 0 < already_collected_value_msat < final_value_msat
1473 // - enough outgoing liquidity:
1474 // final_value_msat <= already_collected_value_msat < recommended_value_msat
1475 // Both these cases (and other cases except reaching recommended_value_msat) mean that
1476 // paths_collection will be stopped because found_new_path==false.
1477 // This is not necessarily a routing failure.
1478 '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() {
1480 // Since we're going payee-to-payer, hitting our node as a target means we should stop
1481 // traversing the graph and arrange the path out of what we found.
1482 if node_id == our_node_id {
1483 let mut new_entry = dist.remove(&our_node_id).unwrap();
1484 let mut ordered_hops: Vec<(PathBuildingHop, NodeFeatures)> = vec!((new_entry.clone(), default_node_features.clone()));
1487 let mut features_set = false;
1488 if let Some(first_channels) = first_hop_targets.get(&ordered_hops.last().unwrap().0.node_id) {
1489 for details in first_channels {
1490 if details.get_outbound_payment_scid().unwrap() == ordered_hops.last().unwrap().0.candidate.short_channel_id() {
1491 ordered_hops.last_mut().unwrap().1 = details.counterparty.features.to_context();
1492 features_set = true;
1498 if let Some(node) = network_nodes.get(&ordered_hops.last().unwrap().0.node_id) {
1499 if let Some(node_info) = node.announcement_info.as_ref() {
1500 ordered_hops.last_mut().unwrap().1 = node_info.features.clone();
1502 ordered_hops.last_mut().unwrap().1 = default_node_features.clone();
1505 // We can fill in features for everything except hops which were
1506 // provided via the invoice we're paying. We could guess based on the
1507 // recipient's features but for now we simply avoid guessing at all.
1511 // Means we succesfully traversed from the payer to the payee, now
1512 // save this path for the payment route. Also, update the liquidity
1513 // remaining on the used hops, so that we take them into account
1514 // while looking for more paths.
1515 if ordered_hops.last().unwrap().0.node_id == payee_node_id {
1519 new_entry = match dist.remove(&ordered_hops.last().unwrap().0.node_id) {
1520 Some(payment_hop) => payment_hop,
1521 // We can't arrive at None because, if we ever add an entry to targets,
1522 // we also fill in the entry in dist (see add_entry!).
1523 None => unreachable!(),
1525 // We "propagate" the fees one hop backward (topologically) here,
1526 // so that fees paid for a HTLC forwarding on the current channel are
1527 // associated with the previous channel (where they will be subtracted).
1528 ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
1529 ordered_hops.push((new_entry.clone(), default_node_features.clone()));
1531 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
1532 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
1534 log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: \n {:#?}",
1535 ordered_hops.len(), value_contribution_msat, ordered_hops.iter().map(|h| &(h.0)).collect::<Vec<&PathBuildingHop>>());
1537 let mut payment_path = PaymentPath {hops: ordered_hops};
1539 // We could have possibly constructed a slightly inconsistent path: since we reduce
1540 // value being transferred along the way, we could have violated htlc_minimum_msat
1541 // on some channels we already passed (assuming dest->source direction). Here, we
1542 // recompute the fees again, so that if that's the case, we match the currently
1543 // underpaid htlc_minimum_msat with fees.
1544 debug_assert_eq!(payment_path.get_value_msat(), value_contribution_msat);
1545 value_contribution_msat = cmp::min(value_contribution_msat, final_value_msat);
1546 payment_path.update_value_and_recompute_fees(value_contribution_msat);
1548 // Since a path allows to transfer as much value as
1549 // the smallest channel it has ("bottleneck"), we should recompute
1550 // the fees so sender HTLC don't overpay fees when traversing
1551 // larger channels than the bottleneck. This may happen because
1552 // when we were selecting those channels we were not aware how much value
1553 // this path will transfer, and the relative fee for them
1554 // might have been computed considering a larger value.
1555 // Remember that we used these channels so that we don't rely
1556 // on the same liquidity in future paths.
1557 let mut prevented_redundant_path_selection = false;
1558 let prev_hop_iter = core::iter::once(&our_node_id)
1559 .chain(payment_path.hops.iter().map(|(hop, _)| &hop.node_id));
1560 for (prev_hop, (hop, _)) in prev_hop_iter.zip(payment_path.hops.iter()) {
1561 let spent_on_hop_msat = value_contribution_msat + hop.next_hops_fee_msat;
1562 let used_liquidity_msat = used_channel_liquidities
1563 .entry((hop.candidate.short_channel_id(), *prev_hop < hop.node_id))
1564 .and_modify(|used_liquidity_msat| *used_liquidity_msat += spent_on_hop_msat)
1565 .or_insert(spent_on_hop_msat);
1566 let hop_capacity = hop.candidate.effective_capacity();
1567 let hop_max_msat = max_htlc_from_capacity(hop_capacity, channel_saturation_pow_half);
1568 if *used_liquidity_msat == hop_max_msat {
1569 // If this path used all of this channel's available liquidity, we know
1570 // this path will not be selected again in the next loop iteration.
1571 prevented_redundant_path_selection = true;
1573 debug_assert!(*used_liquidity_msat <= hop_max_msat);
1575 if !prevented_redundant_path_selection {
1576 // If we weren't capped by hitting a liquidity limit on a channel in the path,
1577 // we'll probably end up picking the same path again on the next iteration.
1578 // Decrease the available liquidity of a hop in the middle of the path.
1579 let victim_scid = payment_path.hops[(payment_path.hops.len()) / 2].0.candidate.short_channel_id();
1580 let exhausted = u64::max_value();
1581 log_trace!(logger, "Disabling channel {} for future path building iterations to avoid duplicates.", victim_scid);
1582 *used_channel_liquidities.entry((victim_scid, false)).or_default() = exhausted;
1583 *used_channel_liquidities.entry((victim_scid, true)).or_default() = exhausted;
1586 // Track the total amount all our collected paths allow to send so that we know
1587 // when to stop looking for more paths
1588 already_collected_value_msat += value_contribution_msat;
1590 payment_paths.push(payment_path);
1591 found_new_path = true;
1592 break 'path_construction;
1595 // If we found a path back to the payee, we shouldn't try to process it again. This is
1596 // the equivalent of the `elem.was_processed` check in
1597 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
1598 if node_id == payee_node_id { continue 'path_construction; }
1600 // Otherwise, since the current target node is not us,
1601 // keep "unrolling" the payment graph from payee to payer by
1602 // finding a way to reach the current target from the payer side.
1603 match network_nodes.get(&node_id) {
1606 add_entries_to_cheapest_to_target_node!(node, node_id, lowest_fee_to_node,
1607 value_contribution_msat, path_htlc_minimum_msat, path_penalty_msat,
1608 total_cltv_delta, path_length_to_node);
1614 if !found_new_path && channel_saturation_pow_half != 0 {
1615 channel_saturation_pow_half = 0;
1616 continue 'paths_collection;
1618 // If we don't support MPP, no use trying to gather more value ever.
1619 break 'paths_collection;
1623 // Stop either when the recommended value is reached or if no new path was found in this
1625 // In the latter case, making another path finding attempt won't help,
1626 // because we deterministically terminated the search due to low liquidity.
1627 if !found_new_path && channel_saturation_pow_half != 0 {
1628 channel_saturation_pow_half = 0;
1629 } else if already_collected_value_msat >= recommended_value_msat || !found_new_path {
1630 log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
1631 already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
1632 break 'paths_collection;
1633 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
1634 // Further, if this was our first walk of the graph, and we weren't limited by an
1635 // htlc_minimum_msat, return immediately because this path should suffice. If we were
1636 // limited by an htlc_minimum_msat value, find another path with a higher value,
1637 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
1638 // still keeping a lower total fee than this path.
1639 if !hit_minimum_limit {
1640 log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
1641 break 'paths_collection;
1643 log_trace!(logger, "Collected our payment amount on the first pass, but running again to collect extra paths with a potentially higher limit.");
1644 path_value_msat = recommended_value_msat;
1649 if payment_paths.len() == 0 {
1650 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1653 if already_collected_value_msat < final_value_msat {
1654 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1658 let mut selected_route = payment_paths;
1660 debug_assert_eq!(selected_route.iter().map(|p| p.get_value_msat()).sum::<u64>(), already_collected_value_msat);
1661 let mut overpaid_value_msat = already_collected_value_msat - final_value_msat;
1663 // First, sort by the cost-per-value of the path, dropping the paths that cost the most for
1664 // the value they contribute towards the payment amount.
1665 // We sort in descending order as we will remove from the front in `retain`, next.
1666 selected_route.sort_unstable_by(|a, b|
1667 (((b.get_cost_msat() as u128) << 64) / (b.get_value_msat() as u128))
1668 .cmp(&(((a.get_cost_msat() as u128) << 64) / (a.get_value_msat() as u128)))
1671 // We should make sure that at least 1 path left.
1672 let mut paths_left = selected_route.len();
1673 selected_route.retain(|path| {
1674 if paths_left == 1 {
1677 let path_value_msat = path.get_value_msat();
1678 if path_value_msat <= overpaid_value_msat {
1679 overpaid_value_msat -= path_value_msat;
1685 debug_assert!(selected_route.len() > 0);
1687 if overpaid_value_msat != 0 {
1689 // Now, subtract the remaining overpaid value from the most-expensive path.
1690 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1691 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1692 selected_route.sort_unstable_by(|a, b| {
1693 let a_f = a.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
1694 let b_f = b.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
1695 a_f.cmp(&b_f).then_with(|| b.get_cost_msat().cmp(&a.get_cost_msat()))
1697 let expensive_payment_path = selected_route.first_mut().unwrap();
1699 // We already dropped all the paths with value below `overpaid_value_msat` above, thus this
1700 // can't go negative.
1701 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
1702 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
1706 // Sort by the path itself and combine redundant paths.
1707 // Note that we sort by SCIDs alone as its simpler but when combining we have to ensure we
1708 // compare both SCIDs and NodeIds as individual nodes may use random aliases causing collisions
1710 selected_route.sort_unstable_by_key(|path| {
1711 let mut key = [0u64; MAX_PATH_LENGTH_ESTIMATE as usize];
1712 debug_assert!(path.hops.len() <= key.len());
1713 for (scid, key) in path.hops.iter().map(|h| h.0.candidate.short_channel_id()).zip(key.iter_mut()) {
1718 for idx in 0..(selected_route.len() - 1) {
1719 if idx + 1 >= selected_route.len() { break; }
1720 if iter_equal(selected_route[idx ].hops.iter().map(|h| (h.0.candidate.short_channel_id(), h.0.node_id)),
1721 selected_route[idx + 1].hops.iter().map(|h| (h.0.candidate.short_channel_id(), h.0.node_id))) {
1722 let new_value = selected_route[idx].get_value_msat() + selected_route[idx + 1].get_value_msat();
1723 selected_route[idx].update_value_and_recompute_fees(new_value);
1724 selected_route.remove(idx + 1);
1728 let mut selected_paths = Vec::<Vec<Result<RouteHop, LightningError>>>::new();
1729 for payment_path in selected_route {
1730 let mut path = payment_path.hops.iter().map(|(payment_hop, node_features)| {
1732 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)})?,
1733 node_features: node_features.clone(),
1734 short_channel_id: payment_hop.candidate.short_channel_id(),
1735 channel_features: payment_hop.candidate.features(),
1736 fee_msat: payment_hop.fee_msat,
1737 cltv_expiry_delta: payment_hop.candidate.cltv_expiry_delta(),
1739 }).collect::<Vec<_>>();
1740 // Propagate the cltv_expiry_delta one hop backwards since the delta from the current hop is
1741 // applicable for the previous hop.
1742 path.iter_mut().rev().fold(final_cltv_expiry_delta, |prev_cltv_expiry_delta, hop| {
1743 core::mem::replace(&mut hop.as_mut().unwrap().cltv_expiry_delta, prev_cltv_expiry_delta)
1745 selected_paths.push(path);
1747 // Make sure we would never create a route with more paths than we allow.
1748 debug_assert!(selected_paths.len() <= payment_params.max_path_count.into());
1750 if let Some(features) = &payment_params.features {
1751 for path in selected_paths.iter_mut() {
1752 if let Ok(route_hop) = path.last_mut().unwrap() {
1753 route_hop.node_features = features.to_context();
1759 paths: selected_paths.into_iter().map(|path| path.into_iter().collect()).collect::<Result<Vec<_>, _>>()?,
1760 payment_params: Some(payment_params.clone()),
1762 log_info!(logger, "Got route to {}: {}", payment_params.payee_pubkey, log_route!(route));
1766 // When an adversarial intermediary node observes a payment, it may be able to infer its
1767 // destination, if the remaining CLTV expiry delta exactly matches a feasible path in the network
1768 // graph. In order to improve privacy, this method obfuscates the CLTV expiry deltas along the
1769 // payment path by adding a randomized 'shadow route' offset to the final hop.
1770 fn add_random_cltv_offset(route: &mut Route, payment_params: &PaymentParameters,
1771 network_graph: &ReadOnlyNetworkGraph, random_seed_bytes: &[u8; 32]
1773 let network_channels = network_graph.channels();
1774 let network_nodes = network_graph.nodes();
1776 for path in route.paths.iter_mut() {
1777 let mut shadow_ctlv_expiry_delta_offset: u32 = 0;
1779 // Remember the last three nodes of the random walk and avoid looping back on them.
1780 // Init with the last three nodes from the actual path, if possible.
1781 let mut nodes_to_avoid: [NodeId; 3] = [NodeId::from_pubkey(&path.last().unwrap().pubkey),
1782 NodeId::from_pubkey(&path.get(path.len().saturating_sub(2)).unwrap().pubkey),
1783 NodeId::from_pubkey(&path.get(path.len().saturating_sub(3)).unwrap().pubkey)];
1785 // Choose the last publicly known node as the starting point for the random walk.
1786 let mut cur_hop: Option<NodeId> = None;
1787 let mut path_nonce = [0u8; 12];
1788 if let Some(starting_hop) = path.iter().rev()
1789 .find(|h| network_nodes.contains_key(&NodeId::from_pubkey(&h.pubkey))) {
1790 cur_hop = Some(NodeId::from_pubkey(&starting_hop.pubkey));
1791 path_nonce.copy_from_slice(&cur_hop.unwrap().as_slice()[..12]);
1794 // Init PRNG with the path-dependant nonce, which is static for private paths.
1795 let mut prng = ChaCha20::new(random_seed_bytes, &path_nonce);
1796 let mut random_path_bytes = [0u8; ::core::mem::size_of::<usize>()];
1798 // Pick a random path length in [1 .. 3]
1799 prng.process_in_place(&mut random_path_bytes);
1800 let random_walk_length = usize::from_be_bytes(random_path_bytes).wrapping_rem(3).wrapping_add(1);
1802 for random_hop in 0..random_walk_length {
1803 // If we don't find a suitable offset in the public network graph, we default to
1804 // MEDIAN_HOP_CLTV_EXPIRY_DELTA.
1805 let mut random_hop_offset = MEDIAN_HOP_CLTV_EXPIRY_DELTA;
1807 if let Some(cur_node_id) = cur_hop {
1808 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
1809 // Randomly choose the next unvisited hop.
1810 prng.process_in_place(&mut random_path_bytes);
1811 if let Some(random_channel) = usize::from_be_bytes(random_path_bytes)
1812 .checked_rem(cur_node.channels.len())
1813 .and_then(|index| cur_node.channels.get(index))
1814 .and_then(|id| network_channels.get(id)) {
1815 random_channel.as_directed_from(&cur_node_id).map(|(dir_info, next_id)| {
1816 if !nodes_to_avoid.iter().any(|x| x == next_id) {
1817 nodes_to_avoid[random_hop] = *next_id;
1818 dir_info.direction().map(|channel_update_info| {
1819 random_hop_offset = channel_update_info.cltv_expiry_delta.into();
1820 cur_hop = Some(*next_id);
1828 shadow_ctlv_expiry_delta_offset = shadow_ctlv_expiry_delta_offset
1829 .checked_add(random_hop_offset)
1830 .unwrap_or(shadow_ctlv_expiry_delta_offset);
1833 // Limit the total offset to reduce the worst-case locked liquidity timevalue
1834 const MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET: u32 = 3*144;
1835 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET);
1837 // Limit the offset so we never exceed the max_total_cltv_expiry_delta. To improve plausibility,
1838 // we choose the limit to be the largest possible multiple of MEDIAN_HOP_CLTV_EXPIRY_DELTA.
1839 let path_total_cltv_expiry_delta: u32 = path.iter().map(|h| h.cltv_expiry_delta).sum();
1840 let mut max_path_offset = payment_params.max_total_cltv_expiry_delta - path_total_cltv_expiry_delta;
1841 max_path_offset = cmp::max(
1842 max_path_offset - (max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA),
1843 max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA);
1844 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, max_path_offset);
1846 // Add 'shadow' CLTV offset to the final hop
1847 if let Some(last_hop) = path.last_mut() {
1848 last_hop.cltv_expiry_delta = last_hop.cltv_expiry_delta
1849 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(last_hop.cltv_expiry_delta);
1854 /// Construct a route from us (payer) to the target node (payee) via the given hops (which should
1855 /// exclude the payer, but include the payee). This may be useful, e.g., for probing the chosen path.
1857 /// Re-uses logic from `find_route`, so the restrictions described there also apply here.
1858 pub fn build_route_from_hops<L: Deref, GL: Deref>(
1859 our_node_pubkey: &PublicKey, hops: &[PublicKey], route_params: &RouteParameters,
1860 network_graph: &NetworkGraph<GL>, logger: L, random_seed_bytes: &[u8; 32]
1861 ) -> Result<Route, LightningError>
1862 where L::Target: Logger, GL::Target: Logger {
1863 let graph_lock = network_graph.read_only();
1864 let mut route = build_route_from_hops_internal(
1865 our_node_pubkey, hops, &route_params.payment_params, &graph_lock,
1866 route_params.final_value_msat, route_params.final_cltv_expiry_delta, logger, random_seed_bytes)?;
1867 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
1871 fn build_route_from_hops_internal<L: Deref>(
1872 our_node_pubkey: &PublicKey, hops: &[PublicKey], payment_params: &PaymentParameters,
1873 network_graph: &ReadOnlyNetworkGraph, final_value_msat: u64, final_cltv_expiry_delta: u32,
1874 logger: L, random_seed_bytes: &[u8; 32]
1875 ) -> Result<Route, LightningError> where L::Target: Logger {
1878 our_node_id: NodeId,
1879 hop_ids: [Option<NodeId>; MAX_PATH_LENGTH_ESTIMATE as usize],
1882 impl Score for HopScorer {
1883 fn channel_penalty_msat(&self, _short_channel_id: u64, source: &NodeId, target: &NodeId,
1884 _usage: ChannelUsage) -> u64
1886 let mut cur_id = self.our_node_id;
1887 for i in 0..self.hop_ids.len() {
1888 if let Some(next_id) = self.hop_ids[i] {
1889 if cur_id == *source && next_id == *target {
1900 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
1902 fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
1904 fn probe_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
1906 fn probe_successful(&mut self, _path: &[&RouteHop]) {}
1909 impl<'a> Writeable for HopScorer {
1911 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), io::Error> {
1916 if hops.len() > MAX_PATH_LENGTH_ESTIMATE.into() {
1917 return Err(LightningError{err: "Cannot build a route exceeding the maximum path length.".to_owned(), action: ErrorAction::IgnoreError});
1920 let our_node_id = NodeId::from_pubkey(our_node_pubkey);
1921 let mut hop_ids = [None; MAX_PATH_LENGTH_ESTIMATE as usize];
1922 for i in 0..hops.len() {
1923 hop_ids[i] = Some(NodeId::from_pubkey(&hops[i]));
1926 let scorer = HopScorer { our_node_id, hop_ids };
1928 get_route(our_node_pubkey, payment_params, network_graph, None, final_value_msat,
1929 final_cltv_expiry_delta, logger, &scorer, random_seed_bytes)
1934 use crate::routing::gossip::{NetworkGraph, P2PGossipSync, NodeId, EffectiveCapacity};
1935 use crate::routing::router::{get_route, build_route_from_hops_internal, add_random_cltv_offset, default_node_features,
1936 PaymentParameters, Route, RouteHint, RouteHintHop, RouteHop, RoutingFees,
1937 DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA, MAX_PATH_LENGTH_ESTIMATE};
1938 use crate::routing::scoring::{ChannelUsage, Score, ProbabilisticScorer, ProbabilisticScoringParameters};
1939 use crate::routing::test_utils::{add_channel, add_or_update_node, build_graph, build_line_graph, id_to_feature_flags, get_nodes, update_channel};
1940 use crate::chain::transaction::OutPoint;
1941 use crate::chain::keysinterface::KeysInterface;
1942 use crate::ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
1943 use crate::ln::msgs::{ErrorAction, LightningError, UnsignedChannelUpdate, MAX_VALUE_MSAT};
1944 use crate::ln::channelmanager;
1945 use crate::util::test_utils as ln_test_utils;
1946 use crate::util::chacha20::ChaCha20;
1948 use crate::util::ser::{Writeable, Writer};
1950 use bitcoin::hashes::Hash;
1951 use bitcoin::network::constants::Network;
1952 use bitcoin::blockdata::constants::genesis_block;
1953 use bitcoin::blockdata::script::Builder;
1954 use bitcoin::blockdata::opcodes;
1955 use bitcoin::blockdata::transaction::TxOut;
1959 use bitcoin::secp256k1::{PublicKey,SecretKey};
1960 use bitcoin::secp256k1::Secp256k1;
1962 use crate::prelude::*;
1963 use crate::sync::Arc;
1965 use core::convert::TryInto;
1967 fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
1968 features: InitFeatures, outbound_capacity_msat: u64) -> channelmanager::ChannelDetails {
1969 channelmanager::ChannelDetails {
1970 channel_id: [0; 32],
1971 counterparty: channelmanager::ChannelCounterparty {
1974 unspendable_punishment_reserve: 0,
1975 forwarding_info: None,
1976 outbound_htlc_minimum_msat: None,
1977 outbound_htlc_maximum_msat: None,
1979 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
1982 outbound_scid_alias: None,
1983 inbound_scid_alias: None,
1984 channel_value_satoshis: 0,
1987 outbound_capacity_msat,
1988 next_outbound_htlc_limit_msat: outbound_capacity_msat,
1989 inbound_capacity_msat: 42,
1990 unspendable_punishment_reserve: None,
1991 confirmations_required: None,
1992 force_close_spend_delay: None,
1993 is_outbound: true, is_channel_ready: true,
1994 is_usable: true, is_public: true,
1995 inbound_htlc_minimum_msat: None,
1996 inbound_htlc_maximum_msat: None,
2002 fn simple_route_test() {
2003 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2004 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2005 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2006 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2007 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2008 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2010 // Simple route to 2 via 1
2012 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) {
2013 assert_eq!(err, "Cannot send a payment of 0 msat");
2014 } else { panic!(); }
2016 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2017 assert_eq!(route.paths[0].len(), 2);
2019 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2020 assert_eq!(route.paths[0][0].short_channel_id, 2);
2021 assert_eq!(route.paths[0][0].fee_msat, 100);
2022 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2023 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2024 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2026 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2027 assert_eq!(route.paths[0][1].short_channel_id, 4);
2028 assert_eq!(route.paths[0][1].fee_msat, 100);
2029 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2030 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2031 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2035 fn invalid_first_hop_test() {
2036 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2037 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2038 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2039 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2040 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2041 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2043 // Simple route to 2 via 1
2045 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
2047 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) =
2048 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) {
2049 assert_eq!(err, "First hop cannot have our_node_pubkey as a destination.");
2050 } else { panic!(); }
2052 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2053 assert_eq!(route.paths[0].len(), 2);
2057 fn htlc_minimum_test() {
2058 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2059 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2060 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2061 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2062 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2063 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2065 // Simple route to 2 via 1
2067 // Disable other paths
2068 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2069 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2070 short_channel_id: 12,
2072 flags: 2, // to disable
2073 cltv_expiry_delta: 0,
2074 htlc_minimum_msat: 0,
2075 htlc_maximum_msat: MAX_VALUE_MSAT,
2077 fee_proportional_millionths: 0,
2078 excess_data: Vec::new()
2080 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2081 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2082 short_channel_id: 3,
2084 flags: 2, // to disable
2085 cltv_expiry_delta: 0,
2086 htlc_minimum_msat: 0,
2087 htlc_maximum_msat: MAX_VALUE_MSAT,
2089 fee_proportional_millionths: 0,
2090 excess_data: Vec::new()
2092 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2093 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2094 short_channel_id: 13,
2096 flags: 2, // to disable
2097 cltv_expiry_delta: 0,
2098 htlc_minimum_msat: 0,
2099 htlc_maximum_msat: MAX_VALUE_MSAT,
2101 fee_proportional_millionths: 0,
2102 excess_data: Vec::new()
2104 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2105 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2106 short_channel_id: 6,
2108 flags: 2, // to disable
2109 cltv_expiry_delta: 0,
2110 htlc_minimum_msat: 0,
2111 htlc_maximum_msat: MAX_VALUE_MSAT,
2113 fee_proportional_millionths: 0,
2114 excess_data: Vec::new()
2116 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2117 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2118 short_channel_id: 7,
2120 flags: 2, // to disable
2121 cltv_expiry_delta: 0,
2122 htlc_minimum_msat: 0,
2123 htlc_maximum_msat: MAX_VALUE_MSAT,
2125 fee_proportional_millionths: 0,
2126 excess_data: Vec::new()
2129 // Check against amount_to_transfer_over_msat.
2130 // Set minimal HTLC of 200_000_000 msat.
2131 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2132 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2133 short_channel_id: 2,
2136 cltv_expiry_delta: 0,
2137 htlc_minimum_msat: 200_000_000,
2138 htlc_maximum_msat: MAX_VALUE_MSAT,
2140 fee_proportional_millionths: 0,
2141 excess_data: Vec::new()
2144 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
2146 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2147 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2148 short_channel_id: 4,
2151 cltv_expiry_delta: 0,
2152 htlc_minimum_msat: 0,
2153 htlc_maximum_msat: 199_999_999,
2155 fee_proportional_millionths: 0,
2156 excess_data: Vec::new()
2159 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
2160 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) {
2161 assert_eq!(err, "Failed to find a path to the given destination");
2162 } else { panic!(); }
2164 // Lift the restriction on the first hop.
2165 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2166 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2167 short_channel_id: 2,
2170 cltv_expiry_delta: 0,
2171 htlc_minimum_msat: 0,
2172 htlc_maximum_msat: MAX_VALUE_MSAT,
2174 fee_proportional_millionths: 0,
2175 excess_data: Vec::new()
2178 // A payment above the minimum should pass
2179 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();
2180 assert_eq!(route.paths[0].len(), 2);
2184 fn htlc_minimum_overpay_test() {
2185 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2186 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2187 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(channelmanager::provided_invoice_features());
2188 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2189 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2190 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2192 // A route to node#2 via two paths.
2193 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
2194 // Thus, they can't send 60 without overpaying.
2195 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2196 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2197 short_channel_id: 2,
2200 cltv_expiry_delta: 0,
2201 htlc_minimum_msat: 35_000,
2202 htlc_maximum_msat: 40_000,
2204 fee_proportional_millionths: 0,
2205 excess_data: Vec::new()
2207 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2208 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2209 short_channel_id: 12,
2212 cltv_expiry_delta: 0,
2213 htlc_minimum_msat: 35_000,
2214 htlc_maximum_msat: 40_000,
2216 fee_proportional_millionths: 0,
2217 excess_data: Vec::new()
2221 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2222 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2223 short_channel_id: 13,
2226 cltv_expiry_delta: 0,
2227 htlc_minimum_msat: 0,
2228 htlc_maximum_msat: MAX_VALUE_MSAT,
2230 fee_proportional_millionths: 0,
2231 excess_data: Vec::new()
2233 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2234 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2235 short_channel_id: 4,
2238 cltv_expiry_delta: 0,
2239 htlc_minimum_msat: 0,
2240 htlc_maximum_msat: MAX_VALUE_MSAT,
2242 fee_proportional_millionths: 0,
2243 excess_data: Vec::new()
2246 // Disable other paths
2247 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2248 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2249 short_channel_id: 1,
2251 flags: 2, // to disable
2252 cltv_expiry_delta: 0,
2253 htlc_minimum_msat: 0,
2254 htlc_maximum_msat: MAX_VALUE_MSAT,
2256 fee_proportional_millionths: 0,
2257 excess_data: Vec::new()
2260 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 60_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2261 // Overpay fees to hit htlc_minimum_msat.
2262 let overpaid_fees = route.paths[0][0].fee_msat + route.paths[1][0].fee_msat;
2263 // TODO: this could be better balanced to overpay 10k and not 15k.
2264 assert_eq!(overpaid_fees, 15_000);
2266 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
2267 // while taking even more fee to match htlc_minimum_msat.
2268 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2269 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2270 short_channel_id: 12,
2273 cltv_expiry_delta: 0,
2274 htlc_minimum_msat: 65_000,
2275 htlc_maximum_msat: 80_000,
2277 fee_proportional_millionths: 0,
2278 excess_data: Vec::new()
2280 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2281 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2282 short_channel_id: 2,
2285 cltv_expiry_delta: 0,
2286 htlc_minimum_msat: 0,
2287 htlc_maximum_msat: MAX_VALUE_MSAT,
2289 fee_proportional_millionths: 0,
2290 excess_data: Vec::new()
2292 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2293 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2294 short_channel_id: 4,
2297 cltv_expiry_delta: 0,
2298 htlc_minimum_msat: 0,
2299 htlc_maximum_msat: MAX_VALUE_MSAT,
2301 fee_proportional_millionths: 100_000,
2302 excess_data: Vec::new()
2305 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 60_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2306 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
2307 assert_eq!(route.paths.len(), 1);
2308 assert_eq!(route.paths[0][0].short_channel_id, 12);
2309 let fees = route.paths[0][0].fee_msat;
2310 assert_eq!(fees, 5_000);
2312 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2313 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
2314 // the other channel.
2315 assert_eq!(route.paths.len(), 1);
2316 assert_eq!(route.paths[0][0].short_channel_id, 2);
2317 let fees = route.paths[0][0].fee_msat;
2318 assert_eq!(fees, 5_000);
2322 fn disable_channels_test() {
2323 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2324 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2325 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2326 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2327 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2328 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2330 // // Disable channels 4 and 12 by flags=2
2331 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2332 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2333 short_channel_id: 4,
2335 flags: 2, // to disable
2336 cltv_expiry_delta: 0,
2337 htlc_minimum_msat: 0,
2338 htlc_maximum_msat: MAX_VALUE_MSAT,
2340 fee_proportional_millionths: 0,
2341 excess_data: Vec::new()
2343 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2344 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2345 short_channel_id: 12,
2347 flags: 2, // to disable
2348 cltv_expiry_delta: 0,
2349 htlc_minimum_msat: 0,
2350 htlc_maximum_msat: MAX_VALUE_MSAT,
2352 fee_proportional_millionths: 0,
2353 excess_data: Vec::new()
2356 // If all the channels require some features we don't understand, route should fail
2357 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) {
2358 assert_eq!(err, "Failed to find a path to the given destination");
2359 } else { panic!(); }
2361 // If we specify a channel to node7, that overrides our local channel view and that gets used
2362 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2363 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();
2364 assert_eq!(route.paths[0].len(), 2);
2366 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2367 assert_eq!(route.paths[0][0].short_channel_id, 42);
2368 assert_eq!(route.paths[0][0].fee_msat, 200);
2369 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2370 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2371 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2373 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2374 assert_eq!(route.paths[0][1].short_channel_id, 13);
2375 assert_eq!(route.paths[0][1].fee_msat, 100);
2376 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2377 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2378 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2382 fn disable_node_test() {
2383 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2384 let (_, 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 nodes 1, 2, and 8 by requiring unknown feature bits
2391 let mut unknown_features = NodeFeatures::empty();
2392 unknown_features.set_unknown_feature_required();
2393 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
2394 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
2395 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
2397 // If all nodes require some features we don't understand, route should fail
2398 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) {
2399 assert_eq!(err, "Failed to find a path to the given destination");
2400 } else { panic!(); }
2402 // If we specify a channel to node7, that overrides our local channel view and that gets used
2403 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2404 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();
2405 assert_eq!(route.paths[0].len(), 2);
2407 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2408 assert_eq!(route.paths[0][0].short_channel_id, 42);
2409 assert_eq!(route.paths[0][0].fee_msat, 200);
2410 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2411 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2412 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2414 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2415 assert_eq!(route.paths[0][1].short_channel_id, 13);
2416 assert_eq!(route.paths[0][1].fee_msat, 100);
2417 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2418 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2419 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2421 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
2422 // naively) assume that the user checked the feature bits on the invoice, which override
2423 // the node_announcement.
2427 fn our_chans_test() {
2428 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2429 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2430 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2431 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2432 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2434 // Route to 1 via 2 and 3 because our channel to 1 is disabled
2435 let payment_params = PaymentParameters::from_node_id(nodes[0]);
2436 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2437 assert_eq!(route.paths[0].len(), 3);
2439 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2440 assert_eq!(route.paths[0][0].short_channel_id, 2);
2441 assert_eq!(route.paths[0][0].fee_msat, 200);
2442 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2443 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2444 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2446 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2447 assert_eq!(route.paths[0][1].short_channel_id, 4);
2448 assert_eq!(route.paths[0][1].fee_msat, 100);
2449 assert_eq!(route.paths[0][1].cltv_expiry_delta, (3 << 4) | 2);
2450 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2451 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2453 assert_eq!(route.paths[0][2].pubkey, nodes[0]);
2454 assert_eq!(route.paths[0][2].short_channel_id, 3);
2455 assert_eq!(route.paths[0][2].fee_msat, 100);
2456 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
2457 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(1));
2458 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(3));
2460 // If we specify a channel to node7, that overrides our local channel view and that gets used
2461 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2462 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2463 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&our_chans.iter().collect::<Vec<_>>()), 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2464 assert_eq!(route.paths[0].len(), 2);
2466 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2467 assert_eq!(route.paths[0][0].short_channel_id, 42);
2468 assert_eq!(route.paths[0][0].fee_msat, 200);
2469 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2470 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2471 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2473 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2474 assert_eq!(route.paths[0][1].short_channel_id, 13);
2475 assert_eq!(route.paths[0][1].fee_msat, 100);
2476 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2477 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2478 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2481 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2482 let zero_fees = RoutingFees {
2484 proportional_millionths: 0,
2486 vec![RouteHint(vec![RouteHintHop {
2487 src_node_id: nodes[3],
2488 short_channel_id: 8,
2490 cltv_expiry_delta: (8 << 4) | 1,
2491 htlc_minimum_msat: None,
2492 htlc_maximum_msat: None,
2494 ]), RouteHint(vec![RouteHintHop {
2495 src_node_id: nodes[4],
2496 short_channel_id: 9,
2499 proportional_millionths: 0,
2501 cltv_expiry_delta: (9 << 4) | 1,
2502 htlc_minimum_msat: None,
2503 htlc_maximum_msat: None,
2504 }]), RouteHint(vec![RouteHintHop {
2505 src_node_id: nodes[5],
2506 short_channel_id: 10,
2508 cltv_expiry_delta: (10 << 4) | 1,
2509 htlc_minimum_msat: None,
2510 htlc_maximum_msat: None,
2514 fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2515 let zero_fees = RoutingFees {
2517 proportional_millionths: 0,
2519 vec![RouteHint(vec![RouteHintHop {
2520 src_node_id: nodes[2],
2521 short_channel_id: 5,
2524 proportional_millionths: 0,
2526 cltv_expiry_delta: (5 << 4) | 1,
2527 htlc_minimum_msat: None,
2528 htlc_maximum_msat: None,
2530 src_node_id: nodes[3],
2531 short_channel_id: 8,
2533 cltv_expiry_delta: (8 << 4) | 1,
2534 htlc_minimum_msat: None,
2535 htlc_maximum_msat: None,
2537 ]), RouteHint(vec![RouteHintHop {
2538 src_node_id: nodes[4],
2539 short_channel_id: 9,
2542 proportional_millionths: 0,
2544 cltv_expiry_delta: (9 << 4) | 1,
2545 htlc_minimum_msat: None,
2546 htlc_maximum_msat: None,
2547 }]), RouteHint(vec![RouteHintHop {
2548 src_node_id: nodes[5],
2549 short_channel_id: 10,
2551 cltv_expiry_delta: (10 << 4) | 1,
2552 htlc_minimum_msat: None,
2553 htlc_maximum_msat: None,
2558 fn partial_route_hint_test() {
2559 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2560 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2561 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2562 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2563 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2565 // Simple test across 2, 3, 5, and 4 via a last_hop channel
2566 // Tests the behaviour when the RouteHint contains a suboptimal hop.
2567 // RouteHint may be partially used by the algo to build the best path.
2569 // First check that last hop can't have its source as the payee.
2570 let invalid_last_hop = RouteHint(vec![RouteHintHop {
2571 src_node_id: nodes[6],
2572 short_channel_id: 8,
2575 proportional_millionths: 0,
2577 cltv_expiry_delta: (8 << 4) | 1,
2578 htlc_minimum_msat: None,
2579 htlc_maximum_msat: None,
2582 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
2583 invalid_last_hops.push(invalid_last_hop);
2585 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(invalid_last_hops);
2586 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) {
2587 assert_eq!(err, "Route hint cannot have the payee as the source.");
2588 } else { panic!(); }
2591 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops_multi_private_channels(&nodes));
2592 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2593 assert_eq!(route.paths[0].len(), 5);
2595 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2596 assert_eq!(route.paths[0][0].short_channel_id, 2);
2597 assert_eq!(route.paths[0][0].fee_msat, 100);
2598 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2599 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2600 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2602 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2603 assert_eq!(route.paths[0][1].short_channel_id, 4);
2604 assert_eq!(route.paths[0][1].fee_msat, 0);
2605 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
2606 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2607 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2609 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2610 assert_eq!(route.paths[0][2].short_channel_id, 6);
2611 assert_eq!(route.paths[0][2].fee_msat, 0);
2612 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
2613 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2614 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2616 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2617 assert_eq!(route.paths[0][3].short_channel_id, 11);
2618 assert_eq!(route.paths[0][3].fee_msat, 0);
2619 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
2620 // If we have a peer in the node map, we'll use their features here since we don't have
2621 // a way of figuring out their features from the invoice:
2622 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2623 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2625 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2626 assert_eq!(route.paths[0][4].short_channel_id, 8);
2627 assert_eq!(route.paths[0][4].fee_msat, 100);
2628 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2629 assert_eq!(route.paths[0][4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
2630 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2633 fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2634 let zero_fees = RoutingFees {
2636 proportional_millionths: 0,
2638 vec![RouteHint(vec![RouteHintHop {
2639 src_node_id: nodes[3],
2640 short_channel_id: 8,
2642 cltv_expiry_delta: (8 << 4) | 1,
2643 htlc_minimum_msat: None,
2644 htlc_maximum_msat: None,
2645 }]), RouteHint(vec![
2647 ]), RouteHint(vec![RouteHintHop {
2648 src_node_id: nodes[5],
2649 short_channel_id: 10,
2651 cltv_expiry_delta: (10 << 4) | 1,
2652 htlc_minimum_msat: None,
2653 htlc_maximum_msat: None,
2658 fn ignores_empty_last_hops_test() {
2659 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2660 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2661 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(empty_last_hop(&nodes));
2662 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2663 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2664 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2666 // Test handling of an empty RouteHint passed in Invoice.
2668 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2669 assert_eq!(route.paths[0].len(), 5);
2671 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2672 assert_eq!(route.paths[0][0].short_channel_id, 2);
2673 assert_eq!(route.paths[0][0].fee_msat, 100);
2674 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2675 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2676 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2678 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2679 assert_eq!(route.paths[0][1].short_channel_id, 4);
2680 assert_eq!(route.paths[0][1].fee_msat, 0);
2681 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
2682 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2683 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2685 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2686 assert_eq!(route.paths[0][2].short_channel_id, 6);
2687 assert_eq!(route.paths[0][2].fee_msat, 0);
2688 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
2689 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2690 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2692 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2693 assert_eq!(route.paths[0][3].short_channel_id, 11);
2694 assert_eq!(route.paths[0][3].fee_msat, 0);
2695 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
2696 // If we have a peer in the node map, we'll use their features here since we don't have
2697 // a way of figuring out their features from the invoice:
2698 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2699 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2701 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2702 assert_eq!(route.paths[0][4].short_channel_id, 8);
2703 assert_eq!(route.paths[0][4].fee_msat, 100);
2704 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2705 assert_eq!(route.paths[0][4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
2706 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2709 /// Builds a trivial last-hop hint that passes through the two nodes given, with channel 0xff00
2711 fn multi_hop_last_hops_hint(hint_hops: [PublicKey; 2]) -> Vec<RouteHint> {
2712 let zero_fees = RoutingFees {
2714 proportional_millionths: 0,
2716 vec![RouteHint(vec![RouteHintHop {
2717 src_node_id: hint_hops[0],
2718 short_channel_id: 0xff00,
2721 proportional_millionths: 0,
2723 cltv_expiry_delta: (5 << 4) | 1,
2724 htlc_minimum_msat: None,
2725 htlc_maximum_msat: None,
2727 src_node_id: hint_hops[1],
2728 short_channel_id: 0xff01,
2730 cltv_expiry_delta: (8 << 4) | 1,
2731 htlc_minimum_msat: None,
2732 htlc_maximum_msat: None,
2737 fn multi_hint_last_hops_test() {
2738 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2739 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2740 let last_hops = multi_hop_last_hops_hint([nodes[2], nodes[3]]);
2741 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops.clone());
2742 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2743 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2744 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2745 // Test through channels 2, 3, 0xff00, 0xff01.
2746 // Test shows that multiple hop hints are considered.
2748 // Disabling channels 6 & 7 by flags=2
2749 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2750 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2751 short_channel_id: 6,
2753 flags: 2, // to disable
2754 cltv_expiry_delta: 0,
2755 htlc_minimum_msat: 0,
2756 htlc_maximum_msat: MAX_VALUE_MSAT,
2758 fee_proportional_millionths: 0,
2759 excess_data: Vec::new()
2761 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2762 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2763 short_channel_id: 7,
2765 flags: 2, // to disable
2766 cltv_expiry_delta: 0,
2767 htlc_minimum_msat: 0,
2768 htlc_maximum_msat: MAX_VALUE_MSAT,
2770 fee_proportional_millionths: 0,
2771 excess_data: Vec::new()
2774 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2775 assert_eq!(route.paths[0].len(), 4);
2777 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2778 assert_eq!(route.paths[0][0].short_channel_id, 2);
2779 assert_eq!(route.paths[0][0].fee_msat, 200);
2780 assert_eq!(route.paths[0][0].cltv_expiry_delta, 65);
2781 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2782 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2784 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2785 assert_eq!(route.paths[0][1].short_channel_id, 4);
2786 assert_eq!(route.paths[0][1].fee_msat, 100);
2787 assert_eq!(route.paths[0][1].cltv_expiry_delta, 81);
2788 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2789 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2791 assert_eq!(route.paths[0][2].pubkey, nodes[3]);
2792 assert_eq!(route.paths[0][2].short_channel_id, last_hops[0].0[0].short_channel_id);
2793 assert_eq!(route.paths[0][2].fee_msat, 0);
2794 assert_eq!(route.paths[0][2].cltv_expiry_delta, 129);
2795 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(4));
2796 assert_eq!(route.paths[0][2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2798 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2799 assert_eq!(route.paths[0][3].short_channel_id, last_hops[0].0[1].short_channel_id);
2800 assert_eq!(route.paths[0][3].fee_msat, 100);
2801 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2802 assert_eq!(route.paths[0][3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
2803 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2807 fn private_multi_hint_last_hops_test() {
2808 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2809 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2811 let non_announced_privkey = SecretKey::from_slice(&hex::decode(format!("{:02x}", 0xf0).repeat(32)).unwrap()[..]).unwrap();
2812 let non_announced_pubkey = PublicKey::from_secret_key(&secp_ctx, &non_announced_privkey);
2814 let last_hops = multi_hop_last_hops_hint([nodes[2], non_announced_pubkey]);
2815 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops.clone());
2816 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2817 // Test through channels 2, 3, 0xff00, 0xff01.
2818 // Test shows that multiple hop hints are considered.
2820 // Disabling channels 6 & 7 by flags=2
2821 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2822 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2823 short_channel_id: 6,
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()
2833 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2834 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2835 short_channel_id: 7,
2837 flags: 2, // to disable
2838 cltv_expiry_delta: 0,
2839 htlc_minimum_msat: 0,
2840 htlc_maximum_msat: MAX_VALUE_MSAT,
2842 fee_proportional_millionths: 0,
2843 excess_data: Vec::new()
2846 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &[42u8; 32]).unwrap();
2847 assert_eq!(route.paths[0].len(), 4);
2849 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2850 assert_eq!(route.paths[0][0].short_channel_id, 2);
2851 assert_eq!(route.paths[0][0].fee_msat, 200);
2852 assert_eq!(route.paths[0][0].cltv_expiry_delta, 65);
2853 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2854 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2856 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2857 assert_eq!(route.paths[0][1].short_channel_id, 4);
2858 assert_eq!(route.paths[0][1].fee_msat, 100);
2859 assert_eq!(route.paths[0][1].cltv_expiry_delta, 81);
2860 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2861 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2863 assert_eq!(route.paths[0][2].pubkey, non_announced_pubkey);
2864 assert_eq!(route.paths[0][2].short_channel_id, last_hops[0].0[0].short_channel_id);
2865 assert_eq!(route.paths[0][2].fee_msat, 0);
2866 assert_eq!(route.paths[0][2].cltv_expiry_delta, 129);
2867 assert_eq!(route.paths[0][2].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
2868 assert_eq!(route.paths[0][2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2870 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2871 assert_eq!(route.paths[0][3].short_channel_id, last_hops[0].0[1].short_channel_id);
2872 assert_eq!(route.paths[0][3].fee_msat, 100);
2873 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2874 assert_eq!(route.paths[0][3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
2875 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2878 fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2879 let zero_fees = RoutingFees {
2881 proportional_millionths: 0,
2883 vec![RouteHint(vec![RouteHintHop {
2884 src_node_id: nodes[4],
2885 short_channel_id: 11,
2887 cltv_expiry_delta: (11 << 4) | 1,
2888 htlc_minimum_msat: None,
2889 htlc_maximum_msat: None,
2891 src_node_id: nodes[3],
2892 short_channel_id: 8,
2894 cltv_expiry_delta: (8 << 4) | 1,
2895 htlc_minimum_msat: None,
2896 htlc_maximum_msat: None,
2897 }]), RouteHint(vec![RouteHintHop {
2898 src_node_id: nodes[4],
2899 short_channel_id: 9,
2902 proportional_millionths: 0,
2904 cltv_expiry_delta: (9 << 4) | 1,
2905 htlc_minimum_msat: None,
2906 htlc_maximum_msat: None,
2907 }]), RouteHint(vec![RouteHintHop {
2908 src_node_id: nodes[5],
2909 short_channel_id: 10,
2911 cltv_expiry_delta: (10 << 4) | 1,
2912 htlc_minimum_msat: None,
2913 htlc_maximum_msat: None,
2918 fn last_hops_with_public_channel_test() {
2919 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2920 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2921 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops_with_public_channel(&nodes));
2922 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2923 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2924 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2925 // This test shows that public routes can be present in the invoice
2926 // which would be handled in the same manner.
2928 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2929 assert_eq!(route.paths[0].len(), 5);
2931 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2932 assert_eq!(route.paths[0][0].short_channel_id, 2);
2933 assert_eq!(route.paths[0][0].fee_msat, 100);
2934 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2935 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2936 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2938 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2939 assert_eq!(route.paths[0][1].short_channel_id, 4);
2940 assert_eq!(route.paths[0][1].fee_msat, 0);
2941 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
2942 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2943 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2945 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2946 assert_eq!(route.paths[0][2].short_channel_id, 6);
2947 assert_eq!(route.paths[0][2].fee_msat, 0);
2948 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
2949 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2950 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2952 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2953 assert_eq!(route.paths[0][3].short_channel_id, 11);
2954 assert_eq!(route.paths[0][3].fee_msat, 0);
2955 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
2956 // If we have a peer in the node map, we'll use their features here since we don't have
2957 // a way of figuring out their features from the invoice:
2958 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2959 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2961 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2962 assert_eq!(route.paths[0][4].short_channel_id, 8);
2963 assert_eq!(route.paths[0][4].fee_msat, 100);
2964 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2965 assert_eq!(route.paths[0][4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
2966 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2970 fn our_chans_last_hop_connect_test() {
2971 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2972 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2973 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2974 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2975 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2977 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
2978 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2979 let mut last_hops = last_hops(&nodes);
2980 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops.clone());
2981 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();
2982 assert_eq!(route.paths[0].len(), 2);
2984 assert_eq!(route.paths[0][0].pubkey, nodes[3]);
2985 assert_eq!(route.paths[0][0].short_channel_id, 42);
2986 assert_eq!(route.paths[0][0].fee_msat, 0);
2987 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 4) | 1);
2988 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2989 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2991 assert_eq!(route.paths[0][1].pubkey, nodes[6]);
2992 assert_eq!(route.paths[0][1].short_channel_id, 8);
2993 assert_eq!(route.paths[0][1].fee_msat, 100);
2994 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2995 assert_eq!(route.paths[0][1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
2996 assert_eq!(route.paths[0][1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2998 last_hops[0].0[0].fees.base_msat = 1000;
3000 // Revert to via 6 as the fee on 8 goes up
3001 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops);
3002 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3003 assert_eq!(route.paths[0].len(), 4);
3005 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3006 assert_eq!(route.paths[0][0].short_channel_id, 2);
3007 assert_eq!(route.paths[0][0].fee_msat, 200); // fee increased as its % of value transferred across node
3008 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
3009 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3010 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3012 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3013 assert_eq!(route.paths[0][1].short_channel_id, 4);
3014 assert_eq!(route.paths[0][1].fee_msat, 100);
3015 assert_eq!(route.paths[0][1].cltv_expiry_delta, (7 << 4) | 1);
3016 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3017 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3019 assert_eq!(route.paths[0][2].pubkey, nodes[5]);
3020 assert_eq!(route.paths[0][2].short_channel_id, 7);
3021 assert_eq!(route.paths[0][2].fee_msat, 0);
3022 assert_eq!(route.paths[0][2].cltv_expiry_delta, (10 << 4) | 1);
3023 // If we have a peer in the node map, we'll use their features here since we don't have
3024 // a way of figuring out their features from the invoice:
3025 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
3026 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(7));
3028 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
3029 assert_eq!(route.paths[0][3].short_channel_id, 10);
3030 assert_eq!(route.paths[0][3].fee_msat, 100);
3031 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
3032 assert_eq!(route.paths[0][3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3033 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3035 // ...but still use 8 for larger payments as 6 has a variable feerate
3036 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 2000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3037 assert_eq!(route.paths[0].len(), 5);
3039 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3040 assert_eq!(route.paths[0][0].short_channel_id, 2);
3041 assert_eq!(route.paths[0][0].fee_msat, 3000);
3042 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
3043 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3044 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3046 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3047 assert_eq!(route.paths[0][1].short_channel_id, 4);
3048 assert_eq!(route.paths[0][1].fee_msat, 0);
3049 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
3050 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3051 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3053 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
3054 assert_eq!(route.paths[0][2].short_channel_id, 6);
3055 assert_eq!(route.paths[0][2].fee_msat, 0);
3056 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
3057 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
3058 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
3060 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
3061 assert_eq!(route.paths[0][3].short_channel_id, 11);
3062 assert_eq!(route.paths[0][3].fee_msat, 1000);
3063 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
3064 // If we have a peer in the node map, we'll use their features here since we don't have
3065 // a way of figuring out their features from the invoice:
3066 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
3067 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
3069 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
3070 assert_eq!(route.paths[0][4].short_channel_id, 8);
3071 assert_eq!(route.paths[0][4].fee_msat, 2000);
3072 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
3073 assert_eq!(route.paths[0][4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3074 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3077 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> {
3078 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
3079 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3080 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3082 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
3083 let last_hops = RouteHint(vec![RouteHintHop {
3084 src_node_id: middle_node_id,
3085 short_channel_id: 8,
3088 proportional_millionths: last_hop_fee_prop,
3090 cltv_expiry_delta: (8 << 4) | 1,
3091 htlc_minimum_msat: None,
3092 htlc_maximum_msat: last_hop_htlc_max,
3094 let payment_params = PaymentParameters::from_node_id(target_node_id).with_route_hints(vec![last_hops]);
3095 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
3096 let scorer = ln_test_utils::TestScorer::with_penalty(0);
3097 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3098 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3099 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
3100 let logger = ln_test_utils::TestLogger::new();
3101 let network_graph = NetworkGraph::new(genesis_hash, &logger);
3102 let route = get_route(&source_node_id, &payment_params, &network_graph.read_only(),
3103 Some(&our_chans.iter().collect::<Vec<_>>()), route_val, 42, &logger, &scorer, &random_seed_bytes);
3108 fn unannounced_path_test() {
3109 // We should be able to send a payment to a destination without any help of a routing graph
3110 // if we have a channel with a common counterparty that appears in the first and last hop
3112 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
3114 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3115 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3116 assert_eq!(route.paths[0].len(), 2);
3118 assert_eq!(route.paths[0][0].pubkey, middle_node_id);
3119 assert_eq!(route.paths[0][0].short_channel_id, 42);
3120 assert_eq!(route.paths[0][0].fee_msat, 1001);
3121 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 4) | 1);
3122 assert_eq!(route.paths[0][0].node_features.le_flags(), &[0b11]);
3123 assert_eq!(route.paths[0][0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3125 assert_eq!(route.paths[0][1].pubkey, target_node_id);
3126 assert_eq!(route.paths[0][1].short_channel_id, 8);
3127 assert_eq!(route.paths[0][1].fee_msat, 1000000);
3128 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
3129 assert_eq!(route.paths[0][1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3130 assert_eq!(route.paths[0][1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3134 fn overflow_unannounced_path_test_liquidity_underflow() {
3135 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
3136 // the last-hop had a fee which overflowed a u64, we'd panic.
3137 // This was due to us adding the first-hop from us unconditionally, causing us to think
3138 // we'd built a path (as our node is in the "best candidate" set), when we had not.
3139 // In this test, we previously hit a subtraction underflow due to having less available
3140 // liquidity at the last hop than 0.
3141 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());
3145 fn overflow_unannounced_path_test_feerate_overflow() {
3146 // This tests for the same case as above, except instead of hitting a subtraction
3147 // underflow, we hit a case where the fee charged at a hop overflowed.
3148 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());
3152 fn available_amount_while_routing_test() {
3153 // Tests whether we choose the correct available channel amount while routing.
3155 let (secp_ctx, network_graph, mut gossip_sync, chain_monitor, logger) = build_graph();
3156 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3157 let scorer = ln_test_utils::TestScorer::with_penalty(0);
3158 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3159 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3160 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(channelmanager::provided_invoice_features());
3162 // We will use a simple single-path route from
3163 // our node to node2 via node0: channels {1, 3}.
3165 // First disable all other paths.
3166 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3167 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3168 short_channel_id: 2,
3171 cltv_expiry_delta: 0,
3172 htlc_minimum_msat: 0,
3173 htlc_maximum_msat: 100_000,
3175 fee_proportional_millionths: 0,
3176 excess_data: Vec::new()
3178 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3179 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3180 short_channel_id: 12,
3183 cltv_expiry_delta: 0,
3184 htlc_minimum_msat: 0,
3185 htlc_maximum_msat: 100_000,
3187 fee_proportional_millionths: 0,
3188 excess_data: Vec::new()
3191 // Make the first channel (#1) very permissive,
3192 // and we will be testing all limits on the second channel.
3193 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3194 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3195 short_channel_id: 1,
3198 cltv_expiry_delta: 0,
3199 htlc_minimum_msat: 0,
3200 htlc_maximum_msat: 1_000_000_000,
3202 fee_proportional_millionths: 0,
3203 excess_data: Vec::new()
3206 // First, let's see if routing works if we have absolutely no idea about the available amount.
3207 // In this case, it should be set to 250_000 sats.
3208 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3209 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3210 short_channel_id: 3,
3213 cltv_expiry_delta: 0,
3214 htlc_minimum_msat: 0,
3215 htlc_maximum_msat: 250_000_000,
3217 fee_proportional_millionths: 0,
3218 excess_data: Vec::new()
3222 // Attempt to route more than available results in a failure.
3223 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3224 &our_id, &payment_params, &network_graph.read_only(), None, 250_000_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3225 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3226 } else { panic!(); }
3230 // Now, attempt to route an exact amount we have should be fine.
3231 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();
3232 assert_eq!(route.paths.len(), 1);
3233 let path = route.paths.last().unwrap();
3234 assert_eq!(path.len(), 2);
3235 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3236 assert_eq!(path.last().unwrap().fee_msat, 250_000_000);
3239 // Check that setting next_outbound_htlc_limit_msat in first_hops limits the channels.
3240 // Disable channel #1 and use another first hop.
3241 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3242 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3243 short_channel_id: 1,
3246 cltv_expiry_delta: 0,
3247 htlc_minimum_msat: 0,
3248 htlc_maximum_msat: 1_000_000_000,
3250 fee_proportional_millionths: 0,
3251 excess_data: Vec::new()
3254 // Now, limit the first_hop by the next_outbound_htlc_limit_msat of 200_000 sats.
3255 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
3258 // Attempt to route more than available results in a failure.
3259 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3260 &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) {
3261 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3262 } else { panic!(); }
3266 // Now, attempt to route an exact amount we have should be fine.
3267 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();
3268 assert_eq!(route.paths.len(), 1);
3269 let path = route.paths.last().unwrap();
3270 assert_eq!(path.len(), 2);
3271 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3272 assert_eq!(path.last().unwrap().fee_msat, 200_000_000);
3275 // Enable channel #1 back.
3276 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3277 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3278 short_channel_id: 1,
3281 cltv_expiry_delta: 0,
3282 htlc_minimum_msat: 0,
3283 htlc_maximum_msat: 1_000_000_000,
3285 fee_proportional_millionths: 0,
3286 excess_data: Vec::new()
3290 // Now let's see if routing works if we know only htlc_maximum_msat.
3291 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3292 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3293 short_channel_id: 3,
3296 cltv_expiry_delta: 0,
3297 htlc_minimum_msat: 0,
3298 htlc_maximum_msat: 15_000,
3300 fee_proportional_millionths: 0,
3301 excess_data: Vec::new()
3305 // Attempt to route more than available results in a failure.
3306 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3307 &our_id, &payment_params, &network_graph.read_only(), None, 15_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3308 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3309 } else { panic!(); }
3313 // Now, attempt to route an exact amount we have should be fine.
3314 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 15_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3315 assert_eq!(route.paths.len(), 1);
3316 let path = route.paths.last().unwrap();
3317 assert_eq!(path.len(), 2);
3318 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3319 assert_eq!(path.last().unwrap().fee_msat, 15_000);
3322 // Now let's see if routing works if we know only capacity from the UTXO.
3324 // We can't change UTXO capacity on the fly, so we'll disable
3325 // the existing channel and add another one with the capacity we need.
3326 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3327 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3328 short_channel_id: 3,
3331 cltv_expiry_delta: 0,
3332 htlc_minimum_msat: 0,
3333 htlc_maximum_msat: MAX_VALUE_MSAT,
3335 fee_proportional_millionths: 0,
3336 excess_data: Vec::new()
3339 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
3340 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
3341 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
3342 .push_opcode(opcodes::all::OP_PUSHNUM_2)
3343 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
3345 *chain_monitor.utxo_ret.lock().unwrap() = Ok(TxOut { value: 15, script_pubkey: good_script.clone() });
3346 gossip_sync.add_chain_access(Some(chain_monitor));
3348 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
3349 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3350 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3351 short_channel_id: 333,
3354 cltv_expiry_delta: (3 << 4) | 1,
3355 htlc_minimum_msat: 0,
3356 htlc_maximum_msat: 15_000,
3358 fee_proportional_millionths: 0,
3359 excess_data: Vec::new()
3361 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3362 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3363 short_channel_id: 333,
3366 cltv_expiry_delta: (3 << 4) | 2,
3367 htlc_minimum_msat: 0,
3368 htlc_maximum_msat: 15_000,
3370 fee_proportional_millionths: 0,
3371 excess_data: Vec::new()
3375 // Attempt to route more than available results in a failure.
3376 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3377 &our_id, &payment_params, &network_graph.read_only(), None, 15_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3378 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3379 } else { panic!(); }
3383 // Now, attempt to route an exact amount we have should be fine.
3384 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 15_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3385 assert_eq!(route.paths.len(), 1);
3386 let path = route.paths.last().unwrap();
3387 assert_eq!(path.len(), 2);
3388 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3389 assert_eq!(path.last().unwrap().fee_msat, 15_000);
3392 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
3393 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3394 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3395 short_channel_id: 333,
3398 cltv_expiry_delta: 0,
3399 htlc_minimum_msat: 0,
3400 htlc_maximum_msat: 10_000,
3402 fee_proportional_millionths: 0,
3403 excess_data: Vec::new()
3407 // Attempt to route more than available results in a failure.
3408 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3409 &our_id, &payment_params, &network_graph.read_only(), None, 10_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3410 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3411 } else { panic!(); }
3415 // Now, attempt to route an exact amount we have should be fine.
3416 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 10_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3417 assert_eq!(route.paths.len(), 1);
3418 let path = route.paths.last().unwrap();
3419 assert_eq!(path.len(), 2);
3420 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3421 assert_eq!(path.last().unwrap().fee_msat, 10_000);
3426 fn available_liquidity_last_hop_test() {
3427 // Check that available liquidity properly limits the path even when only
3428 // one of the latter hops is limited.
3429 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3430 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3431 let scorer = ln_test_utils::TestScorer::with_penalty(0);
3432 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3433 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3434 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(channelmanager::provided_invoice_features());
3436 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3437 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
3438 // Total capacity: 50 sats.
3440 // Disable other potential paths.
3441 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3442 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3443 short_channel_id: 2,
3446 cltv_expiry_delta: 0,
3447 htlc_minimum_msat: 0,
3448 htlc_maximum_msat: 100_000,
3450 fee_proportional_millionths: 0,
3451 excess_data: Vec::new()
3453 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3454 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3455 short_channel_id: 7,
3458 cltv_expiry_delta: 0,
3459 htlc_minimum_msat: 0,
3460 htlc_maximum_msat: 100_000,
3462 fee_proportional_millionths: 0,
3463 excess_data: Vec::new()
3468 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3469 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3470 short_channel_id: 12,
3473 cltv_expiry_delta: 0,
3474 htlc_minimum_msat: 0,
3475 htlc_maximum_msat: 100_000,
3477 fee_proportional_millionths: 0,
3478 excess_data: Vec::new()
3480 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3481 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3482 short_channel_id: 13,
3485 cltv_expiry_delta: 0,
3486 htlc_minimum_msat: 0,
3487 htlc_maximum_msat: 100_000,
3489 fee_proportional_millionths: 0,
3490 excess_data: Vec::new()
3493 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3494 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3495 short_channel_id: 6,
3498 cltv_expiry_delta: 0,
3499 htlc_minimum_msat: 0,
3500 htlc_maximum_msat: 50_000,
3502 fee_proportional_millionths: 0,
3503 excess_data: Vec::new()
3505 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3506 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3507 short_channel_id: 11,
3510 cltv_expiry_delta: 0,
3511 htlc_minimum_msat: 0,
3512 htlc_maximum_msat: 100_000,
3514 fee_proportional_millionths: 0,
3515 excess_data: Vec::new()
3518 // Attempt to route more than available results in a failure.
3519 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3520 &our_id, &payment_params, &network_graph.read_only(), None, 60_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3521 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3522 } else { panic!(); }
3526 // Now, attempt to route 49 sats (just a bit below the capacity).
3527 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 49_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3528 assert_eq!(route.paths.len(), 1);
3529 let mut total_amount_paid_msat = 0;
3530 for path in &route.paths {
3531 assert_eq!(path.len(), 4);
3532 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3533 total_amount_paid_msat += path.last().unwrap().fee_msat;
3535 assert_eq!(total_amount_paid_msat, 49_000);
3539 // Attempt to route an exact amount is also fine
3540 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3541 assert_eq!(route.paths.len(), 1);
3542 let mut total_amount_paid_msat = 0;
3543 for path in &route.paths {
3544 assert_eq!(path.len(), 4);
3545 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3546 total_amount_paid_msat += path.last().unwrap().fee_msat;
3548 assert_eq!(total_amount_paid_msat, 50_000);
3553 fn ignore_fee_first_hop_test() {
3554 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3555 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3556 let scorer = ln_test_utils::TestScorer::with_penalty(0);
3557 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3558 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3559 let payment_params = PaymentParameters::from_node_id(nodes[2]);
3561 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3562 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3563 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3564 short_channel_id: 1,
3567 cltv_expiry_delta: 0,
3568 htlc_minimum_msat: 0,
3569 htlc_maximum_msat: 100_000,
3570 fee_base_msat: 1_000_000,
3571 fee_proportional_millionths: 0,
3572 excess_data: Vec::new()
3574 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3575 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3576 short_channel_id: 3,
3579 cltv_expiry_delta: 0,
3580 htlc_minimum_msat: 0,
3581 htlc_maximum_msat: 50_000,
3583 fee_proportional_millionths: 0,
3584 excess_data: Vec::new()
3588 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3589 assert_eq!(route.paths.len(), 1);
3590 let mut total_amount_paid_msat = 0;
3591 for path in &route.paths {
3592 assert_eq!(path.len(), 2);
3593 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3594 total_amount_paid_msat += path.last().unwrap().fee_msat;
3596 assert_eq!(total_amount_paid_msat, 50_000);
3601 fn simple_mpp_route_test() {
3602 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3603 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3604 let scorer = ln_test_utils::TestScorer::with_penalty(0);
3605 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3606 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3607 let payment_params = PaymentParameters::from_node_id(nodes[2])
3608 .with_features(channelmanager::provided_invoice_features());
3610 // We need a route consisting of 3 paths:
3611 // From our node to node2 via node0, node7, node1 (three paths one hop each).
3612 // To achieve this, the amount being transferred should be around
3613 // the total capacity of these 3 paths.
3615 // First, we set limits on these (previously unlimited) channels.
3616 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
3618 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3619 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3620 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3621 short_channel_id: 1,
3624 cltv_expiry_delta: 0,
3625 htlc_minimum_msat: 0,
3626 htlc_maximum_msat: 100_000,
3628 fee_proportional_millionths: 0,
3629 excess_data: Vec::new()
3631 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3632 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3633 short_channel_id: 3,
3636 cltv_expiry_delta: 0,
3637 htlc_minimum_msat: 0,
3638 htlc_maximum_msat: 50_000,
3640 fee_proportional_millionths: 0,
3641 excess_data: Vec::new()
3644 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
3645 // (total limit 60).
3646 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3647 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3648 short_channel_id: 12,
3651 cltv_expiry_delta: 0,
3652 htlc_minimum_msat: 0,
3653 htlc_maximum_msat: 60_000,
3655 fee_proportional_millionths: 0,
3656 excess_data: Vec::new()
3658 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3659 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3660 short_channel_id: 13,
3663 cltv_expiry_delta: 0,
3664 htlc_minimum_msat: 0,
3665 htlc_maximum_msat: 60_000,
3667 fee_proportional_millionths: 0,
3668 excess_data: Vec::new()
3671 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
3672 // (total capacity 180 sats).
3673 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3674 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3675 short_channel_id: 2,
3678 cltv_expiry_delta: 0,
3679 htlc_minimum_msat: 0,
3680 htlc_maximum_msat: 200_000,
3682 fee_proportional_millionths: 0,
3683 excess_data: Vec::new()
3685 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3686 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3687 short_channel_id: 4,
3690 cltv_expiry_delta: 0,
3691 htlc_minimum_msat: 0,
3692 htlc_maximum_msat: 180_000,
3694 fee_proportional_millionths: 0,
3695 excess_data: Vec::new()
3699 // Attempt to route more than available results in a failure.
3700 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3701 &our_id, &payment_params, &network_graph.read_only(), None, 300_000, 42,
3702 Arc::clone(&logger), &scorer, &random_seed_bytes) {
3703 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3704 } else { panic!(); }
3708 // Attempt to route while setting max_path_count to 0 results in a failure.
3709 let zero_payment_params = payment_params.clone().with_max_path_count(0);
3710 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3711 &our_id, &zero_payment_params, &network_graph.read_only(), None, 100, 42,
3712 Arc::clone(&logger), &scorer, &random_seed_bytes) {
3713 assert_eq!(err, "Can't find a route with no paths allowed.");
3714 } else { panic!(); }
3718 // Attempt to route while setting max_path_count to 3 results in a failure.
3719 // This is the case because the minimal_value_contribution_msat would require each path
3720 // to account for 1/3 of the total value, which is violated by 2 out of 3 paths.
3721 let fail_payment_params = payment_params.clone().with_max_path_count(3);
3722 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3723 &our_id, &fail_payment_params, &network_graph.read_only(), None, 250_000, 42,
3724 Arc::clone(&logger), &scorer, &random_seed_bytes) {
3725 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3726 } else { panic!(); }
3730 // Now, attempt to route 250 sats (just a bit below the capacity).
3731 // Our algorithm should provide us with these 3 paths.
3732 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None,
3733 250_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3734 assert_eq!(route.paths.len(), 3);
3735 let mut total_amount_paid_msat = 0;
3736 for path in &route.paths {
3737 assert_eq!(path.len(), 2);
3738 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3739 total_amount_paid_msat += path.last().unwrap().fee_msat;
3741 assert_eq!(total_amount_paid_msat, 250_000);
3745 // Attempt to route an exact amount is also fine
3746 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None,
3747 290_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3748 assert_eq!(route.paths.len(), 3);
3749 let mut total_amount_paid_msat = 0;
3750 for path in &route.paths {
3751 assert_eq!(path.len(), 2);
3752 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3753 total_amount_paid_msat += path.last().unwrap().fee_msat;
3755 assert_eq!(total_amount_paid_msat, 290_000);
3760 fn long_mpp_route_test() {
3761 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3762 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3763 let scorer = ln_test_utils::TestScorer::with_penalty(0);
3764 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3765 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3766 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(channelmanager::provided_invoice_features());
3768 // We need a route consisting of 3 paths:
3769 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3770 // Note that these paths overlap (channels 5, 12, 13).
3771 // We will route 300 sats.
3772 // Each path will have 100 sats capacity, those channels which
3773 // are used twice will have 200 sats capacity.
3775 // Disable other potential paths.
3776 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3777 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3778 short_channel_id: 2,
3781 cltv_expiry_delta: 0,
3782 htlc_minimum_msat: 0,
3783 htlc_maximum_msat: 100_000,
3785 fee_proportional_millionths: 0,
3786 excess_data: Vec::new()
3788 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3789 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3790 short_channel_id: 7,
3793 cltv_expiry_delta: 0,
3794 htlc_minimum_msat: 0,
3795 htlc_maximum_msat: 100_000,
3797 fee_proportional_millionths: 0,
3798 excess_data: Vec::new()
3801 // Path via {node0, node2} is channels {1, 3, 5}.
3802 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3803 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3804 short_channel_id: 1,
3807 cltv_expiry_delta: 0,
3808 htlc_minimum_msat: 0,
3809 htlc_maximum_msat: 100_000,
3811 fee_proportional_millionths: 0,
3812 excess_data: Vec::new()
3814 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3815 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3816 short_channel_id: 3,
3819 cltv_expiry_delta: 0,
3820 htlc_minimum_msat: 0,
3821 htlc_maximum_msat: 100_000,
3823 fee_proportional_millionths: 0,
3824 excess_data: Vec::new()
3827 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3828 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3829 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3830 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3831 short_channel_id: 5,
3834 cltv_expiry_delta: 0,
3835 htlc_minimum_msat: 0,
3836 htlc_maximum_msat: 200_000,
3838 fee_proportional_millionths: 0,
3839 excess_data: Vec::new()
3842 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3843 // Add 100 sats to the capacities of {12, 13}, because these channels
3844 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3845 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3846 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3847 short_channel_id: 12,
3850 cltv_expiry_delta: 0,
3851 htlc_minimum_msat: 0,
3852 htlc_maximum_msat: 200_000,
3854 fee_proportional_millionths: 0,
3855 excess_data: Vec::new()
3857 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3858 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3859 short_channel_id: 13,
3862 cltv_expiry_delta: 0,
3863 htlc_minimum_msat: 0,
3864 htlc_maximum_msat: 200_000,
3866 fee_proportional_millionths: 0,
3867 excess_data: Vec::new()
3870 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3871 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3872 short_channel_id: 6,
3875 cltv_expiry_delta: 0,
3876 htlc_minimum_msat: 0,
3877 htlc_maximum_msat: 100_000,
3879 fee_proportional_millionths: 0,
3880 excess_data: Vec::new()
3882 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3883 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3884 short_channel_id: 11,
3887 cltv_expiry_delta: 0,
3888 htlc_minimum_msat: 0,
3889 htlc_maximum_msat: 100_000,
3891 fee_proportional_millionths: 0,
3892 excess_data: Vec::new()
3895 // Path via {node7, node2} is channels {12, 13, 5}.
3896 // We already limited them to 200 sats (they are used twice for 100 sats).
3897 // Nothing to do here.
3900 // Attempt to route more than available results in a failure.
3901 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3902 &our_id, &payment_params, &network_graph.read_only(), None, 350_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3903 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3904 } else { panic!(); }
3908 // Now, attempt to route 300 sats (exact amount we can route).
3909 // Our algorithm should provide us with these 3 paths, 100 sats each.
3910 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 300_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3911 assert_eq!(route.paths.len(), 3);
3913 let mut total_amount_paid_msat = 0;
3914 for path in &route.paths {
3915 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3916 total_amount_paid_msat += path.last().unwrap().fee_msat;
3918 assert_eq!(total_amount_paid_msat, 300_000);
3924 fn mpp_cheaper_route_test() {
3925 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3926 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3927 let scorer = ln_test_utils::TestScorer::with_penalty(0);
3928 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3929 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3930 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(channelmanager::provided_invoice_features());
3932 // This test checks that if we have two cheaper paths and one more expensive path,
3933 // so that liquidity-wise any 2 of 3 combination is sufficient,
3934 // two cheaper paths will be taken.
3935 // These paths have equal available liquidity.
3937 // We need a combination of 3 paths:
3938 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3939 // Note that these paths overlap (channels 5, 12, 13).
3940 // Each path will have 100 sats capacity, those channels which
3941 // are used twice will have 200 sats capacity.
3943 // Disable other potential paths.
3944 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3945 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3946 short_channel_id: 2,
3949 cltv_expiry_delta: 0,
3950 htlc_minimum_msat: 0,
3951 htlc_maximum_msat: 100_000,
3953 fee_proportional_millionths: 0,
3954 excess_data: Vec::new()
3956 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3957 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3958 short_channel_id: 7,
3961 cltv_expiry_delta: 0,
3962 htlc_minimum_msat: 0,
3963 htlc_maximum_msat: 100_000,
3965 fee_proportional_millionths: 0,
3966 excess_data: Vec::new()
3969 // Path via {node0, node2} is channels {1, 3, 5}.
3970 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3971 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3972 short_channel_id: 1,
3975 cltv_expiry_delta: 0,
3976 htlc_minimum_msat: 0,
3977 htlc_maximum_msat: 100_000,
3979 fee_proportional_millionths: 0,
3980 excess_data: Vec::new()
3982 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3983 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3984 short_channel_id: 3,
3987 cltv_expiry_delta: 0,
3988 htlc_minimum_msat: 0,
3989 htlc_maximum_msat: 100_000,
3991 fee_proportional_millionths: 0,
3992 excess_data: Vec::new()
3995 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3996 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3997 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3998 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3999 short_channel_id: 5,
4002 cltv_expiry_delta: 0,
4003 htlc_minimum_msat: 0,
4004 htlc_maximum_msat: 200_000,
4006 fee_proportional_millionths: 0,
4007 excess_data: Vec::new()
4010 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4011 // Add 100 sats to the capacities of {12, 13}, because these channels
4012 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
4013 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4014 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4015 short_channel_id: 12,
4018 cltv_expiry_delta: 0,
4019 htlc_minimum_msat: 0,
4020 htlc_maximum_msat: 200_000,
4022 fee_proportional_millionths: 0,
4023 excess_data: Vec::new()
4025 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4026 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4027 short_channel_id: 13,
4030 cltv_expiry_delta: 0,
4031 htlc_minimum_msat: 0,
4032 htlc_maximum_msat: 200_000,
4034 fee_proportional_millionths: 0,
4035 excess_data: Vec::new()
4038 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4039 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4040 short_channel_id: 6,
4043 cltv_expiry_delta: 0,
4044 htlc_minimum_msat: 0,
4045 htlc_maximum_msat: 100_000,
4046 fee_base_msat: 1_000,
4047 fee_proportional_millionths: 0,
4048 excess_data: Vec::new()
4050 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4051 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4052 short_channel_id: 11,
4055 cltv_expiry_delta: 0,
4056 htlc_minimum_msat: 0,
4057 htlc_maximum_msat: 100_000,
4059 fee_proportional_millionths: 0,
4060 excess_data: Vec::new()
4063 // Path via {node7, node2} is channels {12, 13, 5}.
4064 // We already limited them to 200 sats (they are used twice for 100 sats).
4065 // Nothing to do here.
4068 // Now, attempt to route 180 sats.
4069 // Our algorithm should provide us with these 2 paths.
4070 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 180_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4071 assert_eq!(route.paths.len(), 2);
4073 let mut total_value_transferred_msat = 0;
4074 let mut total_paid_msat = 0;
4075 for path in &route.paths {
4076 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
4077 total_value_transferred_msat += path.last().unwrap().fee_msat;
4079 total_paid_msat += hop.fee_msat;
4082 // If we paid fee, this would be higher.
4083 assert_eq!(total_value_transferred_msat, 180_000);
4084 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
4085 assert_eq!(total_fees_paid, 0);
4090 fn fees_on_mpp_route_test() {
4091 // This test makes sure that MPP algorithm properly takes into account
4092 // fees charged on the channels, by making the fees impactful:
4093 // if the fee is not properly accounted for, the behavior is different.
4094 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4095 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4096 let scorer = ln_test_utils::TestScorer::with_penalty(0);
4097 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4098 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4099 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(channelmanager::provided_invoice_features());
4101 // We need a route consisting of 2 paths:
4102 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
4103 // We will route 200 sats, Each path will have 100 sats capacity.
4105 // This test is not particularly stable: e.g.,
4106 // there's a way to route via {node0, node2, node4}.
4107 // It works while pathfinding is deterministic, but can be broken otherwise.
4108 // It's fine to ignore this concern for now.
4110 // Disable other potential paths.
4111 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4112 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4113 short_channel_id: 2,
4116 cltv_expiry_delta: 0,
4117 htlc_minimum_msat: 0,
4118 htlc_maximum_msat: 100_000,
4120 fee_proportional_millionths: 0,
4121 excess_data: Vec::new()
4124 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4125 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4126 short_channel_id: 7,
4129 cltv_expiry_delta: 0,
4130 htlc_minimum_msat: 0,
4131 htlc_maximum_msat: 100_000,
4133 fee_proportional_millionths: 0,
4134 excess_data: Vec::new()
4137 // Path via {node0, node2} is channels {1, 3, 5}.
4138 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4139 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4140 short_channel_id: 1,
4143 cltv_expiry_delta: 0,
4144 htlc_minimum_msat: 0,
4145 htlc_maximum_msat: 100_000,
4147 fee_proportional_millionths: 0,
4148 excess_data: Vec::new()
4150 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4151 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4152 short_channel_id: 3,
4155 cltv_expiry_delta: 0,
4156 htlc_minimum_msat: 0,
4157 htlc_maximum_msat: 100_000,
4159 fee_proportional_millionths: 0,
4160 excess_data: Vec::new()
4163 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4164 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4165 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4166 short_channel_id: 5,
4169 cltv_expiry_delta: 0,
4170 htlc_minimum_msat: 0,
4171 htlc_maximum_msat: 100_000,
4173 fee_proportional_millionths: 0,
4174 excess_data: Vec::new()
4177 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4178 // All channels should be 100 sats capacity. But for the fee experiment,
4179 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
4180 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
4181 // 100 sats (and pay 150 sats in fees for the use of channel 6),
4182 // so no matter how large are other channels,
4183 // the whole path will be limited by 100 sats with just these 2 conditions:
4184 // - channel 12 capacity is 250 sats
4185 // - fee for channel 6 is 150 sats
4186 // Let's test this by enforcing these 2 conditions and removing other limits.
4187 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4188 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4189 short_channel_id: 12,
4192 cltv_expiry_delta: 0,
4193 htlc_minimum_msat: 0,
4194 htlc_maximum_msat: 250_000,
4196 fee_proportional_millionths: 0,
4197 excess_data: Vec::new()
4199 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4200 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4201 short_channel_id: 13,
4204 cltv_expiry_delta: 0,
4205 htlc_minimum_msat: 0,
4206 htlc_maximum_msat: MAX_VALUE_MSAT,
4208 fee_proportional_millionths: 0,
4209 excess_data: Vec::new()
4212 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4213 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4214 short_channel_id: 6,
4217 cltv_expiry_delta: 0,
4218 htlc_minimum_msat: 0,
4219 htlc_maximum_msat: MAX_VALUE_MSAT,
4220 fee_base_msat: 150_000,
4221 fee_proportional_millionths: 0,
4222 excess_data: Vec::new()
4224 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4225 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4226 short_channel_id: 11,
4229 cltv_expiry_delta: 0,
4230 htlc_minimum_msat: 0,
4231 htlc_maximum_msat: MAX_VALUE_MSAT,
4233 fee_proportional_millionths: 0,
4234 excess_data: Vec::new()
4238 // Attempt to route more than available results in a failure.
4239 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4240 &our_id, &payment_params, &network_graph.read_only(), None, 210_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
4241 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4242 } else { panic!(); }
4246 // Now, attempt to route 200 sats (exact amount we can route).
4247 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 200_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4248 assert_eq!(route.paths.len(), 2);
4250 let mut total_amount_paid_msat = 0;
4251 for path in &route.paths {
4252 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
4253 total_amount_paid_msat += path.last().unwrap().fee_msat;
4255 assert_eq!(total_amount_paid_msat, 200_000);
4256 assert_eq!(route.get_total_fees(), 150_000);
4261 fn mpp_with_last_hops() {
4262 // Previously, if we tried to send an MPP payment to a destination which was only reachable
4263 // via a single last-hop route hint, we'd fail to route if we first collected routes
4264 // totaling close but not quite enough to fund the full payment.
4266 // This was because we considered last-hop hints to have exactly the sought payment amount
4267 // instead of the amount we were trying to collect, needlessly limiting our path searching
4268 // at the very first hop.
4270 // Specifically, this interacted with our "all paths must fund at least 5% of total target"
4271 // criterion to cause us to refuse all routes at the last hop hint which would be considered
4272 // to only have the remaining to-collect amount in available liquidity.
4274 // This bug appeared in production in some specific channel configurations.
4275 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4276 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4277 let scorer = ln_test_utils::TestScorer::with_penalty(0);
4278 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4279 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4280 let payment_params = PaymentParameters::from_node_id(PublicKey::from_slice(&[02; 33]).unwrap()).with_features(channelmanager::provided_invoice_features())
4281 .with_route_hints(vec![RouteHint(vec![RouteHintHop {
4282 src_node_id: nodes[2],
4283 short_channel_id: 42,
4284 fees: RoutingFees { base_msat: 0, proportional_millionths: 0 },
4285 cltv_expiry_delta: 42,
4286 htlc_minimum_msat: None,
4287 htlc_maximum_msat: None,
4288 }])]).with_max_channel_saturation_power_of_half(0);
4290 // Keep only two paths from us to nodes[2], both with a 99sat HTLC maximum, with one with
4291 // no fee and one with a 1msat fee. Previously, trying to route 100 sats to nodes[2] here
4292 // would first use the no-fee route and then fail to find a path along the second route as
4293 // we think we can only send up to 1 additional sat over the last-hop but refuse to as its
4294 // under 5% of our payment amount.
4295 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4296 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4297 short_channel_id: 1,
4300 cltv_expiry_delta: (5 << 4) | 5,
4301 htlc_minimum_msat: 0,
4302 htlc_maximum_msat: 99_000,
4303 fee_base_msat: u32::max_value(),
4304 fee_proportional_millionths: u32::max_value(),
4305 excess_data: Vec::new()
4307 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4308 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4309 short_channel_id: 2,
4312 cltv_expiry_delta: (5 << 4) | 3,
4313 htlc_minimum_msat: 0,
4314 htlc_maximum_msat: 99_000,
4315 fee_base_msat: u32::max_value(),
4316 fee_proportional_millionths: u32::max_value(),
4317 excess_data: Vec::new()
4319 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4320 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4321 short_channel_id: 4,
4324 cltv_expiry_delta: (4 << 4) | 1,
4325 htlc_minimum_msat: 0,
4326 htlc_maximum_msat: MAX_VALUE_MSAT,
4328 fee_proportional_millionths: 0,
4329 excess_data: Vec::new()
4331 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4332 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4333 short_channel_id: 13,
4335 flags: 0|2, // Channel disabled
4336 cltv_expiry_delta: (13 << 4) | 1,
4337 htlc_minimum_msat: 0,
4338 htlc_maximum_msat: MAX_VALUE_MSAT,
4340 fee_proportional_millionths: 2000000,
4341 excess_data: Vec::new()
4344 // Get a route for 100 sats and check that we found the MPP route no problem and didn't
4346 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();
4347 assert_eq!(route.paths.len(), 2);
4348 route.paths.sort_by_key(|path| path[0].short_channel_id);
4349 // Paths are manually ordered ordered by SCID, so:
4350 // * the first is channel 1 (0 fee, but 99 sat maximum) -> channel 3 -> channel 42
4351 // * the second is channel 2 (1 msat fee) -> channel 4 -> channel 42
4352 assert_eq!(route.paths[0][0].short_channel_id, 1);
4353 assert_eq!(route.paths[0][0].fee_msat, 0);
4354 assert_eq!(route.paths[0][2].fee_msat, 99_000);
4355 assert_eq!(route.paths[1][0].short_channel_id, 2);
4356 assert_eq!(route.paths[1][0].fee_msat, 1);
4357 assert_eq!(route.paths[1][2].fee_msat, 1_000);
4358 assert_eq!(route.get_total_fees(), 1);
4359 assert_eq!(route.get_total_amount(), 100_000);
4363 fn drop_lowest_channel_mpp_route_test() {
4364 // This test checks that low-capacity channel is dropped when after
4365 // path finding we realize that we found more capacity than we need.
4366 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4367 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4368 let scorer = ln_test_utils::TestScorer::with_penalty(0);
4369 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4370 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4371 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(channelmanager::provided_invoice_features())
4372 .with_max_channel_saturation_power_of_half(0);
4374 // We need a route consisting of 3 paths:
4375 // From our node to node2 via node0, node7, node1 (three paths one hop each).
4377 // The first and the second paths should be sufficient, but the third should be
4378 // cheaper, so that we select it but drop later.
4380 // First, we set limits on these (previously unlimited) channels.
4381 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
4383 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
4384 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4385 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4386 short_channel_id: 1,
4389 cltv_expiry_delta: 0,
4390 htlc_minimum_msat: 0,
4391 htlc_maximum_msat: 100_000,
4393 fee_proportional_millionths: 0,
4394 excess_data: Vec::new()
4396 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4397 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4398 short_channel_id: 3,
4401 cltv_expiry_delta: 0,
4402 htlc_minimum_msat: 0,
4403 htlc_maximum_msat: 50_000,
4405 fee_proportional_millionths: 0,
4406 excess_data: Vec::new()
4409 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
4410 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4411 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4412 short_channel_id: 12,
4415 cltv_expiry_delta: 0,
4416 htlc_minimum_msat: 0,
4417 htlc_maximum_msat: 60_000,
4419 fee_proportional_millionths: 0,
4420 excess_data: Vec::new()
4422 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4423 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4424 short_channel_id: 13,
4427 cltv_expiry_delta: 0,
4428 htlc_minimum_msat: 0,
4429 htlc_maximum_msat: 60_000,
4431 fee_proportional_millionths: 0,
4432 excess_data: Vec::new()
4435 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
4436 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4437 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4438 short_channel_id: 2,
4441 cltv_expiry_delta: 0,
4442 htlc_minimum_msat: 0,
4443 htlc_maximum_msat: 20_000,
4445 fee_proportional_millionths: 0,
4446 excess_data: Vec::new()
4448 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4449 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4450 short_channel_id: 4,
4453 cltv_expiry_delta: 0,
4454 htlc_minimum_msat: 0,
4455 htlc_maximum_msat: 20_000,
4457 fee_proportional_millionths: 0,
4458 excess_data: Vec::new()
4462 // Attempt to route more than available results in a failure.
4463 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4464 &our_id, &payment_params, &network_graph.read_only(), None, 150_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
4465 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4466 } else { panic!(); }
4470 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
4471 // Our algorithm should provide us with these 3 paths.
4472 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 125_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4473 assert_eq!(route.paths.len(), 3);
4474 let mut total_amount_paid_msat = 0;
4475 for path in &route.paths {
4476 assert_eq!(path.len(), 2);
4477 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4478 total_amount_paid_msat += path.last().unwrap().fee_msat;
4480 assert_eq!(total_amount_paid_msat, 125_000);
4484 // Attempt to route without the last small cheap channel
4485 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4486 assert_eq!(route.paths.len(), 2);
4487 let mut total_amount_paid_msat = 0;
4488 for path in &route.paths {
4489 assert_eq!(path.len(), 2);
4490 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4491 total_amount_paid_msat += path.last().unwrap().fee_msat;
4493 assert_eq!(total_amount_paid_msat, 90_000);
4498 fn min_criteria_consistency() {
4499 // Test that we don't use an inconsistent metric between updating and walking nodes during
4500 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
4501 // was updated with a different criterion from the heap sorting, resulting in loops in
4502 // calculated paths. We test for that specific case here.
4504 // We construct a network that looks like this:
4506 // node2 -1(3)2- node3
4510 // node1 -1(5)2- node4 -1(1)2- node6
4516 // We create a loop on the side of our real path - our destination is node 6, with a
4517 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
4518 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
4519 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
4520 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
4521 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
4522 // "previous hop" being set to node 3, creating a loop in the path.
4523 let secp_ctx = Secp256k1::new();
4524 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
4525 let logger = Arc::new(ln_test_utils::TestLogger::new());
4526 let network = Arc::new(NetworkGraph::new(genesis_hash, Arc::clone(&logger)));
4527 let gossip_sync = P2PGossipSync::new(Arc::clone(&network), None, Arc::clone(&logger));
4528 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4529 let scorer = ln_test_utils::TestScorer::with_penalty(0);
4530 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4531 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4532 let payment_params = PaymentParameters::from_node_id(nodes[6]);
4534 add_channel(&gossip_sync, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
4535 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4536 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4537 short_channel_id: 6,
4540 cltv_expiry_delta: (6 << 4) | 0,
4541 htlc_minimum_msat: 0,
4542 htlc_maximum_msat: MAX_VALUE_MSAT,
4544 fee_proportional_millionths: 0,
4545 excess_data: Vec::new()
4547 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
4549 add_channel(&gossip_sync, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4550 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4551 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4552 short_channel_id: 5,
4555 cltv_expiry_delta: (5 << 4) | 0,
4556 htlc_minimum_msat: 0,
4557 htlc_maximum_msat: MAX_VALUE_MSAT,
4559 fee_proportional_millionths: 0,
4560 excess_data: Vec::new()
4562 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
4564 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
4565 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4566 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4567 short_channel_id: 4,
4570 cltv_expiry_delta: (4 << 4) | 0,
4571 htlc_minimum_msat: 0,
4572 htlc_maximum_msat: MAX_VALUE_MSAT,
4574 fee_proportional_millionths: 0,
4575 excess_data: Vec::new()
4577 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
4579 add_channel(&gossip_sync, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
4580 update_channel(&gossip_sync, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
4581 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4582 short_channel_id: 3,
4585 cltv_expiry_delta: (3 << 4) | 0,
4586 htlc_minimum_msat: 0,
4587 htlc_maximum_msat: MAX_VALUE_MSAT,
4589 fee_proportional_millionths: 0,
4590 excess_data: Vec::new()
4592 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
4594 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
4595 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4596 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4597 short_channel_id: 2,
4600 cltv_expiry_delta: (2 << 4) | 0,
4601 htlc_minimum_msat: 0,
4602 htlc_maximum_msat: MAX_VALUE_MSAT,
4604 fee_proportional_millionths: 0,
4605 excess_data: Vec::new()
4608 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
4609 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4610 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4611 short_channel_id: 1,
4614 cltv_expiry_delta: (1 << 4) | 0,
4615 htlc_minimum_msat: 100,
4616 htlc_maximum_msat: MAX_VALUE_MSAT,
4618 fee_proportional_millionths: 0,
4619 excess_data: Vec::new()
4621 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
4624 // Now ensure the route flows simply over nodes 1 and 4 to 6.
4625 let route = get_route(&our_id, &payment_params, &network.read_only(), None, 10_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4626 assert_eq!(route.paths.len(), 1);
4627 assert_eq!(route.paths[0].len(), 3);
4629 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
4630 assert_eq!(route.paths[0][0].short_channel_id, 6);
4631 assert_eq!(route.paths[0][0].fee_msat, 100);
4632 assert_eq!(route.paths[0][0].cltv_expiry_delta, (5 << 4) | 0);
4633 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(1));
4634 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(6));
4636 assert_eq!(route.paths[0][1].pubkey, nodes[4]);
4637 assert_eq!(route.paths[0][1].short_channel_id, 5);
4638 assert_eq!(route.paths[0][1].fee_msat, 0);
4639 assert_eq!(route.paths[0][1].cltv_expiry_delta, (1 << 4) | 0);
4640 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(4));
4641 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(5));
4643 assert_eq!(route.paths[0][2].pubkey, nodes[6]);
4644 assert_eq!(route.paths[0][2].short_channel_id, 1);
4645 assert_eq!(route.paths[0][2].fee_msat, 10_000);
4646 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
4647 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
4648 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(1));
4654 fn exact_fee_liquidity_limit() {
4655 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
4656 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
4657 // we calculated fees on a higher value, resulting in us ignoring such paths.
4658 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4659 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
4660 let scorer = ln_test_utils::TestScorer::with_penalty(0);
4661 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4662 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4663 let payment_params = PaymentParameters::from_node_id(nodes[2]);
4665 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
4667 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4668 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4669 short_channel_id: 2,
4672 cltv_expiry_delta: 0,
4673 htlc_minimum_msat: 0,
4674 htlc_maximum_msat: 85_000,
4676 fee_proportional_millionths: 0,
4677 excess_data: Vec::new()
4680 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4681 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4682 short_channel_id: 12,
4685 cltv_expiry_delta: (4 << 4) | 1,
4686 htlc_minimum_msat: 0,
4687 htlc_maximum_msat: 270_000,
4689 fee_proportional_millionths: 1000000,
4690 excess_data: Vec::new()
4694 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
4695 // 200% fee charged channel 13 in the 1-to-2 direction.
4696 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4697 assert_eq!(route.paths.len(), 1);
4698 assert_eq!(route.paths[0].len(), 2);
4700 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
4701 assert_eq!(route.paths[0][0].short_channel_id, 12);
4702 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
4703 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
4704 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
4705 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
4707 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
4708 assert_eq!(route.paths[0][1].short_channel_id, 13);
4709 assert_eq!(route.paths[0][1].fee_msat, 90_000);
4710 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
4711 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
4712 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
4717 fn htlc_max_reduction_below_min() {
4718 // Test that if, while walking the graph, we reduce the value being sent to meet an
4719 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
4720 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
4721 // resulting in us thinking there is no possible path, even if other paths exist.
4722 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4723 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4724 let scorer = ln_test_utils::TestScorer::with_penalty(0);
4725 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4726 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4727 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(channelmanager::provided_invoice_features());
4729 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
4730 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
4731 // then try to send 90_000.
4732 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4733 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4734 short_channel_id: 2,
4737 cltv_expiry_delta: 0,
4738 htlc_minimum_msat: 0,
4739 htlc_maximum_msat: 80_000,
4741 fee_proportional_millionths: 0,
4742 excess_data: Vec::new()
4744 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4745 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4746 short_channel_id: 4,
4749 cltv_expiry_delta: (4 << 4) | 1,
4750 htlc_minimum_msat: 90_000,
4751 htlc_maximum_msat: MAX_VALUE_MSAT,
4753 fee_proportional_millionths: 0,
4754 excess_data: Vec::new()
4758 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
4759 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
4760 // expensive) channels 12-13 path.
4761 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4762 assert_eq!(route.paths.len(), 1);
4763 assert_eq!(route.paths[0].len(), 2);
4765 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
4766 assert_eq!(route.paths[0][0].short_channel_id, 12);
4767 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
4768 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
4769 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
4770 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
4772 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
4773 assert_eq!(route.paths[0][1].short_channel_id, 13);
4774 assert_eq!(route.paths[0][1].fee_msat, 90_000);
4775 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
4776 assert_eq!(route.paths[0][1].node_features.le_flags(), channelmanager::provided_invoice_features().le_flags());
4777 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
4782 fn multiple_direct_first_hops() {
4783 // Previously we'd only ever considered one first hop path per counterparty.
4784 // However, as we don't restrict users to one channel per peer, we really need to support
4785 // looking at all first hop paths.
4786 // Here we test that we do not ignore all-but-the-last first hop paths per counterparty (as
4787 // we used to do by overwriting the `first_hop_targets` hashmap entry) and that we can MPP
4788 // route over multiple channels with the same first hop.
4789 let secp_ctx = Secp256k1::new();
4790 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4791 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
4792 let logger = Arc::new(ln_test_utils::TestLogger::new());
4793 let network_graph = NetworkGraph::new(genesis_hash, Arc::clone(&logger));
4794 let scorer = ln_test_utils::TestScorer::with_penalty(0);
4795 let payment_params = PaymentParameters::from_node_id(nodes[0]).with_features(channelmanager::provided_invoice_features());
4796 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4797 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4800 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
4801 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(), 200_000),
4802 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(), 10_000),
4803 ]), 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4804 assert_eq!(route.paths.len(), 1);
4805 assert_eq!(route.paths[0].len(), 1);
4807 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
4808 assert_eq!(route.paths[0][0].short_channel_id, 3);
4809 assert_eq!(route.paths[0][0].fee_msat, 100_000);
4812 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
4813 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(), 50_000),
4814 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(), 50_000),
4815 ]), 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4816 assert_eq!(route.paths.len(), 2);
4817 assert_eq!(route.paths[0].len(), 1);
4818 assert_eq!(route.paths[1].len(), 1);
4820 assert!((route.paths[0][0].short_channel_id == 3 && route.paths[1][0].short_channel_id == 2) ||
4821 (route.paths[0][0].short_channel_id == 2 && route.paths[1][0].short_channel_id == 3));
4823 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
4824 assert_eq!(route.paths[0][0].fee_msat, 50_000);
4826 assert_eq!(route.paths[1][0].pubkey, nodes[0]);
4827 assert_eq!(route.paths[1][0].fee_msat, 50_000);
4831 // If we have a bunch of outbound channels to the same node, where most are not
4832 // sufficient to pay the full payment, but one is, we should default to just using the
4833 // one single channel that has sufficient balance, avoiding MPP.
4835 // If we have several options above the 3xpayment value threshold, we should pick the
4836 // smallest of them, avoiding further fragmenting our available outbound balance to
4838 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
4839 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(), 50_000),
4840 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(), 50_000),
4841 &get_channel_details(Some(5), nodes[0], channelmanager::provided_init_features(), 50_000),
4842 &get_channel_details(Some(6), nodes[0], channelmanager::provided_init_features(), 300_000),
4843 &get_channel_details(Some(7), nodes[0], channelmanager::provided_init_features(), 50_000),
4844 &get_channel_details(Some(8), nodes[0], channelmanager::provided_init_features(), 50_000),
4845 &get_channel_details(Some(9), nodes[0], channelmanager::provided_init_features(), 50_000),
4846 &get_channel_details(Some(4), nodes[0], channelmanager::provided_init_features(), 1_000_000),
4847 ]), 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4848 assert_eq!(route.paths.len(), 1);
4849 assert_eq!(route.paths[0].len(), 1);
4851 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
4852 assert_eq!(route.paths[0][0].short_channel_id, 6);
4853 assert_eq!(route.paths[0][0].fee_msat, 100_000);
4858 fn prefers_shorter_route_with_higher_fees() {
4859 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4860 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4861 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
4863 // Without penalizing each hop 100 msats, a longer path with lower fees is chosen.
4864 let scorer = ln_test_utils::TestScorer::with_penalty(0);
4865 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4866 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4867 let route = get_route(
4868 &our_id, &payment_params, &network_graph.read_only(), None, 100, 42,
4869 Arc::clone(&logger), &scorer, &random_seed_bytes
4871 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4873 assert_eq!(route.get_total_fees(), 100);
4874 assert_eq!(route.get_total_amount(), 100);
4875 assert_eq!(path, vec![2, 4, 6, 11, 8]);
4877 // Applying a 100 msat penalty to each hop results in taking channels 7 and 10 to nodes[6]
4878 // from nodes[2] rather than channel 6, 11, and 8, even though the longer path is cheaper.
4879 let scorer = ln_test_utils::TestScorer::with_penalty(100);
4880 let route = get_route(
4881 &our_id, &payment_params, &network_graph.read_only(), None, 100, 42,
4882 Arc::clone(&logger), &scorer, &random_seed_bytes
4884 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4886 assert_eq!(route.get_total_fees(), 300);
4887 assert_eq!(route.get_total_amount(), 100);
4888 assert_eq!(path, vec![2, 4, 7, 10]);
4891 struct BadChannelScorer {
4892 short_channel_id: u64,
4896 impl Writeable for BadChannelScorer {
4897 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
4899 impl Score for BadChannelScorer {
4900 fn channel_penalty_msat(&self, short_channel_id: u64, _: &NodeId, _: &NodeId, _: ChannelUsage) -> u64 {
4901 if short_channel_id == self.short_channel_id { u64::max_value() } else { 0 }
4904 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
4905 fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
4906 fn probe_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
4907 fn probe_successful(&mut self, _path: &[&RouteHop]) {}
4910 struct BadNodeScorer {
4915 impl Writeable for BadNodeScorer {
4916 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
4919 impl Score for BadNodeScorer {
4920 fn channel_penalty_msat(&self, _: u64, _: &NodeId, target: &NodeId, _: ChannelUsage) -> u64 {
4921 if *target == self.node_id { u64::max_value() } else { 0 }
4924 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
4925 fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
4926 fn probe_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
4927 fn probe_successful(&mut self, _path: &[&RouteHop]) {}
4931 fn avoids_routing_through_bad_channels_and_nodes() {
4932 let (secp_ctx, network, _, _, logger) = build_graph();
4933 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4934 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
4935 let network_graph = network.read_only();
4937 // A path to nodes[6] exists when no penalties are applied to any channel.
4938 let scorer = ln_test_utils::TestScorer::with_penalty(0);
4939 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4940 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4941 let route = get_route(
4942 &our_id, &payment_params, &network_graph, None, 100, 42,
4943 Arc::clone(&logger), &scorer, &random_seed_bytes
4945 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4947 assert_eq!(route.get_total_fees(), 100);
4948 assert_eq!(route.get_total_amount(), 100);
4949 assert_eq!(path, vec![2, 4, 6, 11, 8]);
4951 // A different path to nodes[6] exists if channel 6 cannot be routed over.
4952 let scorer = BadChannelScorer { short_channel_id: 6 };
4953 let route = get_route(
4954 &our_id, &payment_params, &network_graph, None, 100, 42,
4955 Arc::clone(&logger), &scorer, &random_seed_bytes
4957 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4959 assert_eq!(route.get_total_fees(), 300);
4960 assert_eq!(route.get_total_amount(), 100);
4961 assert_eq!(path, vec![2, 4, 7, 10]);
4963 // A path to nodes[6] does not exist if nodes[2] cannot be routed through.
4964 let scorer = BadNodeScorer { node_id: NodeId::from_pubkey(&nodes[2]) };
4966 &our_id, &payment_params, &network_graph, None, 100, 42,
4967 Arc::clone(&logger), &scorer, &random_seed_bytes
4969 Err(LightningError { err, .. } ) => {
4970 assert_eq!(err, "Failed to find a path to the given destination");
4972 Ok(_) => panic!("Expected error"),
4977 fn total_fees_single_path() {
4981 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
4982 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4983 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
4986 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
4987 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4988 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
4991 pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
4992 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4993 short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0
4996 payment_params: None,
4999 assert_eq!(route.get_total_fees(), 250);
5000 assert_eq!(route.get_total_amount(), 225);
5004 fn total_fees_multi_path() {
5008 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5009 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5010 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5013 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5014 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5015 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5019 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5020 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5021 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5024 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5025 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5026 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5029 payment_params: None,
5032 assert_eq!(route.get_total_fees(), 200);
5033 assert_eq!(route.get_total_amount(), 300);
5037 fn total_empty_route_no_panic() {
5038 // In an earlier version of `Route::get_total_fees` and `Route::get_total_amount`, they
5039 // would both panic if the route was completely empty. We test to ensure they return 0
5040 // here, even though its somewhat nonsensical as a route.
5041 let route = Route { paths: Vec::new(), payment_params: None };
5043 assert_eq!(route.get_total_fees(), 0);
5044 assert_eq!(route.get_total_amount(), 0);
5048 fn limits_total_cltv_delta() {
5049 let (secp_ctx, network, _, _, logger) = build_graph();
5050 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5051 let network_graph = network.read_only();
5053 let scorer = ln_test_utils::TestScorer::with_penalty(0);
5055 // Make sure that generally there is at least one route available
5056 let feasible_max_total_cltv_delta = 1008;
5057 let feasible_payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes))
5058 .with_max_total_cltv_expiry_delta(feasible_max_total_cltv_delta);
5059 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5060 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5061 let route = get_route(&our_id, &feasible_payment_params, &network_graph, None, 100, 0, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5062 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5063 assert_ne!(path.len(), 0);
5065 // But not if we exclude all paths on the basis of their accumulated CLTV delta
5066 let fail_max_total_cltv_delta = 23;
5067 let fail_payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes))
5068 .with_max_total_cltv_expiry_delta(fail_max_total_cltv_delta);
5069 match get_route(&our_id, &fail_payment_params, &network_graph, None, 100, 0, Arc::clone(&logger), &scorer, &random_seed_bytes)
5071 Err(LightningError { err, .. } ) => {
5072 assert_eq!(err, "Failed to find a path to the given destination");
5074 Ok(_) => panic!("Expected error"),
5079 fn avoids_recently_failed_paths() {
5080 // Ensure that the router always avoids all of the `previously_failed_channels` channels by
5081 // randomly inserting channels into it until we can't find a route anymore.
5082 let (secp_ctx, network, _, _, logger) = build_graph();
5083 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5084 let network_graph = network.read_only();
5086 let scorer = ln_test_utils::TestScorer::with_penalty(0);
5087 let mut payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes))
5088 .with_max_path_count(1);
5089 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5090 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5092 // We should be able to find a route initially, and then after we fail a few random
5093 // channels eventually we won't be able to any longer.
5094 assert!(get_route(&our_id, &payment_params, &network_graph, None, 100, 0, Arc::clone(&logger), &scorer, &random_seed_bytes).is_ok());
5096 if let Ok(route) = get_route(&our_id, &payment_params, &network_graph, None, 100, 0, Arc::clone(&logger), &scorer, &random_seed_bytes) {
5097 for chan in route.paths[0].iter() {
5098 assert!(!payment_params.previously_failed_channels.contains(&chan.short_channel_id));
5100 let victim = (u64::from_ne_bytes(random_seed_bytes[0..8].try_into().unwrap()) as usize)
5101 % route.paths[0].len();
5102 payment_params.previously_failed_channels.push(route.paths[0][victim].short_channel_id);
5108 fn limits_path_length() {
5109 let (secp_ctx, network, _, _, logger) = build_line_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);
5114 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5115 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5117 // First check we can actually create a long route on this graph.
5118 let feasible_payment_params = PaymentParameters::from_node_id(nodes[18]);
5119 let route = get_route(&our_id, &feasible_payment_params, &network_graph, None, 100, 0,
5120 Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5121 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5122 assert!(path.len() == MAX_PATH_LENGTH_ESTIMATE.into());
5124 // But we can't create a path surpassing the MAX_PATH_LENGTH_ESTIMATE limit.
5125 let fail_payment_params = PaymentParameters::from_node_id(nodes[19]);
5126 match get_route(&our_id, &fail_payment_params, &network_graph, None, 100, 0,
5127 Arc::clone(&logger), &scorer, &random_seed_bytes)
5129 Err(LightningError { err, .. } ) => {
5130 assert_eq!(err, "Failed to find a path to the given destination");
5132 Ok(_) => panic!("Expected error"),
5137 fn adds_and_limits_cltv_offset() {
5138 let (secp_ctx, network_graph, _, _, logger) = build_graph();
5139 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5141 let scorer = ln_test_utils::TestScorer::with_penalty(0);
5143 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
5144 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5145 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5146 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5147 assert_eq!(route.paths.len(), 1);
5149 let cltv_expiry_deltas_before = route.paths[0].iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5151 // Check whether the offset added to the last hop by default is in [1 .. DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA]
5152 let mut route_default = route.clone();
5153 add_random_cltv_offset(&mut route_default, &payment_params, &network_graph.read_only(), &random_seed_bytes);
5154 let cltv_expiry_deltas_default = route_default.paths[0].iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5155 assert_eq!(cltv_expiry_deltas_before.split_last().unwrap().1, cltv_expiry_deltas_default.split_last().unwrap().1);
5156 assert!(cltv_expiry_deltas_default.last() > cltv_expiry_deltas_before.last());
5157 assert!(cltv_expiry_deltas_default.last().unwrap() <= &DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA);
5159 // Check that no offset is added when we restrict the max_total_cltv_expiry_delta
5160 let mut route_limited = route.clone();
5161 let limited_max_total_cltv_expiry_delta = cltv_expiry_deltas_before.iter().sum();
5162 let limited_payment_params = payment_params.with_max_total_cltv_expiry_delta(limited_max_total_cltv_expiry_delta);
5163 add_random_cltv_offset(&mut route_limited, &limited_payment_params, &network_graph.read_only(), &random_seed_bytes);
5164 let cltv_expiry_deltas_limited = route_limited.paths[0].iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5165 assert_eq!(cltv_expiry_deltas_before, cltv_expiry_deltas_limited);
5169 fn adds_plausible_cltv_offset() {
5170 let (secp_ctx, network, _, _, logger) = build_graph();
5171 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5172 let network_graph = network.read_only();
5173 let network_nodes = network_graph.nodes();
5174 let network_channels = network_graph.channels();
5175 let scorer = ln_test_utils::TestScorer::with_penalty(0);
5176 let payment_params = PaymentParameters::from_node_id(nodes[3]);
5177 let keys_manager = ln_test_utils::TestKeysInterface::new(&[4u8; 32], Network::Testnet);
5178 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5180 let mut route = get_route(&our_id, &payment_params, &network_graph, None, 100, 0,
5181 Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5182 add_random_cltv_offset(&mut route, &payment_params, &network_graph, &random_seed_bytes);
5184 let mut path_plausibility = vec![];
5186 for p in route.paths {
5187 // 1. Select random observation point
5188 let mut prng = ChaCha20::new(&random_seed_bytes, &[0u8; 12]);
5189 let mut random_bytes = [0u8; ::core::mem::size_of::<usize>()];
5191 prng.process_in_place(&mut random_bytes);
5192 let random_path_index = usize::from_be_bytes(random_bytes).wrapping_rem(p.len());
5193 let observation_point = NodeId::from_pubkey(&p.get(random_path_index).unwrap().pubkey);
5195 // 2. Calculate what CLTV expiry delta we would observe there
5196 let observed_cltv_expiry_delta: u32 = p[random_path_index..].iter().map(|h| h.cltv_expiry_delta).sum();
5198 // 3. Starting from the observation point, find candidate paths
5199 let mut candidates: VecDeque<(NodeId, Vec<u32>)> = VecDeque::new();
5200 candidates.push_back((observation_point, vec![]));
5202 let mut found_plausible_candidate = false;
5204 'candidate_loop: while let Some((cur_node_id, cur_path_cltv_deltas)) = candidates.pop_front() {
5205 if let Some(remaining) = observed_cltv_expiry_delta.checked_sub(cur_path_cltv_deltas.iter().sum::<u32>()) {
5206 if remaining == 0 || remaining.wrapping_rem(40) == 0 || remaining.wrapping_rem(144) == 0 {
5207 found_plausible_candidate = true;
5208 break 'candidate_loop;
5212 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
5213 for channel_id in &cur_node.channels {
5214 if let Some(channel_info) = network_channels.get(&channel_id) {
5215 if let Some((dir_info, next_id)) = channel_info.as_directed_from(&cur_node_id) {
5216 if let Some(channel_update_info) = dir_info.direction() {
5217 let next_cltv_expiry_delta = channel_update_info.cltv_expiry_delta as u32;
5218 if cur_path_cltv_deltas.iter().sum::<u32>()
5219 .saturating_add(next_cltv_expiry_delta) <= observed_cltv_expiry_delta {
5220 let mut new_path_cltv_deltas = cur_path_cltv_deltas.clone();
5221 new_path_cltv_deltas.push(next_cltv_expiry_delta);
5222 candidates.push_back((*next_id, new_path_cltv_deltas));
5231 path_plausibility.push(found_plausible_candidate);
5233 assert!(path_plausibility.iter().all(|x| *x));
5237 fn builds_correct_path_from_hops() {
5238 let (secp_ctx, network, _, _, logger) = build_graph();
5239 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5240 let network_graph = network.read_only();
5242 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5243 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5245 let payment_params = PaymentParameters::from_node_id(nodes[3]);
5246 let hops = [nodes[1], nodes[2], nodes[4], nodes[3]];
5247 let route = build_route_from_hops_internal(&our_id, &hops, &payment_params,
5248 &network_graph, 100, 0, Arc::clone(&logger), &random_seed_bytes).unwrap();
5249 let route_hop_pubkeys = route.paths[0].iter().map(|hop| hop.pubkey).collect::<Vec<_>>();
5250 assert_eq!(hops.len(), route.paths[0].len());
5251 for (idx, hop_pubkey) in hops.iter().enumerate() {
5252 assert!(*hop_pubkey == route_hop_pubkeys[idx]);
5257 fn avoids_saturating_channels() {
5258 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5259 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5261 let scorer = ProbabilisticScorer::new(Default::default(), &*network_graph, Arc::clone(&logger));
5263 // Set the fee on channel 13 to 100% to match channel 4 giving us two equivalent paths (us
5264 // -> node 7 -> node2 and us -> node 1 -> node 2) which we should balance over.
5265 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5266 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5267 short_channel_id: 4,
5270 cltv_expiry_delta: (4 << 4) | 1,
5271 htlc_minimum_msat: 0,
5272 htlc_maximum_msat: 250_000_000,
5274 fee_proportional_millionths: 0,
5275 excess_data: Vec::new()
5277 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5278 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5279 short_channel_id: 13,
5282 cltv_expiry_delta: (13 << 4) | 1,
5283 htlc_minimum_msat: 0,
5284 htlc_maximum_msat: 250_000_000,
5286 fee_proportional_millionths: 0,
5287 excess_data: Vec::new()
5290 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(channelmanager::provided_invoice_features());
5291 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5292 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5293 // 100,000 sats is less than the available liquidity on each channel, set above.
5294 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();
5295 assert_eq!(route.paths.len(), 2);
5296 assert!((route.paths[0][1].short_channel_id == 4 && route.paths[1][1].short_channel_id == 13) ||
5297 (route.paths[1][1].short_channel_id == 4 && route.paths[0][1].short_channel_id == 13));
5300 #[cfg(not(feature = "no-std"))]
5301 pub(super) fn random_init_seed() -> u64 {
5302 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
5303 use core::hash::{BuildHasher, Hasher};
5304 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
5305 println!("Using seed of {}", seed);
5308 #[cfg(not(feature = "no-std"))]
5309 use crate::util::ser::ReadableArgs;
5312 #[cfg(not(feature = "no-std"))]
5313 fn generate_routes() {
5314 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringParameters};
5316 let mut d = match super::bench_utils::get_route_file() {
5323 let logger = ln_test_utils::TestLogger::new();
5324 let graph = NetworkGraph::read(&mut d, &logger).unwrap();
5325 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5326 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5328 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
5329 let mut seed = random_init_seed() as usize;
5330 let nodes = graph.read_only().nodes().clone();
5331 'load_endpoints: for _ in 0..10 {
5333 seed = seed.overflowing_mul(0xdeadbeef).0;
5334 let src = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5335 seed = seed.overflowing_mul(0xdeadbeef).0;
5336 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5337 let payment_params = PaymentParameters::from_node_id(dst);
5338 let amt = seed as u64 % 200_000_000;
5339 let params = ProbabilisticScoringParameters::default();
5340 let scorer = ProbabilisticScorer::new(params, &graph, &logger);
5341 if get_route(src, &payment_params, &graph.read_only(), None, amt, 42, &logger, &scorer, &random_seed_bytes).is_ok() {
5342 continue 'load_endpoints;
5349 #[cfg(not(feature = "no-std"))]
5350 fn generate_routes_mpp() {
5351 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringParameters};
5353 let mut d = match super::bench_utils::get_route_file() {
5360 let logger = ln_test_utils::TestLogger::new();
5361 let graph = NetworkGraph::read(&mut d, &logger).unwrap();
5362 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5363 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5365 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
5366 let mut seed = random_init_seed() as usize;
5367 let nodes = graph.read_only().nodes().clone();
5368 'load_endpoints: for _ in 0..10 {
5370 seed = seed.overflowing_mul(0xdeadbeef).0;
5371 let src = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5372 seed = seed.overflowing_mul(0xdeadbeef).0;
5373 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5374 let payment_params = PaymentParameters::from_node_id(dst).with_features(channelmanager::provided_invoice_features());
5375 let amt = seed as u64 % 200_000_000;
5376 let params = ProbabilisticScoringParameters::default();
5377 let scorer = ProbabilisticScorer::new(params, &graph, &logger);
5378 if get_route(src, &payment_params, &graph.read_only(), None, amt, 42, &logger, &scorer, &random_seed_bytes).is_ok() {
5379 continue 'load_endpoints;
5386 fn honors_manual_penalties() {
5387 let (secp_ctx, network_graph, _, _, logger) = build_line_graph();
5388 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5390 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5391 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5393 let scorer_params = ProbabilisticScoringParameters::default();
5394 let mut scorer = ProbabilisticScorer::new(scorer_params, Arc::clone(&network_graph), Arc::clone(&logger));
5396 // First check set manual penalties are returned by the scorer.
5397 let usage = ChannelUsage {
5399 inflight_htlc_msat: 0,
5400 effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_024_000, htlc_maximum_msat: Some(1_000) },
5402 scorer.set_manual_penalty(&NodeId::from_pubkey(&nodes[3]), 123);
5403 scorer.set_manual_penalty(&NodeId::from_pubkey(&nodes[4]), 456);
5404 assert_eq!(scorer.channel_penalty_msat(42, &NodeId::from_pubkey(&nodes[3]), &NodeId::from_pubkey(&nodes[4]), usage), 456);
5406 // Then check we can get a normal route
5407 let payment_params = PaymentParameters::from_node_id(nodes[10]);
5408 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes);
5409 assert!(route.is_ok());
5411 // Then check that we can't get a route if we ban an intermediate node.
5412 scorer.add_banned(&NodeId::from_pubkey(&nodes[3]));
5413 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes);
5414 assert!(route.is_err());
5416 // Finally make sure we can route again, when we remove the ban.
5417 scorer.remove_banned(&NodeId::from_pubkey(&nodes[3]));
5418 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes);
5419 assert!(route.is_ok());
5423 #[cfg(all(test, not(feature = "no-std")))]
5424 pub(crate) mod bench_utils {
5426 /// Tries to open a network graph file, or panics with a URL to fetch it.
5427 pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
5428 let res = File::open("net_graph-2021-05-31.bin") // By default we're run in RL/lightning
5429 .or_else(|_| File::open("lightning/net_graph-2021-05-31.bin")) // We may be run manually in RL/
5430 .or_else(|_| { // Fall back to guessing based on the binary location
5431 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
5432 let mut path = std::env::current_exe().unwrap();
5433 path.pop(); // lightning-...
5435 path.pop(); // debug
5436 path.pop(); // target
5437 path.push("lightning");
5438 path.push("net_graph-2021-05-31.bin");
5439 eprintln!("{}", path.to_str().unwrap());
5442 .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");
5443 #[cfg(require_route_graph_test)]
5444 return Ok(res.unwrap());
5445 #[cfg(not(require_route_graph_test))]
5450 #[cfg(all(test, feature = "_bench_unstable", not(feature = "no-std")))]
5453 use bitcoin::hashes::Hash;
5454 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
5455 use crate::chain::transaction::OutPoint;
5456 use crate::chain::keysinterface::{KeysManager,KeysInterface};
5457 use crate::ln::channelmanager::{self, ChannelCounterparty, ChannelDetails};
5458 use crate::ln::features::InvoiceFeatures;
5459 use crate::routing::gossip::NetworkGraph;
5460 use crate::routing::scoring::{FixedPenaltyScorer, ProbabilisticScorer, ProbabilisticScoringParameters};
5461 use crate::util::logger::{Logger, Record};
5462 use crate::util::ser::ReadableArgs;
5466 struct DummyLogger {}
5467 impl Logger for DummyLogger {
5468 fn log(&self, _record: &Record) {}
5471 fn read_network_graph(logger: &DummyLogger) -> NetworkGraph<&DummyLogger> {
5472 let mut d = bench_utils::get_route_file().unwrap();
5473 NetworkGraph::read(&mut d, logger).unwrap()
5476 fn payer_pubkey() -> PublicKey {
5477 let secp_ctx = Secp256k1::new();
5478 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
5482 fn first_hop(node_id: PublicKey) -> ChannelDetails {
5484 channel_id: [0; 32],
5485 counterparty: ChannelCounterparty {
5486 features: channelmanager::provided_init_features(),
5488 unspendable_punishment_reserve: 0,
5489 forwarding_info: None,
5490 outbound_htlc_minimum_msat: None,
5491 outbound_htlc_maximum_msat: None,
5493 funding_txo: Some(OutPoint {
5494 txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0
5497 short_channel_id: Some(1),
5498 inbound_scid_alias: None,
5499 outbound_scid_alias: None,
5500 channel_value_satoshis: 10_000_000,
5502 balance_msat: 10_000_000,
5503 outbound_capacity_msat: 10_000_000,
5504 next_outbound_htlc_limit_msat: 10_000_000,
5505 inbound_capacity_msat: 0,
5506 unspendable_punishment_reserve: None,
5507 confirmations_required: None,
5508 force_close_spend_delay: None,
5510 is_channel_ready: true,
5513 inbound_htlc_minimum_msat: None,
5514 inbound_htlc_maximum_msat: None,
5520 fn generate_routes_with_zero_penalty_scorer(bench: &mut Bencher) {
5521 let logger = DummyLogger {};
5522 let network_graph = read_network_graph(&logger);
5523 let scorer = FixedPenaltyScorer::with_penalty(0);
5524 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::empty());
5528 fn generate_mpp_routes_with_zero_penalty_scorer(bench: &mut Bencher) {
5529 let logger = DummyLogger {};
5530 let network_graph = read_network_graph(&logger);
5531 let scorer = FixedPenaltyScorer::with_penalty(0);
5532 generate_routes(bench, &network_graph, scorer, channelmanager::provided_invoice_features());
5536 fn generate_routes_with_probabilistic_scorer(bench: &mut Bencher) {
5537 let logger = DummyLogger {};
5538 let network_graph = read_network_graph(&logger);
5539 let params = ProbabilisticScoringParameters::default();
5540 let scorer = ProbabilisticScorer::new(params, &network_graph, &logger);
5541 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::empty());
5545 fn generate_mpp_routes_with_probabilistic_scorer(bench: &mut Bencher) {
5546 let logger = DummyLogger {};
5547 let network_graph = read_network_graph(&logger);
5548 let params = ProbabilisticScoringParameters::default();
5549 let scorer = ProbabilisticScorer::new(params, &network_graph, &logger);
5550 generate_routes(bench, &network_graph, scorer, channelmanager::provided_invoice_features());
5553 fn generate_routes<S: Score>(
5554 bench: &mut Bencher, graph: &NetworkGraph<&DummyLogger>, mut scorer: S,
5555 features: InvoiceFeatures
5557 let nodes = graph.read_only().nodes().clone();
5558 let payer = payer_pubkey();
5559 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
5560 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5562 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
5563 let mut routes = Vec::new();
5564 let mut route_endpoints = Vec::new();
5565 let mut seed: usize = 0xdeadbeef;
5566 'load_endpoints: for _ in 0..150 {
5569 let src = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5571 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5572 let params = PaymentParameters::from_node_id(dst).with_features(features.clone());
5573 let first_hop = first_hop(src);
5574 let amt = seed as u64 % 1_000_000;
5575 if let Ok(route) = get_route(&payer, ¶ms, &graph.read_only(), Some(&[&first_hop]), amt, 42, &DummyLogger{}, &scorer, &random_seed_bytes) {
5577 route_endpoints.push((first_hop, params, amt));
5578 continue 'load_endpoints;
5583 // ...and seed the scorer with success and failure data...
5584 for route in routes {
5585 let amount = route.get_total_amount();
5586 if amount < 250_000 {
5587 for path in route.paths {
5588 scorer.payment_path_successful(&path.iter().collect::<Vec<_>>());
5590 } else if amount > 750_000 {
5591 for path in route.paths {
5592 let short_channel_id = path[path.len() / 2].short_channel_id;
5593 scorer.payment_path_failed(&path.iter().collect::<Vec<_>>(), short_channel_id);
5598 // Because we've changed channel scores, its possible we'll take different routes to the
5599 // selected destinations, possibly causing us to fail because, eg, the newly-selected path
5600 // requires a too-high CLTV delta.
5601 route_endpoints.retain(|(first_hop, params, amt)| {
5602 get_route(&payer, params, &graph.read_only(), Some(&[first_hop]), *amt, 42, &DummyLogger{}, &scorer, &random_seed_bytes).is_ok()
5604 route_endpoints.truncate(100);
5605 assert_eq!(route_endpoints.len(), 100);
5607 // ...then benchmark finding paths between the nodes we learned.
5610 let (first_hop, params, amt) = &route_endpoints[idx % route_endpoints.len()];
5611 assert!(get_route(&payer, params, &graph.read_only(), Some(&[first_hop]), *amt, 42, &DummyLogger{}, &scorer, &random_seed_bytes).is_ok());