1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! The top-level routing/network map tracking logic lives here.
12 //! You probably want to create a P2PGossipSync and use that as your RoutingMessageHandler and then
13 //! interrogate it to get routes for your own payments.
15 use bitcoin::secp256k1::PublicKey;
17 use crate::ln::channelmanager::ChannelDetails;
18 use crate::ln::features::{ChannelFeatures, InvoiceFeatures, NodeFeatures};
19 use crate::ln::msgs::{DecodeError, ErrorAction, LightningError, MAX_VALUE_MSAT};
20 use crate::routing::gossip::{DirectedChannelInfo, EffectiveCapacity, ReadOnlyNetworkGraph, NetworkGraph, NodeId, RoutingFees};
21 use crate::routing::scoring::{ChannelUsage, Score};
22 use crate::util::ser::{Writeable, Readable, Writer};
23 use crate::util::logger::{Level, Logger};
24 use crate::util::chacha20::ChaCha20;
27 use crate::prelude::*;
28 use alloc::collections::BinaryHeap;
32 /// A trait defining behavior for routing a payment.
34 /// Finds a [`Route`] between `payer` and `payee` for a payment with the given values.
36 &self, payer: &PublicKey, route_params: &RouteParameters,
37 first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: InFlightHtlcs
38 ) -> Result<Route, LightningError>;
41 /// A map with liquidity value (in msat) keyed by a short channel id and the direction the HTLC
42 /// is traveling in. The direction boolean is determined by checking if the HTLC source's public
43 /// key is less than its destination. See [`InFlightHtlcs::used_liquidity_msat`] for more
45 #[cfg(not(any(test, feature = "_test_utils")))]
46 pub struct InFlightHtlcs(HashMap<(u64, bool), u64>);
47 #[cfg(any(test, feature = "_test_utils"))]
48 pub struct InFlightHtlcs(pub HashMap<(u64, bool), u64>);
51 /// Create a new `InFlightHtlcs` via a mapping from:
52 /// (short_channel_id, source_pubkey < target_pubkey) -> used_liquidity_msat
53 pub fn new(inflight_map: HashMap<(u64, bool), u64>) -> Self {
54 InFlightHtlcs(inflight_map)
57 /// Returns liquidity in msat given the public key of the HTLC source, target, and short channel
59 pub fn used_liquidity_msat(&self, source: &NodeId, target: &NodeId, channel_scid: u64) -> Option<u64> {
60 self.0.get(&(channel_scid, source < target)).map(|v| *v)
64 impl Writeable for InFlightHtlcs {
65 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> { self.0.write(writer) }
68 impl Readable for InFlightHtlcs {
69 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
70 let infight_map: HashMap<(u64, bool), u64> = Readable::read(reader)?;
76 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
78 /// The node_id of the node at this hop.
79 pub pubkey: PublicKey,
80 /// The node_announcement features of the node at this hop. For the last hop, these may be
81 /// amended to match the features present in the invoice this node generated.
82 pub node_features: NodeFeatures,
83 /// The channel that should be used from the previous hop to reach this node.
84 pub short_channel_id: u64,
85 /// The channel_announcement features of the channel that should be used from the previous hop
86 /// to reach this node.
87 pub channel_features: ChannelFeatures,
88 /// The fee taken on this hop (for paying for the use of the *next* channel in the path).
89 /// For the last hop, this should be the full value of the payment (might be more than
90 /// requested if we had to match htlc_minimum_msat).
92 /// The CLTV delta added for this hop. For the last hop, this should be the full CLTV value
93 /// expected at the destination, in excess of the current block height.
94 pub cltv_expiry_delta: u32,
97 impl_writeable_tlv_based!(RouteHop, {
98 (0, pubkey, required),
99 (2, node_features, required),
100 (4, short_channel_id, required),
101 (6, channel_features, required),
102 (8, fee_msat, required),
103 (10, cltv_expiry_delta, required),
106 /// A route directs a payment from the sender (us) to the recipient. If the recipient supports MPP,
107 /// it can take multiple paths. Each path is composed of one or more hops through the network.
108 #[derive(Clone, Hash, PartialEq, Eq)]
110 /// The list of routes taken for a single (potentially-)multi-part payment. The pubkey of the
111 /// last RouteHop in each path must be the same. Each entry represents a list of hops, NOT
112 /// INCLUDING our own, where the last hop is the destination. Thus, this must always be at
113 /// least length one. While the maximum length of any given path is variable, keeping the length
114 /// of any path less or equal to 19 should currently ensure it is viable.
115 pub paths: Vec<Vec<RouteHop>>,
116 /// The `payment_params` parameter passed to [`find_route`].
117 /// This is used by `ChannelManager` to track information which may be required for retries,
118 /// provided back to you via [`Event::PaymentPathFailed`].
120 /// [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed
121 pub payment_params: Option<PaymentParameters>,
124 pub(crate) trait RoutePath {
125 /// Gets the fees for a given path, excluding any excess paid to the recipient.
126 fn get_path_fees(&self) -> u64;
128 impl RoutePath for Vec<RouteHop> {
129 fn get_path_fees(&self) -> u64 {
130 // Do not count last hop of each path since that's the full value of the payment
131 self.split_last().map(|(_, path_prefix)| path_prefix).unwrap_or(&[])
132 .iter().map(|hop| &hop.fee_msat)
138 /// Returns the total amount of fees paid on this [`Route`].
140 /// This doesn't include any extra payment made to the recipient, which can happen in excess of
141 /// the amount passed to [`find_route`]'s `params.final_value_msat`.
142 pub fn get_total_fees(&self) -> u64 {
143 self.paths.iter().map(|path| path.get_path_fees()).sum()
146 /// Returns the total amount paid on this [`Route`], excluding the fees.
147 pub fn get_total_amount(&self) -> u64 {
148 return self.paths.iter()
149 .map(|path| path.split_last().map(|(hop, _)| hop.fee_msat).unwrap_or(0))
154 const SERIALIZATION_VERSION: u8 = 1;
155 const MIN_SERIALIZATION_VERSION: u8 = 1;
157 impl Writeable for Route {
158 fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
159 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
160 (self.paths.len() as u64).write(writer)?;
161 for hops in self.paths.iter() {
162 (hops.len() as u8).write(writer)?;
163 for hop in hops.iter() {
167 write_tlv_fields!(writer, {
168 (1, self.payment_params, option),
174 impl Readable for Route {
175 fn read<R: io::Read>(reader: &mut R) -> Result<Route, DecodeError> {
176 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
177 let path_count: u64 = Readable::read(reader)?;
178 let mut paths = Vec::with_capacity(cmp::min(path_count, 128) as usize);
179 for _ in 0..path_count {
180 let hop_count: u8 = Readable::read(reader)?;
181 let mut hops = Vec::with_capacity(hop_count as usize);
182 for _ in 0..hop_count {
183 hops.push(Readable::read(reader)?);
187 let mut payment_params = None;
188 read_tlv_fields!(reader, {
189 (1, payment_params, option),
191 Ok(Route { paths, payment_params })
195 /// Parameters needed to find a [`Route`].
197 /// Passed to [`find_route`] and [`build_route_from_hops`], but also provided in
198 /// [`Event::PaymentPathFailed`] for retrying a failed payment path.
200 /// [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed
201 #[derive(Clone, Debug)]
202 pub struct RouteParameters {
203 /// The parameters of the failed payment path.
204 pub payment_params: PaymentParameters,
206 /// The amount in msats sent on the failed payment path.
207 pub final_value_msat: u64,
209 /// The CLTV on the final hop of the failed payment path.
210 pub final_cltv_expiry_delta: u32,
213 impl_writeable_tlv_based!(RouteParameters, {
214 (0, payment_params, required),
215 (2, final_value_msat, required),
216 (4, final_cltv_expiry_delta, required),
219 /// Maximum total CTLV difference we allow for a full payment path.
220 pub const DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA: u32 = 1008;
222 /// Maximum number of paths we allow an (MPP) payment to have.
223 // The default limit is currently set rather arbitrary - there aren't any real fundamental path-count
224 // limits, but for now more than 10 paths likely carries too much one-path failure.
225 pub const DEFAULT_MAX_PATH_COUNT: u8 = 10;
227 // The median hop CLTV expiry delta currently seen in the network.
228 const MEDIAN_HOP_CLTV_EXPIRY_DELTA: u32 = 40;
230 // During routing, we only consider paths shorter than our maximum length estimate.
231 // In the TLV onion format, there is no fixed maximum length, but the `hop_payloads`
232 // field is always 1300 bytes. As the `tlv_payload` for each hop may vary in length, we have to
233 // estimate how many hops the route may have so that it actually fits the `hop_payloads` field.
235 // We estimate 3+32 (payload length and HMAC) + 2+8 (amt_to_forward) + 2+4 (outgoing_cltv_value) +
236 // 2+8 (short_channel_id) = 61 bytes for each intermediate hop and 3+32
237 // (payload length and HMAC) + 2+8 (amt_to_forward) + 2+4 (outgoing_cltv_value) + 2+32+8
238 // (payment_secret and total_msat) = 93 bytes for the final hop.
239 // Since the length of the potentially included `payment_metadata` is unknown to us, we round
240 // down from (1300-93) / 61 = 19.78... to arrive at a conservative estimate of 19.
241 const MAX_PATH_LENGTH_ESTIMATE: u8 = 19;
243 /// The recipient of a payment.
244 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
245 pub struct PaymentParameters {
246 /// The node id of the payee.
247 pub payee_pubkey: PublicKey,
249 /// Features supported by the payee.
251 /// May be set from the payee's invoice or via [`for_keysend`]. May be `None` if the invoice
252 /// does not contain any features.
254 /// [`for_keysend`]: Self::for_keysend
255 pub features: Option<InvoiceFeatures>,
257 /// Hints for routing to the payee, containing channels connecting the payee to public nodes.
258 pub route_hints: Vec<RouteHint>,
260 /// Expiration of a payment to the payee, in seconds relative to the UNIX epoch.
261 pub expiry_time: Option<u64>,
263 /// The maximum total CLTV delta we accept for the route.
264 /// Defaults to [`DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA`].
265 pub max_total_cltv_expiry_delta: u32,
267 /// The maximum number of paths that may be used by (MPP) payments.
268 /// Defaults to [`DEFAULT_MAX_PATH_COUNT`].
269 pub max_path_count: u8,
271 /// Selects the maximum share of a channel's total capacity which will be sent over a channel,
272 /// as a power of 1/2. A higher value prefers to send the payment using more MPP parts whereas
273 /// a lower value prefers to send larger MPP parts, potentially saturating channels and
274 /// increasing failure probability for those paths.
276 /// Note that this restriction will be relaxed during pathfinding after paths which meet this
277 /// restriction have been found. While paths which meet this criteria will be searched for, it
278 /// is ultimately up to the scorer to select them over other paths.
280 /// A value of 0 will allow payments up to and including a channel's total announced usable
281 /// capacity, a value of one will only use up to half its capacity, two 1/4, etc.
284 pub max_channel_saturation_power_of_half: u8,
286 /// A list of SCIDs which this payment was previously attempted over and which caused the
287 /// payment to fail. Future attempts for the same payment shouldn't be relayed through any of
289 pub previously_failed_channels: Vec<u64>,
292 impl_writeable_tlv_based!(PaymentParameters, {
293 (0, payee_pubkey, required),
294 (1, max_total_cltv_expiry_delta, (default_value, DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA)),
295 (2, features, option),
296 (3, max_path_count, (default_value, DEFAULT_MAX_PATH_COUNT)),
297 (4, route_hints, vec_type),
298 (5, max_channel_saturation_power_of_half, (default_value, 2)),
299 (6, expiry_time, option),
300 (7, previously_failed_channels, vec_type),
303 impl PaymentParameters {
304 /// Creates a payee with the node id of the given `pubkey`.
305 pub fn from_node_id(payee_pubkey: PublicKey) -> Self {
311 max_total_cltv_expiry_delta: DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA,
312 max_path_count: DEFAULT_MAX_PATH_COUNT,
313 max_channel_saturation_power_of_half: 2,
314 previously_failed_channels: Vec::new(),
318 /// Creates a payee with the node id of the given `pubkey` to use for keysend payments.
319 pub fn for_keysend(payee_pubkey: PublicKey) -> Self {
320 Self::from_node_id(payee_pubkey).with_features(InvoiceFeatures::for_keysend())
323 /// Includes the payee's features.
325 /// (C-not exported) since bindings don't support move semantics
326 pub fn with_features(self, features: InvoiceFeatures) -> Self {
327 Self { features: Some(features), ..self }
330 /// Includes hints for routing to the payee.
332 /// (C-not exported) since bindings don't support move semantics
333 pub fn with_route_hints(self, route_hints: Vec<RouteHint>) -> Self {
334 Self { route_hints, ..self }
337 /// Includes a payment expiration in seconds relative to the UNIX epoch.
339 /// (C-not exported) since bindings don't support move semantics
340 pub fn with_expiry_time(self, expiry_time: u64) -> Self {
341 Self { expiry_time: Some(expiry_time), ..self }
344 /// Includes a limit for the total CLTV expiry delta which is considered during routing
346 /// (C-not exported) since bindings don't support move semantics
347 pub fn with_max_total_cltv_expiry_delta(self, max_total_cltv_expiry_delta: u32) -> Self {
348 Self { max_total_cltv_expiry_delta, ..self }
351 /// Includes a limit for the maximum number of payment paths that may be used.
353 /// (C-not exported) since bindings don't support move semantics
354 pub fn with_max_path_count(self, max_path_count: u8) -> Self {
355 Self { max_path_count, ..self }
358 /// Includes a limit for the maximum number of payment paths that may be used.
360 /// (C-not exported) since bindings don't support move semantics
361 pub fn with_max_channel_saturation_power_of_half(self, max_channel_saturation_power_of_half: u8) -> Self {
362 Self { max_channel_saturation_power_of_half, ..self }
366 /// A list of hops along a payment path terminating with a channel to the recipient.
367 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
368 pub struct RouteHint(pub Vec<RouteHintHop>);
370 impl Writeable for RouteHint {
371 fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
372 (self.0.len() as u64).write(writer)?;
373 for hop in self.0.iter() {
380 impl Readable for RouteHint {
381 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
382 let hop_count: u64 = Readable::read(reader)?;
383 let mut hops = Vec::with_capacity(cmp::min(hop_count, 16) as usize);
384 for _ in 0..hop_count {
385 hops.push(Readable::read(reader)?);
391 /// A channel descriptor for a hop along a payment path.
392 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
393 pub struct RouteHintHop {
394 /// The node_id of the non-target end of the route
395 pub src_node_id: PublicKey,
396 /// The short_channel_id of this channel
397 pub short_channel_id: u64,
398 /// The fees which must be paid to use this channel
399 pub fees: RoutingFees,
400 /// The difference in CLTV values between this node and the next node.
401 pub cltv_expiry_delta: u16,
402 /// The minimum value, in msat, which must be relayed to the next hop.
403 pub htlc_minimum_msat: Option<u64>,
404 /// The maximum value in msat available for routing with a single HTLC.
405 pub htlc_maximum_msat: Option<u64>,
408 impl_writeable_tlv_based!(RouteHintHop, {
409 (0, src_node_id, required),
410 (1, htlc_minimum_msat, option),
411 (2, short_channel_id, required),
412 (3, htlc_maximum_msat, option),
414 (6, cltv_expiry_delta, required),
417 #[derive(Eq, PartialEq)]
418 struct RouteGraphNode {
420 lowest_fee_to_peer_through_node: u64,
421 lowest_fee_to_node: u64,
422 total_cltv_delta: u32,
423 // The maximum value a yet-to-be-constructed payment path might flow through this node.
424 // This value is upper-bounded by us by:
425 // - how much is needed for a path being constructed
426 // - how much value can channels following this node (up to the destination) can contribute,
427 // considering their capacity and fees
428 value_contribution_msat: u64,
429 /// The effective htlc_minimum_msat at this hop. If a later hop on the path had a higher HTLC
430 /// minimum, we use it, plus the fees required at each earlier hop to meet it.
431 path_htlc_minimum_msat: u64,
432 /// All penalties incurred from this hop on the way to the destination, as calculated using
434 path_penalty_msat: u64,
435 /// The number of hops walked up to this node.
436 path_length_to_node: u8,
439 impl cmp::Ord for RouteGraphNode {
440 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
441 let other_score = cmp::max(other.lowest_fee_to_peer_through_node, other.path_htlc_minimum_msat)
442 .saturating_add(other.path_penalty_msat);
443 let self_score = cmp::max(self.lowest_fee_to_peer_through_node, self.path_htlc_minimum_msat)
444 .saturating_add(self.path_penalty_msat);
445 other_score.cmp(&self_score).then_with(|| other.node_id.cmp(&self.node_id))
449 impl cmp::PartialOrd for RouteGraphNode {
450 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
451 Some(self.cmp(other))
455 /// A wrapper around the various hop representations.
457 /// Used to construct a [`PathBuildingHop`] and to estimate [`EffectiveCapacity`].
458 #[derive(Clone, Debug)]
459 enum CandidateRouteHop<'a> {
460 /// A hop from the payer, where the outbound liquidity is known.
462 details: &'a ChannelDetails,
464 /// A hop found in the [`ReadOnlyNetworkGraph`], where the channel capacity may be unknown.
466 info: DirectedChannelInfo<'a>,
467 short_channel_id: u64,
469 /// A hop to the payee found in the payment invoice, though not necessarily a direct channel.
471 hint: &'a RouteHintHop,
475 impl<'a> CandidateRouteHop<'a> {
476 fn short_channel_id(&self) -> u64 {
478 CandidateRouteHop::FirstHop { details } => details.get_outbound_payment_scid().unwrap(),
479 CandidateRouteHop::PublicHop { short_channel_id, .. } => *short_channel_id,
480 CandidateRouteHop::PrivateHop { hint } => hint.short_channel_id,
484 // NOTE: This may alloc memory so avoid calling it in a hot code path.
485 fn features(&self) -> ChannelFeatures {
487 CandidateRouteHop::FirstHop { details } => details.counterparty.features.to_context(),
488 CandidateRouteHop::PublicHop { info, .. } => info.channel().features.clone(),
489 CandidateRouteHop::PrivateHop { .. } => ChannelFeatures::empty(),
493 fn cltv_expiry_delta(&self) -> u32 {
495 CandidateRouteHop::FirstHop { .. } => 0,
496 CandidateRouteHop::PublicHop { info, .. } => info.direction().cltv_expiry_delta as u32,
497 CandidateRouteHop::PrivateHop { hint } => hint.cltv_expiry_delta as u32,
501 fn htlc_minimum_msat(&self) -> u64 {
503 CandidateRouteHop::FirstHop { .. } => 0,
504 CandidateRouteHop::PublicHop { info, .. } => info.direction().htlc_minimum_msat,
505 CandidateRouteHop::PrivateHop { hint } => hint.htlc_minimum_msat.unwrap_or(0),
509 fn fees(&self) -> RoutingFees {
511 CandidateRouteHop::FirstHop { .. } => RoutingFees {
512 base_msat: 0, proportional_millionths: 0,
514 CandidateRouteHop::PublicHop { info, .. } => info.direction().fees,
515 CandidateRouteHop::PrivateHop { hint } => hint.fees,
519 fn effective_capacity(&self) -> EffectiveCapacity {
521 CandidateRouteHop::FirstHop { details } => EffectiveCapacity::ExactLiquidity {
522 liquidity_msat: details.next_outbound_htlc_limit_msat,
524 CandidateRouteHop::PublicHop { info, .. } => info.effective_capacity(),
525 CandidateRouteHop::PrivateHop { .. } => EffectiveCapacity::Infinite,
531 fn max_htlc_from_capacity(capacity: EffectiveCapacity, max_channel_saturation_power_of_half: u8) -> u64 {
532 let saturation_shift: u32 = max_channel_saturation_power_of_half as u32;
534 EffectiveCapacity::ExactLiquidity { liquidity_msat } => liquidity_msat,
535 EffectiveCapacity::Infinite => u64::max_value(),
536 EffectiveCapacity::Unknown => EffectiveCapacity::Unknown.as_msat(),
537 EffectiveCapacity::MaximumHTLC { amount_msat } =>
538 amount_msat.checked_shr(saturation_shift).unwrap_or(0),
539 EffectiveCapacity::Total { capacity_msat, htlc_maximum_msat } =>
540 cmp::min(capacity_msat.checked_shr(saturation_shift).unwrap_or(0), htlc_maximum_msat),
544 fn iter_equal<I1: Iterator, I2: Iterator>(mut iter_a: I1, mut iter_b: I2)
545 -> bool where I1::Item: PartialEq<I2::Item> {
547 let a = iter_a.next();
548 let b = iter_b.next();
549 if a.is_none() && b.is_none() { return true; }
550 if a.is_none() || b.is_none() { return false; }
551 if a.unwrap().ne(&b.unwrap()) { return false; }
555 /// It's useful to keep track of the hops associated with the fees required to use them,
556 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
557 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
558 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
560 struct PathBuildingHop<'a> {
561 // Note that this should be dropped in favor of loading it from CandidateRouteHop, but doing so
562 // is a larger refactor and will require careful performance analysis.
564 candidate: CandidateRouteHop<'a>,
567 /// Minimal fees required to route to the source node of the current hop via any of its inbound channels.
568 src_lowest_inbound_fees: RoutingFees,
569 /// All the fees paid *after* this channel on the way to the destination
570 next_hops_fee_msat: u64,
571 /// Fee paid for the use of the current channel (see candidate.fees()).
572 /// The value will be actually deducted from the counterparty balance on the previous link.
573 hop_use_fee_msat: u64,
574 /// Used to compare channels when choosing the for routing.
575 /// Includes paying for the use of a hop and the following hops, as well as
576 /// an estimated cost of reaching this hop.
577 /// Might get stale when fees are recomputed. Primarily for internal use.
579 /// A mirror of the same field in RouteGraphNode. Note that this is only used during the graph
580 /// walk and may be invalid thereafter.
581 path_htlc_minimum_msat: u64,
582 /// All penalties incurred from this channel on the way to the destination, as calculated using
584 path_penalty_msat: u64,
585 /// If we've already processed a node as the best node, we shouldn't process it again. Normally
586 /// we'd just ignore it if we did as all channels would have a higher new fee, but because we
587 /// may decrease the amounts in use as we walk the graph, the actual calculated fee may
588 /// decrease as well. Thus, we have to explicitly track which nodes have been processed and
589 /// avoid processing them again.
591 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
592 // In tests, we apply further sanity checks on cases where we skip nodes we already processed
593 // to ensure it is specifically in cases where the fee has gone down because of a decrease in
594 // value_contribution_msat, which requires tracking it here. See comments below where it is
595 // used for more info.
596 value_contribution_msat: u64,
599 impl<'a> core::fmt::Debug for PathBuildingHop<'a> {
600 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
601 let mut debug_struct = f.debug_struct("PathBuildingHop");
603 .field("node_id", &self.node_id)
604 .field("short_channel_id", &self.candidate.short_channel_id())
605 .field("total_fee_msat", &self.total_fee_msat)
606 .field("next_hops_fee_msat", &self.next_hops_fee_msat)
607 .field("hop_use_fee_msat", &self.hop_use_fee_msat)
608 .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)))
609 .field("path_penalty_msat", &self.path_penalty_msat)
610 .field("path_htlc_minimum_msat", &self.path_htlc_minimum_msat)
611 .field("cltv_expiry_delta", &self.candidate.cltv_expiry_delta());
612 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
613 let debug_struct = debug_struct
614 .field("value_contribution_msat", &self.value_contribution_msat);
615 debug_struct.finish()
619 // Instantiated with a list of hops with correct data in them collected during path finding,
620 // an instance of this struct should be further modified only via given methods.
622 struct PaymentPath<'a> {
623 hops: Vec<(PathBuildingHop<'a>, NodeFeatures)>,
626 impl<'a> PaymentPath<'a> {
627 // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
628 fn get_value_msat(&self) -> u64 {
629 self.hops.last().unwrap().0.fee_msat
632 fn get_path_penalty_msat(&self) -> u64 {
633 self.hops.first().map(|h| h.0.path_penalty_msat).unwrap_or(u64::max_value())
636 fn get_total_fee_paid_msat(&self) -> u64 {
637 if self.hops.len() < 1 {
641 // Can't use next_hops_fee_msat because it gets outdated.
642 for (i, (hop, _)) in self.hops.iter().enumerate() {
643 if i != self.hops.len() - 1 {
644 result += hop.fee_msat;
650 fn get_cost_msat(&self) -> u64 {
651 self.get_total_fee_paid_msat().saturating_add(self.get_path_penalty_msat())
654 // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
655 // to change fees may result in an inconsistency.
657 // Sometimes we call this function right after constructing a path which is inconsistent in
658 // that it the value being transferred has decreased while we were doing path finding, leading
659 // to the fees being paid not lining up with the actual limits.
661 // Note that this function is not aware of the available_liquidity limit, and thus does not
662 // support increasing the value being transferred beyond what was selected during the initial
664 fn update_value_and_recompute_fees(&mut self, value_msat: u64) {
665 let mut total_fee_paid_msat = 0 as u64;
666 for i in (0..self.hops.len()).rev() {
667 let last_hop = i == self.hops.len() - 1;
669 // For non-last-hop, this value will represent the fees paid on the current hop. It
670 // will consist of the fees for the use of the next hop, and extra fees to match
671 // htlc_minimum_msat of the current channel. Last hop is handled separately.
672 let mut cur_hop_fees_msat = 0;
674 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().0.hop_use_fee_msat;
677 let mut cur_hop = &mut self.hops.get_mut(i).unwrap().0;
678 cur_hop.next_hops_fee_msat = total_fee_paid_msat;
679 // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
680 // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
681 // set it too high just to maliciously take more fees by exploiting this
682 // match htlc_minimum_msat logic.
683 let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
684 if let Some(extra_fees_msat) = cur_hop.candidate.htlc_minimum_msat().checked_sub(cur_hop_transferred_amount_msat) {
685 // Note that there is a risk that *previous hops* (those closer to us, as we go
686 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
688 // This might make us end up with a broken route, although this should be super-rare
689 // in practice, both because of how healthy channels look like, and how we pick
690 // channels in add_entry.
691 // Also, this can't be exploited more heavily than *announce a free path and fail
693 cur_hop_transferred_amount_msat += extra_fees_msat;
694 total_fee_paid_msat += extra_fees_msat;
695 cur_hop_fees_msat += extra_fees_msat;
699 // Final hop is a special case: it usually has just value_msat (by design), but also
700 // it still could overpay for the htlc_minimum_msat.
701 cur_hop.fee_msat = cur_hop_transferred_amount_msat;
703 // Propagate updated fees for the use of the channels to one hop back, where they
704 // will be actually paid (fee_msat). The last hop is handled above separately.
705 cur_hop.fee_msat = cur_hop_fees_msat;
708 // Fee for the use of the current hop which will be deducted on the previous hop.
709 // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
710 // this channel is free for us.
712 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.candidate.fees()) {
713 cur_hop.hop_use_fee_msat = new_fee;
714 total_fee_paid_msat += new_fee;
716 // It should not be possible because this function is called only to reduce the
717 // value. In that case, compute_fee was already called with the same fees for
718 // larger amount and there was no overflow.
726 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
727 let proportional_fee_millions =
728 amount_msat.checked_mul(channel_fees.proportional_millionths as u64);
729 if let Some(new_fee) = proportional_fee_millions.and_then(|part| {
730 (channel_fees.base_msat as u64).checked_add(part / 1_000_000) }) {
734 // This function may be (indirectly) called without any verification,
735 // with channel_fees provided by a caller. We should handle it gracefully.
740 /// The default `features` we assume for a node in a route, when no `features` are known about that
743 /// Default features are:
744 /// * variable_length_onion_optional
745 fn default_node_features() -> NodeFeatures {
746 let mut features = NodeFeatures::empty();
747 features.set_variable_length_onion_optional();
751 /// Finds a route from us (payer) to the given target node (payee).
753 /// If the payee provided features in their invoice, they should be provided via `params.payee`.
754 /// Without this, MPP will only be used if the payee's features are available in the network graph.
756 /// Private routing paths between a public node and the target may be included in `params.payee`.
758 /// If some channels aren't announced, it may be useful to fill in `first_hops` with the results
759 /// from [`ChannelManager::list_usable_channels`]. If it is filled in, the view of these channels
760 /// from `network_graph` will be ignored, and only those in `first_hops` will be used.
762 /// The fees on channels from us to the next hop are ignored as they are assumed to all be equal.
763 /// However, the enabled/disabled bit on such channels as well as the `htlc_minimum_msat` /
764 /// `htlc_maximum_msat` *are* checked as they may change based on the receiving node.
768 /// May be used to re-compute a [`Route`] when handling a [`Event::PaymentPathFailed`]. Any
769 /// adjustments to the [`NetworkGraph`] and channel scores should be made prior to calling this
774 /// Panics if first_hops contains channels without short_channel_ids;
775 /// [`ChannelManager::list_usable_channels`] will never include such channels.
777 /// [`ChannelManager::list_usable_channels`]: crate::ln::channelmanager::ChannelManager::list_usable_channels
778 /// [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed
779 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
780 pub fn find_route<L: Deref, GL: Deref, S: Score>(
781 our_node_pubkey: &PublicKey, route_params: &RouteParameters,
782 network_graph: &NetworkGraph<GL>, first_hops: Option<&[&ChannelDetails]>, logger: L,
783 scorer: &S, random_seed_bytes: &[u8; 32]
784 ) -> Result<Route, LightningError>
785 where L::Target: Logger, GL::Target: Logger {
786 let graph_lock = network_graph.read_only();
787 let mut route = get_route(our_node_pubkey, &route_params.payment_params, &graph_lock, first_hops,
788 route_params.final_value_msat, route_params.final_cltv_expiry_delta, logger, scorer,
790 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
794 pub(crate) fn get_route<L: Deref, S: Score>(
795 our_node_pubkey: &PublicKey, payment_params: &PaymentParameters, network_graph: &ReadOnlyNetworkGraph,
796 first_hops: Option<&[&ChannelDetails]>, final_value_msat: u64, final_cltv_expiry_delta: u32,
797 logger: L, scorer: &S, _random_seed_bytes: &[u8; 32]
798 ) -> Result<Route, LightningError>
799 where L::Target: Logger {
800 let payee_node_id = NodeId::from_pubkey(&payment_params.payee_pubkey);
801 let our_node_id = NodeId::from_pubkey(&our_node_pubkey);
803 if payee_node_id == our_node_id {
804 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
807 if final_value_msat > MAX_VALUE_MSAT {
808 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
811 if final_value_msat == 0 {
812 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
815 for route in payment_params.route_hints.iter() {
816 for hop in &route.0 {
817 if hop.src_node_id == payment_params.payee_pubkey {
818 return Err(LightningError{err: "Route hint cannot have the payee as the source.".to_owned(), action: ErrorAction::IgnoreError});
822 if payment_params.max_total_cltv_expiry_delta <= final_cltv_expiry_delta {
823 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});
826 // The general routing idea is the following:
827 // 1. Fill first/last hops communicated by the caller.
828 // 2. Attempt to construct a path from payer to payee for transferring
829 // any ~sufficient (described later) value.
830 // If succeed, remember which channels were used and how much liquidity they have available,
831 // so that future paths don't rely on the same liquidity.
832 // 3. Proceed to the next step if:
833 // - we hit the recommended target value;
834 // - OR if we could not construct a new path. Any next attempt will fail too.
835 // Otherwise, repeat step 2.
836 // 4. See if we managed to collect paths which aggregately are able to transfer target value
837 // (not recommended value).
838 // 5. If yes, proceed. If not, fail routing.
839 // 6. Select the paths which have the lowest cost (fee plus scorer penalty) per amount
840 // transferred up to the transfer target value.
841 // 7. Reduce the value of the last path until we are sending only the target value.
842 // 8. If our maximum channel saturation limit caused us to pick two identical paths, combine
843 // them so that we're not sending two HTLCs along the same path.
845 // As for the actual search algorithm,
846 // we do a payee-to-payer pseudo-Dijkstra's sorting by each node's distance from the payee
847 // plus the minimum per-HTLC fee to get from it to another node (aka "shitty pseudo-A*").
849 // We are not a faithful Dijkstra's implementation because we can change values which impact
850 // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
851 // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) than
852 // the value we are currently attempting to send over a path, we simply reduce the value being
853 // sent along the path for any hops after that channel. This may imply that later fees (which
854 // we've already tabulated) are lower because a smaller value is passing through the channels
855 // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
856 // channels which were selected earlier (and which may still be used for other paths without a
857 // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
860 // One potentially problematic case for this algorithm would be if there are many
861 // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
862 // graph walking), we may never find a path which is not liquidity-limited and has lower
863 // proportional fee (and only lower absolute fee when considering the ultimate value sent).
864 // Because we only consider paths with at least 5% of the total value being sent, the damage
865 // from such a case should be limited, however this could be further reduced in the future by
866 // calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
867 // limits for the purposes of fee calculation.
869 // Alternatively, we could store more detailed path information in the heap (targets, below)
870 // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
871 // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
872 // and practically (as we would need to store dynamically-allocated path information in heap
873 // objects, increasing malloc traffic and indirect memory access significantly). Further, the
874 // results of such an algorithm would likely be biased towards lower-value paths.
876 // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
877 // outside of our current search value, running a path search more times to gather candidate
878 // paths at different values. While this may be acceptable, further path searches may increase
879 // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
880 // graph for candidate paths, calculating the maximum value which can realistically be sent at
881 // the same time, remaining generic across different payment values.
883 // TODO: There are a few tweaks we could do, including possibly pre-calculating more stuff
884 // to use as the A* heuristic beyond just the cost to get one node further than the current
887 let network_channels = network_graph.channels();
888 let network_nodes = network_graph.nodes();
890 if payment_params.max_path_count == 0 {
891 return Err(LightningError{err: "Can't find a route with no paths allowed.".to_owned(), action: ErrorAction::IgnoreError});
894 // Allow MPP only if we have a features set from somewhere that indicates the payee supports
895 // it. If the payee supports it they're supposed to include it in the invoice, so that should
897 let allow_mpp = if payment_params.max_path_count == 1 {
899 } else if let Some(features) = &payment_params.features {
900 features.supports_basic_mpp()
901 } else if let Some(node) = network_nodes.get(&payee_node_id) {
902 if let Some(node_info) = node.announcement_info.as_ref() {
903 node_info.features.supports_basic_mpp()
907 log_trace!(logger, "Searching for a route from payer {} to payee {} {} MPP and {} first hops {}overriding the network graph", our_node_pubkey,
908 payment_params.payee_pubkey, if allow_mpp { "with" } else { "without" },
909 first_hops.map(|hops| hops.len()).unwrap_or(0), if first_hops.is_some() { "" } else { "not " });
912 // Prepare the data we'll use for payee-to-payer search by
913 // inserting first hops suggested by the caller as targets.
914 // Our search will then attempt to reach them while traversing from the payee node.
915 let mut first_hop_targets: HashMap<_, Vec<&ChannelDetails>> =
916 HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
917 if let Some(hops) = first_hops {
919 if chan.get_outbound_payment_scid().is_none() {
920 panic!("first_hops should be filled in with usable channels, not pending ones");
922 if chan.counterparty.node_id == *our_node_pubkey {
923 return Err(LightningError{err: "First hop cannot have our_node_pubkey as a destination.".to_owned(), action: ErrorAction::IgnoreError});
926 .entry(NodeId::from_pubkey(&chan.counterparty.node_id))
927 .or_insert(Vec::new())
930 if first_hop_targets.is_empty() {
931 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
935 // The main heap containing all candidate next-hops sorted by their score (max(A* fee,
936 // htlc_minimum)). Ideally this would be a heap which allowed cheap score reduction instead of
937 // adding duplicate entries when we find a better path to a given node.
938 let mut targets: BinaryHeap<RouteGraphNode> = BinaryHeap::new();
940 // Map from node_id to information about the best current path to that node, including feerate
942 let mut dist: HashMap<NodeId, PathBuildingHop> = HashMap::with_capacity(network_nodes.len());
944 // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
945 // indicating that we may wish to try again with a higher value, potentially paying to meet an
946 // htlc_minimum with extra fees while still finding a cheaper path.
947 let mut hit_minimum_limit;
949 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
950 // We start with a path_value of the exact amount we want, and if that generates a route we may
951 // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
952 // amount we want in total across paths, selecting the best subset at the end.
953 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
954 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
955 let mut path_value_msat = final_value_msat;
957 // Routing Fragmentation Mitigation heuristic:
959 // Routing fragmentation across many payment paths increases the overall routing
960 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
961 // Taking too many smaller paths also increases the chance of payment failure.
962 // Thus to avoid this effect, we require from our collected links to provide
963 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
964 // This requirement is currently set to be 1/max_path_count of the payment
965 // value to ensure we only ever return routes that do not violate this limit.
966 let minimal_value_contribution_msat: u64 = if allow_mpp {
967 (final_value_msat + (payment_params.max_path_count as u64 - 1)) / payment_params.max_path_count as u64
972 // When we start collecting routes we enforce the max_channel_saturation_power_of_half
973 // requirement strictly. After we've collected enough (or if we fail to find new routes) we
974 // drop the requirement by setting this to 0.
975 let mut channel_saturation_pow_half = payment_params.max_channel_saturation_power_of_half;
977 // Keep track of how much liquidity has been used in selected channels. Used to determine
978 // if the channel can be used by additional MPP paths or to inform path finding decisions. It is
979 // aware of direction *only* to ensure that the correct htlc_maximum_msat value is used. Hence,
980 // liquidity used in one direction will not offset any used in the opposite direction.
981 let mut used_channel_liquidities: HashMap<(u64, bool), u64> =
982 HashMap::with_capacity(network_nodes.len());
984 // Keeping track of how much value we already collected across other paths. Helps to decide
985 // when we want to stop looking for new paths.
986 let mut already_collected_value_msat = 0;
988 for (_, channels) in first_hop_targets.iter_mut() {
989 // Sort the first_hops channels to the same node(s) in priority order of which channel we'd
992 // First, if channels are below `recommended_value_msat`, sort them in descending order,
993 // preferring larger channels to avoid splitting the payment into more MPP parts than is
996 // Second, because simply always sorting in descending order would always use our largest
997 // available outbound capacity, needlessly fragmenting our available channel capacities,
998 // sort channels above `recommended_value_msat` in ascending order, preferring channels
999 // which have enough, but not too much, capacity for the payment.
1000 channels.sort_unstable_by(|chan_a, chan_b| {
1001 if chan_b.next_outbound_htlc_limit_msat < recommended_value_msat || chan_a.next_outbound_htlc_limit_msat < recommended_value_msat {
1002 // Sort in descending order
1003 chan_b.next_outbound_htlc_limit_msat.cmp(&chan_a.next_outbound_htlc_limit_msat)
1005 // Sort in ascending order
1006 chan_a.next_outbound_htlc_limit_msat.cmp(&chan_b.next_outbound_htlc_limit_msat)
1011 log_trace!(logger, "Building path from {} (payee) to {} (us/payer) for value {} msat.", payment_params.payee_pubkey, our_node_pubkey, final_value_msat);
1013 macro_rules! add_entry {
1014 // Adds entry which goes from $src_node_id to $dest_node_id over the $candidate hop.
1015 // $next_hops_fee_msat represents the fees paid for using all the channels *after* this one,
1016 // since that value has to be transferred over this channel.
1017 // Returns whether this channel caused an update to `targets`.
1018 ( $candidate: expr, $src_node_id: expr, $dest_node_id: expr, $next_hops_fee_msat: expr,
1019 $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr,
1020 $next_hops_path_penalty_msat: expr, $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => { {
1021 // We "return" whether we updated the path at the end, via this:
1022 let mut did_add_update_path_to_src_node = false;
1023 // Channels to self should not be used. This is more of belt-and-suspenders, because in
1024 // practice these cases should be caught earlier:
1025 // - for regular channels at channel announcement (TODO)
1026 // - for first and last hops early in get_route
1027 if $src_node_id != $dest_node_id {
1028 let short_channel_id = $candidate.short_channel_id();
1029 let effective_capacity = $candidate.effective_capacity();
1030 let htlc_maximum_msat = max_htlc_from_capacity(effective_capacity, channel_saturation_pow_half);
1032 // It is tricky to subtract $next_hops_fee_msat from available liquidity here.
1033 // It may be misleading because we might later choose to reduce the value transferred
1034 // over these channels, and the channel which was insufficient might become sufficient.
1035 // Worst case: we drop a good channel here because it can't cover the high following
1036 // fees caused by one expensive channel, but then this channel could have been used
1037 // if the amount being transferred over this path is lower.
1038 // We do this for now, but this is a subject for removal.
1039 if let Some(mut available_value_contribution_msat) = htlc_maximum_msat.checked_sub($next_hops_fee_msat) {
1040 let used_liquidity_msat = used_channel_liquidities
1041 .get(&(short_channel_id, $src_node_id < $dest_node_id))
1042 .map_or(0, |used_liquidity_msat| {
1043 available_value_contribution_msat = available_value_contribution_msat
1044 .saturating_sub(*used_liquidity_msat);
1045 *used_liquidity_msat
1048 // Verify the liquidity offered by this channel complies to the minimal contribution.
1049 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
1050 // Do not consider candidate hops that would exceed the maximum path length.
1051 let path_length_to_node = $next_hops_path_length + 1;
1052 let exceeds_max_path_length = path_length_to_node > MAX_PATH_LENGTH_ESTIMATE;
1054 // Do not consider candidates that exceed the maximum total cltv expiry limit.
1055 // In order to already account for some of the privacy enhancing random CLTV
1056 // expiry delta offset we add on top later, we subtract a rough estimate
1057 // (2*MEDIAN_HOP_CLTV_EXPIRY_DELTA) here.
1058 let max_total_cltv_expiry_delta = (payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta)
1059 .checked_sub(2*MEDIAN_HOP_CLTV_EXPIRY_DELTA)
1060 .unwrap_or(payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta);
1061 let hop_total_cltv_delta = ($next_hops_cltv_delta as u32)
1062 .saturating_add($candidate.cltv_expiry_delta());
1063 let exceeds_cltv_delta_limit = hop_total_cltv_delta > max_total_cltv_expiry_delta;
1065 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
1066 // Includes paying fees for the use of the following channels.
1067 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
1068 Some(result) => result,
1069 // Can't overflow due to how the values were computed right above.
1070 None => unreachable!(),
1072 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
1073 let over_path_minimum_msat = amount_to_transfer_over_msat >= $candidate.htlc_minimum_msat() &&
1074 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
1076 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
1077 let may_overpay_to_meet_path_minimum_msat =
1078 ((amount_to_transfer_over_msat < $candidate.htlc_minimum_msat() &&
1079 recommended_value_msat > $candidate.htlc_minimum_msat()) ||
1080 (amount_to_transfer_over_msat < $next_hops_path_htlc_minimum_msat &&
1081 recommended_value_msat > $next_hops_path_htlc_minimum_msat));
1083 let payment_failed_on_this_channel =
1084 payment_params.previously_failed_channels.contains(&short_channel_id);
1086 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
1087 // bother considering this channel. If retrying with recommended_value_msat may
1088 // allow us to hit the HTLC minimum limit, set htlc_minimum_limit so that we go
1089 // around again with a higher amount.
1090 if !contributes_sufficient_value || exceeds_max_path_length ||
1091 exceeds_cltv_delta_limit || payment_failed_on_this_channel {
1092 // Path isn't useful, ignore it and move on.
1093 } else if may_overpay_to_meet_path_minimum_msat {
1094 hit_minimum_limit = true;
1095 } else if over_path_minimum_msat {
1096 // Note that low contribution here (limited by available_liquidity_msat)
1097 // might violate htlc_minimum_msat on the hops which are next along the
1098 // payment path (upstream to the payee). To avoid that, we recompute
1099 // path fees knowing the final path contribution after constructing it.
1100 let path_htlc_minimum_msat = compute_fees($next_hops_path_htlc_minimum_msat, $candidate.fees())
1101 .and_then(|fee_msat| fee_msat.checked_add($next_hops_path_htlc_minimum_msat))
1102 .map(|fee_msat| cmp::max(fee_msat, $candidate.htlc_minimum_msat()))
1103 .unwrap_or_else(|| u64::max_value());
1104 let hm_entry = dist.entry($src_node_id);
1105 let old_entry = hm_entry.or_insert_with(|| {
1106 // If there was previously no known way to access the source node
1107 // (recall it goes payee-to-payer) of short_channel_id, first add a
1108 // semi-dummy record just to compute the fees to reach the source node.
1109 // This will affect our decision on selecting short_channel_id
1110 // as a way to reach the $dest_node_id.
1111 let mut fee_base_msat = 0;
1112 let mut fee_proportional_millionths = 0;
1113 if let Some(Some(fees)) = network_nodes.get(&$src_node_id).map(|node| node.lowest_inbound_channel_fees) {
1114 fee_base_msat = fees.base_msat;
1115 fee_proportional_millionths = fees.proportional_millionths;
1118 node_id: $dest_node_id.clone(),
1119 candidate: $candidate.clone(),
1121 src_lowest_inbound_fees: RoutingFees {
1122 base_msat: fee_base_msat,
1123 proportional_millionths: fee_proportional_millionths,
1125 next_hops_fee_msat: u64::max_value(),
1126 hop_use_fee_msat: u64::max_value(),
1127 total_fee_msat: u64::max_value(),
1128 path_htlc_minimum_msat,
1129 path_penalty_msat: u64::max_value(),
1130 was_processed: false,
1131 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
1132 value_contribution_msat,
1136 #[allow(unused_mut)] // We only use the mut in cfg(test)
1137 let mut should_process = !old_entry.was_processed;
1138 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
1140 // In test/fuzzing builds, we do extra checks to make sure the skipping
1141 // of already-seen nodes only happens in cases we expect (see below).
1142 if !should_process { should_process = true; }
1146 let mut hop_use_fee_msat = 0;
1147 let mut total_fee_msat = $next_hops_fee_msat;
1149 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
1150 // will have the same effective-fee
1151 if $src_node_id != our_node_id {
1152 match compute_fees(amount_to_transfer_over_msat, $candidate.fees()) {
1153 // max_value means we'll always fail
1154 // the old_entry.total_fee_msat > total_fee_msat check
1155 None => total_fee_msat = u64::max_value(),
1157 hop_use_fee_msat = fee_msat;
1158 total_fee_msat += hop_use_fee_msat;
1159 // When calculating the lowest inbound fees to a node, we
1160 // calculate fees here not based on the actual value we think
1161 // will flow over this channel, but on the minimum value that
1162 // we'll accept flowing over it. The minimum accepted value
1163 // is a constant through each path collection run, ensuring
1164 // consistent basis. Otherwise we may later find a
1165 // different path to the source node that is more expensive,
1166 // but which we consider to be cheaper because we are capacity
1167 // constrained and the relative fee becomes lower.
1168 match compute_fees(minimal_value_contribution_msat, old_entry.src_lowest_inbound_fees)
1169 .map(|a| a.checked_add(total_fee_msat)) {
1174 total_fee_msat = u64::max_value();
1181 let channel_usage = ChannelUsage {
1182 amount_msat: amount_to_transfer_over_msat,
1183 inflight_htlc_msat: used_liquidity_msat,
1186 let channel_penalty_msat = scorer.channel_penalty_msat(
1187 short_channel_id, &$src_node_id, &$dest_node_id, channel_usage
1189 let path_penalty_msat = $next_hops_path_penalty_msat
1190 .saturating_add(channel_penalty_msat);
1191 let new_graph_node = RouteGraphNode {
1192 node_id: $src_node_id,
1193 lowest_fee_to_peer_through_node: total_fee_msat,
1194 lowest_fee_to_node: $next_hops_fee_msat as u64 + hop_use_fee_msat,
1195 total_cltv_delta: hop_total_cltv_delta,
1196 value_contribution_msat,
1197 path_htlc_minimum_msat,
1199 path_length_to_node,
1202 // Update the way of reaching $src_node_id with the given short_channel_id (from $dest_node_id),
1203 // if this way is cheaper than the already known
1204 // (considering the cost to "reach" this channel from the route destination,
1205 // the cost of using this channel,
1206 // and the cost of routing to the source node of this channel).
1207 // Also, consider that htlc_minimum_msat_difference, because we might end up
1208 // paying it. Consider the following exploit:
1209 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
1210 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
1211 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
1212 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
1214 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
1215 // but it may require additional tracking - we don't want to double-count
1216 // the fees included in $next_hops_path_htlc_minimum_msat, but also
1217 // can't use something that may decrease on future hops.
1218 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat)
1219 .saturating_add(old_entry.path_penalty_msat);
1220 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat)
1221 .saturating_add(path_penalty_msat);
1223 if !old_entry.was_processed && new_cost < old_cost {
1224 targets.push(new_graph_node);
1225 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
1226 old_entry.hop_use_fee_msat = hop_use_fee_msat;
1227 old_entry.total_fee_msat = total_fee_msat;
1228 old_entry.node_id = $dest_node_id.clone();
1229 old_entry.candidate = $candidate.clone();
1230 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
1231 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
1232 old_entry.path_penalty_msat = path_penalty_msat;
1233 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
1235 old_entry.value_contribution_msat = value_contribution_msat;
1237 did_add_update_path_to_src_node = true;
1238 } else if old_entry.was_processed && new_cost < old_cost {
1239 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
1241 // If we're skipping processing a node which was previously
1242 // processed even though we found another path to it with a
1243 // cheaper fee, check that it was because the second path we
1244 // found (which we are processing now) has a lower value
1245 // contribution due to an HTLC minimum limit.
1247 // e.g. take a graph with two paths from node 1 to node 2, one
1248 // through channel A, and one through channel B. Channel A and
1249 // B are both in the to-process heap, with their scores set by
1250 // a higher htlc_minimum than fee.
1251 // Channel A is processed first, and the channels onwards from
1252 // node 1 are added to the to-process heap. Thereafter, we pop
1253 // Channel B off of the heap, note that it has a much more
1254 // restrictive htlc_maximum_msat, and recalculate the fees for
1255 // all of node 1's channels using the new, reduced, amount.
1257 // This would be bogus - we'd be selecting a higher-fee path
1258 // with a lower htlc_maximum_msat instead of the one we'd
1259 // already decided to use.
1260 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
1262 value_contribution_msat + path_penalty_msat <
1263 old_entry.value_contribution_msat + old_entry.path_penalty_msat
1271 did_add_update_path_to_src_node
1275 let default_node_features = default_node_features();
1277 // Find ways (channels with destination) to reach a given node and store them
1278 // in the corresponding data structures (routing graph etc).
1279 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
1280 // meaning how much will be paid in fees after this node (to the best of our knowledge).
1281 // This data can later be helpful to optimize routing (pay lower fees).
1282 macro_rules! add_entries_to_cheapest_to_target_node {
1283 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr, $next_hops_value_contribution: expr,
1284 $next_hops_path_htlc_minimum_msat: expr, $next_hops_path_penalty_msat: expr,
1285 $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => {
1286 let skip_node = if let Some(elem) = dist.get_mut(&$node_id) {
1287 let was_processed = elem.was_processed;
1288 elem.was_processed = true;
1291 // Entries are added to dist in add_entry!() when there is a channel from a node.
1292 // Because there are no channels from payee, it will not have a dist entry at this point.
1293 // If we're processing any other node, it is always be the result of a channel from it.
1294 assert_eq!($node_id, payee_node_id);
1299 if let Some(first_channels) = first_hop_targets.get(&$node_id) {
1300 for details in first_channels {
1301 let candidate = CandidateRouteHop::FirstHop { details };
1302 add_entry!(candidate, our_node_id, $node_id, $fee_to_target_msat,
1303 $next_hops_value_contribution,
1304 $next_hops_path_htlc_minimum_msat, $next_hops_path_penalty_msat,
1305 $next_hops_cltv_delta, $next_hops_path_length);
1309 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
1312 &default_node_features
1315 if !features.requires_unknown_bits() {
1316 for chan_id in $node.channels.iter() {
1317 let chan = network_channels.get(chan_id).unwrap();
1318 if !chan.features.requires_unknown_bits() {
1319 if let Some((directed_channel, source)) = chan.as_directed_to(&$node_id) {
1320 if first_hops.is_none() || *source != our_node_id {
1321 if directed_channel.direction().enabled {
1322 let candidate = CandidateRouteHop::PublicHop {
1323 info: directed_channel,
1324 short_channel_id: *chan_id,
1326 add_entry!(candidate, *source, $node_id,
1327 $fee_to_target_msat,
1328 $next_hops_value_contribution,
1329 $next_hops_path_htlc_minimum_msat,
1330 $next_hops_path_penalty_msat,
1331 $next_hops_cltv_delta, $next_hops_path_length);
1342 let mut payment_paths = Vec::<PaymentPath>::new();
1344 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
1345 'paths_collection: loop {
1346 // For every new path, start from scratch, except for used_channel_liquidities, which
1347 // helps to avoid reusing previously selected paths in future iterations.
1350 hit_minimum_limit = false;
1352 // If first hop is a private channel and the only way to reach the payee, this is the only
1353 // place where it could be added.
1354 if let Some(first_channels) = first_hop_targets.get(&payee_node_id) {
1355 for details in first_channels {
1356 let candidate = CandidateRouteHop::FirstHop { details };
1357 let added = add_entry!(candidate, our_node_id, payee_node_id, 0, path_value_msat,
1359 log_trace!(logger, "{} direct route to payee via SCID {}",
1360 if added { "Added" } else { "Skipped" }, candidate.short_channel_id());
1364 // Add the payee as a target, so that the payee-to-payer
1365 // search algorithm knows what to start with.
1366 match network_nodes.get(&payee_node_id) {
1367 // The payee is not in our network graph, so nothing to add here.
1368 // There is still a chance of reaching them via last_hops though,
1369 // so don't yet fail the payment here.
1370 // If not, targets.pop() will not even let us enter the loop in step 2.
1373 add_entries_to_cheapest_to_target_node!(node, payee_node_id, 0, path_value_msat, 0, 0u64, 0, 0);
1378 // If a caller provided us with last hops, add them to routing targets. Since this happens
1379 // earlier than general path finding, they will be somewhat prioritized, although currently
1380 // it matters only if the fees are exactly the same.
1381 for route in payment_params.route_hints.iter().filter(|route| !route.0.is_empty()) {
1382 let first_hop_in_route = &(route.0)[0];
1383 let have_hop_src_in_graph =
1384 // Only add the hops in this route to our candidate set if either
1385 // we have a direct channel to the first hop or the first hop is
1386 // in the regular network graph.
1387 first_hop_targets.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some() ||
1388 network_nodes.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some();
1389 if have_hop_src_in_graph {
1390 // We start building the path from reverse, i.e., from payee
1391 // to the first RouteHintHop in the path.
1392 let hop_iter = route.0.iter().rev();
1393 let prev_hop_iter = core::iter::once(&payment_params.payee_pubkey).chain(
1394 route.0.iter().skip(1).rev().map(|hop| &hop.src_node_id));
1395 let mut hop_used = true;
1396 let mut aggregate_next_hops_fee_msat: u64 = 0;
1397 let mut aggregate_next_hops_path_htlc_minimum_msat: u64 = 0;
1398 let mut aggregate_next_hops_path_penalty_msat: u64 = 0;
1399 let mut aggregate_next_hops_cltv_delta: u32 = 0;
1400 let mut aggregate_next_hops_path_length: u8 = 0;
1402 for (idx, (hop, prev_hop_id)) in hop_iter.zip(prev_hop_iter).enumerate() {
1403 let source = NodeId::from_pubkey(&hop.src_node_id);
1404 let target = NodeId::from_pubkey(&prev_hop_id);
1405 let candidate = network_channels
1406 .get(&hop.short_channel_id)
1407 .and_then(|channel| channel.as_directed_to(&target))
1408 .map(|(info, _)| CandidateRouteHop::PublicHop {
1410 short_channel_id: hop.short_channel_id,
1412 .unwrap_or_else(|| CandidateRouteHop::PrivateHop { hint: hop });
1414 if !add_entry!(candidate, source, target, aggregate_next_hops_fee_msat,
1415 path_value_msat, aggregate_next_hops_path_htlc_minimum_msat,
1416 aggregate_next_hops_path_penalty_msat,
1417 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length) {
1418 // If this hop was not used then there is no use checking the preceding
1419 // hops in the RouteHint. We can break by just searching for a direct
1420 // channel between last checked hop and first_hop_targets.
1424 let used_liquidity_msat = used_channel_liquidities
1425 .get(&(hop.short_channel_id, source < target)).copied().unwrap_or(0);
1426 let channel_usage = ChannelUsage {
1427 amount_msat: final_value_msat + aggregate_next_hops_fee_msat,
1428 inflight_htlc_msat: used_liquidity_msat,
1429 effective_capacity: candidate.effective_capacity(),
1431 let channel_penalty_msat = scorer.channel_penalty_msat(
1432 hop.short_channel_id, &source, &target, channel_usage
1434 aggregate_next_hops_path_penalty_msat = aggregate_next_hops_path_penalty_msat
1435 .saturating_add(channel_penalty_msat);
1437 aggregate_next_hops_cltv_delta = aggregate_next_hops_cltv_delta
1438 .saturating_add(hop.cltv_expiry_delta as u32);
1440 aggregate_next_hops_path_length = aggregate_next_hops_path_length
1443 // Searching for a direct channel between last checked hop and first_hop_targets
1444 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&prev_hop_id)) {
1445 for details in first_channels {
1446 let candidate = CandidateRouteHop::FirstHop { details };
1447 add_entry!(candidate, our_node_id, NodeId::from_pubkey(&prev_hop_id),
1448 aggregate_next_hops_fee_msat, path_value_msat,
1449 aggregate_next_hops_path_htlc_minimum_msat,
1450 aggregate_next_hops_path_penalty_msat, aggregate_next_hops_cltv_delta,
1451 aggregate_next_hops_path_length);
1459 // In the next values of the iterator, the aggregate fees already reflects
1460 // the sum of value sent from payer (final_value_msat) and routing fees
1461 // for the last node in the RouteHint. We need to just add the fees to
1462 // route through the current node so that the preceding node (next iteration)
1464 let hops_fee = compute_fees(aggregate_next_hops_fee_msat + final_value_msat, hop.fees)
1465 .map_or(None, |inc| inc.checked_add(aggregate_next_hops_fee_msat));
1466 aggregate_next_hops_fee_msat = if let Some(val) = hops_fee { val } else { break; };
1468 let hop_htlc_minimum_msat = candidate.htlc_minimum_msat();
1469 let hop_htlc_minimum_msat_inc = if let Some(val) = compute_fees(aggregate_next_hops_path_htlc_minimum_msat, hop.fees) { val } else { break; };
1470 let hops_path_htlc_minimum = aggregate_next_hops_path_htlc_minimum_msat
1471 .checked_add(hop_htlc_minimum_msat_inc);
1472 aggregate_next_hops_path_htlc_minimum_msat = if let Some(val) = hops_path_htlc_minimum { cmp::max(hop_htlc_minimum_msat, val) } else { break; };
1474 if idx == route.0.len() - 1 {
1475 // The last hop in this iterator is the first hop in
1476 // overall RouteHint.
1477 // If this hop connects to a node with which we have a direct channel,
1478 // ignore the network graph and, if the last hop was added, add our
1479 // direct channel to the candidate set.
1481 // Note that we *must* check if the last hop was added as `add_entry`
1482 // always assumes that the third argument is a node to which we have a
1484 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&hop.src_node_id)) {
1485 for details in first_channels {
1486 let candidate = CandidateRouteHop::FirstHop { details };
1487 add_entry!(candidate, our_node_id,
1488 NodeId::from_pubkey(&hop.src_node_id),
1489 aggregate_next_hops_fee_msat, path_value_msat,
1490 aggregate_next_hops_path_htlc_minimum_msat,
1491 aggregate_next_hops_path_penalty_msat,
1492 aggregate_next_hops_cltv_delta,
1493 aggregate_next_hops_path_length);
1501 log_trace!(logger, "Starting main path collection loop with {} nodes pre-filled from first/last hops.", targets.len());
1503 // At this point, targets are filled with the data from first and
1504 // last hops communicated by the caller, and the payment receiver.
1505 let mut found_new_path = false;
1508 // If this loop terminates due the exhaustion of targets, two situations are possible:
1509 // - not enough outgoing liquidity:
1510 // 0 < already_collected_value_msat < final_value_msat
1511 // - enough outgoing liquidity:
1512 // final_value_msat <= already_collected_value_msat < recommended_value_msat
1513 // Both these cases (and other cases except reaching recommended_value_msat) mean that
1514 // paths_collection will be stopped because found_new_path==false.
1515 // This is not necessarily a routing failure.
1516 '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() {
1518 // Since we're going payee-to-payer, hitting our node as a target means we should stop
1519 // traversing the graph and arrange the path out of what we found.
1520 if node_id == our_node_id {
1521 let mut new_entry = dist.remove(&our_node_id).unwrap();
1522 let mut ordered_hops: Vec<(PathBuildingHop, NodeFeatures)> = vec!((new_entry.clone(), default_node_features.clone()));
1525 let mut features_set = false;
1526 if let Some(first_channels) = first_hop_targets.get(&ordered_hops.last().unwrap().0.node_id) {
1527 for details in first_channels {
1528 if details.get_outbound_payment_scid().unwrap() == ordered_hops.last().unwrap().0.candidate.short_channel_id() {
1529 ordered_hops.last_mut().unwrap().1 = details.counterparty.features.to_context();
1530 features_set = true;
1536 if let Some(node) = network_nodes.get(&ordered_hops.last().unwrap().0.node_id) {
1537 if let Some(node_info) = node.announcement_info.as_ref() {
1538 ordered_hops.last_mut().unwrap().1 = node_info.features.clone();
1540 ordered_hops.last_mut().unwrap().1 = default_node_features.clone();
1543 // We can fill in features for everything except hops which were
1544 // provided via the invoice we're paying. We could guess based on the
1545 // recipient's features but for now we simply avoid guessing at all.
1549 // Means we succesfully traversed from the payer to the payee, now
1550 // save this path for the payment route. Also, update the liquidity
1551 // remaining on the used hops, so that we take them into account
1552 // while looking for more paths.
1553 if ordered_hops.last().unwrap().0.node_id == payee_node_id {
1557 new_entry = match dist.remove(&ordered_hops.last().unwrap().0.node_id) {
1558 Some(payment_hop) => payment_hop,
1559 // We can't arrive at None because, if we ever add an entry to targets,
1560 // we also fill in the entry in dist (see add_entry!).
1561 None => unreachable!(),
1563 // We "propagate" the fees one hop backward (topologically) here,
1564 // so that fees paid for a HTLC forwarding on the current channel are
1565 // associated with the previous channel (where they will be subtracted).
1566 ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
1567 ordered_hops.push((new_entry.clone(), default_node_features.clone()));
1569 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
1570 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
1572 log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: \n {:#?}",
1573 ordered_hops.len(), value_contribution_msat, ordered_hops.iter().map(|h| &(h.0)).collect::<Vec<&PathBuildingHop>>());
1575 let mut payment_path = PaymentPath {hops: ordered_hops};
1577 // We could have possibly constructed a slightly inconsistent path: since we reduce
1578 // value being transferred along the way, we could have violated htlc_minimum_msat
1579 // on some channels we already passed (assuming dest->source direction). Here, we
1580 // recompute the fees again, so that if that's the case, we match the currently
1581 // underpaid htlc_minimum_msat with fees.
1582 debug_assert_eq!(payment_path.get_value_msat(), value_contribution_msat);
1583 value_contribution_msat = cmp::min(value_contribution_msat, final_value_msat);
1584 payment_path.update_value_and_recompute_fees(value_contribution_msat);
1586 // Since a path allows to transfer as much value as
1587 // the smallest channel it has ("bottleneck"), we should recompute
1588 // the fees so sender HTLC don't overpay fees when traversing
1589 // larger channels than the bottleneck. This may happen because
1590 // when we were selecting those channels we were not aware how much value
1591 // this path will transfer, and the relative fee for them
1592 // might have been computed considering a larger value.
1593 // Remember that we used these channels so that we don't rely
1594 // on the same liquidity in future paths.
1595 let mut prevented_redundant_path_selection = false;
1596 let prev_hop_iter = core::iter::once(&our_node_id)
1597 .chain(payment_path.hops.iter().map(|(hop, _)| &hop.node_id));
1598 for (prev_hop, (hop, _)) in prev_hop_iter.zip(payment_path.hops.iter()) {
1599 let spent_on_hop_msat = value_contribution_msat + hop.next_hops_fee_msat;
1600 let used_liquidity_msat = used_channel_liquidities
1601 .entry((hop.candidate.short_channel_id(), *prev_hop < hop.node_id))
1602 .and_modify(|used_liquidity_msat| *used_liquidity_msat += spent_on_hop_msat)
1603 .or_insert(spent_on_hop_msat);
1604 let hop_capacity = hop.candidate.effective_capacity();
1605 let hop_max_msat = max_htlc_from_capacity(hop_capacity, channel_saturation_pow_half);
1606 if *used_liquidity_msat == hop_max_msat {
1607 // If this path used all of this channel's available liquidity, we know
1608 // this path will not be selected again in the next loop iteration.
1609 prevented_redundant_path_selection = true;
1611 debug_assert!(*used_liquidity_msat <= hop_max_msat);
1613 if !prevented_redundant_path_selection {
1614 // If we weren't capped by hitting a liquidity limit on a channel in the path,
1615 // we'll probably end up picking the same path again on the next iteration.
1616 // Decrease the available liquidity of a hop in the middle of the path.
1617 let victim_scid = payment_path.hops[(payment_path.hops.len()) / 2].0.candidate.short_channel_id();
1618 let exhausted = u64::max_value();
1619 log_trace!(logger, "Disabling channel {} for future path building iterations to avoid duplicates.", victim_scid);
1620 *used_channel_liquidities.entry((victim_scid, false)).or_default() = exhausted;
1621 *used_channel_liquidities.entry((victim_scid, true)).or_default() = exhausted;
1624 // Track the total amount all our collected paths allow to send so that we know
1625 // when to stop looking for more paths
1626 already_collected_value_msat += value_contribution_msat;
1628 payment_paths.push(payment_path);
1629 found_new_path = true;
1630 break 'path_construction;
1633 // If we found a path back to the payee, we shouldn't try to process it again. This is
1634 // the equivalent of the `elem.was_processed` check in
1635 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
1636 if node_id == payee_node_id { continue 'path_construction; }
1638 // Otherwise, since the current target node is not us,
1639 // keep "unrolling" the payment graph from payee to payer by
1640 // finding a way to reach the current target from the payer side.
1641 match network_nodes.get(&node_id) {
1644 add_entries_to_cheapest_to_target_node!(node, node_id, lowest_fee_to_node,
1645 value_contribution_msat, path_htlc_minimum_msat, path_penalty_msat,
1646 total_cltv_delta, path_length_to_node);
1652 if !found_new_path && channel_saturation_pow_half != 0 {
1653 channel_saturation_pow_half = 0;
1654 continue 'paths_collection;
1656 // If we don't support MPP, no use trying to gather more value ever.
1657 break 'paths_collection;
1661 // Stop either when the recommended value is reached or if no new path was found in this
1663 // In the latter case, making another path finding attempt won't help,
1664 // because we deterministically terminated the search due to low liquidity.
1665 if !found_new_path && channel_saturation_pow_half != 0 {
1666 channel_saturation_pow_half = 0;
1667 } else if already_collected_value_msat >= recommended_value_msat || !found_new_path {
1668 log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
1669 already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
1670 break 'paths_collection;
1671 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
1672 // Further, if this was our first walk of the graph, and we weren't limited by an
1673 // htlc_minimum_msat, return immediately because this path should suffice. If we were
1674 // limited by an htlc_minimum_msat value, find another path with a higher value,
1675 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
1676 // still keeping a lower total fee than this path.
1677 if !hit_minimum_limit {
1678 log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
1679 break 'paths_collection;
1681 log_trace!(logger, "Collected our payment amount on the first pass, but running again to collect extra paths with a potentially higher limit.");
1682 path_value_msat = recommended_value_msat;
1687 if payment_paths.len() == 0 {
1688 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1691 if already_collected_value_msat < final_value_msat {
1692 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1696 let mut selected_route = payment_paths;
1698 debug_assert_eq!(selected_route.iter().map(|p| p.get_value_msat()).sum::<u64>(), already_collected_value_msat);
1699 let mut overpaid_value_msat = already_collected_value_msat - final_value_msat;
1701 // First, sort by the cost-per-value of the path, dropping the paths that cost the most for
1702 // the value they contribute towards the payment amount.
1703 // We sort in descending order as we will remove from the front in `retain`, next.
1704 selected_route.sort_unstable_by(|a, b|
1705 (((b.get_cost_msat() as u128) << 64) / (b.get_value_msat() as u128))
1706 .cmp(&(((a.get_cost_msat() as u128) << 64) / (a.get_value_msat() as u128)))
1709 // We should make sure that at least 1 path left.
1710 let mut paths_left = selected_route.len();
1711 selected_route.retain(|path| {
1712 if paths_left == 1 {
1715 let path_value_msat = path.get_value_msat();
1716 if path_value_msat <= overpaid_value_msat {
1717 overpaid_value_msat -= path_value_msat;
1723 debug_assert!(selected_route.len() > 0);
1725 if overpaid_value_msat != 0 {
1727 // Now, subtract the remaining overpaid value from the most-expensive path.
1728 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1729 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1730 selected_route.sort_unstable_by(|a, b| {
1731 let a_f = a.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
1732 let b_f = b.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
1733 a_f.cmp(&b_f).then_with(|| b.get_cost_msat().cmp(&a.get_cost_msat()))
1735 let expensive_payment_path = selected_route.first_mut().unwrap();
1737 // We already dropped all the paths with value below `overpaid_value_msat` above, thus this
1738 // can't go negative.
1739 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
1740 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
1744 // Sort by the path itself and combine redundant paths.
1745 // Note that we sort by SCIDs alone as its simpler but when combining we have to ensure we
1746 // compare both SCIDs and NodeIds as individual nodes may use random aliases causing collisions
1748 selected_route.sort_unstable_by_key(|path| {
1749 let mut key = [0u64; MAX_PATH_LENGTH_ESTIMATE as usize];
1750 debug_assert!(path.hops.len() <= key.len());
1751 for (scid, key) in path.hops.iter().map(|h| h.0.candidate.short_channel_id()).zip(key.iter_mut()) {
1756 for idx in 0..(selected_route.len() - 1) {
1757 if idx + 1 >= selected_route.len() { break; }
1758 if iter_equal(selected_route[idx ].hops.iter().map(|h| (h.0.candidate.short_channel_id(), h.0.node_id)),
1759 selected_route[idx + 1].hops.iter().map(|h| (h.0.candidate.short_channel_id(), h.0.node_id))) {
1760 let new_value = selected_route[idx].get_value_msat() + selected_route[idx + 1].get_value_msat();
1761 selected_route[idx].update_value_and_recompute_fees(new_value);
1762 selected_route.remove(idx + 1);
1766 let mut selected_paths = Vec::<Vec<Result<RouteHop, LightningError>>>::new();
1767 for payment_path in selected_route {
1768 let mut path = payment_path.hops.iter().map(|(payment_hop, node_features)| {
1770 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)})?,
1771 node_features: node_features.clone(),
1772 short_channel_id: payment_hop.candidate.short_channel_id(),
1773 channel_features: payment_hop.candidate.features(),
1774 fee_msat: payment_hop.fee_msat,
1775 cltv_expiry_delta: payment_hop.candidate.cltv_expiry_delta(),
1777 }).collect::<Vec<_>>();
1778 // Propagate the cltv_expiry_delta one hop backwards since the delta from the current hop is
1779 // applicable for the previous hop.
1780 path.iter_mut().rev().fold(final_cltv_expiry_delta, |prev_cltv_expiry_delta, hop| {
1781 core::mem::replace(&mut hop.as_mut().unwrap().cltv_expiry_delta, prev_cltv_expiry_delta)
1783 selected_paths.push(path);
1785 // Make sure we would never create a route with more paths than we allow.
1786 debug_assert!(selected_paths.len() <= payment_params.max_path_count.into());
1788 if let Some(features) = &payment_params.features {
1789 for path in selected_paths.iter_mut() {
1790 if let Ok(route_hop) = path.last_mut().unwrap() {
1791 route_hop.node_features = features.to_context();
1797 paths: selected_paths.into_iter().map(|path| path.into_iter().collect()).collect::<Result<Vec<_>, _>>()?,
1798 payment_params: Some(payment_params.clone()),
1800 log_info!(logger, "Got route to {}: {}", payment_params.payee_pubkey, log_route!(route));
1804 // When an adversarial intermediary node observes a payment, it may be able to infer its
1805 // destination, if the remaining CLTV expiry delta exactly matches a feasible path in the network
1806 // graph. In order to improve privacy, this method obfuscates the CLTV expiry deltas along the
1807 // payment path by adding a randomized 'shadow route' offset to the final hop.
1808 fn add_random_cltv_offset(route: &mut Route, payment_params: &PaymentParameters,
1809 network_graph: &ReadOnlyNetworkGraph, random_seed_bytes: &[u8; 32]
1811 let network_channels = network_graph.channels();
1812 let network_nodes = network_graph.nodes();
1814 for path in route.paths.iter_mut() {
1815 let mut shadow_ctlv_expiry_delta_offset: u32 = 0;
1817 // Remember the last three nodes of the random walk and avoid looping back on them.
1818 // Init with the last three nodes from the actual path, if possible.
1819 let mut nodes_to_avoid: [NodeId; 3] = [NodeId::from_pubkey(&path.last().unwrap().pubkey),
1820 NodeId::from_pubkey(&path.get(path.len().saturating_sub(2)).unwrap().pubkey),
1821 NodeId::from_pubkey(&path.get(path.len().saturating_sub(3)).unwrap().pubkey)];
1823 // Choose the last publicly known node as the starting point for the random walk.
1824 let mut cur_hop: Option<NodeId> = None;
1825 let mut path_nonce = [0u8; 12];
1826 if let Some(starting_hop) = path.iter().rev()
1827 .find(|h| network_nodes.contains_key(&NodeId::from_pubkey(&h.pubkey))) {
1828 cur_hop = Some(NodeId::from_pubkey(&starting_hop.pubkey));
1829 path_nonce.copy_from_slice(&cur_hop.unwrap().as_slice()[..12]);
1832 // Init PRNG with the path-dependant nonce, which is static for private paths.
1833 let mut prng = ChaCha20::new(random_seed_bytes, &path_nonce);
1834 let mut random_path_bytes = [0u8; ::core::mem::size_of::<usize>()];
1836 // Pick a random path length in [1 .. 3]
1837 prng.process_in_place(&mut random_path_bytes);
1838 let random_walk_length = usize::from_be_bytes(random_path_bytes).wrapping_rem(3).wrapping_add(1);
1840 for random_hop in 0..random_walk_length {
1841 // If we don't find a suitable offset in the public network graph, we default to
1842 // MEDIAN_HOP_CLTV_EXPIRY_DELTA.
1843 let mut random_hop_offset = MEDIAN_HOP_CLTV_EXPIRY_DELTA;
1845 if let Some(cur_node_id) = cur_hop {
1846 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
1847 // Randomly choose the next unvisited hop.
1848 prng.process_in_place(&mut random_path_bytes);
1849 if let Some(random_channel) = usize::from_be_bytes(random_path_bytes)
1850 .checked_rem(cur_node.channels.len())
1851 .and_then(|index| cur_node.channels.get(index))
1852 .and_then(|id| network_channels.get(id)) {
1853 random_channel.as_directed_from(&cur_node_id).map(|(dir_info, next_id)| {
1854 if !nodes_to_avoid.iter().any(|x| x == next_id) {
1855 nodes_to_avoid[random_hop] = *next_id;
1856 random_hop_offset = dir_info.direction().cltv_expiry_delta.into();
1857 cur_hop = Some(*next_id);
1864 shadow_ctlv_expiry_delta_offset = shadow_ctlv_expiry_delta_offset
1865 .checked_add(random_hop_offset)
1866 .unwrap_or(shadow_ctlv_expiry_delta_offset);
1869 // Limit the total offset to reduce the worst-case locked liquidity timevalue
1870 const MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET: u32 = 3*144;
1871 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET);
1873 // Limit the offset so we never exceed the max_total_cltv_expiry_delta. To improve plausibility,
1874 // we choose the limit to be the largest possible multiple of MEDIAN_HOP_CLTV_EXPIRY_DELTA.
1875 let path_total_cltv_expiry_delta: u32 = path.iter().map(|h| h.cltv_expiry_delta).sum();
1876 let mut max_path_offset = payment_params.max_total_cltv_expiry_delta - path_total_cltv_expiry_delta;
1877 max_path_offset = cmp::max(
1878 max_path_offset - (max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA),
1879 max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA);
1880 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, max_path_offset);
1882 // Add 'shadow' CLTV offset to the final hop
1883 if let Some(last_hop) = path.last_mut() {
1884 last_hop.cltv_expiry_delta = last_hop.cltv_expiry_delta
1885 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(last_hop.cltv_expiry_delta);
1890 /// Construct a route from us (payer) to the target node (payee) via the given hops (which should
1891 /// exclude the payer, but include the payee). This may be useful, e.g., for probing the chosen path.
1893 /// Re-uses logic from `find_route`, so the restrictions described there also apply here.
1894 pub fn build_route_from_hops<L: Deref, GL: Deref>(
1895 our_node_pubkey: &PublicKey, hops: &[PublicKey], route_params: &RouteParameters,
1896 network_graph: &NetworkGraph<GL>, logger: L, random_seed_bytes: &[u8; 32]
1897 ) -> Result<Route, LightningError>
1898 where L::Target: Logger, GL::Target: Logger {
1899 let graph_lock = network_graph.read_only();
1900 let mut route = build_route_from_hops_internal(
1901 our_node_pubkey, hops, &route_params.payment_params, &graph_lock,
1902 route_params.final_value_msat, route_params.final_cltv_expiry_delta, logger, random_seed_bytes)?;
1903 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
1907 fn build_route_from_hops_internal<L: Deref>(
1908 our_node_pubkey: &PublicKey, hops: &[PublicKey], payment_params: &PaymentParameters,
1909 network_graph: &ReadOnlyNetworkGraph, final_value_msat: u64, final_cltv_expiry_delta: u32,
1910 logger: L, random_seed_bytes: &[u8; 32]
1911 ) -> Result<Route, LightningError> where L::Target: Logger {
1914 our_node_id: NodeId,
1915 hop_ids: [Option<NodeId>; MAX_PATH_LENGTH_ESTIMATE as usize],
1918 impl Score for HopScorer {
1919 fn channel_penalty_msat(&self, _short_channel_id: u64, source: &NodeId, target: &NodeId,
1920 _usage: ChannelUsage) -> u64
1922 let mut cur_id = self.our_node_id;
1923 for i in 0..self.hop_ids.len() {
1924 if let Some(next_id) = self.hop_ids[i] {
1925 if cur_id == *source && next_id == *target {
1936 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
1938 fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
1940 fn probe_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
1942 fn probe_successful(&mut self, _path: &[&RouteHop]) {}
1945 impl<'a> Writeable for HopScorer {
1947 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), io::Error> {
1952 if hops.len() > MAX_PATH_LENGTH_ESTIMATE.into() {
1953 return Err(LightningError{err: "Cannot build a route exceeding the maximum path length.".to_owned(), action: ErrorAction::IgnoreError});
1956 let our_node_id = NodeId::from_pubkey(our_node_pubkey);
1957 let mut hop_ids = [None; MAX_PATH_LENGTH_ESTIMATE as usize];
1958 for i in 0..hops.len() {
1959 hop_ids[i] = Some(NodeId::from_pubkey(&hops[i]));
1962 let scorer = HopScorer { our_node_id, hop_ids };
1964 get_route(our_node_pubkey, payment_params, network_graph, None, final_value_msat,
1965 final_cltv_expiry_delta, logger, &scorer, random_seed_bytes)
1970 use crate::routing::gossip::{NetworkGraph, P2PGossipSync, NodeId, EffectiveCapacity};
1971 use crate::routing::router::{get_route, build_route_from_hops_internal, add_random_cltv_offset, default_node_features,
1972 PaymentParameters, Route, RouteHint, RouteHintHop, RouteHop, RoutingFees,
1973 DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA, MAX_PATH_LENGTH_ESTIMATE};
1974 use crate::routing::scoring::{ChannelUsage, Score, ProbabilisticScorer, ProbabilisticScoringParameters};
1975 use crate::routing::test_utils::{add_channel, add_or_update_node, build_graph, build_line_graph, id_to_feature_flags, get_nodes, update_channel};
1976 use crate::chain::transaction::OutPoint;
1977 use crate::chain::keysinterface::KeysInterface;
1978 use crate::ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
1979 use crate::ln::msgs::{ErrorAction, LightningError, UnsignedChannelUpdate, MAX_VALUE_MSAT};
1980 use crate::ln::channelmanager;
1981 use crate::util::test_utils as ln_test_utils;
1982 use crate::util::chacha20::ChaCha20;
1984 use crate::util::ser::{Writeable, Writer};
1986 use bitcoin::hashes::Hash;
1987 use bitcoin::network::constants::Network;
1988 use bitcoin::blockdata::constants::genesis_block;
1989 use bitcoin::blockdata::script::Builder;
1990 use bitcoin::blockdata::opcodes;
1991 use bitcoin::blockdata::transaction::TxOut;
1995 use bitcoin::secp256k1::{PublicKey,SecretKey};
1996 use bitcoin::secp256k1::Secp256k1;
1998 use crate::prelude::*;
1999 use crate::sync::Arc;
2001 use core::convert::TryInto;
2003 fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
2004 features: InitFeatures, outbound_capacity_msat: u64) -> channelmanager::ChannelDetails {
2005 channelmanager::ChannelDetails {
2006 channel_id: [0; 32],
2007 counterparty: channelmanager::ChannelCounterparty {
2010 unspendable_punishment_reserve: 0,
2011 forwarding_info: None,
2012 outbound_htlc_minimum_msat: None,
2013 outbound_htlc_maximum_msat: None,
2015 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
2018 outbound_scid_alias: None,
2019 inbound_scid_alias: None,
2020 channel_value_satoshis: 0,
2023 outbound_capacity_msat,
2024 next_outbound_htlc_limit_msat: outbound_capacity_msat,
2025 inbound_capacity_msat: 42,
2026 unspendable_punishment_reserve: None,
2027 confirmations_required: None,
2028 force_close_spend_delay: None,
2029 is_outbound: true, is_channel_ready: true,
2030 is_usable: true, is_public: true,
2031 inbound_htlc_minimum_msat: None,
2032 inbound_htlc_maximum_msat: None,
2038 fn simple_route_test() {
2039 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2040 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2041 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2042 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2043 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2044 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2046 // Simple route to 2 via 1
2048 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) {
2049 assert_eq!(err, "Cannot send a payment of 0 msat");
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);
2055 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2056 assert_eq!(route.paths[0][0].short_channel_id, 2);
2057 assert_eq!(route.paths[0][0].fee_msat, 100);
2058 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2059 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2060 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2062 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2063 assert_eq!(route.paths[0][1].short_channel_id, 4);
2064 assert_eq!(route.paths[0][1].fee_msat, 100);
2065 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2066 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2067 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2071 fn invalid_first_hop_test() {
2072 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2073 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2074 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2075 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2076 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2077 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2079 // Simple route to 2 via 1
2081 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
2083 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) =
2084 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) {
2085 assert_eq!(err, "First hop cannot have our_node_pubkey as a destination.");
2086 } else { panic!(); }
2088 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2089 assert_eq!(route.paths[0].len(), 2);
2093 fn htlc_minimum_test() {
2094 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2095 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2096 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2097 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2098 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2099 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2101 // Simple route to 2 via 1
2103 // Disable other paths
2104 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2105 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2106 short_channel_id: 12,
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[0], UnsignedChannelUpdate {
2117 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2118 short_channel_id: 3,
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()
2128 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2129 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2130 short_channel_id: 13,
2132 flags: 2, // to disable
2133 cltv_expiry_delta: 0,
2134 htlc_minimum_msat: 0,
2135 htlc_maximum_msat: MAX_VALUE_MSAT,
2137 fee_proportional_millionths: 0,
2138 excess_data: Vec::new()
2140 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2141 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2142 short_channel_id: 6,
2144 flags: 2, // to disable
2145 cltv_expiry_delta: 0,
2146 htlc_minimum_msat: 0,
2147 htlc_maximum_msat: MAX_VALUE_MSAT,
2149 fee_proportional_millionths: 0,
2150 excess_data: Vec::new()
2152 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2153 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2154 short_channel_id: 7,
2156 flags: 2, // to disable
2157 cltv_expiry_delta: 0,
2158 htlc_minimum_msat: 0,
2159 htlc_maximum_msat: MAX_VALUE_MSAT,
2161 fee_proportional_millionths: 0,
2162 excess_data: Vec::new()
2165 // Check against amount_to_transfer_over_msat.
2166 // Set minimal HTLC of 200_000_000 msat.
2167 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2168 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2169 short_channel_id: 2,
2172 cltv_expiry_delta: 0,
2173 htlc_minimum_msat: 200_000_000,
2174 htlc_maximum_msat: MAX_VALUE_MSAT,
2176 fee_proportional_millionths: 0,
2177 excess_data: Vec::new()
2180 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
2182 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2183 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2184 short_channel_id: 4,
2187 cltv_expiry_delta: 0,
2188 htlc_minimum_msat: 0,
2189 htlc_maximum_msat: 199_999_999,
2191 fee_proportional_millionths: 0,
2192 excess_data: Vec::new()
2195 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
2196 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) {
2197 assert_eq!(err, "Failed to find a path to the given destination");
2198 } else { panic!(); }
2200 // Lift the restriction on the first hop.
2201 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2202 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2203 short_channel_id: 2,
2206 cltv_expiry_delta: 0,
2207 htlc_minimum_msat: 0,
2208 htlc_maximum_msat: MAX_VALUE_MSAT,
2210 fee_proportional_millionths: 0,
2211 excess_data: Vec::new()
2214 // A payment above the minimum should pass
2215 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();
2216 assert_eq!(route.paths[0].len(), 2);
2220 fn htlc_minimum_overpay_test() {
2221 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2222 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2223 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(channelmanager::provided_invoice_features());
2224 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2225 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2226 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2228 // A route to node#2 via two paths.
2229 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
2230 // Thus, they can't send 60 without overpaying.
2231 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2232 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2233 short_channel_id: 2,
2236 cltv_expiry_delta: 0,
2237 htlc_minimum_msat: 35_000,
2238 htlc_maximum_msat: 40_000,
2240 fee_proportional_millionths: 0,
2241 excess_data: Vec::new()
2243 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2244 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2245 short_channel_id: 12,
2248 cltv_expiry_delta: 0,
2249 htlc_minimum_msat: 35_000,
2250 htlc_maximum_msat: 40_000,
2252 fee_proportional_millionths: 0,
2253 excess_data: Vec::new()
2257 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2258 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2259 short_channel_id: 13,
2262 cltv_expiry_delta: 0,
2263 htlc_minimum_msat: 0,
2264 htlc_maximum_msat: MAX_VALUE_MSAT,
2266 fee_proportional_millionths: 0,
2267 excess_data: Vec::new()
2269 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2270 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2271 short_channel_id: 4,
2274 cltv_expiry_delta: 0,
2275 htlc_minimum_msat: 0,
2276 htlc_maximum_msat: MAX_VALUE_MSAT,
2278 fee_proportional_millionths: 0,
2279 excess_data: Vec::new()
2282 // Disable other paths
2283 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2284 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2285 short_channel_id: 1,
2287 flags: 2, // to disable
2288 cltv_expiry_delta: 0,
2289 htlc_minimum_msat: 0,
2290 htlc_maximum_msat: MAX_VALUE_MSAT,
2292 fee_proportional_millionths: 0,
2293 excess_data: Vec::new()
2296 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 60_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2297 // Overpay fees to hit htlc_minimum_msat.
2298 let overpaid_fees = route.paths[0][0].fee_msat + route.paths[1][0].fee_msat;
2299 // TODO: this could be better balanced to overpay 10k and not 15k.
2300 assert_eq!(overpaid_fees, 15_000);
2302 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
2303 // while taking even more fee to match htlc_minimum_msat.
2304 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2305 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2306 short_channel_id: 12,
2309 cltv_expiry_delta: 0,
2310 htlc_minimum_msat: 65_000,
2311 htlc_maximum_msat: 80_000,
2313 fee_proportional_millionths: 0,
2314 excess_data: Vec::new()
2316 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2317 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2318 short_channel_id: 2,
2321 cltv_expiry_delta: 0,
2322 htlc_minimum_msat: 0,
2323 htlc_maximum_msat: MAX_VALUE_MSAT,
2325 fee_proportional_millionths: 0,
2326 excess_data: Vec::new()
2328 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2329 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2330 short_channel_id: 4,
2333 cltv_expiry_delta: 0,
2334 htlc_minimum_msat: 0,
2335 htlc_maximum_msat: MAX_VALUE_MSAT,
2337 fee_proportional_millionths: 100_000,
2338 excess_data: Vec::new()
2341 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 60_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2342 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
2343 assert_eq!(route.paths.len(), 1);
2344 assert_eq!(route.paths[0][0].short_channel_id, 12);
2345 let fees = route.paths[0][0].fee_msat;
2346 assert_eq!(fees, 5_000);
2348 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2349 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
2350 // the other channel.
2351 assert_eq!(route.paths.len(), 1);
2352 assert_eq!(route.paths[0][0].short_channel_id, 2);
2353 let fees = route.paths[0][0].fee_msat;
2354 assert_eq!(fees, 5_000);
2358 fn disable_channels_test() {
2359 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2360 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2361 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2362 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2363 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2364 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2366 // // Disable channels 4 and 12 by flags=2
2367 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2368 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2369 short_channel_id: 4,
2371 flags: 2, // to disable
2372 cltv_expiry_delta: 0,
2373 htlc_minimum_msat: 0,
2374 htlc_maximum_msat: MAX_VALUE_MSAT,
2376 fee_proportional_millionths: 0,
2377 excess_data: Vec::new()
2379 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2380 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2381 short_channel_id: 12,
2383 flags: 2, // to disable
2384 cltv_expiry_delta: 0,
2385 htlc_minimum_msat: 0,
2386 htlc_maximum_msat: MAX_VALUE_MSAT,
2388 fee_proportional_millionths: 0,
2389 excess_data: Vec::new()
2392 // If all the channels require some features we don't understand, route should fail
2393 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) {
2394 assert_eq!(err, "Failed to find a path to the given destination");
2395 } else { panic!(); }
2397 // If we specify a channel to node7, that overrides our local channel view and that gets used
2398 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2399 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();
2400 assert_eq!(route.paths[0].len(), 2);
2402 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2403 assert_eq!(route.paths[0][0].short_channel_id, 42);
2404 assert_eq!(route.paths[0][0].fee_msat, 200);
2405 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2406 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2407 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2409 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2410 assert_eq!(route.paths[0][1].short_channel_id, 13);
2411 assert_eq!(route.paths[0][1].fee_msat, 100);
2412 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2413 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2414 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2418 fn disable_node_test() {
2419 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2420 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2421 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2422 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2423 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2424 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2426 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
2427 let mut unknown_features = NodeFeatures::empty();
2428 unknown_features.set_unknown_feature_required();
2429 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
2430 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
2431 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
2433 // If all nodes require some features we don't understand, route should fail
2434 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
2435 assert_eq!(err, "Failed to find a path to the given destination");
2436 } else { panic!(); }
2438 // If we specify a channel to node7, that overrides our local channel view and that gets used
2439 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2440 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&our_chans.iter().collect::<Vec<_>>()), 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2441 assert_eq!(route.paths[0].len(), 2);
2443 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2444 assert_eq!(route.paths[0][0].short_channel_id, 42);
2445 assert_eq!(route.paths[0][0].fee_msat, 200);
2446 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2447 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2448 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2450 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2451 assert_eq!(route.paths[0][1].short_channel_id, 13);
2452 assert_eq!(route.paths[0][1].fee_msat, 100);
2453 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2454 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2455 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2457 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
2458 // naively) assume that the user checked the feature bits on the invoice, which override
2459 // the node_announcement.
2463 fn our_chans_test() {
2464 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2465 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2466 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2467 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2468 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2470 // Route to 1 via 2 and 3 because our channel to 1 is disabled
2471 let payment_params = PaymentParameters::from_node_id(nodes[0]);
2472 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2473 assert_eq!(route.paths[0].len(), 3);
2475 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2476 assert_eq!(route.paths[0][0].short_channel_id, 2);
2477 assert_eq!(route.paths[0][0].fee_msat, 200);
2478 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2479 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2480 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2482 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2483 assert_eq!(route.paths[0][1].short_channel_id, 4);
2484 assert_eq!(route.paths[0][1].fee_msat, 100);
2485 assert_eq!(route.paths[0][1].cltv_expiry_delta, (3 << 4) | 2);
2486 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2487 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2489 assert_eq!(route.paths[0][2].pubkey, nodes[0]);
2490 assert_eq!(route.paths[0][2].short_channel_id, 3);
2491 assert_eq!(route.paths[0][2].fee_msat, 100);
2492 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
2493 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(1));
2494 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(3));
2496 // If we specify a channel to node7, that overrides our local channel view and that gets used
2497 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2498 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2499 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();
2500 assert_eq!(route.paths[0].len(), 2);
2502 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2503 assert_eq!(route.paths[0][0].short_channel_id, 42);
2504 assert_eq!(route.paths[0][0].fee_msat, 200);
2505 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2506 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2507 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2509 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2510 assert_eq!(route.paths[0][1].short_channel_id, 13);
2511 assert_eq!(route.paths[0][1].fee_msat, 100);
2512 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2513 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2514 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2517 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2518 let zero_fees = RoutingFees {
2520 proportional_millionths: 0,
2522 vec![RouteHint(vec![RouteHintHop {
2523 src_node_id: nodes[3],
2524 short_channel_id: 8,
2526 cltv_expiry_delta: (8 << 4) | 1,
2527 htlc_minimum_msat: None,
2528 htlc_maximum_msat: None,
2530 ]), RouteHint(vec![RouteHintHop {
2531 src_node_id: nodes[4],
2532 short_channel_id: 9,
2535 proportional_millionths: 0,
2537 cltv_expiry_delta: (9 << 4) | 1,
2538 htlc_minimum_msat: None,
2539 htlc_maximum_msat: None,
2540 }]), RouteHint(vec![RouteHintHop {
2541 src_node_id: nodes[5],
2542 short_channel_id: 10,
2544 cltv_expiry_delta: (10 << 4) | 1,
2545 htlc_minimum_msat: None,
2546 htlc_maximum_msat: None,
2550 fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2551 let zero_fees = RoutingFees {
2553 proportional_millionths: 0,
2555 vec![RouteHint(vec![RouteHintHop {
2556 src_node_id: nodes[2],
2557 short_channel_id: 5,
2560 proportional_millionths: 0,
2562 cltv_expiry_delta: (5 << 4) | 1,
2563 htlc_minimum_msat: None,
2564 htlc_maximum_msat: None,
2566 src_node_id: nodes[3],
2567 short_channel_id: 8,
2569 cltv_expiry_delta: (8 << 4) | 1,
2570 htlc_minimum_msat: None,
2571 htlc_maximum_msat: None,
2573 ]), RouteHint(vec![RouteHintHop {
2574 src_node_id: nodes[4],
2575 short_channel_id: 9,
2578 proportional_millionths: 0,
2580 cltv_expiry_delta: (9 << 4) | 1,
2581 htlc_minimum_msat: None,
2582 htlc_maximum_msat: None,
2583 }]), RouteHint(vec![RouteHintHop {
2584 src_node_id: nodes[5],
2585 short_channel_id: 10,
2587 cltv_expiry_delta: (10 << 4) | 1,
2588 htlc_minimum_msat: None,
2589 htlc_maximum_msat: None,
2594 fn partial_route_hint_test() {
2595 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2596 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2597 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2598 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2599 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2601 // Simple test across 2, 3, 5, and 4 via a last_hop channel
2602 // Tests the behaviour when the RouteHint contains a suboptimal hop.
2603 // RouteHint may be partially used by the algo to build the best path.
2605 // First check that last hop can't have its source as the payee.
2606 let invalid_last_hop = RouteHint(vec![RouteHintHop {
2607 src_node_id: nodes[6],
2608 short_channel_id: 8,
2611 proportional_millionths: 0,
2613 cltv_expiry_delta: (8 << 4) | 1,
2614 htlc_minimum_msat: None,
2615 htlc_maximum_msat: None,
2618 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
2619 invalid_last_hops.push(invalid_last_hop);
2621 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(invalid_last_hops);
2622 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) {
2623 assert_eq!(err, "Route hint cannot have the payee as the source.");
2624 } else { panic!(); }
2627 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops_multi_private_channels(&nodes));
2628 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2629 assert_eq!(route.paths[0].len(), 5);
2631 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2632 assert_eq!(route.paths[0][0].short_channel_id, 2);
2633 assert_eq!(route.paths[0][0].fee_msat, 100);
2634 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2635 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2636 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2638 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2639 assert_eq!(route.paths[0][1].short_channel_id, 4);
2640 assert_eq!(route.paths[0][1].fee_msat, 0);
2641 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
2642 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2643 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2645 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2646 assert_eq!(route.paths[0][2].short_channel_id, 6);
2647 assert_eq!(route.paths[0][2].fee_msat, 0);
2648 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
2649 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2650 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2652 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2653 assert_eq!(route.paths[0][3].short_channel_id, 11);
2654 assert_eq!(route.paths[0][3].fee_msat, 0);
2655 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
2656 // If we have a peer in the node map, we'll use their features here since we don't have
2657 // a way of figuring out their features from the invoice:
2658 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2659 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2661 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2662 assert_eq!(route.paths[0][4].short_channel_id, 8);
2663 assert_eq!(route.paths[0][4].fee_msat, 100);
2664 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2665 assert_eq!(route.paths[0][4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
2666 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2669 fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2670 let zero_fees = RoutingFees {
2672 proportional_millionths: 0,
2674 vec![RouteHint(vec![RouteHintHop {
2675 src_node_id: nodes[3],
2676 short_channel_id: 8,
2678 cltv_expiry_delta: (8 << 4) | 1,
2679 htlc_minimum_msat: None,
2680 htlc_maximum_msat: None,
2681 }]), RouteHint(vec![
2683 ]), RouteHint(vec![RouteHintHop {
2684 src_node_id: nodes[5],
2685 short_channel_id: 10,
2687 cltv_expiry_delta: (10 << 4) | 1,
2688 htlc_minimum_msat: None,
2689 htlc_maximum_msat: None,
2694 fn ignores_empty_last_hops_test() {
2695 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2696 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2697 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(empty_last_hop(&nodes));
2698 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2699 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2700 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2702 // Test handling of an empty RouteHint passed in Invoice.
2704 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2705 assert_eq!(route.paths[0].len(), 5);
2707 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2708 assert_eq!(route.paths[0][0].short_channel_id, 2);
2709 assert_eq!(route.paths[0][0].fee_msat, 100);
2710 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2711 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2712 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2714 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2715 assert_eq!(route.paths[0][1].short_channel_id, 4);
2716 assert_eq!(route.paths[0][1].fee_msat, 0);
2717 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
2718 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2719 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2721 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2722 assert_eq!(route.paths[0][2].short_channel_id, 6);
2723 assert_eq!(route.paths[0][2].fee_msat, 0);
2724 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
2725 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2726 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2728 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2729 assert_eq!(route.paths[0][3].short_channel_id, 11);
2730 assert_eq!(route.paths[0][3].fee_msat, 0);
2731 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
2732 // If we have a peer in the node map, we'll use their features here since we don't have
2733 // a way of figuring out their features from the invoice:
2734 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2735 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2737 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2738 assert_eq!(route.paths[0][4].short_channel_id, 8);
2739 assert_eq!(route.paths[0][4].fee_msat, 100);
2740 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2741 assert_eq!(route.paths[0][4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
2742 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2745 /// Builds a trivial last-hop hint that passes through the two nodes given, with channel 0xff00
2747 fn multi_hop_last_hops_hint(hint_hops: [PublicKey; 2]) -> Vec<RouteHint> {
2748 let zero_fees = RoutingFees {
2750 proportional_millionths: 0,
2752 vec![RouteHint(vec![RouteHintHop {
2753 src_node_id: hint_hops[0],
2754 short_channel_id: 0xff00,
2757 proportional_millionths: 0,
2759 cltv_expiry_delta: (5 << 4) | 1,
2760 htlc_minimum_msat: None,
2761 htlc_maximum_msat: None,
2763 src_node_id: hint_hops[1],
2764 short_channel_id: 0xff01,
2766 cltv_expiry_delta: (8 << 4) | 1,
2767 htlc_minimum_msat: None,
2768 htlc_maximum_msat: None,
2773 fn multi_hint_last_hops_test() {
2774 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2775 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2776 let last_hops = multi_hop_last_hops_hint([nodes[2], nodes[3]]);
2777 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops.clone());
2778 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2779 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2780 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2781 // Test through channels 2, 3, 0xff00, 0xff01.
2782 // Test shows that multiple hop hints are considered.
2784 // Disabling channels 6 & 7 by flags=2
2785 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2786 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2787 short_channel_id: 6,
2789 flags: 2, // to disable
2790 cltv_expiry_delta: 0,
2791 htlc_minimum_msat: 0,
2792 htlc_maximum_msat: MAX_VALUE_MSAT,
2794 fee_proportional_millionths: 0,
2795 excess_data: Vec::new()
2797 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2798 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2799 short_channel_id: 7,
2801 flags: 2, // to disable
2802 cltv_expiry_delta: 0,
2803 htlc_minimum_msat: 0,
2804 htlc_maximum_msat: MAX_VALUE_MSAT,
2806 fee_proportional_millionths: 0,
2807 excess_data: Vec::new()
2810 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2811 assert_eq!(route.paths[0].len(), 4);
2813 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2814 assert_eq!(route.paths[0][0].short_channel_id, 2);
2815 assert_eq!(route.paths[0][0].fee_msat, 200);
2816 assert_eq!(route.paths[0][0].cltv_expiry_delta, 65);
2817 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2818 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2820 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2821 assert_eq!(route.paths[0][1].short_channel_id, 4);
2822 assert_eq!(route.paths[0][1].fee_msat, 100);
2823 assert_eq!(route.paths[0][1].cltv_expiry_delta, 81);
2824 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2825 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2827 assert_eq!(route.paths[0][2].pubkey, nodes[3]);
2828 assert_eq!(route.paths[0][2].short_channel_id, last_hops[0].0[0].short_channel_id);
2829 assert_eq!(route.paths[0][2].fee_msat, 0);
2830 assert_eq!(route.paths[0][2].cltv_expiry_delta, 129);
2831 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(4));
2832 assert_eq!(route.paths[0][2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2834 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2835 assert_eq!(route.paths[0][3].short_channel_id, last_hops[0].0[1].short_channel_id);
2836 assert_eq!(route.paths[0][3].fee_msat, 100);
2837 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2838 assert_eq!(route.paths[0][3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
2839 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2843 fn private_multi_hint_last_hops_test() {
2844 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2845 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2847 let non_announced_privkey = SecretKey::from_slice(&hex::decode(format!("{:02x}", 0xf0).repeat(32)).unwrap()[..]).unwrap();
2848 let non_announced_pubkey = PublicKey::from_secret_key(&secp_ctx, &non_announced_privkey);
2850 let last_hops = multi_hop_last_hops_hint([nodes[2], non_announced_pubkey]);
2851 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops.clone());
2852 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2853 // Test through channels 2, 3, 0xff00, 0xff01.
2854 // Test shows that multiple hop hints are considered.
2856 // Disabling channels 6 & 7 by flags=2
2857 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2858 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2859 short_channel_id: 6,
2861 flags: 2, // to disable
2862 cltv_expiry_delta: 0,
2863 htlc_minimum_msat: 0,
2864 htlc_maximum_msat: MAX_VALUE_MSAT,
2866 fee_proportional_millionths: 0,
2867 excess_data: Vec::new()
2869 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2870 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2871 short_channel_id: 7,
2873 flags: 2, // to disable
2874 cltv_expiry_delta: 0,
2875 htlc_minimum_msat: 0,
2876 htlc_maximum_msat: MAX_VALUE_MSAT,
2878 fee_proportional_millionths: 0,
2879 excess_data: Vec::new()
2882 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &[42u8; 32]).unwrap();
2883 assert_eq!(route.paths[0].len(), 4);
2885 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2886 assert_eq!(route.paths[0][0].short_channel_id, 2);
2887 assert_eq!(route.paths[0][0].fee_msat, 200);
2888 assert_eq!(route.paths[0][0].cltv_expiry_delta, 65);
2889 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2890 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2892 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2893 assert_eq!(route.paths[0][1].short_channel_id, 4);
2894 assert_eq!(route.paths[0][1].fee_msat, 100);
2895 assert_eq!(route.paths[0][1].cltv_expiry_delta, 81);
2896 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2897 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2899 assert_eq!(route.paths[0][2].pubkey, non_announced_pubkey);
2900 assert_eq!(route.paths[0][2].short_channel_id, last_hops[0].0[0].short_channel_id);
2901 assert_eq!(route.paths[0][2].fee_msat, 0);
2902 assert_eq!(route.paths[0][2].cltv_expiry_delta, 129);
2903 assert_eq!(route.paths[0][2].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
2904 assert_eq!(route.paths[0][2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2906 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2907 assert_eq!(route.paths[0][3].short_channel_id, last_hops[0].0[1].short_channel_id);
2908 assert_eq!(route.paths[0][3].fee_msat, 100);
2909 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2910 assert_eq!(route.paths[0][3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
2911 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2914 fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2915 let zero_fees = RoutingFees {
2917 proportional_millionths: 0,
2919 vec![RouteHint(vec![RouteHintHop {
2920 src_node_id: nodes[4],
2921 short_channel_id: 11,
2923 cltv_expiry_delta: (11 << 4) | 1,
2924 htlc_minimum_msat: None,
2925 htlc_maximum_msat: None,
2927 src_node_id: nodes[3],
2928 short_channel_id: 8,
2930 cltv_expiry_delta: (8 << 4) | 1,
2931 htlc_minimum_msat: None,
2932 htlc_maximum_msat: None,
2933 }]), RouteHint(vec![RouteHintHop {
2934 src_node_id: nodes[4],
2935 short_channel_id: 9,
2938 proportional_millionths: 0,
2940 cltv_expiry_delta: (9 << 4) | 1,
2941 htlc_minimum_msat: None,
2942 htlc_maximum_msat: None,
2943 }]), RouteHint(vec![RouteHintHop {
2944 src_node_id: nodes[5],
2945 short_channel_id: 10,
2947 cltv_expiry_delta: (10 << 4) | 1,
2948 htlc_minimum_msat: None,
2949 htlc_maximum_msat: None,
2954 fn last_hops_with_public_channel_test() {
2955 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2956 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2957 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops_with_public_channel(&nodes));
2958 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2959 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2960 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2961 // This test shows that public routes can be present in the invoice
2962 // which would be handled in the same manner.
2964 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2965 assert_eq!(route.paths[0].len(), 5);
2967 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2968 assert_eq!(route.paths[0][0].short_channel_id, 2);
2969 assert_eq!(route.paths[0][0].fee_msat, 100);
2970 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2971 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2972 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2974 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2975 assert_eq!(route.paths[0][1].short_channel_id, 4);
2976 assert_eq!(route.paths[0][1].fee_msat, 0);
2977 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
2978 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2979 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2981 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2982 assert_eq!(route.paths[0][2].short_channel_id, 6);
2983 assert_eq!(route.paths[0][2].fee_msat, 0);
2984 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
2985 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2986 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2988 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2989 assert_eq!(route.paths[0][3].short_channel_id, 11);
2990 assert_eq!(route.paths[0][3].fee_msat, 0);
2991 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
2992 // If we have a peer in the node map, we'll use their features here since we don't have
2993 // a way of figuring out their features from the invoice:
2994 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2995 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2997 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2998 assert_eq!(route.paths[0][4].short_channel_id, 8);
2999 assert_eq!(route.paths[0][4].fee_msat, 100);
3000 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
3001 assert_eq!(route.paths[0][4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3002 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3006 fn our_chans_last_hop_connect_test() {
3007 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3008 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3009 let scorer = ln_test_utils::TestScorer::with_penalty(0);
3010 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3011 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3013 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
3014 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3015 let mut last_hops = last_hops(&nodes);
3016 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops.clone());
3017 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();
3018 assert_eq!(route.paths[0].len(), 2);
3020 assert_eq!(route.paths[0][0].pubkey, nodes[3]);
3021 assert_eq!(route.paths[0][0].short_channel_id, 42);
3022 assert_eq!(route.paths[0][0].fee_msat, 0);
3023 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 4) | 1);
3024 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
3025 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3027 assert_eq!(route.paths[0][1].pubkey, nodes[6]);
3028 assert_eq!(route.paths[0][1].short_channel_id, 8);
3029 assert_eq!(route.paths[0][1].fee_msat, 100);
3030 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
3031 assert_eq!(route.paths[0][1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3032 assert_eq!(route.paths[0][1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3034 last_hops[0].0[0].fees.base_msat = 1000;
3036 // Revert to via 6 as the fee on 8 goes up
3037 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops);
3038 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3039 assert_eq!(route.paths[0].len(), 4);
3041 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3042 assert_eq!(route.paths[0][0].short_channel_id, 2);
3043 assert_eq!(route.paths[0][0].fee_msat, 200); // fee increased as its % of value transferred across node
3044 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
3045 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3046 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3048 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3049 assert_eq!(route.paths[0][1].short_channel_id, 4);
3050 assert_eq!(route.paths[0][1].fee_msat, 100);
3051 assert_eq!(route.paths[0][1].cltv_expiry_delta, (7 << 4) | 1);
3052 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3053 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3055 assert_eq!(route.paths[0][2].pubkey, nodes[5]);
3056 assert_eq!(route.paths[0][2].short_channel_id, 7);
3057 assert_eq!(route.paths[0][2].fee_msat, 0);
3058 assert_eq!(route.paths[0][2].cltv_expiry_delta, (10 << 4) | 1);
3059 // If we have a peer in the node map, we'll use their features here since we don't have
3060 // a way of figuring out their features from the invoice:
3061 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
3062 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(7));
3064 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
3065 assert_eq!(route.paths[0][3].short_channel_id, 10);
3066 assert_eq!(route.paths[0][3].fee_msat, 100);
3067 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
3068 assert_eq!(route.paths[0][3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3069 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3071 // ...but still use 8 for larger payments as 6 has a variable feerate
3072 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 2000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3073 assert_eq!(route.paths[0].len(), 5);
3075 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3076 assert_eq!(route.paths[0][0].short_channel_id, 2);
3077 assert_eq!(route.paths[0][0].fee_msat, 3000);
3078 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
3079 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3080 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3082 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3083 assert_eq!(route.paths[0][1].short_channel_id, 4);
3084 assert_eq!(route.paths[0][1].fee_msat, 0);
3085 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
3086 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3087 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3089 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
3090 assert_eq!(route.paths[0][2].short_channel_id, 6);
3091 assert_eq!(route.paths[0][2].fee_msat, 0);
3092 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
3093 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
3094 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
3096 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
3097 assert_eq!(route.paths[0][3].short_channel_id, 11);
3098 assert_eq!(route.paths[0][3].fee_msat, 1000);
3099 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
3100 // If we have a peer in the node map, we'll use their features here since we don't have
3101 // a way of figuring out their features from the invoice:
3102 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
3103 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
3105 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
3106 assert_eq!(route.paths[0][4].short_channel_id, 8);
3107 assert_eq!(route.paths[0][4].fee_msat, 2000);
3108 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
3109 assert_eq!(route.paths[0][4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3110 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3113 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> {
3114 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
3115 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3116 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3118 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
3119 let last_hops = RouteHint(vec![RouteHintHop {
3120 src_node_id: middle_node_id,
3121 short_channel_id: 8,
3124 proportional_millionths: last_hop_fee_prop,
3126 cltv_expiry_delta: (8 << 4) | 1,
3127 htlc_minimum_msat: None,
3128 htlc_maximum_msat: last_hop_htlc_max,
3130 let payment_params = PaymentParameters::from_node_id(target_node_id).with_route_hints(vec![last_hops]);
3131 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
3132 let scorer = ln_test_utils::TestScorer::with_penalty(0);
3133 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3134 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3135 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
3136 let logger = ln_test_utils::TestLogger::new();
3137 let network_graph = NetworkGraph::new(genesis_hash, &logger);
3138 let route = get_route(&source_node_id, &payment_params, &network_graph.read_only(),
3139 Some(&our_chans.iter().collect::<Vec<_>>()), route_val, 42, &logger, &scorer, &random_seed_bytes);
3144 fn unannounced_path_test() {
3145 // We should be able to send a payment to a destination without any help of a routing graph
3146 // if we have a channel with a common counterparty that appears in the first and last hop
3148 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
3150 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3151 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3152 assert_eq!(route.paths[0].len(), 2);
3154 assert_eq!(route.paths[0][0].pubkey, middle_node_id);
3155 assert_eq!(route.paths[0][0].short_channel_id, 42);
3156 assert_eq!(route.paths[0][0].fee_msat, 1001);
3157 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 4) | 1);
3158 assert_eq!(route.paths[0][0].node_features.le_flags(), &[0b11]);
3159 assert_eq!(route.paths[0][0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3161 assert_eq!(route.paths[0][1].pubkey, target_node_id);
3162 assert_eq!(route.paths[0][1].short_channel_id, 8);
3163 assert_eq!(route.paths[0][1].fee_msat, 1000000);
3164 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
3165 assert_eq!(route.paths[0][1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3166 assert_eq!(route.paths[0][1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3170 fn overflow_unannounced_path_test_liquidity_underflow() {
3171 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
3172 // the last-hop had a fee which overflowed a u64, we'd panic.
3173 // This was due to us adding the first-hop from us unconditionally, causing us to think
3174 // we'd built a path (as our node is in the "best candidate" set), when we had not.
3175 // In this test, we previously hit a subtraction underflow due to having less available
3176 // liquidity at the last hop than 0.
3177 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());
3181 fn overflow_unannounced_path_test_feerate_overflow() {
3182 // This tests for the same case as above, except instead of hitting a subtraction
3183 // underflow, we hit a case where the fee charged at a hop overflowed.
3184 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());
3188 fn available_amount_while_routing_test() {
3189 // Tests whether we choose the correct available channel amount while routing.
3191 let (secp_ctx, network_graph, mut gossip_sync, chain_monitor, logger) = build_graph();
3192 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3193 let scorer = ln_test_utils::TestScorer::with_penalty(0);
3194 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3195 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3196 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(channelmanager::provided_invoice_features());
3198 // We will use a simple single-path route from
3199 // our node to node2 via node0: channels {1, 3}.
3201 // First disable all other paths.
3202 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3203 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3204 short_channel_id: 2,
3207 cltv_expiry_delta: 0,
3208 htlc_minimum_msat: 0,
3209 htlc_maximum_msat: 100_000,
3211 fee_proportional_millionths: 0,
3212 excess_data: Vec::new()
3214 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3215 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3216 short_channel_id: 12,
3219 cltv_expiry_delta: 0,
3220 htlc_minimum_msat: 0,
3221 htlc_maximum_msat: 100_000,
3223 fee_proportional_millionths: 0,
3224 excess_data: Vec::new()
3227 // Make the first channel (#1) very permissive,
3228 // and we will be testing all limits on the second channel.
3229 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3230 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3231 short_channel_id: 1,
3234 cltv_expiry_delta: 0,
3235 htlc_minimum_msat: 0,
3236 htlc_maximum_msat: 1_000_000_000,
3238 fee_proportional_millionths: 0,
3239 excess_data: Vec::new()
3242 // First, let's see if routing works if we have absolutely no idea about the available amount.
3243 // In this case, it should be set to 250_000 sats.
3244 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3245 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3246 short_channel_id: 3,
3249 cltv_expiry_delta: 0,
3250 htlc_minimum_msat: 0,
3251 htlc_maximum_msat: 250_000_000,
3253 fee_proportional_millionths: 0,
3254 excess_data: Vec::new()
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(), None, 250_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(), None, 250_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, 250_000_000);
3275 // Check that setting next_outbound_htlc_limit_msat in first_hops limits the channels.
3276 // Disable channel #1 and use another first hop.
3277 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3278 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3279 short_channel_id: 1,
3282 cltv_expiry_delta: 0,
3283 htlc_minimum_msat: 0,
3284 htlc_maximum_msat: 1_000_000_000,
3286 fee_proportional_millionths: 0,
3287 excess_data: Vec::new()
3290 // Now, limit the first_hop by the next_outbound_htlc_limit_msat of 200_000 sats.
3291 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
3294 // Attempt to route more than available results in a failure.
3295 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3296 &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) {
3297 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3298 } else { panic!(); }
3302 // Now, attempt to route an exact amount we have should be fine.
3303 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();
3304 assert_eq!(route.paths.len(), 1);
3305 let path = route.paths.last().unwrap();
3306 assert_eq!(path.len(), 2);
3307 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3308 assert_eq!(path.last().unwrap().fee_msat, 200_000_000);
3311 // Enable channel #1 back.
3312 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3313 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3314 short_channel_id: 1,
3317 cltv_expiry_delta: 0,
3318 htlc_minimum_msat: 0,
3319 htlc_maximum_msat: 1_000_000_000,
3321 fee_proportional_millionths: 0,
3322 excess_data: Vec::new()
3326 // Now let's see if routing works if we know only htlc_maximum_msat.
3327 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3328 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3329 short_channel_id: 3,
3332 cltv_expiry_delta: 0,
3333 htlc_minimum_msat: 0,
3334 htlc_maximum_msat: 15_000,
3336 fee_proportional_millionths: 0,
3337 excess_data: Vec::new()
3341 // Attempt to route more than available results in a failure.
3342 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3343 &our_id, &payment_params, &network_graph.read_only(), None, 15_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3344 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3345 } else { panic!(); }
3349 // Now, attempt to route an exact amount we have should be fine.
3350 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 15_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3351 assert_eq!(route.paths.len(), 1);
3352 let path = route.paths.last().unwrap();
3353 assert_eq!(path.len(), 2);
3354 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3355 assert_eq!(path.last().unwrap().fee_msat, 15_000);
3358 // Now let's see if routing works if we know only capacity from the UTXO.
3360 // We can't change UTXO capacity on the fly, so we'll disable
3361 // the existing channel and add another one with the capacity we need.
3362 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3363 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3364 short_channel_id: 3,
3367 cltv_expiry_delta: 0,
3368 htlc_minimum_msat: 0,
3369 htlc_maximum_msat: MAX_VALUE_MSAT,
3371 fee_proportional_millionths: 0,
3372 excess_data: Vec::new()
3375 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
3376 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
3377 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
3378 .push_opcode(opcodes::all::OP_PUSHNUM_2)
3379 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
3381 *chain_monitor.utxo_ret.lock().unwrap() = Ok(TxOut { value: 15, script_pubkey: good_script.clone() });
3382 gossip_sync.add_chain_access(Some(chain_monitor));
3384 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
3385 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3386 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3387 short_channel_id: 333,
3390 cltv_expiry_delta: (3 << 4) | 1,
3391 htlc_minimum_msat: 0,
3392 htlc_maximum_msat: 15_000,
3394 fee_proportional_millionths: 0,
3395 excess_data: Vec::new()
3397 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3398 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3399 short_channel_id: 333,
3402 cltv_expiry_delta: (3 << 4) | 2,
3403 htlc_minimum_msat: 0,
3404 htlc_maximum_msat: 15_000,
3406 fee_proportional_millionths: 0,
3407 excess_data: Vec::new()
3411 // Attempt to route more than available results in a failure.
3412 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3413 &our_id, &payment_params, &network_graph.read_only(), None, 15_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3414 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3415 } else { panic!(); }
3419 // Now, attempt to route an exact amount we have should be fine.
3420 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 15_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3421 assert_eq!(route.paths.len(), 1);
3422 let path = route.paths.last().unwrap();
3423 assert_eq!(path.len(), 2);
3424 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3425 assert_eq!(path.last().unwrap().fee_msat, 15_000);
3428 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
3429 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3430 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3431 short_channel_id: 333,
3434 cltv_expiry_delta: 0,
3435 htlc_minimum_msat: 0,
3436 htlc_maximum_msat: 10_000,
3438 fee_proportional_millionths: 0,
3439 excess_data: Vec::new()
3443 // Attempt to route more than available results in a failure.
3444 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3445 &our_id, &payment_params, &network_graph.read_only(), None, 10_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3446 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3447 } else { panic!(); }
3451 // Now, attempt to route an exact amount we have should be fine.
3452 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 10_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3453 assert_eq!(route.paths.len(), 1);
3454 let path = route.paths.last().unwrap();
3455 assert_eq!(path.len(), 2);
3456 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3457 assert_eq!(path.last().unwrap().fee_msat, 10_000);
3462 fn available_liquidity_last_hop_test() {
3463 // Check that available liquidity properly limits the path even when only
3464 // one of the latter hops is limited.
3465 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3466 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3467 let scorer = ln_test_utils::TestScorer::with_penalty(0);
3468 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3469 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3470 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(channelmanager::provided_invoice_features());
3472 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3473 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
3474 // Total capacity: 50 sats.
3476 // Disable other potential paths.
3477 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3478 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3479 short_channel_id: 2,
3482 cltv_expiry_delta: 0,
3483 htlc_minimum_msat: 0,
3484 htlc_maximum_msat: 100_000,
3486 fee_proportional_millionths: 0,
3487 excess_data: Vec::new()
3489 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3490 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3491 short_channel_id: 7,
3494 cltv_expiry_delta: 0,
3495 htlc_minimum_msat: 0,
3496 htlc_maximum_msat: 100_000,
3498 fee_proportional_millionths: 0,
3499 excess_data: Vec::new()
3504 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3505 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3506 short_channel_id: 12,
3509 cltv_expiry_delta: 0,
3510 htlc_minimum_msat: 0,
3511 htlc_maximum_msat: 100_000,
3513 fee_proportional_millionths: 0,
3514 excess_data: Vec::new()
3516 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3517 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3518 short_channel_id: 13,
3521 cltv_expiry_delta: 0,
3522 htlc_minimum_msat: 0,
3523 htlc_maximum_msat: 100_000,
3525 fee_proportional_millionths: 0,
3526 excess_data: Vec::new()
3529 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3530 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3531 short_channel_id: 6,
3534 cltv_expiry_delta: 0,
3535 htlc_minimum_msat: 0,
3536 htlc_maximum_msat: 50_000,
3538 fee_proportional_millionths: 0,
3539 excess_data: Vec::new()
3541 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3542 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3543 short_channel_id: 11,
3546 cltv_expiry_delta: 0,
3547 htlc_minimum_msat: 0,
3548 htlc_maximum_msat: 100_000,
3550 fee_proportional_millionths: 0,
3551 excess_data: Vec::new()
3554 // Attempt to route more than available results in a failure.
3555 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3556 &our_id, &payment_params, &network_graph.read_only(), None, 60_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3557 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3558 } else { panic!(); }
3562 // Now, attempt to route 49 sats (just a bit below the capacity).
3563 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 49_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3564 assert_eq!(route.paths.len(), 1);
3565 let mut total_amount_paid_msat = 0;
3566 for path in &route.paths {
3567 assert_eq!(path.len(), 4);
3568 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3569 total_amount_paid_msat += path.last().unwrap().fee_msat;
3571 assert_eq!(total_amount_paid_msat, 49_000);
3575 // Attempt to route an exact amount is also fine
3576 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3577 assert_eq!(route.paths.len(), 1);
3578 let mut total_amount_paid_msat = 0;
3579 for path in &route.paths {
3580 assert_eq!(path.len(), 4);
3581 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3582 total_amount_paid_msat += path.last().unwrap().fee_msat;
3584 assert_eq!(total_amount_paid_msat, 50_000);
3589 fn ignore_fee_first_hop_test() {
3590 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3591 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3592 let scorer = ln_test_utils::TestScorer::with_penalty(0);
3593 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3594 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3595 let payment_params = PaymentParameters::from_node_id(nodes[2]);
3597 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3598 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3599 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3600 short_channel_id: 1,
3603 cltv_expiry_delta: 0,
3604 htlc_minimum_msat: 0,
3605 htlc_maximum_msat: 100_000,
3606 fee_base_msat: 1_000_000,
3607 fee_proportional_millionths: 0,
3608 excess_data: Vec::new()
3610 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3611 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3612 short_channel_id: 3,
3615 cltv_expiry_delta: 0,
3616 htlc_minimum_msat: 0,
3617 htlc_maximum_msat: 50_000,
3619 fee_proportional_millionths: 0,
3620 excess_data: Vec::new()
3624 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3625 assert_eq!(route.paths.len(), 1);
3626 let mut total_amount_paid_msat = 0;
3627 for path in &route.paths {
3628 assert_eq!(path.len(), 2);
3629 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3630 total_amount_paid_msat += path.last().unwrap().fee_msat;
3632 assert_eq!(total_amount_paid_msat, 50_000);
3637 fn simple_mpp_route_test() {
3638 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3639 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3640 let scorer = ln_test_utils::TestScorer::with_penalty(0);
3641 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3642 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3643 let payment_params = PaymentParameters::from_node_id(nodes[2])
3644 .with_features(channelmanager::provided_invoice_features());
3646 // We need a route consisting of 3 paths:
3647 // From our node to node2 via node0, node7, node1 (three paths one hop each).
3648 // To achieve this, the amount being transferred should be around
3649 // the total capacity of these 3 paths.
3651 // First, we set limits on these (previously unlimited) channels.
3652 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
3654 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3655 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3656 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3657 short_channel_id: 1,
3660 cltv_expiry_delta: 0,
3661 htlc_minimum_msat: 0,
3662 htlc_maximum_msat: 100_000,
3664 fee_proportional_millionths: 0,
3665 excess_data: Vec::new()
3667 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3668 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3669 short_channel_id: 3,
3672 cltv_expiry_delta: 0,
3673 htlc_minimum_msat: 0,
3674 htlc_maximum_msat: 50_000,
3676 fee_proportional_millionths: 0,
3677 excess_data: Vec::new()
3680 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
3681 // (total limit 60).
3682 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3683 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3684 short_channel_id: 12,
3687 cltv_expiry_delta: 0,
3688 htlc_minimum_msat: 0,
3689 htlc_maximum_msat: 60_000,
3691 fee_proportional_millionths: 0,
3692 excess_data: Vec::new()
3694 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3695 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3696 short_channel_id: 13,
3699 cltv_expiry_delta: 0,
3700 htlc_minimum_msat: 0,
3701 htlc_maximum_msat: 60_000,
3703 fee_proportional_millionths: 0,
3704 excess_data: Vec::new()
3707 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
3708 // (total capacity 180 sats).
3709 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3710 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3711 short_channel_id: 2,
3714 cltv_expiry_delta: 0,
3715 htlc_minimum_msat: 0,
3716 htlc_maximum_msat: 200_000,
3718 fee_proportional_millionths: 0,
3719 excess_data: Vec::new()
3721 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3722 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3723 short_channel_id: 4,
3726 cltv_expiry_delta: 0,
3727 htlc_minimum_msat: 0,
3728 htlc_maximum_msat: 180_000,
3730 fee_proportional_millionths: 0,
3731 excess_data: Vec::new()
3735 // Attempt to route more than available results in a failure.
3736 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3737 &our_id, &payment_params, &network_graph.read_only(), None, 300_000, 42,
3738 Arc::clone(&logger), &scorer, &random_seed_bytes) {
3739 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3740 } else { panic!(); }
3744 // Attempt to route while setting max_path_count to 0 results in a failure.
3745 let zero_payment_params = payment_params.clone().with_max_path_count(0);
3746 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3747 &our_id, &zero_payment_params, &network_graph.read_only(), None, 100, 42,
3748 Arc::clone(&logger), &scorer, &random_seed_bytes) {
3749 assert_eq!(err, "Can't find a route with no paths allowed.");
3750 } else { panic!(); }
3754 // Attempt to route while setting max_path_count to 3 results in a failure.
3755 // This is the case because the minimal_value_contribution_msat would require each path
3756 // to account for 1/3 of the total value, which is violated by 2 out of 3 paths.
3757 let fail_payment_params = payment_params.clone().with_max_path_count(3);
3758 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3759 &our_id, &fail_payment_params, &network_graph.read_only(), None, 250_000, 42,
3760 Arc::clone(&logger), &scorer, &random_seed_bytes) {
3761 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3762 } else { panic!(); }
3766 // Now, attempt to route 250 sats (just a bit below the capacity).
3767 // Our algorithm should provide us with these 3 paths.
3768 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None,
3769 250_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3770 assert_eq!(route.paths.len(), 3);
3771 let mut total_amount_paid_msat = 0;
3772 for path in &route.paths {
3773 assert_eq!(path.len(), 2);
3774 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3775 total_amount_paid_msat += path.last().unwrap().fee_msat;
3777 assert_eq!(total_amount_paid_msat, 250_000);
3781 // Attempt to route an exact amount is also fine
3782 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None,
3783 290_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3784 assert_eq!(route.paths.len(), 3);
3785 let mut total_amount_paid_msat = 0;
3786 for path in &route.paths {
3787 assert_eq!(path.len(), 2);
3788 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3789 total_amount_paid_msat += path.last().unwrap().fee_msat;
3791 assert_eq!(total_amount_paid_msat, 290_000);
3796 fn long_mpp_route_test() {
3797 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3798 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3799 let scorer = ln_test_utils::TestScorer::with_penalty(0);
3800 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3801 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3802 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(channelmanager::provided_invoice_features());
3804 // We need a route consisting of 3 paths:
3805 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3806 // Note that these paths overlap (channels 5, 12, 13).
3807 // We will route 300 sats.
3808 // Each path will have 100 sats capacity, those channels which
3809 // are used twice will have 200 sats capacity.
3811 // Disable other potential paths.
3812 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3813 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3814 short_channel_id: 2,
3817 cltv_expiry_delta: 0,
3818 htlc_minimum_msat: 0,
3819 htlc_maximum_msat: 100_000,
3821 fee_proportional_millionths: 0,
3822 excess_data: Vec::new()
3824 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3825 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3826 short_channel_id: 7,
3829 cltv_expiry_delta: 0,
3830 htlc_minimum_msat: 0,
3831 htlc_maximum_msat: 100_000,
3833 fee_proportional_millionths: 0,
3834 excess_data: Vec::new()
3837 // Path via {node0, node2} is channels {1, 3, 5}.
3838 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3839 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3840 short_channel_id: 1,
3843 cltv_expiry_delta: 0,
3844 htlc_minimum_msat: 0,
3845 htlc_maximum_msat: 100_000,
3847 fee_proportional_millionths: 0,
3848 excess_data: Vec::new()
3850 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3851 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3852 short_channel_id: 3,
3855 cltv_expiry_delta: 0,
3856 htlc_minimum_msat: 0,
3857 htlc_maximum_msat: 100_000,
3859 fee_proportional_millionths: 0,
3860 excess_data: Vec::new()
3863 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3864 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3865 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3866 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3867 short_channel_id: 5,
3870 cltv_expiry_delta: 0,
3871 htlc_minimum_msat: 0,
3872 htlc_maximum_msat: 200_000,
3874 fee_proportional_millionths: 0,
3875 excess_data: Vec::new()
3878 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3879 // Add 100 sats to the capacities of {12, 13}, because these channels
3880 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3881 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3882 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3883 short_channel_id: 12,
3886 cltv_expiry_delta: 0,
3887 htlc_minimum_msat: 0,
3888 htlc_maximum_msat: 200_000,
3890 fee_proportional_millionths: 0,
3891 excess_data: Vec::new()
3893 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3894 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3895 short_channel_id: 13,
3898 cltv_expiry_delta: 0,
3899 htlc_minimum_msat: 0,
3900 htlc_maximum_msat: 200_000,
3902 fee_proportional_millionths: 0,
3903 excess_data: Vec::new()
3906 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3907 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3908 short_channel_id: 6,
3911 cltv_expiry_delta: 0,
3912 htlc_minimum_msat: 0,
3913 htlc_maximum_msat: 100_000,
3915 fee_proportional_millionths: 0,
3916 excess_data: Vec::new()
3918 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3919 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3920 short_channel_id: 11,
3923 cltv_expiry_delta: 0,
3924 htlc_minimum_msat: 0,
3925 htlc_maximum_msat: 100_000,
3927 fee_proportional_millionths: 0,
3928 excess_data: Vec::new()
3931 // Path via {node7, node2} is channels {12, 13, 5}.
3932 // We already limited them to 200 sats (they are used twice for 100 sats).
3933 // Nothing to do here.
3936 // Attempt to route more than available results in a failure.
3937 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3938 &our_id, &payment_params, &network_graph.read_only(), None, 350_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3939 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3940 } else { panic!(); }
3944 // Now, attempt to route 300 sats (exact amount we can route).
3945 // Our algorithm should provide us with these 3 paths, 100 sats each.
3946 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 300_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3947 assert_eq!(route.paths.len(), 3);
3949 let mut total_amount_paid_msat = 0;
3950 for path in &route.paths {
3951 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3952 total_amount_paid_msat += path.last().unwrap().fee_msat;
3954 assert_eq!(total_amount_paid_msat, 300_000);
3960 fn mpp_cheaper_route_test() {
3961 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3962 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3963 let scorer = ln_test_utils::TestScorer::with_penalty(0);
3964 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3965 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3966 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(channelmanager::provided_invoice_features());
3968 // This test checks that if we have two cheaper paths and one more expensive path,
3969 // so that liquidity-wise any 2 of 3 combination is sufficient,
3970 // two cheaper paths will be taken.
3971 // These paths have equal available liquidity.
3973 // We need a combination of 3 paths:
3974 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3975 // Note that these paths overlap (channels 5, 12, 13).
3976 // Each path will have 100 sats capacity, those channels which
3977 // are used twice will have 200 sats capacity.
3979 // Disable other potential paths.
3980 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3981 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3982 short_channel_id: 2,
3985 cltv_expiry_delta: 0,
3986 htlc_minimum_msat: 0,
3987 htlc_maximum_msat: 100_000,
3989 fee_proportional_millionths: 0,
3990 excess_data: Vec::new()
3992 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3993 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3994 short_channel_id: 7,
3997 cltv_expiry_delta: 0,
3998 htlc_minimum_msat: 0,
3999 htlc_maximum_msat: 100_000,
4001 fee_proportional_millionths: 0,
4002 excess_data: Vec::new()
4005 // Path via {node0, node2} is channels {1, 3, 5}.
4006 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4007 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4008 short_channel_id: 1,
4011 cltv_expiry_delta: 0,
4012 htlc_minimum_msat: 0,
4013 htlc_maximum_msat: 100_000,
4015 fee_proportional_millionths: 0,
4016 excess_data: Vec::new()
4018 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4019 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4020 short_channel_id: 3,
4023 cltv_expiry_delta: 0,
4024 htlc_minimum_msat: 0,
4025 htlc_maximum_msat: 100_000,
4027 fee_proportional_millionths: 0,
4028 excess_data: Vec::new()
4031 // Capacity of 200 sats because this channel will be used by 3rd path as well.
4032 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4033 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4034 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4035 short_channel_id: 5,
4038 cltv_expiry_delta: 0,
4039 htlc_minimum_msat: 0,
4040 htlc_maximum_msat: 200_000,
4042 fee_proportional_millionths: 0,
4043 excess_data: Vec::new()
4046 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4047 // Add 100 sats to the capacities of {12, 13}, because these channels
4048 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
4049 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4050 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4051 short_channel_id: 12,
4054 cltv_expiry_delta: 0,
4055 htlc_minimum_msat: 0,
4056 htlc_maximum_msat: 200_000,
4058 fee_proportional_millionths: 0,
4059 excess_data: Vec::new()
4061 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4062 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4063 short_channel_id: 13,
4066 cltv_expiry_delta: 0,
4067 htlc_minimum_msat: 0,
4068 htlc_maximum_msat: 200_000,
4070 fee_proportional_millionths: 0,
4071 excess_data: Vec::new()
4074 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4075 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4076 short_channel_id: 6,
4079 cltv_expiry_delta: 0,
4080 htlc_minimum_msat: 0,
4081 htlc_maximum_msat: 100_000,
4082 fee_base_msat: 1_000,
4083 fee_proportional_millionths: 0,
4084 excess_data: Vec::new()
4086 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4087 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4088 short_channel_id: 11,
4091 cltv_expiry_delta: 0,
4092 htlc_minimum_msat: 0,
4093 htlc_maximum_msat: 100_000,
4095 fee_proportional_millionths: 0,
4096 excess_data: Vec::new()
4099 // Path via {node7, node2} is channels {12, 13, 5}.
4100 // We already limited them to 200 sats (they are used twice for 100 sats).
4101 // Nothing to do here.
4104 // Now, attempt to route 180 sats.
4105 // Our algorithm should provide us with these 2 paths.
4106 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 180_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4107 assert_eq!(route.paths.len(), 2);
4109 let mut total_value_transferred_msat = 0;
4110 let mut total_paid_msat = 0;
4111 for path in &route.paths {
4112 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
4113 total_value_transferred_msat += path.last().unwrap().fee_msat;
4115 total_paid_msat += hop.fee_msat;
4118 // If we paid fee, this would be higher.
4119 assert_eq!(total_value_transferred_msat, 180_000);
4120 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
4121 assert_eq!(total_fees_paid, 0);
4126 fn fees_on_mpp_route_test() {
4127 // This test makes sure that MPP algorithm properly takes into account
4128 // fees charged on the channels, by making the fees impactful:
4129 // if the fee is not properly accounted for, the behavior is different.
4130 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4131 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4132 let scorer = ln_test_utils::TestScorer::with_penalty(0);
4133 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4134 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4135 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(channelmanager::provided_invoice_features());
4137 // We need a route consisting of 2 paths:
4138 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
4139 // We will route 200 sats, Each path will have 100 sats capacity.
4141 // This test is not particularly stable: e.g.,
4142 // there's a way to route via {node0, node2, node4}.
4143 // It works while pathfinding is deterministic, but can be broken otherwise.
4144 // It's fine to ignore this concern for now.
4146 // Disable other potential paths.
4147 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4148 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4149 short_channel_id: 2,
4152 cltv_expiry_delta: 0,
4153 htlc_minimum_msat: 0,
4154 htlc_maximum_msat: 100_000,
4156 fee_proportional_millionths: 0,
4157 excess_data: Vec::new()
4160 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4161 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4162 short_channel_id: 7,
4165 cltv_expiry_delta: 0,
4166 htlc_minimum_msat: 0,
4167 htlc_maximum_msat: 100_000,
4169 fee_proportional_millionths: 0,
4170 excess_data: Vec::new()
4173 // Path via {node0, node2} is channels {1, 3, 5}.
4174 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4175 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4176 short_channel_id: 1,
4179 cltv_expiry_delta: 0,
4180 htlc_minimum_msat: 0,
4181 htlc_maximum_msat: 100_000,
4183 fee_proportional_millionths: 0,
4184 excess_data: Vec::new()
4186 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4187 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4188 short_channel_id: 3,
4191 cltv_expiry_delta: 0,
4192 htlc_minimum_msat: 0,
4193 htlc_maximum_msat: 100_000,
4195 fee_proportional_millionths: 0,
4196 excess_data: Vec::new()
4199 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4200 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4201 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4202 short_channel_id: 5,
4205 cltv_expiry_delta: 0,
4206 htlc_minimum_msat: 0,
4207 htlc_maximum_msat: 100_000,
4209 fee_proportional_millionths: 0,
4210 excess_data: Vec::new()
4213 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4214 // All channels should be 100 sats capacity. But for the fee experiment,
4215 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
4216 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
4217 // 100 sats (and pay 150 sats in fees for the use of channel 6),
4218 // so no matter how large are other channels,
4219 // the whole path will be limited by 100 sats with just these 2 conditions:
4220 // - channel 12 capacity is 250 sats
4221 // - fee for channel 6 is 150 sats
4222 // Let's test this by enforcing these 2 conditions and removing other limits.
4223 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4224 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4225 short_channel_id: 12,
4228 cltv_expiry_delta: 0,
4229 htlc_minimum_msat: 0,
4230 htlc_maximum_msat: 250_000,
4232 fee_proportional_millionths: 0,
4233 excess_data: Vec::new()
4235 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4236 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4237 short_channel_id: 13,
4240 cltv_expiry_delta: 0,
4241 htlc_minimum_msat: 0,
4242 htlc_maximum_msat: MAX_VALUE_MSAT,
4244 fee_proportional_millionths: 0,
4245 excess_data: Vec::new()
4248 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4249 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4250 short_channel_id: 6,
4253 cltv_expiry_delta: 0,
4254 htlc_minimum_msat: 0,
4255 htlc_maximum_msat: MAX_VALUE_MSAT,
4256 fee_base_msat: 150_000,
4257 fee_proportional_millionths: 0,
4258 excess_data: Vec::new()
4260 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4261 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4262 short_channel_id: 11,
4265 cltv_expiry_delta: 0,
4266 htlc_minimum_msat: 0,
4267 htlc_maximum_msat: MAX_VALUE_MSAT,
4269 fee_proportional_millionths: 0,
4270 excess_data: Vec::new()
4274 // Attempt to route more than available results in a failure.
4275 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4276 &our_id, &payment_params, &network_graph.read_only(), None, 210_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
4277 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4278 } else { panic!(); }
4282 // Now, attempt to route 200 sats (exact amount we can route).
4283 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 200_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4284 assert_eq!(route.paths.len(), 2);
4286 let mut total_amount_paid_msat = 0;
4287 for path in &route.paths {
4288 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
4289 total_amount_paid_msat += path.last().unwrap().fee_msat;
4291 assert_eq!(total_amount_paid_msat, 200_000);
4292 assert_eq!(route.get_total_fees(), 150_000);
4297 fn mpp_with_last_hops() {
4298 // Previously, if we tried to send an MPP payment to a destination which was only reachable
4299 // via a single last-hop route hint, we'd fail to route if we first collected routes
4300 // totaling close but not quite enough to fund the full payment.
4302 // This was because we considered last-hop hints to have exactly the sought payment amount
4303 // instead of the amount we were trying to collect, needlessly limiting our path searching
4304 // at the very first hop.
4306 // Specifically, this interacted with our "all paths must fund at least 5% of total target"
4307 // criterion to cause us to refuse all routes at the last hop hint which would be considered
4308 // to only have the remaining to-collect amount in available liquidity.
4310 // This bug appeared in production in some specific channel configurations.
4311 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4312 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4313 let scorer = ln_test_utils::TestScorer::with_penalty(0);
4314 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4315 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4316 let payment_params = PaymentParameters::from_node_id(PublicKey::from_slice(&[02; 33]).unwrap()).with_features(channelmanager::provided_invoice_features())
4317 .with_route_hints(vec![RouteHint(vec![RouteHintHop {
4318 src_node_id: nodes[2],
4319 short_channel_id: 42,
4320 fees: RoutingFees { base_msat: 0, proportional_millionths: 0 },
4321 cltv_expiry_delta: 42,
4322 htlc_minimum_msat: None,
4323 htlc_maximum_msat: None,
4324 }])]).with_max_channel_saturation_power_of_half(0);
4326 // Keep only two paths from us to nodes[2], both with a 99sat HTLC maximum, with one with
4327 // no fee and one with a 1msat fee. Previously, trying to route 100 sats to nodes[2] here
4328 // would first use the no-fee route and then fail to find a path along the second route as
4329 // we think we can only send up to 1 additional sat over the last-hop but refuse to as its
4330 // under 5% of our payment amount.
4331 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4332 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4333 short_channel_id: 1,
4336 cltv_expiry_delta: (5 << 4) | 5,
4337 htlc_minimum_msat: 0,
4338 htlc_maximum_msat: 99_000,
4339 fee_base_msat: u32::max_value(),
4340 fee_proportional_millionths: u32::max_value(),
4341 excess_data: Vec::new()
4343 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4344 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4345 short_channel_id: 2,
4348 cltv_expiry_delta: (5 << 4) | 3,
4349 htlc_minimum_msat: 0,
4350 htlc_maximum_msat: 99_000,
4351 fee_base_msat: u32::max_value(),
4352 fee_proportional_millionths: u32::max_value(),
4353 excess_data: Vec::new()
4355 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4356 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4357 short_channel_id: 4,
4360 cltv_expiry_delta: (4 << 4) | 1,
4361 htlc_minimum_msat: 0,
4362 htlc_maximum_msat: MAX_VALUE_MSAT,
4364 fee_proportional_millionths: 0,
4365 excess_data: Vec::new()
4367 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4368 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4369 short_channel_id: 13,
4371 flags: 0|2, // Channel disabled
4372 cltv_expiry_delta: (13 << 4) | 1,
4373 htlc_minimum_msat: 0,
4374 htlc_maximum_msat: MAX_VALUE_MSAT,
4376 fee_proportional_millionths: 2000000,
4377 excess_data: Vec::new()
4380 // Get a route for 100 sats and check that we found the MPP route no problem and didn't
4382 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();
4383 assert_eq!(route.paths.len(), 2);
4384 route.paths.sort_by_key(|path| path[0].short_channel_id);
4385 // Paths are manually ordered ordered by SCID, so:
4386 // * the first is channel 1 (0 fee, but 99 sat maximum) -> channel 3 -> channel 42
4387 // * the second is channel 2 (1 msat fee) -> channel 4 -> channel 42
4388 assert_eq!(route.paths[0][0].short_channel_id, 1);
4389 assert_eq!(route.paths[0][0].fee_msat, 0);
4390 assert_eq!(route.paths[0][2].fee_msat, 99_000);
4391 assert_eq!(route.paths[1][0].short_channel_id, 2);
4392 assert_eq!(route.paths[1][0].fee_msat, 1);
4393 assert_eq!(route.paths[1][2].fee_msat, 1_000);
4394 assert_eq!(route.get_total_fees(), 1);
4395 assert_eq!(route.get_total_amount(), 100_000);
4399 fn drop_lowest_channel_mpp_route_test() {
4400 // This test checks that low-capacity channel is dropped when after
4401 // path finding we realize that we found more capacity than we need.
4402 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4403 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4404 let scorer = ln_test_utils::TestScorer::with_penalty(0);
4405 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4406 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4407 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(channelmanager::provided_invoice_features())
4408 .with_max_channel_saturation_power_of_half(0);
4410 // We need a route consisting of 3 paths:
4411 // From our node to node2 via node0, node7, node1 (three paths one hop each).
4413 // The first and the second paths should be sufficient, but the third should be
4414 // cheaper, so that we select it but drop later.
4416 // First, we set limits on these (previously unlimited) channels.
4417 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
4419 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
4420 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4421 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4422 short_channel_id: 1,
4425 cltv_expiry_delta: 0,
4426 htlc_minimum_msat: 0,
4427 htlc_maximum_msat: 100_000,
4429 fee_proportional_millionths: 0,
4430 excess_data: Vec::new()
4432 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4433 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4434 short_channel_id: 3,
4437 cltv_expiry_delta: 0,
4438 htlc_minimum_msat: 0,
4439 htlc_maximum_msat: 50_000,
4441 fee_proportional_millionths: 0,
4442 excess_data: Vec::new()
4445 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
4446 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4447 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4448 short_channel_id: 12,
4451 cltv_expiry_delta: 0,
4452 htlc_minimum_msat: 0,
4453 htlc_maximum_msat: 60_000,
4455 fee_proportional_millionths: 0,
4456 excess_data: Vec::new()
4458 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4459 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4460 short_channel_id: 13,
4463 cltv_expiry_delta: 0,
4464 htlc_minimum_msat: 0,
4465 htlc_maximum_msat: 60_000,
4467 fee_proportional_millionths: 0,
4468 excess_data: Vec::new()
4471 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
4472 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4473 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4474 short_channel_id: 2,
4477 cltv_expiry_delta: 0,
4478 htlc_minimum_msat: 0,
4479 htlc_maximum_msat: 20_000,
4481 fee_proportional_millionths: 0,
4482 excess_data: Vec::new()
4484 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4485 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4486 short_channel_id: 4,
4489 cltv_expiry_delta: 0,
4490 htlc_minimum_msat: 0,
4491 htlc_maximum_msat: 20_000,
4493 fee_proportional_millionths: 0,
4494 excess_data: Vec::new()
4498 // Attempt to route more than available results in a failure.
4499 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4500 &our_id, &payment_params, &network_graph.read_only(), None, 150_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
4501 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4502 } else { panic!(); }
4506 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
4507 // Our algorithm should provide us with these 3 paths.
4508 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 125_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4509 assert_eq!(route.paths.len(), 3);
4510 let mut total_amount_paid_msat = 0;
4511 for path in &route.paths {
4512 assert_eq!(path.len(), 2);
4513 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4514 total_amount_paid_msat += path.last().unwrap().fee_msat;
4516 assert_eq!(total_amount_paid_msat, 125_000);
4520 // Attempt to route without the last small cheap channel
4521 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4522 assert_eq!(route.paths.len(), 2);
4523 let mut total_amount_paid_msat = 0;
4524 for path in &route.paths {
4525 assert_eq!(path.len(), 2);
4526 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4527 total_amount_paid_msat += path.last().unwrap().fee_msat;
4529 assert_eq!(total_amount_paid_msat, 90_000);
4534 fn min_criteria_consistency() {
4535 // Test that we don't use an inconsistent metric between updating and walking nodes during
4536 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
4537 // was updated with a different criterion from the heap sorting, resulting in loops in
4538 // calculated paths. We test for that specific case here.
4540 // We construct a network that looks like this:
4542 // node2 -1(3)2- node3
4546 // node1 -1(5)2- node4 -1(1)2- node6
4552 // We create a loop on the side of our real path - our destination is node 6, with a
4553 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
4554 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
4555 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
4556 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
4557 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
4558 // "previous hop" being set to node 3, creating a loop in the path.
4559 let secp_ctx = Secp256k1::new();
4560 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
4561 let logger = Arc::new(ln_test_utils::TestLogger::new());
4562 let network = Arc::new(NetworkGraph::new(genesis_hash, Arc::clone(&logger)));
4563 let gossip_sync = P2PGossipSync::new(Arc::clone(&network), None, Arc::clone(&logger));
4564 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4565 let scorer = ln_test_utils::TestScorer::with_penalty(0);
4566 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4567 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4568 let payment_params = PaymentParameters::from_node_id(nodes[6]);
4570 add_channel(&gossip_sync, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
4571 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4572 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4573 short_channel_id: 6,
4576 cltv_expiry_delta: (6 << 4) | 0,
4577 htlc_minimum_msat: 0,
4578 htlc_maximum_msat: MAX_VALUE_MSAT,
4580 fee_proportional_millionths: 0,
4581 excess_data: Vec::new()
4583 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
4585 add_channel(&gossip_sync, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4586 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4587 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4588 short_channel_id: 5,
4591 cltv_expiry_delta: (5 << 4) | 0,
4592 htlc_minimum_msat: 0,
4593 htlc_maximum_msat: MAX_VALUE_MSAT,
4595 fee_proportional_millionths: 0,
4596 excess_data: Vec::new()
4598 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
4600 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
4601 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4602 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4603 short_channel_id: 4,
4606 cltv_expiry_delta: (4 << 4) | 0,
4607 htlc_minimum_msat: 0,
4608 htlc_maximum_msat: MAX_VALUE_MSAT,
4610 fee_proportional_millionths: 0,
4611 excess_data: Vec::new()
4613 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
4615 add_channel(&gossip_sync, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
4616 update_channel(&gossip_sync, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
4617 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4618 short_channel_id: 3,
4621 cltv_expiry_delta: (3 << 4) | 0,
4622 htlc_minimum_msat: 0,
4623 htlc_maximum_msat: MAX_VALUE_MSAT,
4625 fee_proportional_millionths: 0,
4626 excess_data: Vec::new()
4628 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
4630 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
4631 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4632 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4633 short_channel_id: 2,
4636 cltv_expiry_delta: (2 << 4) | 0,
4637 htlc_minimum_msat: 0,
4638 htlc_maximum_msat: MAX_VALUE_MSAT,
4640 fee_proportional_millionths: 0,
4641 excess_data: Vec::new()
4644 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
4645 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4646 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4647 short_channel_id: 1,
4650 cltv_expiry_delta: (1 << 4) | 0,
4651 htlc_minimum_msat: 100,
4652 htlc_maximum_msat: MAX_VALUE_MSAT,
4654 fee_proportional_millionths: 0,
4655 excess_data: Vec::new()
4657 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
4660 // Now ensure the route flows simply over nodes 1 and 4 to 6.
4661 let route = get_route(&our_id, &payment_params, &network.read_only(), None, 10_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4662 assert_eq!(route.paths.len(), 1);
4663 assert_eq!(route.paths[0].len(), 3);
4665 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
4666 assert_eq!(route.paths[0][0].short_channel_id, 6);
4667 assert_eq!(route.paths[0][0].fee_msat, 100);
4668 assert_eq!(route.paths[0][0].cltv_expiry_delta, (5 << 4) | 0);
4669 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(1));
4670 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(6));
4672 assert_eq!(route.paths[0][1].pubkey, nodes[4]);
4673 assert_eq!(route.paths[0][1].short_channel_id, 5);
4674 assert_eq!(route.paths[0][1].fee_msat, 0);
4675 assert_eq!(route.paths[0][1].cltv_expiry_delta, (1 << 4) | 0);
4676 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(4));
4677 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(5));
4679 assert_eq!(route.paths[0][2].pubkey, nodes[6]);
4680 assert_eq!(route.paths[0][2].short_channel_id, 1);
4681 assert_eq!(route.paths[0][2].fee_msat, 10_000);
4682 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
4683 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
4684 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(1));
4690 fn exact_fee_liquidity_limit() {
4691 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
4692 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
4693 // we calculated fees on a higher value, resulting in us ignoring such paths.
4694 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4695 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
4696 let scorer = ln_test_utils::TestScorer::with_penalty(0);
4697 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4698 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4699 let payment_params = PaymentParameters::from_node_id(nodes[2]);
4701 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
4703 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4704 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4705 short_channel_id: 2,
4708 cltv_expiry_delta: 0,
4709 htlc_minimum_msat: 0,
4710 htlc_maximum_msat: 85_000,
4712 fee_proportional_millionths: 0,
4713 excess_data: Vec::new()
4716 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4717 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4718 short_channel_id: 12,
4721 cltv_expiry_delta: (4 << 4) | 1,
4722 htlc_minimum_msat: 0,
4723 htlc_maximum_msat: 270_000,
4725 fee_proportional_millionths: 1000000,
4726 excess_data: Vec::new()
4730 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
4731 // 200% fee charged channel 13 in the 1-to-2 direction.
4732 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4733 assert_eq!(route.paths.len(), 1);
4734 assert_eq!(route.paths[0].len(), 2);
4736 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
4737 assert_eq!(route.paths[0][0].short_channel_id, 12);
4738 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
4739 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
4740 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
4741 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
4743 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
4744 assert_eq!(route.paths[0][1].short_channel_id, 13);
4745 assert_eq!(route.paths[0][1].fee_msat, 90_000);
4746 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
4747 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
4748 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
4753 fn htlc_max_reduction_below_min() {
4754 // Test that if, while walking the graph, we reduce the value being sent to meet an
4755 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
4756 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
4757 // resulting in us thinking there is no possible path, even if other paths exist.
4758 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4759 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4760 let scorer = ln_test_utils::TestScorer::with_penalty(0);
4761 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4762 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4763 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(channelmanager::provided_invoice_features());
4765 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
4766 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
4767 // then try to send 90_000.
4768 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4769 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4770 short_channel_id: 2,
4773 cltv_expiry_delta: 0,
4774 htlc_minimum_msat: 0,
4775 htlc_maximum_msat: 80_000,
4777 fee_proportional_millionths: 0,
4778 excess_data: Vec::new()
4780 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4781 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4782 short_channel_id: 4,
4785 cltv_expiry_delta: (4 << 4) | 1,
4786 htlc_minimum_msat: 90_000,
4787 htlc_maximum_msat: MAX_VALUE_MSAT,
4789 fee_proportional_millionths: 0,
4790 excess_data: Vec::new()
4794 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
4795 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
4796 // expensive) channels 12-13 path.
4797 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4798 assert_eq!(route.paths.len(), 1);
4799 assert_eq!(route.paths[0].len(), 2);
4801 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
4802 assert_eq!(route.paths[0][0].short_channel_id, 12);
4803 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
4804 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
4805 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
4806 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
4808 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
4809 assert_eq!(route.paths[0][1].short_channel_id, 13);
4810 assert_eq!(route.paths[0][1].fee_msat, 90_000);
4811 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
4812 assert_eq!(route.paths[0][1].node_features.le_flags(), channelmanager::provided_invoice_features().le_flags());
4813 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
4818 fn multiple_direct_first_hops() {
4819 // Previously we'd only ever considered one first hop path per counterparty.
4820 // However, as we don't restrict users to one channel per peer, we really need to support
4821 // looking at all first hop paths.
4822 // Here we test that we do not ignore all-but-the-last first hop paths per counterparty (as
4823 // we used to do by overwriting the `first_hop_targets` hashmap entry) and that we can MPP
4824 // route over multiple channels with the same first hop.
4825 let secp_ctx = Secp256k1::new();
4826 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4827 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
4828 let logger = Arc::new(ln_test_utils::TestLogger::new());
4829 let network_graph = NetworkGraph::new(genesis_hash, Arc::clone(&logger));
4830 let scorer = ln_test_utils::TestScorer::with_penalty(0);
4831 let payment_params = PaymentParameters::from_node_id(nodes[0]).with_features(channelmanager::provided_invoice_features());
4832 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4833 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4836 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
4837 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(), 200_000),
4838 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(), 10_000),
4839 ]), 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4840 assert_eq!(route.paths.len(), 1);
4841 assert_eq!(route.paths[0].len(), 1);
4843 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
4844 assert_eq!(route.paths[0][0].short_channel_id, 3);
4845 assert_eq!(route.paths[0][0].fee_msat, 100_000);
4848 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
4849 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(), 50_000),
4850 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(), 50_000),
4851 ]), 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4852 assert_eq!(route.paths.len(), 2);
4853 assert_eq!(route.paths[0].len(), 1);
4854 assert_eq!(route.paths[1].len(), 1);
4856 assert!((route.paths[0][0].short_channel_id == 3 && route.paths[1][0].short_channel_id == 2) ||
4857 (route.paths[0][0].short_channel_id == 2 && route.paths[1][0].short_channel_id == 3));
4859 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
4860 assert_eq!(route.paths[0][0].fee_msat, 50_000);
4862 assert_eq!(route.paths[1][0].pubkey, nodes[0]);
4863 assert_eq!(route.paths[1][0].fee_msat, 50_000);
4867 // If we have a bunch of outbound channels to the same node, where most are not
4868 // sufficient to pay the full payment, but one is, we should default to just using the
4869 // one single channel that has sufficient balance, avoiding MPP.
4871 // If we have several options above the 3xpayment value threshold, we should pick the
4872 // smallest of them, avoiding further fragmenting our available outbound balance to
4874 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
4875 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(), 50_000),
4876 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(), 50_000),
4877 &get_channel_details(Some(5), nodes[0], channelmanager::provided_init_features(), 50_000),
4878 &get_channel_details(Some(6), nodes[0], channelmanager::provided_init_features(), 300_000),
4879 &get_channel_details(Some(7), nodes[0], channelmanager::provided_init_features(), 50_000),
4880 &get_channel_details(Some(8), nodes[0], channelmanager::provided_init_features(), 50_000),
4881 &get_channel_details(Some(9), nodes[0], channelmanager::provided_init_features(), 50_000),
4882 &get_channel_details(Some(4), nodes[0], channelmanager::provided_init_features(), 1_000_000),
4883 ]), 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4884 assert_eq!(route.paths.len(), 1);
4885 assert_eq!(route.paths[0].len(), 1);
4887 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
4888 assert_eq!(route.paths[0][0].short_channel_id, 6);
4889 assert_eq!(route.paths[0][0].fee_msat, 100_000);
4894 fn prefers_shorter_route_with_higher_fees() {
4895 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4896 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4897 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
4899 // Without penalizing each hop 100 msats, a longer path with lower fees is chosen.
4900 let scorer = ln_test_utils::TestScorer::with_penalty(0);
4901 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4902 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4903 let route = get_route(
4904 &our_id, &payment_params, &network_graph.read_only(), None, 100, 42,
4905 Arc::clone(&logger), &scorer, &random_seed_bytes
4907 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4909 assert_eq!(route.get_total_fees(), 100);
4910 assert_eq!(route.get_total_amount(), 100);
4911 assert_eq!(path, vec![2, 4, 6, 11, 8]);
4913 // Applying a 100 msat penalty to each hop results in taking channels 7 and 10 to nodes[6]
4914 // from nodes[2] rather than channel 6, 11, and 8, even though the longer path is cheaper.
4915 let scorer = ln_test_utils::TestScorer::with_penalty(100);
4916 let route = get_route(
4917 &our_id, &payment_params, &network_graph.read_only(), None, 100, 42,
4918 Arc::clone(&logger), &scorer, &random_seed_bytes
4920 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4922 assert_eq!(route.get_total_fees(), 300);
4923 assert_eq!(route.get_total_amount(), 100);
4924 assert_eq!(path, vec![2, 4, 7, 10]);
4927 struct BadChannelScorer {
4928 short_channel_id: u64,
4932 impl Writeable for BadChannelScorer {
4933 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
4935 impl Score for BadChannelScorer {
4936 fn channel_penalty_msat(&self, short_channel_id: u64, _: &NodeId, _: &NodeId, _: ChannelUsage) -> u64 {
4937 if short_channel_id == self.short_channel_id { u64::max_value() } else { 0 }
4940 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
4941 fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
4942 fn probe_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
4943 fn probe_successful(&mut self, _path: &[&RouteHop]) {}
4946 struct BadNodeScorer {
4951 impl Writeable for BadNodeScorer {
4952 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
4955 impl Score for BadNodeScorer {
4956 fn channel_penalty_msat(&self, _: u64, _: &NodeId, target: &NodeId, _: ChannelUsage) -> u64 {
4957 if *target == self.node_id { u64::max_value() } else { 0 }
4960 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
4961 fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
4962 fn probe_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
4963 fn probe_successful(&mut self, _path: &[&RouteHop]) {}
4967 fn avoids_routing_through_bad_channels_and_nodes() {
4968 let (secp_ctx, network, _, _, logger) = build_graph();
4969 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4970 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
4971 let network_graph = network.read_only();
4973 // A path to nodes[6] exists when no penalties are applied to any channel.
4974 let scorer = ln_test_utils::TestScorer::with_penalty(0);
4975 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4976 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4977 let route = get_route(
4978 &our_id, &payment_params, &network_graph, None, 100, 42,
4979 Arc::clone(&logger), &scorer, &random_seed_bytes
4981 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4983 assert_eq!(route.get_total_fees(), 100);
4984 assert_eq!(route.get_total_amount(), 100);
4985 assert_eq!(path, vec![2, 4, 6, 11, 8]);
4987 // A different path to nodes[6] exists if channel 6 cannot be routed over.
4988 let scorer = BadChannelScorer { short_channel_id: 6 };
4989 let route = get_route(
4990 &our_id, &payment_params, &network_graph, None, 100, 42,
4991 Arc::clone(&logger), &scorer, &random_seed_bytes
4993 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4995 assert_eq!(route.get_total_fees(), 300);
4996 assert_eq!(route.get_total_amount(), 100);
4997 assert_eq!(path, vec![2, 4, 7, 10]);
4999 // A path to nodes[6] does not exist if nodes[2] cannot be routed through.
5000 let scorer = BadNodeScorer { node_id: NodeId::from_pubkey(&nodes[2]) };
5002 &our_id, &payment_params, &network_graph, None, 100, 42,
5003 Arc::clone(&logger), &scorer, &random_seed_bytes
5005 Err(LightningError { err, .. } ) => {
5006 assert_eq!(err, "Failed to find a path to the given destination");
5008 Ok(_) => panic!("Expected error"),
5013 fn total_fees_single_path() {
5017 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5018 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5019 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5022 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5023 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5024 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5027 pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
5028 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5029 short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0
5032 payment_params: None,
5035 assert_eq!(route.get_total_fees(), 250);
5036 assert_eq!(route.get_total_amount(), 225);
5040 fn total_fees_multi_path() {
5044 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5045 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5046 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5049 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5050 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5051 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5055 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5056 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5057 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5060 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5061 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5062 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5065 payment_params: None,
5068 assert_eq!(route.get_total_fees(), 200);
5069 assert_eq!(route.get_total_amount(), 300);
5073 fn total_empty_route_no_panic() {
5074 // In an earlier version of `Route::get_total_fees` and `Route::get_total_amount`, they
5075 // would both panic if the route was completely empty. We test to ensure they return 0
5076 // here, even though its somewhat nonsensical as a route.
5077 let route = Route { paths: Vec::new(), payment_params: None };
5079 assert_eq!(route.get_total_fees(), 0);
5080 assert_eq!(route.get_total_amount(), 0);
5084 fn limits_total_cltv_delta() {
5085 let (secp_ctx, network, _, _, logger) = build_graph();
5086 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5087 let network_graph = network.read_only();
5089 let scorer = ln_test_utils::TestScorer::with_penalty(0);
5091 // Make sure that generally there is at least one route available
5092 let feasible_max_total_cltv_delta = 1008;
5093 let feasible_payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes))
5094 .with_max_total_cltv_expiry_delta(feasible_max_total_cltv_delta);
5095 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5096 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5097 let route = get_route(&our_id, &feasible_payment_params, &network_graph, None, 100, 0, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5098 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5099 assert_ne!(path.len(), 0);
5101 // But not if we exclude all paths on the basis of their accumulated CLTV delta
5102 let fail_max_total_cltv_delta = 23;
5103 let fail_payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes))
5104 .with_max_total_cltv_expiry_delta(fail_max_total_cltv_delta);
5105 match get_route(&our_id, &fail_payment_params, &network_graph, None, 100, 0, Arc::clone(&logger), &scorer, &random_seed_bytes)
5107 Err(LightningError { err, .. } ) => {
5108 assert_eq!(err, "Failed to find a path to the given destination");
5110 Ok(_) => panic!("Expected error"),
5115 fn avoids_recently_failed_paths() {
5116 // Ensure that the router always avoids all of the `previously_failed_channels` channels by
5117 // randomly inserting channels into it until we can't find a route anymore.
5118 let (secp_ctx, network, _, _, logger) = build_graph();
5119 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5120 let network_graph = network.read_only();
5122 let scorer = ln_test_utils::TestScorer::with_penalty(0);
5123 let mut payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes))
5124 .with_max_path_count(1);
5125 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5126 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5128 // We should be able to find a route initially, and then after we fail a few random
5129 // channels eventually we won't be able to any longer.
5130 assert!(get_route(&our_id, &payment_params, &network_graph, None, 100, 0, Arc::clone(&logger), &scorer, &random_seed_bytes).is_ok());
5132 if let Ok(route) = get_route(&our_id, &payment_params, &network_graph, None, 100, 0, Arc::clone(&logger), &scorer, &random_seed_bytes) {
5133 for chan in route.paths[0].iter() {
5134 assert!(!payment_params.previously_failed_channels.contains(&chan.short_channel_id));
5136 let victim = (u64::from_ne_bytes(random_seed_bytes[0..8].try_into().unwrap()) as usize)
5137 % route.paths[0].len();
5138 payment_params.previously_failed_channels.push(route.paths[0][victim].short_channel_id);
5144 fn limits_path_length() {
5145 let (secp_ctx, network, _, _, logger) = build_line_graph();
5146 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5147 let network_graph = network.read_only();
5149 let scorer = ln_test_utils::TestScorer::with_penalty(0);
5150 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5151 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5153 // First check we can actually create a long route on this graph.
5154 let feasible_payment_params = PaymentParameters::from_node_id(nodes[18]);
5155 let route = get_route(&our_id, &feasible_payment_params, &network_graph, None, 100, 0,
5156 Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5157 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5158 assert!(path.len() == MAX_PATH_LENGTH_ESTIMATE.into());
5160 // But we can't create a path surpassing the MAX_PATH_LENGTH_ESTIMATE limit.
5161 let fail_payment_params = PaymentParameters::from_node_id(nodes[19]);
5162 match get_route(&our_id, &fail_payment_params, &network_graph, None, 100, 0,
5163 Arc::clone(&logger), &scorer, &random_seed_bytes)
5165 Err(LightningError { err, .. } ) => {
5166 assert_eq!(err, "Failed to find a path to the given destination");
5168 Ok(_) => panic!("Expected error"),
5173 fn adds_and_limits_cltv_offset() {
5174 let (secp_ctx, network_graph, _, _, logger) = build_graph();
5175 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5177 let scorer = ln_test_utils::TestScorer::with_penalty(0);
5179 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
5180 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5181 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5182 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5183 assert_eq!(route.paths.len(), 1);
5185 let cltv_expiry_deltas_before = route.paths[0].iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5187 // Check whether the offset added to the last hop by default is in [1 .. DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA]
5188 let mut route_default = route.clone();
5189 add_random_cltv_offset(&mut route_default, &payment_params, &network_graph.read_only(), &random_seed_bytes);
5190 let cltv_expiry_deltas_default = route_default.paths[0].iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5191 assert_eq!(cltv_expiry_deltas_before.split_last().unwrap().1, cltv_expiry_deltas_default.split_last().unwrap().1);
5192 assert!(cltv_expiry_deltas_default.last() > cltv_expiry_deltas_before.last());
5193 assert!(cltv_expiry_deltas_default.last().unwrap() <= &DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA);
5195 // Check that no offset is added when we restrict the max_total_cltv_expiry_delta
5196 let mut route_limited = route.clone();
5197 let limited_max_total_cltv_expiry_delta = cltv_expiry_deltas_before.iter().sum();
5198 let limited_payment_params = payment_params.with_max_total_cltv_expiry_delta(limited_max_total_cltv_expiry_delta);
5199 add_random_cltv_offset(&mut route_limited, &limited_payment_params, &network_graph.read_only(), &random_seed_bytes);
5200 let cltv_expiry_deltas_limited = route_limited.paths[0].iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5201 assert_eq!(cltv_expiry_deltas_before, cltv_expiry_deltas_limited);
5205 fn adds_plausible_cltv_offset() {
5206 let (secp_ctx, network, _, _, logger) = build_graph();
5207 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5208 let network_graph = network.read_only();
5209 let network_nodes = network_graph.nodes();
5210 let network_channels = network_graph.channels();
5211 let scorer = ln_test_utils::TestScorer::with_penalty(0);
5212 let payment_params = PaymentParameters::from_node_id(nodes[3]);
5213 let keys_manager = ln_test_utils::TestKeysInterface::new(&[4u8; 32], Network::Testnet);
5214 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5216 let mut route = get_route(&our_id, &payment_params, &network_graph, None, 100, 0,
5217 Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5218 add_random_cltv_offset(&mut route, &payment_params, &network_graph, &random_seed_bytes);
5220 let mut path_plausibility = vec![];
5222 for p in route.paths {
5223 // 1. Select random observation point
5224 let mut prng = ChaCha20::new(&random_seed_bytes, &[0u8; 12]);
5225 let mut random_bytes = [0u8; ::core::mem::size_of::<usize>()];
5227 prng.process_in_place(&mut random_bytes);
5228 let random_path_index = usize::from_be_bytes(random_bytes).wrapping_rem(p.len());
5229 let observation_point = NodeId::from_pubkey(&p.get(random_path_index).unwrap().pubkey);
5231 // 2. Calculate what CLTV expiry delta we would observe there
5232 let observed_cltv_expiry_delta: u32 = p[random_path_index..].iter().map(|h| h.cltv_expiry_delta).sum();
5234 // 3. Starting from the observation point, find candidate paths
5235 let mut candidates: VecDeque<(NodeId, Vec<u32>)> = VecDeque::new();
5236 candidates.push_back((observation_point, vec![]));
5238 let mut found_plausible_candidate = false;
5240 'candidate_loop: while let Some((cur_node_id, cur_path_cltv_deltas)) = candidates.pop_front() {
5241 if let Some(remaining) = observed_cltv_expiry_delta.checked_sub(cur_path_cltv_deltas.iter().sum::<u32>()) {
5242 if remaining == 0 || remaining.wrapping_rem(40) == 0 || remaining.wrapping_rem(144) == 0 {
5243 found_plausible_candidate = true;
5244 break 'candidate_loop;
5248 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
5249 for channel_id in &cur_node.channels {
5250 if let Some(channel_info) = network_channels.get(&channel_id) {
5251 if let Some((dir_info, next_id)) = channel_info.as_directed_from(&cur_node_id) {
5252 let next_cltv_expiry_delta = dir_info.direction().cltv_expiry_delta as u32;
5253 if cur_path_cltv_deltas.iter().sum::<u32>()
5254 .saturating_add(next_cltv_expiry_delta) <= observed_cltv_expiry_delta {
5255 let mut new_path_cltv_deltas = cur_path_cltv_deltas.clone();
5256 new_path_cltv_deltas.push(next_cltv_expiry_delta);
5257 candidates.push_back((*next_id, new_path_cltv_deltas));
5265 path_plausibility.push(found_plausible_candidate);
5267 assert!(path_plausibility.iter().all(|x| *x));
5271 fn builds_correct_path_from_hops() {
5272 let (secp_ctx, network, _, _, logger) = build_graph();
5273 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5274 let network_graph = network.read_only();
5276 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5277 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5279 let payment_params = PaymentParameters::from_node_id(nodes[3]);
5280 let hops = [nodes[1], nodes[2], nodes[4], nodes[3]];
5281 let route = build_route_from_hops_internal(&our_id, &hops, &payment_params,
5282 &network_graph, 100, 0, Arc::clone(&logger), &random_seed_bytes).unwrap();
5283 let route_hop_pubkeys = route.paths[0].iter().map(|hop| hop.pubkey).collect::<Vec<_>>();
5284 assert_eq!(hops.len(), route.paths[0].len());
5285 for (idx, hop_pubkey) in hops.iter().enumerate() {
5286 assert!(*hop_pubkey == route_hop_pubkeys[idx]);
5291 fn avoids_saturating_channels() {
5292 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5293 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5295 let scorer = ProbabilisticScorer::new(Default::default(), &*network_graph, Arc::clone(&logger));
5297 // Set the fee on channel 13 to 100% to match channel 4 giving us two equivalent paths (us
5298 // -> node 7 -> node2 and us -> node 1 -> node 2) which we should balance over.
5299 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5300 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5301 short_channel_id: 4,
5304 cltv_expiry_delta: (4 << 4) | 1,
5305 htlc_minimum_msat: 0,
5306 htlc_maximum_msat: 250_000_000,
5308 fee_proportional_millionths: 0,
5309 excess_data: Vec::new()
5311 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5312 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5313 short_channel_id: 13,
5316 cltv_expiry_delta: (13 << 4) | 1,
5317 htlc_minimum_msat: 0,
5318 htlc_maximum_msat: 250_000_000,
5320 fee_proportional_millionths: 0,
5321 excess_data: Vec::new()
5324 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(channelmanager::provided_invoice_features());
5325 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5326 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5327 // 100,000 sats is less than the available liquidity on each channel, set above.
5328 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();
5329 assert_eq!(route.paths.len(), 2);
5330 assert!((route.paths[0][1].short_channel_id == 4 && route.paths[1][1].short_channel_id == 13) ||
5331 (route.paths[1][1].short_channel_id == 4 && route.paths[0][1].short_channel_id == 13));
5334 #[cfg(not(feature = "no-std"))]
5335 pub(super) fn random_init_seed() -> u64 {
5336 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
5337 use core::hash::{BuildHasher, Hasher};
5338 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
5339 println!("Using seed of {}", seed);
5342 #[cfg(not(feature = "no-std"))]
5343 use crate::util::ser::ReadableArgs;
5346 #[cfg(not(feature = "no-std"))]
5347 fn generate_routes() {
5348 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringParameters};
5350 let mut d = match super::bench_utils::get_route_file() {
5357 let logger = ln_test_utils::TestLogger::new();
5358 let graph = NetworkGraph::read(&mut d, &logger).unwrap();
5359 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5360 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5362 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
5363 let mut seed = random_init_seed() as usize;
5364 let nodes = graph.read_only().nodes().clone();
5365 'load_endpoints: for _ in 0..10 {
5367 seed = seed.overflowing_mul(0xdeadbeef).0;
5368 let src = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5369 seed = seed.overflowing_mul(0xdeadbeef).0;
5370 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5371 let payment_params = PaymentParameters::from_node_id(dst);
5372 let amt = seed as u64 % 200_000_000;
5373 let params = ProbabilisticScoringParameters::default();
5374 let scorer = ProbabilisticScorer::new(params, &graph, &logger);
5375 if get_route(src, &payment_params, &graph.read_only(), None, amt, 42, &logger, &scorer, &random_seed_bytes).is_ok() {
5376 continue 'load_endpoints;
5383 #[cfg(not(feature = "no-std"))]
5384 fn generate_routes_mpp() {
5385 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringParameters};
5387 let mut d = match super::bench_utils::get_route_file() {
5394 let logger = ln_test_utils::TestLogger::new();
5395 let graph = NetworkGraph::read(&mut d, &logger).unwrap();
5396 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5397 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5399 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
5400 let mut seed = random_init_seed() as usize;
5401 let nodes = graph.read_only().nodes().clone();
5402 'load_endpoints: for _ in 0..10 {
5404 seed = seed.overflowing_mul(0xdeadbeef).0;
5405 let src = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5406 seed = seed.overflowing_mul(0xdeadbeef).0;
5407 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5408 let payment_params = PaymentParameters::from_node_id(dst).with_features(channelmanager::provided_invoice_features());
5409 let amt = seed as u64 % 200_000_000;
5410 let params = ProbabilisticScoringParameters::default();
5411 let scorer = ProbabilisticScorer::new(params, &graph, &logger);
5412 if get_route(src, &payment_params, &graph.read_only(), None, amt, 42, &logger, &scorer, &random_seed_bytes).is_ok() {
5413 continue 'load_endpoints;
5420 fn honors_manual_penalties() {
5421 let (secp_ctx, network_graph, _, _, logger) = build_line_graph();
5422 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5424 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5425 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5427 let scorer_params = ProbabilisticScoringParameters::default();
5428 let mut scorer = ProbabilisticScorer::new(scorer_params, Arc::clone(&network_graph), Arc::clone(&logger));
5430 // First check set manual penalties are returned by the scorer.
5431 let usage = ChannelUsage {
5433 inflight_htlc_msat: 0,
5434 effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_024_000, htlc_maximum_msat: 1_000 },
5436 scorer.set_manual_penalty(&NodeId::from_pubkey(&nodes[3]), 123);
5437 scorer.set_manual_penalty(&NodeId::from_pubkey(&nodes[4]), 456);
5438 assert_eq!(scorer.channel_penalty_msat(42, &NodeId::from_pubkey(&nodes[3]), &NodeId::from_pubkey(&nodes[4]), usage), 456);
5440 // Then check we can get a normal route
5441 let payment_params = PaymentParameters::from_node_id(nodes[10]);
5442 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes);
5443 assert!(route.is_ok());
5445 // Then check that we can't get a route if we ban an intermediate node.
5446 scorer.add_banned(&NodeId::from_pubkey(&nodes[3]));
5447 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes);
5448 assert!(route.is_err());
5450 // Finally make sure we can route again, when we remove the ban.
5451 scorer.remove_banned(&NodeId::from_pubkey(&nodes[3]));
5452 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes);
5453 assert!(route.is_ok());
5457 #[cfg(all(test, not(feature = "no-std")))]
5458 pub(crate) mod bench_utils {
5460 /// Tries to open a network graph file, or panics with a URL to fetch it.
5461 pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
5462 let res = File::open("net_graph-2021-05-31.bin") // By default we're run in RL/lightning
5463 .or_else(|_| File::open("lightning/net_graph-2021-05-31.bin")) // We may be run manually in RL/
5464 .or_else(|_| { // Fall back to guessing based on the binary location
5465 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
5466 let mut path = std::env::current_exe().unwrap();
5467 path.pop(); // lightning-...
5469 path.pop(); // debug
5470 path.pop(); // target
5471 path.push("lightning");
5472 path.push("net_graph-2021-05-31.bin");
5473 eprintln!("{}", path.to_str().unwrap());
5476 .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");
5477 #[cfg(require_route_graph_test)]
5478 return Ok(res.unwrap());
5479 #[cfg(not(require_route_graph_test))]
5484 #[cfg(all(test, feature = "_bench_unstable", not(feature = "no-std")))]
5487 use bitcoin::hashes::Hash;
5488 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
5489 use crate::chain::transaction::OutPoint;
5490 use crate::chain::keysinterface::{KeysManager,KeysInterface};
5491 use crate::ln::channelmanager::{self, ChannelCounterparty, ChannelDetails};
5492 use crate::ln::features::InvoiceFeatures;
5493 use crate::routing::gossip::NetworkGraph;
5494 use crate::routing::scoring::{FixedPenaltyScorer, ProbabilisticScorer, ProbabilisticScoringParameters};
5495 use crate::util::logger::{Logger, Record};
5496 use crate::util::ser::ReadableArgs;
5500 struct DummyLogger {}
5501 impl Logger for DummyLogger {
5502 fn log(&self, _record: &Record) {}
5505 fn read_network_graph(logger: &DummyLogger) -> NetworkGraph<&DummyLogger> {
5506 let mut d = bench_utils::get_route_file().unwrap();
5507 NetworkGraph::read(&mut d, logger).unwrap()
5510 fn payer_pubkey() -> PublicKey {
5511 let secp_ctx = Secp256k1::new();
5512 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
5516 fn first_hop(node_id: PublicKey) -> ChannelDetails {
5518 channel_id: [0; 32],
5519 counterparty: ChannelCounterparty {
5520 features: channelmanager::provided_init_features(),
5522 unspendable_punishment_reserve: 0,
5523 forwarding_info: None,
5524 outbound_htlc_minimum_msat: None,
5525 outbound_htlc_maximum_msat: None,
5527 funding_txo: Some(OutPoint {
5528 txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0
5531 short_channel_id: Some(1),
5532 inbound_scid_alias: None,
5533 outbound_scid_alias: None,
5534 channel_value_satoshis: 10_000_000,
5536 balance_msat: 10_000_000,
5537 outbound_capacity_msat: 10_000_000,
5538 next_outbound_htlc_limit_msat: 10_000_000,
5539 inbound_capacity_msat: 0,
5540 unspendable_punishment_reserve: None,
5541 confirmations_required: None,
5542 force_close_spend_delay: None,
5544 is_channel_ready: true,
5547 inbound_htlc_minimum_msat: None,
5548 inbound_htlc_maximum_msat: None,
5554 fn generate_routes_with_zero_penalty_scorer(bench: &mut Bencher) {
5555 let logger = DummyLogger {};
5556 let network_graph = read_network_graph(&logger);
5557 let scorer = FixedPenaltyScorer::with_penalty(0);
5558 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::empty());
5562 fn generate_mpp_routes_with_zero_penalty_scorer(bench: &mut Bencher) {
5563 let logger = DummyLogger {};
5564 let network_graph = read_network_graph(&logger);
5565 let scorer = FixedPenaltyScorer::with_penalty(0);
5566 generate_routes(bench, &network_graph, scorer, channelmanager::provided_invoice_features());
5570 fn generate_routes_with_probabilistic_scorer(bench: &mut Bencher) {
5571 let logger = DummyLogger {};
5572 let network_graph = read_network_graph(&logger);
5573 let params = ProbabilisticScoringParameters::default();
5574 let scorer = ProbabilisticScorer::new(params, &network_graph, &logger);
5575 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::empty());
5579 fn generate_mpp_routes_with_probabilistic_scorer(bench: &mut Bencher) {
5580 let logger = DummyLogger {};
5581 let network_graph = read_network_graph(&logger);
5582 let params = ProbabilisticScoringParameters::default();
5583 let scorer = ProbabilisticScorer::new(params, &network_graph, &logger);
5584 generate_routes(bench, &network_graph, scorer, channelmanager::provided_invoice_features());
5587 fn generate_routes<S: Score>(
5588 bench: &mut Bencher, graph: &NetworkGraph<&DummyLogger>, mut scorer: S,
5589 features: InvoiceFeatures
5591 let nodes = graph.read_only().nodes().clone();
5592 let payer = payer_pubkey();
5593 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
5594 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5596 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
5597 let mut routes = Vec::new();
5598 let mut route_endpoints = Vec::new();
5599 let mut seed: usize = 0xdeadbeef;
5600 'load_endpoints: for _ in 0..150 {
5603 let src = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5605 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5606 let params = PaymentParameters::from_node_id(dst).with_features(features.clone());
5607 let first_hop = first_hop(src);
5608 let amt = seed as u64 % 1_000_000;
5609 if let Ok(route) = get_route(&payer, ¶ms, &graph.read_only(), Some(&[&first_hop]), amt, 42, &DummyLogger{}, &scorer, &random_seed_bytes) {
5611 route_endpoints.push((first_hop, params, amt));
5612 continue 'load_endpoints;
5617 // ...and seed the scorer with success and failure data...
5618 for route in routes {
5619 let amount = route.get_total_amount();
5620 if amount < 250_000 {
5621 for path in route.paths {
5622 scorer.payment_path_successful(&path.iter().collect::<Vec<_>>());
5624 } else if amount > 750_000 {
5625 for path in route.paths {
5626 let short_channel_id = path[path.len() / 2].short_channel_id;
5627 scorer.payment_path_failed(&path.iter().collect::<Vec<_>>(), short_channel_id);
5632 // Because we've changed channel scores, its possible we'll take different routes to the
5633 // selected destinations, possibly causing us to fail because, eg, the newly-selected path
5634 // requires a too-high CLTV delta.
5635 route_endpoints.retain(|(first_hop, params, amt)| {
5636 get_route(&payer, params, &graph.read_only(), Some(&[first_hop]), *amt, 42, &DummyLogger{}, &scorer, &random_seed_bytes).is_ok()
5638 route_endpoints.truncate(100);
5639 assert_eq!(route_endpoints.len(), 100);
5641 // ...then benchmark finding paths between the nodes we learned.
5644 let (first_hop, params, amt) = &route_endpoints[idx % route_endpoints.len()];
5645 assert!(get_route(&payer, params, &graph.read_only(), Some(&[first_hop]), *amt, 42, &DummyLogger{}, &scorer, &random_seed_bytes).is_ok());