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 legacy onion format, the maximum number of hops used to be a fixed value of 20.
232 // However, in the TLV onion format, there is no fixed maximum length, but the `hop_payloads`
233 // field is always 1300 bytes. As the `tlv_payload` for each hop may vary in length, we have to
234 // estimate how many hops the route may have so that it actually fits the `hop_payloads` field.
236 // We estimate 3+32 (payload length and HMAC) + 2+8 (amt_to_forward) + 2+4 (outgoing_cltv_value) +
237 // 2+8 (short_channel_id) = 61 bytes for each intermediate hop and 3+32
238 // (payload length and HMAC) + 2+8 (amt_to_forward) + 2+4 (outgoing_cltv_value) + 2+32+8
239 // (payment_secret and total_msat) = 93 bytes for the final hop.
240 // Since the length of the potentially included `payment_metadata` is unknown to us, we round
241 // down from (1300-93) / 61 = 19.78... to arrive at a conservative estimate of 19.
242 const MAX_PATH_LENGTH_ESTIMATE: u8 = 19;
244 /// The recipient of a payment.
245 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
246 pub struct PaymentParameters {
247 /// The node id of the payee.
248 pub payee_pubkey: PublicKey,
250 /// Features supported by the payee.
252 /// May be set from the payee's invoice or via [`for_keysend`]. May be `None` if the invoice
253 /// does not contain any features.
255 /// [`for_keysend`]: Self::for_keysend
256 pub features: Option<InvoiceFeatures>,
258 /// Hints for routing to the payee, containing channels connecting the payee to public nodes.
259 pub route_hints: Vec<RouteHint>,
261 /// Expiration of a payment to the payee, in seconds relative to the UNIX epoch.
262 pub expiry_time: Option<u64>,
264 /// The maximum total CLTV delta we accept for the route.
265 /// Defaults to [`DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA`].
266 pub max_total_cltv_expiry_delta: u32,
268 /// The maximum number of paths that may be used by (MPP) payments.
269 /// Defaults to [`DEFAULT_MAX_PATH_COUNT`].
270 pub max_path_count: u8,
272 /// Selects the maximum share of a channel's total capacity which will be sent over a channel,
273 /// as a power of 1/2. A higher value prefers to send the payment using more MPP parts whereas
274 /// a lower value prefers to send larger MPP parts, potentially saturating channels and
275 /// increasing failure probability for those paths.
277 /// Note that this restriction will be relaxed during pathfinding after paths which meet this
278 /// restriction have been found. While paths which meet this criteria will be searched for, it
279 /// is ultimately up to the scorer to select them over other paths.
281 /// A value of 0 will allow payments up to and including a channel's total announced usable
282 /// capacity, a value of one will only use up to half its capacity, two 1/4, etc.
285 pub max_channel_saturation_power_of_half: u8,
287 /// A list of SCIDs which this payment was previously attempted over and which caused the
288 /// payment to fail. Future attempts for the same payment shouldn't be relayed through any of
290 pub previously_failed_channels: Vec<u64>,
293 impl_writeable_tlv_based!(PaymentParameters, {
294 (0, payee_pubkey, required),
295 (1, max_total_cltv_expiry_delta, (default_value, DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA)),
296 (2, features, option),
297 (3, max_path_count, (default_value, DEFAULT_MAX_PATH_COUNT)),
298 (4, route_hints, vec_type),
299 (5, max_channel_saturation_power_of_half, (default_value, 2)),
300 (6, expiry_time, option),
301 (7, previously_failed_channels, vec_type),
304 impl PaymentParameters {
305 /// Creates a payee with the node id of the given `pubkey`.
306 pub fn from_node_id(payee_pubkey: PublicKey) -> Self {
312 max_total_cltv_expiry_delta: DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA,
313 max_path_count: DEFAULT_MAX_PATH_COUNT,
314 max_channel_saturation_power_of_half: 2,
315 previously_failed_channels: Vec::new(),
319 /// Creates a payee with the node id of the given `pubkey` to use for keysend payments.
320 pub fn for_keysend(payee_pubkey: PublicKey) -> Self {
321 Self::from_node_id(payee_pubkey).with_features(InvoiceFeatures::for_keysend())
324 /// Includes the payee's features.
326 /// (C-not exported) since bindings don't support move semantics
327 pub fn with_features(self, features: InvoiceFeatures) -> Self {
328 Self { features: Some(features), ..self }
331 /// Includes hints for routing to the payee.
333 /// (C-not exported) since bindings don't support move semantics
334 pub fn with_route_hints(self, route_hints: Vec<RouteHint>) -> Self {
335 Self { route_hints, ..self }
338 /// Includes a payment expiration in seconds relative to the UNIX epoch.
340 /// (C-not exported) since bindings don't support move semantics
341 pub fn with_expiry_time(self, expiry_time: u64) -> Self {
342 Self { expiry_time: Some(expiry_time), ..self }
345 /// Includes a limit for the total CLTV expiry delta which is considered during routing
347 /// (C-not exported) since bindings don't support move semantics
348 pub fn with_max_total_cltv_expiry_delta(self, max_total_cltv_expiry_delta: u32) -> Self {
349 Self { max_total_cltv_expiry_delta, ..self }
352 /// Includes a limit for the maximum number of payment paths that may be used.
354 /// (C-not exported) since bindings don't support move semantics
355 pub fn with_max_path_count(self, max_path_count: u8) -> Self {
356 Self { max_path_count, ..self }
359 /// Includes a limit for the maximum number of payment paths that may be used.
361 /// (C-not exported) since bindings don't support move semantics
362 pub fn with_max_channel_saturation_power_of_half(self, max_channel_saturation_power_of_half: u8) -> Self {
363 Self { max_channel_saturation_power_of_half, ..self }
367 /// A list of hops along a payment path terminating with a channel to the recipient.
368 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
369 pub struct RouteHint(pub Vec<RouteHintHop>);
371 impl Writeable for RouteHint {
372 fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
373 (self.0.len() as u64).write(writer)?;
374 for hop in self.0.iter() {
381 impl Readable for RouteHint {
382 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
383 let hop_count: u64 = Readable::read(reader)?;
384 let mut hops = Vec::with_capacity(cmp::min(hop_count, 16) as usize);
385 for _ in 0..hop_count {
386 hops.push(Readable::read(reader)?);
392 /// A channel descriptor for a hop along a payment path.
393 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
394 pub struct RouteHintHop {
395 /// The node_id of the non-target end of the route
396 pub src_node_id: PublicKey,
397 /// The short_channel_id of this channel
398 pub short_channel_id: u64,
399 /// The fees which must be paid to use this channel
400 pub fees: RoutingFees,
401 /// The difference in CLTV values between this node and the next node.
402 pub cltv_expiry_delta: u16,
403 /// The minimum value, in msat, which must be relayed to the next hop.
404 pub htlc_minimum_msat: Option<u64>,
405 /// The maximum value in msat available for routing with a single HTLC.
406 pub htlc_maximum_msat: Option<u64>,
409 impl_writeable_tlv_based!(RouteHintHop, {
410 (0, src_node_id, required),
411 (1, htlc_minimum_msat, option),
412 (2, short_channel_id, required),
413 (3, htlc_maximum_msat, option),
415 (6, cltv_expiry_delta, required),
418 #[derive(Eq, PartialEq)]
419 struct RouteGraphNode {
421 lowest_fee_to_peer_through_node: u64,
422 lowest_fee_to_node: u64,
423 total_cltv_delta: u32,
424 // The maximum value a yet-to-be-constructed payment path might flow through this node.
425 // This value is upper-bounded by us by:
426 // - how much is needed for a path being constructed
427 // - how much value can channels following this node (up to the destination) can contribute,
428 // considering their capacity and fees
429 value_contribution_msat: u64,
430 /// The effective htlc_minimum_msat at this hop. If a later hop on the path had a higher HTLC
431 /// minimum, we use it, plus the fees required at each earlier hop to meet it.
432 path_htlc_minimum_msat: u64,
433 /// All penalties incurred from this hop on the way to the destination, as calculated using
435 path_penalty_msat: u64,
436 /// The number of hops walked up to this node.
437 path_length_to_node: u8,
440 impl cmp::Ord for RouteGraphNode {
441 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
442 let other_score = cmp::max(other.lowest_fee_to_peer_through_node, other.path_htlc_minimum_msat)
443 .saturating_add(other.path_penalty_msat);
444 let self_score = cmp::max(self.lowest_fee_to_peer_through_node, self.path_htlc_minimum_msat)
445 .saturating_add(self.path_penalty_msat);
446 other_score.cmp(&self_score).then_with(|| other.node_id.cmp(&self.node_id))
450 impl cmp::PartialOrd for RouteGraphNode {
451 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
452 Some(self.cmp(other))
456 /// A wrapper around the various hop representations.
458 /// Used to construct a [`PathBuildingHop`] and to estimate [`EffectiveCapacity`].
459 #[derive(Clone, Debug)]
460 enum CandidateRouteHop<'a> {
461 /// A hop from the payer, where the outbound liquidity is known.
463 details: &'a ChannelDetails,
465 /// A hop found in the [`ReadOnlyNetworkGraph`], where the channel capacity may be unknown.
467 info: DirectedChannelInfo<'a>,
468 short_channel_id: u64,
470 /// A hop to the payee found in the payment invoice, though not necessarily a direct channel.
472 hint: &'a RouteHintHop,
476 impl<'a> CandidateRouteHop<'a> {
477 fn short_channel_id(&self) -> u64 {
479 CandidateRouteHop::FirstHop { details } => details.get_outbound_payment_scid().unwrap(),
480 CandidateRouteHop::PublicHop { short_channel_id, .. } => *short_channel_id,
481 CandidateRouteHop::PrivateHop { hint } => hint.short_channel_id,
485 // NOTE: This may alloc memory so avoid calling it in a hot code path.
486 fn features(&self) -> ChannelFeatures {
488 CandidateRouteHop::FirstHop { details } => details.counterparty.features.to_context(),
489 CandidateRouteHop::PublicHop { info, .. } => info.channel().features.clone(),
490 CandidateRouteHop::PrivateHop { .. } => ChannelFeatures::empty(),
494 fn cltv_expiry_delta(&self) -> u32 {
496 CandidateRouteHop::FirstHop { .. } => 0,
497 CandidateRouteHop::PublicHop { info, .. } => info.direction().cltv_expiry_delta as u32,
498 CandidateRouteHop::PrivateHop { hint } => hint.cltv_expiry_delta as u32,
502 fn htlc_minimum_msat(&self) -> u64 {
504 CandidateRouteHop::FirstHop { .. } => 0,
505 CandidateRouteHop::PublicHop { info, .. } => info.direction().htlc_minimum_msat,
506 CandidateRouteHop::PrivateHop { hint } => hint.htlc_minimum_msat.unwrap_or(0),
510 fn fees(&self) -> RoutingFees {
512 CandidateRouteHop::FirstHop { .. } => RoutingFees {
513 base_msat: 0, proportional_millionths: 0,
515 CandidateRouteHop::PublicHop { info, .. } => info.direction().fees,
516 CandidateRouteHop::PrivateHop { hint } => hint.fees,
520 fn effective_capacity(&self) -> EffectiveCapacity {
522 CandidateRouteHop::FirstHop { details } => EffectiveCapacity::ExactLiquidity {
523 liquidity_msat: details.next_outbound_htlc_limit_msat,
525 CandidateRouteHop::PublicHop { info, .. } => info.effective_capacity(),
526 CandidateRouteHop::PrivateHop { .. } => EffectiveCapacity::Infinite,
532 fn max_htlc_from_capacity(capacity: EffectiveCapacity, max_channel_saturation_power_of_half: u8) -> u64 {
533 let saturation_shift: u32 = max_channel_saturation_power_of_half as u32;
535 EffectiveCapacity::ExactLiquidity { liquidity_msat } => liquidity_msat,
536 EffectiveCapacity::Infinite => u64::max_value(),
537 EffectiveCapacity::Unknown => EffectiveCapacity::Unknown.as_msat(),
538 EffectiveCapacity::MaximumHTLC { amount_msat } =>
539 amount_msat.checked_shr(saturation_shift).unwrap_or(0),
540 EffectiveCapacity::Total { capacity_msat, htlc_maximum_msat } =>
541 cmp::min(capacity_msat.checked_shr(saturation_shift).unwrap_or(0), htlc_maximum_msat),
545 fn iter_equal<I1: Iterator, I2: Iterator>(mut iter_a: I1, mut iter_b: I2)
546 -> bool where I1::Item: PartialEq<I2::Item> {
548 let a = iter_a.next();
549 let b = iter_b.next();
550 if a.is_none() && b.is_none() { return true; }
551 if a.is_none() || b.is_none() { return false; }
552 if a.unwrap().ne(&b.unwrap()) { return false; }
556 /// It's useful to keep track of the hops associated with the fees required to use them,
557 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
558 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
559 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
561 struct PathBuildingHop<'a> {
562 // Note that this should be dropped in favor of loading it from CandidateRouteHop, but doing so
563 // is a larger refactor and will require careful performance analysis.
565 candidate: CandidateRouteHop<'a>,
568 /// Minimal fees required to route to the source node of the current hop via any of its inbound channels.
569 src_lowest_inbound_fees: RoutingFees,
570 /// All the fees paid *after* this channel on the way to the destination
571 next_hops_fee_msat: u64,
572 /// Fee paid for the use of the current channel (see candidate.fees()).
573 /// The value will be actually deducted from the counterparty balance on the previous link.
574 hop_use_fee_msat: u64,
575 /// Used to compare channels when choosing the for routing.
576 /// Includes paying for the use of a hop and the following hops, as well as
577 /// an estimated cost of reaching this hop.
578 /// Might get stale when fees are recomputed. Primarily for internal use.
580 /// A mirror of the same field in RouteGraphNode. Note that this is only used during the graph
581 /// walk and may be invalid thereafter.
582 path_htlc_minimum_msat: u64,
583 /// All penalties incurred from this channel on the way to the destination, as calculated using
585 path_penalty_msat: u64,
586 /// If we've already processed a node as the best node, we shouldn't process it again. Normally
587 /// we'd just ignore it if we did as all channels would have a higher new fee, but because we
588 /// may decrease the amounts in use as we walk the graph, the actual calculated fee may
589 /// decrease as well. Thus, we have to explicitly track which nodes have been processed and
590 /// avoid processing them again.
592 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
593 // In tests, we apply further sanity checks on cases where we skip nodes we already processed
594 // to ensure it is specifically in cases where the fee has gone down because of a decrease in
595 // value_contribution_msat, which requires tracking it here. See comments below where it is
596 // used for more info.
597 value_contribution_msat: u64,
600 impl<'a> core::fmt::Debug for PathBuildingHop<'a> {
601 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
602 let mut debug_struct = f.debug_struct("PathBuildingHop");
604 .field("node_id", &self.node_id)
605 .field("short_channel_id", &self.candidate.short_channel_id())
606 .field("total_fee_msat", &self.total_fee_msat)
607 .field("next_hops_fee_msat", &self.next_hops_fee_msat)
608 .field("hop_use_fee_msat", &self.hop_use_fee_msat)
609 .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)))
610 .field("path_penalty_msat", &self.path_penalty_msat)
611 .field("path_htlc_minimum_msat", &self.path_htlc_minimum_msat)
612 .field("cltv_expiry_delta", &self.candidate.cltv_expiry_delta());
613 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
614 let debug_struct = debug_struct
615 .field("value_contribution_msat", &self.value_contribution_msat);
616 debug_struct.finish()
620 // Instantiated with a list of hops with correct data in them collected during path finding,
621 // an instance of this struct should be further modified only via given methods.
623 struct PaymentPath<'a> {
624 hops: Vec<(PathBuildingHop<'a>, NodeFeatures)>,
627 impl<'a> PaymentPath<'a> {
628 // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
629 fn get_value_msat(&self) -> u64 {
630 self.hops.last().unwrap().0.fee_msat
633 fn get_path_penalty_msat(&self) -> u64 {
634 self.hops.first().map(|h| h.0.path_penalty_msat).unwrap_or(u64::max_value())
637 fn get_total_fee_paid_msat(&self) -> u64 {
638 if self.hops.len() < 1 {
642 // Can't use next_hops_fee_msat because it gets outdated.
643 for (i, (hop, _)) in self.hops.iter().enumerate() {
644 if i != self.hops.len() - 1 {
645 result += hop.fee_msat;
651 fn get_cost_msat(&self) -> u64 {
652 self.get_total_fee_paid_msat().saturating_add(self.get_path_penalty_msat())
655 // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
656 // to change fees may result in an inconsistency.
658 // Sometimes we call this function right after constructing a path which is inconsistent in
659 // that it the value being transferred has decreased while we were doing path finding, leading
660 // to the fees being paid not lining up with the actual limits.
662 // Note that this function is not aware of the available_liquidity limit, and thus does not
663 // support increasing the value being transferred beyond what was selected during the initial
665 fn update_value_and_recompute_fees(&mut self, value_msat: u64) {
666 let mut total_fee_paid_msat = 0 as u64;
667 for i in (0..self.hops.len()).rev() {
668 let last_hop = i == self.hops.len() - 1;
670 // For non-last-hop, this value will represent the fees paid on the current hop. It
671 // will consist of the fees for the use of the next hop, and extra fees to match
672 // htlc_minimum_msat of the current channel. Last hop is handled separately.
673 let mut cur_hop_fees_msat = 0;
675 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().0.hop_use_fee_msat;
678 let mut cur_hop = &mut self.hops.get_mut(i).unwrap().0;
679 cur_hop.next_hops_fee_msat = total_fee_paid_msat;
680 // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
681 // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
682 // set it too high just to maliciously take more fees by exploiting this
683 // match htlc_minimum_msat logic.
684 let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
685 if let Some(extra_fees_msat) = cur_hop.candidate.htlc_minimum_msat().checked_sub(cur_hop_transferred_amount_msat) {
686 // Note that there is a risk that *previous hops* (those closer to us, as we go
687 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
689 // This might make us end up with a broken route, although this should be super-rare
690 // in practice, both because of how healthy channels look like, and how we pick
691 // channels in add_entry.
692 // Also, this can't be exploited more heavily than *announce a free path and fail
694 cur_hop_transferred_amount_msat += extra_fees_msat;
695 total_fee_paid_msat += extra_fees_msat;
696 cur_hop_fees_msat += extra_fees_msat;
700 // Final hop is a special case: it usually has just value_msat (by design), but also
701 // it still could overpay for the htlc_minimum_msat.
702 cur_hop.fee_msat = cur_hop_transferred_amount_msat;
704 // Propagate updated fees for the use of the channels to one hop back, where they
705 // will be actually paid (fee_msat). The last hop is handled above separately.
706 cur_hop.fee_msat = cur_hop_fees_msat;
709 // Fee for the use of the current hop which will be deducted on the previous hop.
710 // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
711 // this channel is free for us.
713 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.candidate.fees()) {
714 cur_hop.hop_use_fee_msat = new_fee;
715 total_fee_paid_msat += new_fee;
717 // It should not be possible because this function is called only to reduce the
718 // value. In that case, compute_fee was already called with the same fees for
719 // larger amount and there was no overflow.
727 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
728 let proportional_fee_millions =
729 amount_msat.checked_mul(channel_fees.proportional_millionths as u64);
730 if let Some(new_fee) = proportional_fee_millions.and_then(|part| {
731 (channel_fees.base_msat as u64).checked_add(part / 1_000_000) }) {
735 // This function may be (indirectly) called without any verification,
736 // with channel_fees provided by a caller. We should handle it gracefully.
741 /// The default `features` we assume for a node in a route, when no `features` are known about that
744 /// Default features are:
745 /// * variable_length_onion_optional
746 fn default_node_features() -> NodeFeatures {
747 let mut features = NodeFeatures::empty();
748 features.set_variable_length_onion_optional();
752 /// Finds a route from us (payer) to the given target node (payee).
754 /// If the payee provided features in their invoice, they should be provided via `params.payee`.
755 /// Without this, MPP will only be used if the payee's features are available in the network graph.
757 /// Private routing paths between a public node and the target may be included in `params.payee`.
759 /// If some channels aren't announced, it may be useful to fill in `first_hops` with the results
760 /// from [`ChannelManager::list_usable_channels`]. If it is filled in, the view of these channels
761 /// from `network_graph` will be ignored, and only those in `first_hops` will be used.
763 /// The fees on channels from us to the next hop are ignored as they are assumed to all be equal.
764 /// However, the enabled/disabled bit on such channels as well as the `htlc_minimum_msat` /
765 /// `htlc_maximum_msat` *are* checked as they may change based on the receiving node.
769 /// May be used to re-compute a [`Route`] when handling a [`Event::PaymentPathFailed`]. Any
770 /// adjustments to the [`NetworkGraph`] and channel scores should be made prior to calling this
775 /// Panics if first_hops contains channels without short_channel_ids;
776 /// [`ChannelManager::list_usable_channels`] will never include such channels.
778 /// [`ChannelManager::list_usable_channels`]: crate::ln::channelmanager::ChannelManager::list_usable_channels
779 /// [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed
780 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
781 pub fn find_route<L: Deref, GL: Deref, S: Score>(
782 our_node_pubkey: &PublicKey, route_params: &RouteParameters,
783 network_graph: &NetworkGraph<GL>, first_hops: Option<&[&ChannelDetails]>, logger: L,
784 scorer: &S, random_seed_bytes: &[u8; 32]
785 ) -> Result<Route, LightningError>
786 where L::Target: Logger, GL::Target: Logger {
787 let graph_lock = network_graph.read_only();
788 let mut route = get_route(our_node_pubkey, &route_params.payment_params, &graph_lock, first_hops,
789 route_params.final_value_msat, route_params.final_cltv_expiry_delta, logger, scorer,
791 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
795 pub(crate) fn get_route<L: Deref, S: Score>(
796 our_node_pubkey: &PublicKey, payment_params: &PaymentParameters, network_graph: &ReadOnlyNetworkGraph,
797 first_hops: Option<&[&ChannelDetails]>, final_value_msat: u64, final_cltv_expiry_delta: u32,
798 logger: L, scorer: &S, _random_seed_bytes: &[u8; 32]
799 ) -> Result<Route, LightningError>
800 where L::Target: Logger {
801 let payee_node_id = NodeId::from_pubkey(&payment_params.payee_pubkey);
802 let our_node_id = NodeId::from_pubkey(&our_node_pubkey);
804 if payee_node_id == our_node_id {
805 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
808 if final_value_msat > MAX_VALUE_MSAT {
809 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
812 if final_value_msat == 0 {
813 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
816 for route in payment_params.route_hints.iter() {
817 for hop in &route.0 {
818 if hop.src_node_id == payment_params.payee_pubkey {
819 return Err(LightningError{err: "Route hint cannot have the payee as the source.".to_owned(), action: ErrorAction::IgnoreError});
823 if payment_params.max_total_cltv_expiry_delta <= final_cltv_expiry_delta {
824 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});
827 // The general routing idea is the following:
828 // 1. Fill first/last hops communicated by the caller.
829 // 2. Attempt to construct a path from payer to payee for transferring
830 // any ~sufficient (described later) value.
831 // If succeed, remember which channels were used and how much liquidity they have available,
832 // so that future paths don't rely on the same liquidity.
833 // 3. Proceed to the next step if:
834 // - we hit the recommended target value;
835 // - OR if we could not construct a new path. Any next attempt will fail too.
836 // Otherwise, repeat step 2.
837 // 4. See if we managed to collect paths which aggregately are able to transfer target value
838 // (not recommended value).
839 // 5. If yes, proceed. If not, fail routing.
840 // 6. Select the paths which have the lowest cost (fee plus scorer penalty) per amount
841 // transferred up to the transfer target value.
842 // 7. Reduce the value of the last path until we are sending only the target value.
843 // 8. If our maximum channel saturation limit caused us to pick two identical paths, combine
844 // them so that we're not sending two HTLCs along the same path.
846 // As for the actual search algorithm,
847 // we do a payee-to-payer pseudo-Dijkstra's sorting by each node's distance from the payee
848 // plus the minimum per-HTLC fee to get from it to another node (aka "shitty pseudo-A*").
850 // We are not a faithful Dijkstra's implementation because we can change values which impact
851 // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
852 // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) than
853 // the value we are currently attempting to send over a path, we simply reduce the value being
854 // sent along the path for any hops after that channel. This may imply that later fees (which
855 // we've already tabulated) are lower because a smaller value is passing through the channels
856 // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
857 // channels which were selected earlier (and which may still be used for other paths without a
858 // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
861 // One potentially problematic case for this algorithm would be if there are many
862 // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
863 // graph walking), we may never find a path which is not liquidity-limited and has lower
864 // proportional fee (and only lower absolute fee when considering the ultimate value sent).
865 // Because we only consider paths with at least 5% of the total value being sent, the damage
866 // from such a case should be limited, however this could be further reduced in the future by
867 // calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
868 // limits for the purposes of fee calculation.
870 // Alternatively, we could store more detailed path information in the heap (targets, below)
871 // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
872 // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
873 // and practically (as we would need to store dynamically-allocated path information in heap
874 // objects, increasing malloc traffic and indirect memory access significantly). Further, the
875 // results of such an algorithm would likely be biased towards lower-value paths.
877 // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
878 // outside of our current search value, running a path search more times to gather candidate
879 // paths at different values. While this may be acceptable, further path searches may increase
880 // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
881 // graph for candidate paths, calculating the maximum value which can realistically be sent at
882 // the same time, remaining generic across different payment values.
884 // TODO: There are a few tweaks we could do, including possibly pre-calculating more stuff
885 // to use as the A* heuristic beyond just the cost to get one node further than the current
888 let network_channels = network_graph.channels();
889 let network_nodes = network_graph.nodes();
891 if payment_params.max_path_count == 0 {
892 return Err(LightningError{err: "Can't find a route with no paths allowed.".to_owned(), action: ErrorAction::IgnoreError});
895 // Allow MPP only if we have a features set from somewhere that indicates the payee supports
896 // it. If the payee supports it they're supposed to include it in the invoice, so that should
898 let allow_mpp = if payment_params.max_path_count == 1 {
900 } else if let Some(features) = &payment_params.features {
901 features.supports_basic_mpp()
902 } else if let Some(node) = network_nodes.get(&payee_node_id) {
903 if let Some(node_info) = node.announcement_info.as_ref() {
904 node_info.features.supports_basic_mpp()
908 log_trace!(logger, "Searching for a route from payer {} to payee {} {} MPP and {} first hops {}overriding the network graph", our_node_pubkey,
909 payment_params.payee_pubkey, if allow_mpp { "with" } else { "without" },
910 first_hops.map(|hops| hops.len()).unwrap_or(0), if first_hops.is_some() { "" } else { "not " });
913 // Prepare the data we'll use for payee-to-payer search by
914 // inserting first hops suggested by the caller as targets.
915 // Our search will then attempt to reach them while traversing from the payee node.
916 let mut first_hop_targets: HashMap<_, Vec<&ChannelDetails>> =
917 HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
918 if let Some(hops) = first_hops {
920 if chan.get_outbound_payment_scid().is_none() {
921 panic!("first_hops should be filled in with usable channels, not pending ones");
923 if chan.counterparty.node_id == *our_node_pubkey {
924 return Err(LightningError{err: "First hop cannot have our_node_pubkey as a destination.".to_owned(), action: ErrorAction::IgnoreError});
927 .entry(NodeId::from_pubkey(&chan.counterparty.node_id))
928 .or_insert(Vec::new())
931 if first_hop_targets.is_empty() {
932 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
936 // The main heap containing all candidate next-hops sorted by their score (max(A* fee,
937 // htlc_minimum)). Ideally this would be a heap which allowed cheap score reduction instead of
938 // adding duplicate entries when we find a better path to a given node.
939 let mut targets: BinaryHeap<RouteGraphNode> = BinaryHeap::new();
941 // Map from node_id to information about the best current path to that node, including feerate
943 let mut dist: HashMap<NodeId, PathBuildingHop> = HashMap::with_capacity(network_nodes.len());
945 // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
946 // indicating that we may wish to try again with a higher value, potentially paying to meet an
947 // htlc_minimum with extra fees while still finding a cheaper path.
948 let mut hit_minimum_limit;
950 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
951 // We start with a path_value of the exact amount we want, and if that generates a route we may
952 // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
953 // amount we want in total across paths, selecting the best subset at the end.
954 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
955 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
956 let mut path_value_msat = final_value_msat;
958 // Routing Fragmentation Mitigation heuristic:
960 // Routing fragmentation across many payment paths increases the overall routing
961 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
962 // Taking too many smaller paths also increases the chance of payment failure.
963 // Thus to avoid this effect, we require from our collected links to provide
964 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
965 // This requirement is currently set to be 1/max_path_count of the payment
966 // value to ensure we only ever return routes that do not violate this limit.
967 let minimal_value_contribution_msat: u64 = if allow_mpp {
968 (final_value_msat + (payment_params.max_path_count as u64 - 1)) / payment_params.max_path_count as u64
973 // When we start collecting routes we enforce the max_channel_saturation_power_of_half
974 // requirement strictly. After we've collected enough (or if we fail to find new routes) we
975 // drop the requirement by setting this to 0.
976 let mut channel_saturation_pow_half = payment_params.max_channel_saturation_power_of_half;
978 // Keep track of how much liquidity has been used in selected channels. Used to determine
979 // if the channel can be used by additional MPP paths or to inform path finding decisions. It is
980 // aware of direction *only* to ensure that the correct htlc_maximum_msat value is used. Hence,
981 // liquidity used in one direction will not offset any used in the opposite direction.
982 let mut used_channel_liquidities: HashMap<(u64, bool), u64> =
983 HashMap::with_capacity(network_nodes.len());
985 // Keeping track of how much value we already collected across other paths. Helps to decide
986 // when we want to stop looking for new paths.
987 let mut already_collected_value_msat = 0;
989 for (_, channels) in first_hop_targets.iter_mut() {
990 // Sort the first_hops channels to the same node(s) in priority order of which channel we'd
993 // First, if channels are below `recommended_value_msat`, sort them in descending order,
994 // preferring larger channels to avoid splitting the payment into more MPP parts than is
997 // Second, because simply always sorting in descending order would always use our largest
998 // available outbound capacity, needlessly fragmenting our available channel capacities,
999 // sort channels above `recommended_value_msat` in ascending order, preferring channels
1000 // which have enough, but not too much, capacity for the payment.
1001 channels.sort_unstable_by(|chan_a, chan_b| {
1002 if chan_b.next_outbound_htlc_limit_msat < recommended_value_msat || chan_a.next_outbound_htlc_limit_msat < recommended_value_msat {
1003 // Sort in descending order
1004 chan_b.next_outbound_htlc_limit_msat.cmp(&chan_a.next_outbound_htlc_limit_msat)
1006 // Sort in ascending order
1007 chan_a.next_outbound_htlc_limit_msat.cmp(&chan_b.next_outbound_htlc_limit_msat)
1012 log_trace!(logger, "Building path from {} (payee) to {} (us/payer) for value {} msat.", payment_params.payee_pubkey, our_node_pubkey, final_value_msat);
1014 macro_rules! add_entry {
1015 // Adds entry which goes from $src_node_id to $dest_node_id over the $candidate hop.
1016 // $next_hops_fee_msat represents the fees paid for using all the channels *after* this one,
1017 // since that value has to be transferred over this channel.
1018 // Returns whether this channel caused an update to `targets`.
1019 ( $candidate: expr, $src_node_id: expr, $dest_node_id: expr, $next_hops_fee_msat: expr,
1020 $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr,
1021 $next_hops_path_penalty_msat: expr, $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => { {
1022 // We "return" whether we updated the path at the end, via this:
1023 let mut did_add_update_path_to_src_node = false;
1024 // Channels to self should not be used. This is more of belt-and-suspenders, because in
1025 // practice these cases should be caught earlier:
1026 // - for regular channels at channel announcement (TODO)
1027 // - for first and last hops early in get_route
1028 if $src_node_id != $dest_node_id {
1029 let short_channel_id = $candidate.short_channel_id();
1030 let effective_capacity = $candidate.effective_capacity();
1031 let htlc_maximum_msat = max_htlc_from_capacity(effective_capacity, channel_saturation_pow_half);
1033 // It is tricky to subtract $next_hops_fee_msat from available liquidity here.
1034 // It may be misleading because we might later choose to reduce the value transferred
1035 // over these channels, and the channel which was insufficient might become sufficient.
1036 // Worst case: we drop a good channel here because it can't cover the high following
1037 // fees caused by one expensive channel, but then this channel could have been used
1038 // if the amount being transferred over this path is lower.
1039 // We do this for now, but this is a subject for removal.
1040 if let Some(mut available_value_contribution_msat) = htlc_maximum_msat.checked_sub($next_hops_fee_msat) {
1041 let used_liquidity_msat = used_channel_liquidities
1042 .get(&(short_channel_id, $src_node_id < $dest_node_id))
1043 .map_or(0, |used_liquidity_msat| {
1044 available_value_contribution_msat = available_value_contribution_msat
1045 .saturating_sub(*used_liquidity_msat);
1046 *used_liquidity_msat
1049 // Verify the liquidity offered by this channel complies to the minimal contribution.
1050 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
1051 // Do not consider candidate hops that would exceed the maximum path length.
1052 let path_length_to_node = $next_hops_path_length + 1;
1053 let exceeds_max_path_length = path_length_to_node > MAX_PATH_LENGTH_ESTIMATE;
1055 // Do not consider candidates that exceed the maximum total cltv expiry limit.
1056 // In order to already account for some of the privacy enhancing random CLTV
1057 // expiry delta offset we add on top later, we subtract a rough estimate
1058 // (2*MEDIAN_HOP_CLTV_EXPIRY_DELTA) here.
1059 let max_total_cltv_expiry_delta = (payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta)
1060 .checked_sub(2*MEDIAN_HOP_CLTV_EXPIRY_DELTA)
1061 .unwrap_or(payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta);
1062 let hop_total_cltv_delta = ($next_hops_cltv_delta as u32)
1063 .saturating_add($candidate.cltv_expiry_delta());
1064 let exceeds_cltv_delta_limit = hop_total_cltv_delta > max_total_cltv_expiry_delta;
1066 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
1067 // Includes paying fees for the use of the following channels.
1068 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
1069 Some(result) => result,
1070 // Can't overflow due to how the values were computed right above.
1071 None => unreachable!(),
1073 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
1074 let over_path_minimum_msat = amount_to_transfer_over_msat >= $candidate.htlc_minimum_msat() &&
1075 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
1077 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
1078 let may_overpay_to_meet_path_minimum_msat =
1079 ((amount_to_transfer_over_msat < $candidate.htlc_minimum_msat() &&
1080 recommended_value_msat > $candidate.htlc_minimum_msat()) ||
1081 (amount_to_transfer_over_msat < $next_hops_path_htlc_minimum_msat &&
1082 recommended_value_msat > $next_hops_path_htlc_minimum_msat));
1084 let payment_failed_on_this_channel =
1085 payment_params.previously_failed_channels.contains(&short_channel_id);
1087 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
1088 // bother considering this channel. If retrying with recommended_value_msat may
1089 // allow us to hit the HTLC minimum limit, set htlc_minimum_limit so that we go
1090 // around again with a higher amount.
1091 if !contributes_sufficient_value || exceeds_max_path_length ||
1092 exceeds_cltv_delta_limit || payment_failed_on_this_channel {
1093 // Path isn't useful, ignore it and move on.
1094 } else if may_overpay_to_meet_path_minimum_msat {
1095 hit_minimum_limit = true;
1096 } else if over_path_minimum_msat {
1097 // Note that low contribution here (limited by available_liquidity_msat)
1098 // might violate htlc_minimum_msat on the hops which are next along the
1099 // payment path (upstream to the payee). To avoid that, we recompute
1100 // path fees knowing the final path contribution after constructing it.
1101 let path_htlc_minimum_msat = compute_fees($next_hops_path_htlc_minimum_msat, $candidate.fees())
1102 .and_then(|fee_msat| fee_msat.checked_add($next_hops_path_htlc_minimum_msat))
1103 .map(|fee_msat| cmp::max(fee_msat, $candidate.htlc_minimum_msat()))
1104 .unwrap_or_else(|| u64::max_value());
1105 let hm_entry = dist.entry($src_node_id);
1106 let old_entry = hm_entry.or_insert_with(|| {
1107 // If there was previously no known way to access the source node
1108 // (recall it goes payee-to-payer) of short_channel_id, first add a
1109 // semi-dummy record just to compute the fees to reach the source node.
1110 // This will affect our decision on selecting short_channel_id
1111 // as a way to reach the $dest_node_id.
1112 let mut fee_base_msat = 0;
1113 let mut fee_proportional_millionths = 0;
1114 if let Some(Some(fees)) = network_nodes.get(&$src_node_id).map(|node| node.lowest_inbound_channel_fees) {
1115 fee_base_msat = fees.base_msat;
1116 fee_proportional_millionths = fees.proportional_millionths;
1119 node_id: $dest_node_id.clone(),
1120 candidate: $candidate.clone(),
1122 src_lowest_inbound_fees: RoutingFees {
1123 base_msat: fee_base_msat,
1124 proportional_millionths: fee_proportional_millionths,
1126 next_hops_fee_msat: u64::max_value(),
1127 hop_use_fee_msat: u64::max_value(),
1128 total_fee_msat: u64::max_value(),
1129 path_htlc_minimum_msat,
1130 path_penalty_msat: u64::max_value(),
1131 was_processed: false,
1132 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
1133 value_contribution_msat,
1137 #[allow(unused_mut)] // We only use the mut in cfg(test)
1138 let mut should_process = !old_entry.was_processed;
1139 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
1141 // In test/fuzzing builds, we do extra checks to make sure the skipping
1142 // of already-seen nodes only happens in cases we expect (see below).
1143 if !should_process { should_process = true; }
1147 let mut hop_use_fee_msat = 0;
1148 let mut total_fee_msat = $next_hops_fee_msat;
1150 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
1151 // will have the same effective-fee
1152 if $src_node_id != our_node_id {
1153 match compute_fees(amount_to_transfer_over_msat, $candidate.fees()) {
1154 // max_value means we'll always fail
1155 // the old_entry.total_fee_msat > total_fee_msat check
1156 None => total_fee_msat = u64::max_value(),
1158 hop_use_fee_msat = fee_msat;
1159 total_fee_msat += hop_use_fee_msat;
1160 // When calculating the lowest inbound fees to a node, we
1161 // calculate fees here not based on the actual value we think
1162 // will flow over this channel, but on the minimum value that
1163 // we'll accept flowing over it. The minimum accepted value
1164 // is a constant through each path collection run, ensuring
1165 // consistent basis. Otherwise we may later find a
1166 // different path to the source node that is more expensive,
1167 // but which we consider to be cheaper because we are capacity
1168 // constrained and the relative fee becomes lower.
1169 match compute_fees(minimal_value_contribution_msat, old_entry.src_lowest_inbound_fees)
1170 .map(|a| a.checked_add(total_fee_msat)) {
1175 total_fee_msat = u64::max_value();
1182 let channel_usage = ChannelUsage {
1183 amount_msat: amount_to_transfer_over_msat,
1184 inflight_htlc_msat: used_liquidity_msat,
1187 let channel_penalty_msat = scorer.channel_penalty_msat(
1188 short_channel_id, &$src_node_id, &$dest_node_id, channel_usage
1190 let path_penalty_msat = $next_hops_path_penalty_msat
1191 .saturating_add(channel_penalty_msat);
1192 let new_graph_node = RouteGraphNode {
1193 node_id: $src_node_id,
1194 lowest_fee_to_peer_through_node: total_fee_msat,
1195 lowest_fee_to_node: $next_hops_fee_msat as u64 + hop_use_fee_msat,
1196 total_cltv_delta: hop_total_cltv_delta,
1197 value_contribution_msat,
1198 path_htlc_minimum_msat,
1200 path_length_to_node,
1203 // Update the way of reaching $src_node_id with the given short_channel_id (from $dest_node_id),
1204 // if this way is cheaper than the already known
1205 // (considering the cost to "reach" this channel from the route destination,
1206 // the cost of using this channel,
1207 // and the cost of routing to the source node of this channel).
1208 // Also, consider that htlc_minimum_msat_difference, because we might end up
1209 // paying it. Consider the following exploit:
1210 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
1211 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
1212 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
1213 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
1215 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
1216 // but it may require additional tracking - we don't want to double-count
1217 // the fees included in $next_hops_path_htlc_minimum_msat, but also
1218 // can't use something that may decrease on future hops.
1219 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat)
1220 .saturating_add(old_entry.path_penalty_msat);
1221 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat)
1222 .saturating_add(path_penalty_msat);
1224 if !old_entry.was_processed && new_cost < old_cost {
1225 targets.push(new_graph_node);
1226 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
1227 old_entry.hop_use_fee_msat = hop_use_fee_msat;
1228 old_entry.total_fee_msat = total_fee_msat;
1229 old_entry.node_id = $dest_node_id.clone();
1230 old_entry.candidate = $candidate.clone();
1231 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
1232 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
1233 old_entry.path_penalty_msat = path_penalty_msat;
1234 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
1236 old_entry.value_contribution_msat = value_contribution_msat;
1238 did_add_update_path_to_src_node = true;
1239 } else if old_entry.was_processed && new_cost < old_cost {
1240 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
1242 // If we're skipping processing a node which was previously
1243 // processed even though we found another path to it with a
1244 // cheaper fee, check that it was because the second path we
1245 // found (which we are processing now) has a lower value
1246 // contribution due to an HTLC minimum limit.
1248 // e.g. take a graph with two paths from node 1 to node 2, one
1249 // through channel A, and one through channel B. Channel A and
1250 // B are both in the to-process heap, with their scores set by
1251 // a higher htlc_minimum than fee.
1252 // Channel A is processed first, and the channels onwards from
1253 // node 1 are added to the to-process heap. Thereafter, we pop
1254 // Channel B off of the heap, note that it has a much more
1255 // restrictive htlc_maximum_msat, and recalculate the fees for
1256 // all of node 1's channels using the new, reduced, amount.
1258 // This would be bogus - we'd be selecting a higher-fee path
1259 // with a lower htlc_maximum_msat instead of the one we'd
1260 // already decided to use.
1261 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
1263 value_contribution_msat + path_penalty_msat <
1264 old_entry.value_contribution_msat + old_entry.path_penalty_msat
1272 did_add_update_path_to_src_node
1276 let default_node_features = default_node_features();
1278 // Find ways (channels with destination) to reach a given node and store them
1279 // in the corresponding data structures (routing graph etc).
1280 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
1281 // meaning how much will be paid in fees after this node (to the best of our knowledge).
1282 // This data can later be helpful to optimize routing (pay lower fees).
1283 macro_rules! add_entries_to_cheapest_to_target_node {
1284 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr, $next_hops_value_contribution: expr,
1285 $next_hops_path_htlc_minimum_msat: expr, $next_hops_path_penalty_msat: expr,
1286 $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => {
1287 let skip_node = if let Some(elem) = dist.get_mut(&$node_id) {
1288 let was_processed = elem.was_processed;
1289 elem.was_processed = true;
1292 // Entries are added to dist in add_entry!() when there is a channel from a node.
1293 // Because there are no channels from payee, it will not have a dist entry at this point.
1294 // If we're processing any other node, it is always be the result of a channel from it.
1295 assert_eq!($node_id, payee_node_id);
1300 if let Some(first_channels) = first_hop_targets.get(&$node_id) {
1301 for details in first_channels {
1302 let candidate = CandidateRouteHop::FirstHop { details };
1303 add_entry!(candidate, our_node_id, $node_id, $fee_to_target_msat,
1304 $next_hops_value_contribution,
1305 $next_hops_path_htlc_minimum_msat, $next_hops_path_penalty_msat,
1306 $next_hops_cltv_delta, $next_hops_path_length);
1310 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
1313 &default_node_features
1316 if !features.requires_unknown_bits() {
1317 for chan_id in $node.channels.iter() {
1318 let chan = network_channels.get(chan_id).unwrap();
1319 if !chan.features.requires_unknown_bits() {
1320 if let Some((directed_channel, source)) = chan.as_directed_to(&$node_id) {
1321 if first_hops.is_none() || *source != our_node_id {
1322 if directed_channel.direction().enabled {
1323 let candidate = CandidateRouteHop::PublicHop {
1324 info: directed_channel,
1325 short_channel_id: *chan_id,
1327 add_entry!(candidate, *source, $node_id,
1328 $fee_to_target_msat,
1329 $next_hops_value_contribution,
1330 $next_hops_path_htlc_minimum_msat,
1331 $next_hops_path_penalty_msat,
1332 $next_hops_cltv_delta, $next_hops_path_length);
1343 let mut payment_paths = Vec::<PaymentPath>::new();
1345 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
1346 'paths_collection: loop {
1347 // For every new path, start from scratch, except for used_channel_liquidities, which
1348 // helps to avoid reusing previously selected paths in future iterations.
1351 hit_minimum_limit = false;
1353 // If first hop is a private channel and the only way to reach the payee, this is the only
1354 // place where it could be added.
1355 if let Some(first_channels) = first_hop_targets.get(&payee_node_id) {
1356 for details in first_channels {
1357 let candidate = CandidateRouteHop::FirstHop { details };
1358 let added = add_entry!(candidate, our_node_id, payee_node_id, 0, path_value_msat,
1360 log_trace!(logger, "{} direct route to payee via SCID {}",
1361 if added { "Added" } else { "Skipped" }, candidate.short_channel_id());
1365 // Add the payee as a target, so that the payee-to-payer
1366 // search algorithm knows what to start with.
1367 match network_nodes.get(&payee_node_id) {
1368 // The payee is not in our network graph, so nothing to add here.
1369 // There is still a chance of reaching them via last_hops though,
1370 // so don't yet fail the payment here.
1371 // If not, targets.pop() will not even let us enter the loop in step 2.
1374 add_entries_to_cheapest_to_target_node!(node, payee_node_id, 0, path_value_msat, 0, 0u64, 0, 0);
1379 // If a caller provided us with last hops, add them to routing targets. Since this happens
1380 // earlier than general path finding, they will be somewhat prioritized, although currently
1381 // it matters only if the fees are exactly the same.
1382 for route in payment_params.route_hints.iter().filter(|route| !route.0.is_empty()) {
1383 let first_hop_in_route = &(route.0)[0];
1384 let have_hop_src_in_graph =
1385 // Only add the hops in this route to our candidate set if either
1386 // we have a direct channel to the first hop or the first hop is
1387 // in the regular network graph.
1388 first_hop_targets.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some() ||
1389 network_nodes.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some();
1390 if have_hop_src_in_graph {
1391 // We start building the path from reverse, i.e., from payee
1392 // to the first RouteHintHop in the path.
1393 let hop_iter = route.0.iter().rev();
1394 let prev_hop_iter = core::iter::once(&payment_params.payee_pubkey).chain(
1395 route.0.iter().skip(1).rev().map(|hop| &hop.src_node_id));
1396 let mut hop_used = true;
1397 let mut aggregate_next_hops_fee_msat: u64 = 0;
1398 let mut aggregate_next_hops_path_htlc_minimum_msat: u64 = 0;
1399 let mut aggregate_next_hops_path_penalty_msat: u64 = 0;
1400 let mut aggregate_next_hops_cltv_delta: u32 = 0;
1401 let mut aggregate_next_hops_path_length: u8 = 0;
1403 for (idx, (hop, prev_hop_id)) in hop_iter.zip(prev_hop_iter).enumerate() {
1404 let source = NodeId::from_pubkey(&hop.src_node_id);
1405 let target = NodeId::from_pubkey(&prev_hop_id);
1406 let candidate = network_channels
1407 .get(&hop.short_channel_id)
1408 .and_then(|channel| channel.as_directed_to(&target))
1409 .map(|(info, _)| CandidateRouteHop::PublicHop {
1411 short_channel_id: hop.short_channel_id,
1413 .unwrap_or_else(|| CandidateRouteHop::PrivateHop { hint: hop });
1415 if !add_entry!(candidate, source, target, aggregate_next_hops_fee_msat,
1416 path_value_msat, aggregate_next_hops_path_htlc_minimum_msat,
1417 aggregate_next_hops_path_penalty_msat,
1418 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length) {
1419 // If this hop was not used then there is no use checking the preceding
1420 // hops in the RouteHint. We can break by just searching for a direct
1421 // channel between last checked hop and first_hop_targets.
1425 let used_liquidity_msat = used_channel_liquidities
1426 .get(&(hop.short_channel_id, source < target)).copied().unwrap_or(0);
1427 let channel_usage = ChannelUsage {
1428 amount_msat: final_value_msat + aggregate_next_hops_fee_msat,
1429 inflight_htlc_msat: used_liquidity_msat,
1430 effective_capacity: candidate.effective_capacity(),
1432 let channel_penalty_msat = scorer.channel_penalty_msat(
1433 hop.short_channel_id, &source, &target, channel_usage
1435 aggregate_next_hops_path_penalty_msat = aggregate_next_hops_path_penalty_msat
1436 .saturating_add(channel_penalty_msat);
1438 aggregate_next_hops_cltv_delta = aggregate_next_hops_cltv_delta
1439 .saturating_add(hop.cltv_expiry_delta as u32);
1441 aggregate_next_hops_path_length = aggregate_next_hops_path_length
1444 // Searching for a direct channel between last checked hop and first_hop_targets
1445 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&prev_hop_id)) {
1446 for details in first_channels {
1447 let candidate = CandidateRouteHop::FirstHop { details };
1448 add_entry!(candidate, our_node_id, NodeId::from_pubkey(&prev_hop_id),
1449 aggregate_next_hops_fee_msat, path_value_msat,
1450 aggregate_next_hops_path_htlc_minimum_msat,
1451 aggregate_next_hops_path_penalty_msat, aggregate_next_hops_cltv_delta,
1452 aggregate_next_hops_path_length);
1460 // In the next values of the iterator, the aggregate fees already reflects
1461 // the sum of value sent from payer (final_value_msat) and routing fees
1462 // for the last node in the RouteHint. We need to just add the fees to
1463 // route through the current node so that the preceding node (next iteration)
1465 let hops_fee = compute_fees(aggregate_next_hops_fee_msat + final_value_msat, hop.fees)
1466 .map_or(None, |inc| inc.checked_add(aggregate_next_hops_fee_msat));
1467 aggregate_next_hops_fee_msat = if let Some(val) = hops_fee { val } else { break; };
1469 let hop_htlc_minimum_msat = candidate.htlc_minimum_msat();
1470 let hop_htlc_minimum_msat_inc = if let Some(val) = compute_fees(aggregate_next_hops_path_htlc_minimum_msat, hop.fees) { val } else { break; };
1471 let hops_path_htlc_minimum = aggregate_next_hops_path_htlc_minimum_msat
1472 .checked_add(hop_htlc_minimum_msat_inc);
1473 aggregate_next_hops_path_htlc_minimum_msat = if let Some(val) = hops_path_htlc_minimum { cmp::max(hop_htlc_minimum_msat, val) } else { break; };
1475 if idx == route.0.len() - 1 {
1476 // The last hop in this iterator is the first hop in
1477 // overall RouteHint.
1478 // If this hop connects to a node with which we have a direct channel,
1479 // ignore the network graph and, if the last hop was added, add our
1480 // direct channel to the candidate set.
1482 // Note that we *must* check if the last hop was added as `add_entry`
1483 // always assumes that the third argument is a node to which we have a
1485 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&hop.src_node_id)) {
1486 for details in first_channels {
1487 let candidate = CandidateRouteHop::FirstHop { details };
1488 add_entry!(candidate, our_node_id,
1489 NodeId::from_pubkey(&hop.src_node_id),
1490 aggregate_next_hops_fee_msat, path_value_msat,
1491 aggregate_next_hops_path_htlc_minimum_msat,
1492 aggregate_next_hops_path_penalty_msat,
1493 aggregate_next_hops_cltv_delta,
1494 aggregate_next_hops_path_length);
1502 log_trace!(logger, "Starting main path collection loop with {} nodes pre-filled from first/last hops.", targets.len());
1504 // At this point, targets are filled with the data from first and
1505 // last hops communicated by the caller, and the payment receiver.
1506 let mut found_new_path = false;
1509 // If this loop terminates due the exhaustion of targets, two situations are possible:
1510 // - not enough outgoing liquidity:
1511 // 0 < already_collected_value_msat < final_value_msat
1512 // - enough outgoing liquidity:
1513 // final_value_msat <= already_collected_value_msat < recommended_value_msat
1514 // Both these cases (and other cases except reaching recommended_value_msat) mean that
1515 // paths_collection will be stopped because found_new_path==false.
1516 // This is not necessarily a routing failure.
1517 '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() {
1519 // Since we're going payee-to-payer, hitting our node as a target means we should stop
1520 // traversing the graph and arrange the path out of what we found.
1521 if node_id == our_node_id {
1522 let mut new_entry = dist.remove(&our_node_id).unwrap();
1523 let mut ordered_hops: Vec<(PathBuildingHop, NodeFeatures)> = vec!((new_entry.clone(), default_node_features.clone()));
1526 let mut features_set = false;
1527 if let Some(first_channels) = first_hop_targets.get(&ordered_hops.last().unwrap().0.node_id) {
1528 for details in first_channels {
1529 if details.get_outbound_payment_scid().unwrap() == ordered_hops.last().unwrap().0.candidate.short_channel_id() {
1530 ordered_hops.last_mut().unwrap().1 = details.counterparty.features.to_context();
1531 features_set = true;
1537 if let Some(node) = network_nodes.get(&ordered_hops.last().unwrap().0.node_id) {
1538 if let Some(node_info) = node.announcement_info.as_ref() {
1539 ordered_hops.last_mut().unwrap().1 = node_info.features.clone();
1541 ordered_hops.last_mut().unwrap().1 = default_node_features.clone();
1544 // We can fill in features for everything except hops which were
1545 // provided via the invoice we're paying. We could guess based on the
1546 // recipient's features but for now we simply avoid guessing at all.
1550 // Means we succesfully traversed from the payer to the payee, now
1551 // save this path for the payment route. Also, update the liquidity
1552 // remaining on the used hops, so that we take them into account
1553 // while looking for more paths.
1554 if ordered_hops.last().unwrap().0.node_id == payee_node_id {
1558 new_entry = match dist.remove(&ordered_hops.last().unwrap().0.node_id) {
1559 Some(payment_hop) => payment_hop,
1560 // We can't arrive at None because, if we ever add an entry to targets,
1561 // we also fill in the entry in dist (see add_entry!).
1562 None => unreachable!(),
1564 // We "propagate" the fees one hop backward (topologically) here,
1565 // so that fees paid for a HTLC forwarding on the current channel are
1566 // associated with the previous channel (where they will be subtracted).
1567 ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
1568 ordered_hops.push((new_entry.clone(), default_node_features.clone()));
1570 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
1571 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
1573 log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: \n {:#?}",
1574 ordered_hops.len(), value_contribution_msat, ordered_hops.iter().map(|h| &(h.0)).collect::<Vec<&PathBuildingHop>>());
1576 let mut payment_path = PaymentPath {hops: ordered_hops};
1578 // We could have possibly constructed a slightly inconsistent path: since we reduce
1579 // value being transferred along the way, we could have violated htlc_minimum_msat
1580 // on some channels we already passed (assuming dest->source direction). Here, we
1581 // recompute the fees again, so that if that's the case, we match the currently
1582 // underpaid htlc_minimum_msat with fees.
1583 debug_assert_eq!(payment_path.get_value_msat(), value_contribution_msat);
1584 value_contribution_msat = cmp::min(value_contribution_msat, final_value_msat);
1585 payment_path.update_value_and_recompute_fees(value_contribution_msat);
1587 // Since a path allows to transfer as much value as
1588 // the smallest channel it has ("bottleneck"), we should recompute
1589 // the fees so sender HTLC don't overpay fees when traversing
1590 // larger channels than the bottleneck. This may happen because
1591 // when we were selecting those channels we were not aware how much value
1592 // this path will transfer, and the relative fee for them
1593 // might have been computed considering a larger value.
1594 // Remember that we used these channels so that we don't rely
1595 // on the same liquidity in future paths.
1596 let mut prevented_redundant_path_selection = false;
1597 let prev_hop_iter = core::iter::once(&our_node_id)
1598 .chain(payment_path.hops.iter().map(|(hop, _)| &hop.node_id));
1599 for (prev_hop, (hop, _)) in prev_hop_iter.zip(payment_path.hops.iter()) {
1600 let spent_on_hop_msat = value_contribution_msat + hop.next_hops_fee_msat;
1601 let used_liquidity_msat = used_channel_liquidities
1602 .entry((hop.candidate.short_channel_id(), *prev_hop < hop.node_id))
1603 .and_modify(|used_liquidity_msat| *used_liquidity_msat += spent_on_hop_msat)
1604 .or_insert(spent_on_hop_msat);
1605 let hop_capacity = hop.candidate.effective_capacity();
1606 let hop_max_msat = max_htlc_from_capacity(hop_capacity, channel_saturation_pow_half);
1607 if *used_liquidity_msat == hop_max_msat {
1608 // If this path used all of this channel's available liquidity, we know
1609 // this path will not be selected again in the next loop iteration.
1610 prevented_redundant_path_selection = true;
1612 debug_assert!(*used_liquidity_msat <= hop_max_msat);
1614 if !prevented_redundant_path_selection {
1615 // If we weren't capped by hitting a liquidity limit on a channel in the path,
1616 // we'll probably end up picking the same path again on the next iteration.
1617 // Decrease the available liquidity of a hop in the middle of the path.
1618 let victim_scid = payment_path.hops[(payment_path.hops.len()) / 2].0.candidate.short_channel_id();
1619 let exhausted = u64::max_value();
1620 log_trace!(logger, "Disabling channel {} for future path building iterations to avoid duplicates.", victim_scid);
1621 *used_channel_liquidities.entry((victim_scid, false)).or_default() = exhausted;
1622 *used_channel_liquidities.entry((victim_scid, true)).or_default() = exhausted;
1625 // Track the total amount all our collected paths allow to send so that we know
1626 // when to stop looking for more paths
1627 already_collected_value_msat += value_contribution_msat;
1629 payment_paths.push(payment_path);
1630 found_new_path = true;
1631 break 'path_construction;
1634 // If we found a path back to the payee, we shouldn't try to process it again. This is
1635 // the equivalent of the `elem.was_processed` check in
1636 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
1637 if node_id == payee_node_id { continue 'path_construction; }
1639 // Otherwise, since the current target node is not us,
1640 // keep "unrolling" the payment graph from payee to payer by
1641 // finding a way to reach the current target from the payer side.
1642 match network_nodes.get(&node_id) {
1645 add_entries_to_cheapest_to_target_node!(node, node_id, lowest_fee_to_node,
1646 value_contribution_msat, path_htlc_minimum_msat, path_penalty_msat,
1647 total_cltv_delta, path_length_to_node);
1653 if !found_new_path && channel_saturation_pow_half != 0 {
1654 channel_saturation_pow_half = 0;
1655 continue 'paths_collection;
1657 // If we don't support MPP, no use trying to gather more value ever.
1658 break 'paths_collection;
1662 // Stop either when the recommended value is reached or if no new path was found in this
1664 // In the latter case, making another path finding attempt won't help,
1665 // because we deterministically terminated the search due to low liquidity.
1666 if !found_new_path && channel_saturation_pow_half != 0 {
1667 channel_saturation_pow_half = 0;
1668 } else if already_collected_value_msat >= recommended_value_msat || !found_new_path {
1669 log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
1670 already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
1671 break 'paths_collection;
1672 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
1673 // Further, if this was our first walk of the graph, and we weren't limited by an
1674 // htlc_minimum_msat, return immediately because this path should suffice. If we were
1675 // limited by an htlc_minimum_msat value, find another path with a higher value,
1676 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
1677 // still keeping a lower total fee than this path.
1678 if !hit_minimum_limit {
1679 log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
1680 break 'paths_collection;
1682 log_trace!(logger, "Collected our payment amount on the first pass, but running again to collect extra paths with a potentially higher limit.");
1683 path_value_msat = recommended_value_msat;
1688 if payment_paths.len() == 0 {
1689 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1692 if already_collected_value_msat < final_value_msat {
1693 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1697 let mut selected_route = payment_paths;
1699 debug_assert_eq!(selected_route.iter().map(|p| p.get_value_msat()).sum::<u64>(), already_collected_value_msat);
1700 let mut overpaid_value_msat = already_collected_value_msat - final_value_msat;
1702 // First, sort by the cost-per-value of the path, dropping the paths that cost the most for
1703 // the value they contribute towards the payment amount.
1704 // We sort in descending order as we will remove from the front in `retain`, next.
1705 selected_route.sort_unstable_by(|a, b|
1706 (((b.get_cost_msat() as u128) << 64) / (b.get_value_msat() as u128))
1707 .cmp(&(((a.get_cost_msat() as u128) << 64) / (a.get_value_msat() as u128)))
1710 // We should make sure that at least 1 path left.
1711 let mut paths_left = selected_route.len();
1712 selected_route.retain(|path| {
1713 if paths_left == 1 {
1716 let path_value_msat = path.get_value_msat();
1717 if path_value_msat <= overpaid_value_msat {
1718 overpaid_value_msat -= path_value_msat;
1724 debug_assert!(selected_route.len() > 0);
1726 if overpaid_value_msat != 0 {
1728 // Now, subtract the remaining overpaid value from the most-expensive path.
1729 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1730 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1731 selected_route.sort_unstable_by(|a, b| {
1732 let a_f = a.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
1733 let b_f = b.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
1734 a_f.cmp(&b_f).then_with(|| b.get_cost_msat().cmp(&a.get_cost_msat()))
1736 let expensive_payment_path = selected_route.first_mut().unwrap();
1738 // We already dropped all the paths with value below `overpaid_value_msat` above, thus this
1739 // can't go negative.
1740 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
1741 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
1745 // Sort by the path itself and combine redundant paths.
1746 // Note that we sort by SCIDs alone as its simpler but when combining we have to ensure we
1747 // compare both SCIDs and NodeIds as individual nodes may use random aliases causing collisions
1749 selected_route.sort_unstable_by_key(|path| {
1750 let mut key = [0u64; MAX_PATH_LENGTH_ESTIMATE as usize];
1751 debug_assert!(path.hops.len() <= key.len());
1752 for (scid, key) in path.hops.iter().map(|h| h.0.candidate.short_channel_id()).zip(key.iter_mut()) {
1757 for idx in 0..(selected_route.len() - 1) {
1758 if idx + 1 >= selected_route.len() { break; }
1759 if iter_equal(selected_route[idx ].hops.iter().map(|h| (h.0.candidate.short_channel_id(), h.0.node_id)),
1760 selected_route[idx + 1].hops.iter().map(|h| (h.0.candidate.short_channel_id(), h.0.node_id))) {
1761 let new_value = selected_route[idx].get_value_msat() + selected_route[idx + 1].get_value_msat();
1762 selected_route[idx].update_value_and_recompute_fees(new_value);
1763 selected_route.remove(idx + 1);
1767 let mut selected_paths = Vec::<Vec<Result<RouteHop, LightningError>>>::new();
1768 for payment_path in selected_route {
1769 let mut path = payment_path.hops.iter().map(|(payment_hop, node_features)| {
1771 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)})?,
1772 node_features: node_features.clone(),
1773 short_channel_id: payment_hop.candidate.short_channel_id(),
1774 channel_features: payment_hop.candidate.features(),
1775 fee_msat: payment_hop.fee_msat,
1776 cltv_expiry_delta: payment_hop.candidate.cltv_expiry_delta(),
1778 }).collect::<Vec<_>>();
1779 // Propagate the cltv_expiry_delta one hop backwards since the delta from the current hop is
1780 // applicable for the previous hop.
1781 path.iter_mut().rev().fold(final_cltv_expiry_delta, |prev_cltv_expiry_delta, hop| {
1782 core::mem::replace(&mut hop.as_mut().unwrap().cltv_expiry_delta, prev_cltv_expiry_delta)
1784 selected_paths.push(path);
1786 // Make sure we would never create a route with more paths than we allow.
1787 debug_assert!(selected_paths.len() <= payment_params.max_path_count.into());
1789 if let Some(features) = &payment_params.features {
1790 for path in selected_paths.iter_mut() {
1791 if let Ok(route_hop) = path.last_mut().unwrap() {
1792 route_hop.node_features = features.to_context();
1798 paths: selected_paths.into_iter().map(|path| path.into_iter().collect()).collect::<Result<Vec<_>, _>>()?,
1799 payment_params: Some(payment_params.clone()),
1801 log_info!(logger, "Got route to {}: {}", payment_params.payee_pubkey, log_route!(route));
1805 // When an adversarial intermediary node observes a payment, it may be able to infer its
1806 // destination, if the remaining CLTV expiry delta exactly matches a feasible path in the network
1807 // graph. In order to improve privacy, this method obfuscates the CLTV expiry deltas along the
1808 // payment path by adding a randomized 'shadow route' offset to the final hop.
1809 fn add_random_cltv_offset(route: &mut Route, payment_params: &PaymentParameters,
1810 network_graph: &ReadOnlyNetworkGraph, random_seed_bytes: &[u8; 32]
1812 let network_channels = network_graph.channels();
1813 let network_nodes = network_graph.nodes();
1815 for path in route.paths.iter_mut() {
1816 let mut shadow_ctlv_expiry_delta_offset: u32 = 0;
1818 // Remember the last three nodes of the random walk and avoid looping back on them.
1819 // Init with the last three nodes from the actual path, if possible.
1820 let mut nodes_to_avoid: [NodeId; 3] = [NodeId::from_pubkey(&path.last().unwrap().pubkey),
1821 NodeId::from_pubkey(&path.get(path.len().saturating_sub(2)).unwrap().pubkey),
1822 NodeId::from_pubkey(&path.get(path.len().saturating_sub(3)).unwrap().pubkey)];
1824 // Choose the last publicly known node as the starting point for the random walk.
1825 let mut cur_hop: Option<NodeId> = None;
1826 let mut path_nonce = [0u8; 12];
1827 if let Some(starting_hop) = path.iter().rev()
1828 .find(|h| network_nodes.contains_key(&NodeId::from_pubkey(&h.pubkey))) {
1829 cur_hop = Some(NodeId::from_pubkey(&starting_hop.pubkey));
1830 path_nonce.copy_from_slice(&cur_hop.unwrap().as_slice()[..12]);
1833 // Init PRNG with the path-dependant nonce, which is static for private paths.
1834 let mut prng = ChaCha20::new(random_seed_bytes, &path_nonce);
1835 let mut random_path_bytes = [0u8; ::core::mem::size_of::<usize>()];
1837 // Pick a random path length in [1 .. 3]
1838 prng.process_in_place(&mut random_path_bytes);
1839 let random_walk_length = usize::from_be_bytes(random_path_bytes).wrapping_rem(3).wrapping_add(1);
1841 for random_hop in 0..random_walk_length {
1842 // If we don't find a suitable offset in the public network graph, we default to
1843 // MEDIAN_HOP_CLTV_EXPIRY_DELTA.
1844 let mut random_hop_offset = MEDIAN_HOP_CLTV_EXPIRY_DELTA;
1846 if let Some(cur_node_id) = cur_hop {
1847 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
1848 // Randomly choose the next unvisited hop.
1849 prng.process_in_place(&mut random_path_bytes);
1850 if let Some(random_channel) = usize::from_be_bytes(random_path_bytes)
1851 .checked_rem(cur_node.channels.len())
1852 .and_then(|index| cur_node.channels.get(index))
1853 .and_then(|id| network_channels.get(id)) {
1854 random_channel.as_directed_from(&cur_node_id).map(|(dir_info, next_id)| {
1855 if !nodes_to_avoid.iter().any(|x| x == next_id) {
1856 nodes_to_avoid[random_hop] = *next_id;
1857 random_hop_offset = dir_info.direction().cltv_expiry_delta.into();
1858 cur_hop = Some(*next_id);
1865 shadow_ctlv_expiry_delta_offset = shadow_ctlv_expiry_delta_offset
1866 .checked_add(random_hop_offset)
1867 .unwrap_or(shadow_ctlv_expiry_delta_offset);
1870 // Limit the total offset to reduce the worst-case locked liquidity timevalue
1871 const MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET: u32 = 3*144;
1872 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET);
1874 // Limit the offset so we never exceed the max_total_cltv_expiry_delta. To improve plausibility,
1875 // we choose the limit to be the largest possible multiple of MEDIAN_HOP_CLTV_EXPIRY_DELTA.
1876 let path_total_cltv_expiry_delta: u32 = path.iter().map(|h| h.cltv_expiry_delta).sum();
1877 let mut max_path_offset = payment_params.max_total_cltv_expiry_delta - path_total_cltv_expiry_delta;
1878 max_path_offset = cmp::max(
1879 max_path_offset - (max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA),
1880 max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA);
1881 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, max_path_offset);
1883 // Add 'shadow' CLTV offset to the final hop
1884 if let Some(last_hop) = path.last_mut() {
1885 last_hop.cltv_expiry_delta = last_hop.cltv_expiry_delta
1886 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(last_hop.cltv_expiry_delta);
1891 /// Construct a route from us (payer) to the target node (payee) via the given hops (which should
1892 /// exclude the payer, but include the payee). This may be useful, e.g., for probing the chosen path.
1894 /// Re-uses logic from `find_route`, so the restrictions described there also apply here.
1895 pub fn build_route_from_hops<L: Deref, GL: Deref>(
1896 our_node_pubkey: &PublicKey, hops: &[PublicKey], route_params: &RouteParameters,
1897 network_graph: &NetworkGraph<GL>, logger: L, random_seed_bytes: &[u8; 32]
1898 ) -> Result<Route, LightningError>
1899 where L::Target: Logger, GL::Target: Logger {
1900 let graph_lock = network_graph.read_only();
1901 let mut route = build_route_from_hops_internal(
1902 our_node_pubkey, hops, &route_params.payment_params, &graph_lock,
1903 route_params.final_value_msat, route_params.final_cltv_expiry_delta, logger, random_seed_bytes)?;
1904 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
1908 fn build_route_from_hops_internal<L: Deref>(
1909 our_node_pubkey: &PublicKey, hops: &[PublicKey], payment_params: &PaymentParameters,
1910 network_graph: &ReadOnlyNetworkGraph, final_value_msat: u64, final_cltv_expiry_delta: u32,
1911 logger: L, random_seed_bytes: &[u8; 32]
1912 ) -> Result<Route, LightningError> where L::Target: Logger {
1915 our_node_id: NodeId,
1916 hop_ids: [Option<NodeId>; MAX_PATH_LENGTH_ESTIMATE as usize],
1919 impl Score for HopScorer {
1920 fn channel_penalty_msat(&self, _short_channel_id: u64, source: &NodeId, target: &NodeId,
1921 _usage: ChannelUsage) -> u64
1923 let mut cur_id = self.our_node_id;
1924 for i in 0..self.hop_ids.len() {
1925 if let Some(next_id) = self.hop_ids[i] {
1926 if cur_id == *source && next_id == *target {
1937 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
1939 fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
1941 fn probe_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
1943 fn probe_successful(&mut self, _path: &[&RouteHop]) {}
1946 impl<'a> Writeable for HopScorer {
1948 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), io::Error> {
1953 if hops.len() > MAX_PATH_LENGTH_ESTIMATE.into() {
1954 return Err(LightningError{err: "Cannot build a route exceeding the maximum path length.".to_owned(), action: ErrorAction::IgnoreError});
1957 let our_node_id = NodeId::from_pubkey(our_node_pubkey);
1958 let mut hop_ids = [None; MAX_PATH_LENGTH_ESTIMATE as usize];
1959 for i in 0..hops.len() {
1960 hop_ids[i] = Some(NodeId::from_pubkey(&hops[i]));
1963 let scorer = HopScorer { our_node_id, hop_ids };
1965 get_route(our_node_pubkey, payment_params, network_graph, None, final_value_msat,
1966 final_cltv_expiry_delta, logger, &scorer, random_seed_bytes)
1971 use crate::routing::gossip::{NetworkGraph, P2PGossipSync, NodeId, EffectiveCapacity};
1972 use crate::routing::router::{get_route, build_route_from_hops_internal, add_random_cltv_offset, default_node_features,
1973 PaymentParameters, Route, RouteHint, RouteHintHop, RouteHop, RoutingFees,
1974 DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA, MAX_PATH_LENGTH_ESTIMATE};
1975 use crate::routing::scoring::{ChannelUsage, Score, ProbabilisticScorer, ProbabilisticScoringParameters};
1976 use crate::routing::test_utils::{add_channel, add_or_update_node, build_graph, build_line_graph, id_to_feature_flags, get_nodes, update_channel};
1977 use crate::chain::transaction::OutPoint;
1978 use crate::chain::keysinterface::KeysInterface;
1979 use crate::ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
1980 use crate::ln::msgs::{ErrorAction, LightningError, UnsignedChannelUpdate, MAX_VALUE_MSAT};
1981 use crate::ln::channelmanager;
1982 use crate::util::test_utils as ln_test_utils;
1983 use crate::util::chacha20::ChaCha20;
1985 use crate::util::ser::{Writeable, Writer};
1987 use bitcoin::hashes::Hash;
1988 use bitcoin::network::constants::Network;
1989 use bitcoin::blockdata::constants::genesis_block;
1990 use bitcoin::blockdata::script::Builder;
1991 use bitcoin::blockdata::opcodes;
1992 use bitcoin::blockdata::transaction::TxOut;
1996 use bitcoin::secp256k1::{PublicKey,SecretKey};
1997 use bitcoin::secp256k1::Secp256k1;
1999 use crate::prelude::*;
2000 use crate::sync::Arc;
2002 use core::convert::TryInto;
2004 fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
2005 features: InitFeatures, outbound_capacity_msat: u64) -> channelmanager::ChannelDetails {
2006 channelmanager::ChannelDetails {
2007 channel_id: [0; 32],
2008 counterparty: channelmanager::ChannelCounterparty {
2011 unspendable_punishment_reserve: 0,
2012 forwarding_info: None,
2013 outbound_htlc_minimum_msat: None,
2014 outbound_htlc_maximum_msat: None,
2016 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
2019 outbound_scid_alias: None,
2020 inbound_scid_alias: None,
2021 channel_value_satoshis: 0,
2024 outbound_capacity_msat,
2025 next_outbound_htlc_limit_msat: outbound_capacity_msat,
2026 inbound_capacity_msat: 42,
2027 unspendable_punishment_reserve: None,
2028 confirmations_required: None,
2029 force_close_spend_delay: None,
2030 is_outbound: true, is_channel_ready: true,
2031 is_usable: true, is_public: true,
2032 inbound_htlc_minimum_msat: None,
2033 inbound_htlc_maximum_msat: None,
2039 fn simple_route_test() {
2040 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2041 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2042 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2043 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2044 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2045 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2047 // Simple route to 2 via 1
2049 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) {
2050 assert_eq!(err, "Cannot send a payment of 0 msat");
2051 } else { panic!(); }
2053 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2054 assert_eq!(route.paths[0].len(), 2);
2056 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2057 assert_eq!(route.paths[0][0].short_channel_id, 2);
2058 assert_eq!(route.paths[0][0].fee_msat, 100);
2059 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2060 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2061 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2063 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2064 assert_eq!(route.paths[0][1].short_channel_id, 4);
2065 assert_eq!(route.paths[0][1].fee_msat, 100);
2066 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2067 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2068 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2072 fn invalid_first_hop_test() {
2073 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2074 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2075 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2076 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2077 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2078 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2080 // Simple route to 2 via 1
2082 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
2084 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) =
2085 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) {
2086 assert_eq!(err, "First hop cannot have our_node_pubkey as a destination.");
2087 } else { panic!(); }
2089 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2090 assert_eq!(route.paths[0].len(), 2);
2094 fn htlc_minimum_test() {
2095 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2096 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2097 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2098 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2099 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2100 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2102 // Simple route to 2 via 1
2104 // Disable other paths
2105 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2106 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2107 short_channel_id: 12,
2109 flags: 2, // to disable
2110 cltv_expiry_delta: 0,
2111 htlc_minimum_msat: 0,
2112 htlc_maximum_msat: MAX_VALUE_MSAT,
2114 fee_proportional_millionths: 0,
2115 excess_data: Vec::new()
2117 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2118 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2119 short_channel_id: 3,
2121 flags: 2, // to disable
2122 cltv_expiry_delta: 0,
2123 htlc_minimum_msat: 0,
2124 htlc_maximum_msat: MAX_VALUE_MSAT,
2126 fee_proportional_millionths: 0,
2127 excess_data: Vec::new()
2129 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2130 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2131 short_channel_id: 13,
2133 flags: 2, // to disable
2134 cltv_expiry_delta: 0,
2135 htlc_minimum_msat: 0,
2136 htlc_maximum_msat: MAX_VALUE_MSAT,
2138 fee_proportional_millionths: 0,
2139 excess_data: Vec::new()
2141 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2142 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2143 short_channel_id: 6,
2145 flags: 2, // to disable
2146 cltv_expiry_delta: 0,
2147 htlc_minimum_msat: 0,
2148 htlc_maximum_msat: MAX_VALUE_MSAT,
2150 fee_proportional_millionths: 0,
2151 excess_data: Vec::new()
2153 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2154 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2155 short_channel_id: 7,
2157 flags: 2, // to disable
2158 cltv_expiry_delta: 0,
2159 htlc_minimum_msat: 0,
2160 htlc_maximum_msat: MAX_VALUE_MSAT,
2162 fee_proportional_millionths: 0,
2163 excess_data: Vec::new()
2166 // Check against amount_to_transfer_over_msat.
2167 // Set minimal HTLC of 200_000_000 msat.
2168 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2169 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2170 short_channel_id: 2,
2173 cltv_expiry_delta: 0,
2174 htlc_minimum_msat: 200_000_000,
2175 htlc_maximum_msat: MAX_VALUE_MSAT,
2177 fee_proportional_millionths: 0,
2178 excess_data: Vec::new()
2181 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
2183 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2184 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2185 short_channel_id: 4,
2188 cltv_expiry_delta: 0,
2189 htlc_minimum_msat: 0,
2190 htlc_maximum_msat: 199_999_999,
2192 fee_proportional_millionths: 0,
2193 excess_data: Vec::new()
2196 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
2197 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) {
2198 assert_eq!(err, "Failed to find a path to the given destination");
2199 } else { panic!(); }
2201 // Lift the restriction on the first hop.
2202 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2203 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2204 short_channel_id: 2,
2207 cltv_expiry_delta: 0,
2208 htlc_minimum_msat: 0,
2209 htlc_maximum_msat: MAX_VALUE_MSAT,
2211 fee_proportional_millionths: 0,
2212 excess_data: Vec::new()
2215 // A payment above the minimum should pass
2216 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();
2217 assert_eq!(route.paths[0].len(), 2);
2221 fn htlc_minimum_overpay_test() {
2222 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2223 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2224 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(channelmanager::provided_invoice_features());
2225 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2226 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2227 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2229 // A route to node#2 via two paths.
2230 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
2231 // Thus, they can't send 60 without overpaying.
2232 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2233 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2234 short_channel_id: 2,
2237 cltv_expiry_delta: 0,
2238 htlc_minimum_msat: 35_000,
2239 htlc_maximum_msat: 40_000,
2241 fee_proportional_millionths: 0,
2242 excess_data: Vec::new()
2244 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2245 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2246 short_channel_id: 12,
2249 cltv_expiry_delta: 0,
2250 htlc_minimum_msat: 35_000,
2251 htlc_maximum_msat: 40_000,
2253 fee_proportional_millionths: 0,
2254 excess_data: Vec::new()
2258 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2259 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2260 short_channel_id: 13,
2263 cltv_expiry_delta: 0,
2264 htlc_minimum_msat: 0,
2265 htlc_maximum_msat: MAX_VALUE_MSAT,
2267 fee_proportional_millionths: 0,
2268 excess_data: Vec::new()
2270 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2271 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2272 short_channel_id: 4,
2275 cltv_expiry_delta: 0,
2276 htlc_minimum_msat: 0,
2277 htlc_maximum_msat: MAX_VALUE_MSAT,
2279 fee_proportional_millionths: 0,
2280 excess_data: Vec::new()
2283 // Disable other paths
2284 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2285 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2286 short_channel_id: 1,
2288 flags: 2, // to disable
2289 cltv_expiry_delta: 0,
2290 htlc_minimum_msat: 0,
2291 htlc_maximum_msat: MAX_VALUE_MSAT,
2293 fee_proportional_millionths: 0,
2294 excess_data: Vec::new()
2297 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 60_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2298 // Overpay fees to hit htlc_minimum_msat.
2299 let overpaid_fees = route.paths[0][0].fee_msat + route.paths[1][0].fee_msat;
2300 // TODO: this could be better balanced to overpay 10k and not 15k.
2301 assert_eq!(overpaid_fees, 15_000);
2303 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
2304 // while taking even more fee to match htlc_minimum_msat.
2305 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2306 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2307 short_channel_id: 12,
2310 cltv_expiry_delta: 0,
2311 htlc_minimum_msat: 65_000,
2312 htlc_maximum_msat: 80_000,
2314 fee_proportional_millionths: 0,
2315 excess_data: Vec::new()
2317 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2318 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2319 short_channel_id: 2,
2322 cltv_expiry_delta: 0,
2323 htlc_minimum_msat: 0,
2324 htlc_maximum_msat: MAX_VALUE_MSAT,
2326 fee_proportional_millionths: 0,
2327 excess_data: Vec::new()
2329 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2330 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2331 short_channel_id: 4,
2334 cltv_expiry_delta: 0,
2335 htlc_minimum_msat: 0,
2336 htlc_maximum_msat: MAX_VALUE_MSAT,
2338 fee_proportional_millionths: 100_000,
2339 excess_data: Vec::new()
2342 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 60_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2343 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
2344 assert_eq!(route.paths.len(), 1);
2345 assert_eq!(route.paths[0][0].short_channel_id, 12);
2346 let fees = route.paths[0][0].fee_msat;
2347 assert_eq!(fees, 5_000);
2349 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2350 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
2351 // the other channel.
2352 assert_eq!(route.paths.len(), 1);
2353 assert_eq!(route.paths[0][0].short_channel_id, 2);
2354 let fees = route.paths[0][0].fee_msat;
2355 assert_eq!(fees, 5_000);
2359 fn disable_channels_test() {
2360 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2361 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2362 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2363 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2364 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2365 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2367 // // Disable channels 4 and 12 by flags=2
2368 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2369 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2370 short_channel_id: 4,
2372 flags: 2, // to disable
2373 cltv_expiry_delta: 0,
2374 htlc_minimum_msat: 0,
2375 htlc_maximum_msat: MAX_VALUE_MSAT,
2377 fee_proportional_millionths: 0,
2378 excess_data: Vec::new()
2380 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2381 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2382 short_channel_id: 12,
2384 flags: 2, // to disable
2385 cltv_expiry_delta: 0,
2386 htlc_minimum_msat: 0,
2387 htlc_maximum_msat: MAX_VALUE_MSAT,
2389 fee_proportional_millionths: 0,
2390 excess_data: Vec::new()
2393 // If all the channels require some features we don't understand, route should fail
2394 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) {
2395 assert_eq!(err, "Failed to find a path to the given destination");
2396 } else { panic!(); }
2398 // If we specify a channel to node7, that overrides our local channel view and that gets used
2399 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2400 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();
2401 assert_eq!(route.paths[0].len(), 2);
2403 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2404 assert_eq!(route.paths[0][0].short_channel_id, 42);
2405 assert_eq!(route.paths[0][0].fee_msat, 200);
2406 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2407 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2408 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2410 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2411 assert_eq!(route.paths[0][1].short_channel_id, 13);
2412 assert_eq!(route.paths[0][1].fee_msat, 100);
2413 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2414 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2415 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2419 fn disable_node_test() {
2420 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2421 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2422 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2423 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2424 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2425 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2427 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
2428 let mut unknown_features = NodeFeatures::empty();
2429 unknown_features.set_unknown_feature_required();
2430 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
2431 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
2432 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
2434 // If all nodes require some features we don't understand, route should fail
2435 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) {
2436 assert_eq!(err, "Failed to find a path to the given destination");
2437 } else { panic!(); }
2439 // If we specify a channel to node7, that overrides our local channel view and that gets used
2440 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2441 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();
2442 assert_eq!(route.paths[0].len(), 2);
2444 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2445 assert_eq!(route.paths[0][0].short_channel_id, 42);
2446 assert_eq!(route.paths[0][0].fee_msat, 200);
2447 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2448 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2449 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2451 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2452 assert_eq!(route.paths[0][1].short_channel_id, 13);
2453 assert_eq!(route.paths[0][1].fee_msat, 100);
2454 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2455 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2456 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2458 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
2459 // naively) assume that the user checked the feature bits on the invoice, which override
2460 // the node_announcement.
2464 fn our_chans_test() {
2465 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2466 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2467 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2468 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2469 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2471 // Route to 1 via 2 and 3 because our channel to 1 is disabled
2472 let payment_params = PaymentParameters::from_node_id(nodes[0]);
2473 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2474 assert_eq!(route.paths[0].len(), 3);
2476 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2477 assert_eq!(route.paths[0][0].short_channel_id, 2);
2478 assert_eq!(route.paths[0][0].fee_msat, 200);
2479 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2480 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2481 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2483 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2484 assert_eq!(route.paths[0][1].short_channel_id, 4);
2485 assert_eq!(route.paths[0][1].fee_msat, 100);
2486 assert_eq!(route.paths[0][1].cltv_expiry_delta, (3 << 4) | 2);
2487 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2488 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2490 assert_eq!(route.paths[0][2].pubkey, nodes[0]);
2491 assert_eq!(route.paths[0][2].short_channel_id, 3);
2492 assert_eq!(route.paths[0][2].fee_msat, 100);
2493 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
2494 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(1));
2495 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(3));
2497 // If we specify a channel to node7, that overrides our local channel view and that gets used
2498 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2499 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2500 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();
2501 assert_eq!(route.paths[0].len(), 2);
2503 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2504 assert_eq!(route.paths[0][0].short_channel_id, 42);
2505 assert_eq!(route.paths[0][0].fee_msat, 200);
2506 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2507 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2508 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2510 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2511 assert_eq!(route.paths[0][1].short_channel_id, 13);
2512 assert_eq!(route.paths[0][1].fee_msat, 100);
2513 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2514 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2515 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2518 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2519 let zero_fees = RoutingFees {
2521 proportional_millionths: 0,
2523 vec![RouteHint(vec![RouteHintHop {
2524 src_node_id: nodes[3],
2525 short_channel_id: 8,
2527 cltv_expiry_delta: (8 << 4) | 1,
2528 htlc_minimum_msat: None,
2529 htlc_maximum_msat: None,
2531 ]), RouteHint(vec![RouteHintHop {
2532 src_node_id: nodes[4],
2533 short_channel_id: 9,
2536 proportional_millionths: 0,
2538 cltv_expiry_delta: (9 << 4) | 1,
2539 htlc_minimum_msat: None,
2540 htlc_maximum_msat: None,
2541 }]), RouteHint(vec![RouteHintHop {
2542 src_node_id: nodes[5],
2543 short_channel_id: 10,
2545 cltv_expiry_delta: (10 << 4) | 1,
2546 htlc_minimum_msat: None,
2547 htlc_maximum_msat: None,
2551 fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2552 let zero_fees = RoutingFees {
2554 proportional_millionths: 0,
2556 vec![RouteHint(vec![RouteHintHop {
2557 src_node_id: nodes[2],
2558 short_channel_id: 5,
2561 proportional_millionths: 0,
2563 cltv_expiry_delta: (5 << 4) | 1,
2564 htlc_minimum_msat: None,
2565 htlc_maximum_msat: None,
2567 src_node_id: nodes[3],
2568 short_channel_id: 8,
2570 cltv_expiry_delta: (8 << 4) | 1,
2571 htlc_minimum_msat: None,
2572 htlc_maximum_msat: None,
2574 ]), RouteHint(vec![RouteHintHop {
2575 src_node_id: nodes[4],
2576 short_channel_id: 9,
2579 proportional_millionths: 0,
2581 cltv_expiry_delta: (9 << 4) | 1,
2582 htlc_minimum_msat: None,
2583 htlc_maximum_msat: None,
2584 }]), RouteHint(vec![RouteHintHop {
2585 src_node_id: nodes[5],
2586 short_channel_id: 10,
2588 cltv_expiry_delta: (10 << 4) | 1,
2589 htlc_minimum_msat: None,
2590 htlc_maximum_msat: None,
2595 fn partial_route_hint_test() {
2596 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2597 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2598 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2599 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2600 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2602 // Simple test across 2, 3, 5, and 4 via a last_hop channel
2603 // Tests the behaviour when the RouteHint contains a suboptimal hop.
2604 // RouteHint may be partially used by the algo to build the best path.
2606 // First check that last hop can't have its source as the payee.
2607 let invalid_last_hop = RouteHint(vec![RouteHintHop {
2608 src_node_id: nodes[6],
2609 short_channel_id: 8,
2612 proportional_millionths: 0,
2614 cltv_expiry_delta: (8 << 4) | 1,
2615 htlc_minimum_msat: None,
2616 htlc_maximum_msat: None,
2619 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
2620 invalid_last_hops.push(invalid_last_hop);
2622 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(invalid_last_hops);
2623 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) {
2624 assert_eq!(err, "Route hint cannot have the payee as the source.");
2625 } else { panic!(); }
2628 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops_multi_private_channels(&nodes));
2629 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2630 assert_eq!(route.paths[0].len(), 5);
2632 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2633 assert_eq!(route.paths[0][0].short_channel_id, 2);
2634 assert_eq!(route.paths[0][0].fee_msat, 100);
2635 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2636 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2637 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2639 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2640 assert_eq!(route.paths[0][1].short_channel_id, 4);
2641 assert_eq!(route.paths[0][1].fee_msat, 0);
2642 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
2643 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2644 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2646 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2647 assert_eq!(route.paths[0][2].short_channel_id, 6);
2648 assert_eq!(route.paths[0][2].fee_msat, 0);
2649 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
2650 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2651 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2653 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2654 assert_eq!(route.paths[0][3].short_channel_id, 11);
2655 assert_eq!(route.paths[0][3].fee_msat, 0);
2656 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
2657 // If we have a peer in the node map, we'll use their features here since we don't have
2658 // a way of figuring out their features from the invoice:
2659 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2660 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2662 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2663 assert_eq!(route.paths[0][4].short_channel_id, 8);
2664 assert_eq!(route.paths[0][4].fee_msat, 100);
2665 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2666 assert_eq!(route.paths[0][4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
2667 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2670 fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2671 let zero_fees = RoutingFees {
2673 proportional_millionths: 0,
2675 vec![RouteHint(vec![RouteHintHop {
2676 src_node_id: nodes[3],
2677 short_channel_id: 8,
2679 cltv_expiry_delta: (8 << 4) | 1,
2680 htlc_minimum_msat: None,
2681 htlc_maximum_msat: None,
2682 }]), RouteHint(vec![
2684 ]), RouteHint(vec![RouteHintHop {
2685 src_node_id: nodes[5],
2686 short_channel_id: 10,
2688 cltv_expiry_delta: (10 << 4) | 1,
2689 htlc_minimum_msat: None,
2690 htlc_maximum_msat: None,
2695 fn ignores_empty_last_hops_test() {
2696 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2697 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2698 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(empty_last_hop(&nodes));
2699 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2700 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2701 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2703 // Test handling of an empty RouteHint passed in Invoice.
2705 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2706 assert_eq!(route.paths[0].len(), 5);
2708 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2709 assert_eq!(route.paths[0][0].short_channel_id, 2);
2710 assert_eq!(route.paths[0][0].fee_msat, 100);
2711 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2712 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2713 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2715 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2716 assert_eq!(route.paths[0][1].short_channel_id, 4);
2717 assert_eq!(route.paths[0][1].fee_msat, 0);
2718 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
2719 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2720 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2722 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2723 assert_eq!(route.paths[0][2].short_channel_id, 6);
2724 assert_eq!(route.paths[0][2].fee_msat, 0);
2725 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
2726 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2727 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2729 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2730 assert_eq!(route.paths[0][3].short_channel_id, 11);
2731 assert_eq!(route.paths[0][3].fee_msat, 0);
2732 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
2733 // If we have a peer in the node map, we'll use their features here since we don't have
2734 // a way of figuring out their features from the invoice:
2735 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2736 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2738 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2739 assert_eq!(route.paths[0][4].short_channel_id, 8);
2740 assert_eq!(route.paths[0][4].fee_msat, 100);
2741 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2742 assert_eq!(route.paths[0][4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
2743 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2746 /// Builds a trivial last-hop hint that passes through the two nodes given, with channel 0xff00
2748 fn multi_hop_last_hops_hint(hint_hops: [PublicKey; 2]) -> Vec<RouteHint> {
2749 let zero_fees = RoutingFees {
2751 proportional_millionths: 0,
2753 vec![RouteHint(vec![RouteHintHop {
2754 src_node_id: hint_hops[0],
2755 short_channel_id: 0xff00,
2758 proportional_millionths: 0,
2760 cltv_expiry_delta: (5 << 4) | 1,
2761 htlc_minimum_msat: None,
2762 htlc_maximum_msat: None,
2764 src_node_id: hint_hops[1],
2765 short_channel_id: 0xff01,
2767 cltv_expiry_delta: (8 << 4) | 1,
2768 htlc_minimum_msat: None,
2769 htlc_maximum_msat: None,
2774 fn multi_hint_last_hops_test() {
2775 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2776 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2777 let last_hops = multi_hop_last_hops_hint([nodes[2], nodes[3]]);
2778 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops.clone());
2779 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2780 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2781 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2782 // Test through channels 2, 3, 0xff00, 0xff01.
2783 // Test shows that multiple hop hints are considered.
2785 // Disabling channels 6 & 7 by flags=2
2786 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2787 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2788 short_channel_id: 6,
2790 flags: 2, // to disable
2791 cltv_expiry_delta: 0,
2792 htlc_minimum_msat: 0,
2793 htlc_maximum_msat: MAX_VALUE_MSAT,
2795 fee_proportional_millionths: 0,
2796 excess_data: Vec::new()
2798 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2799 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2800 short_channel_id: 7,
2802 flags: 2, // to disable
2803 cltv_expiry_delta: 0,
2804 htlc_minimum_msat: 0,
2805 htlc_maximum_msat: MAX_VALUE_MSAT,
2807 fee_proportional_millionths: 0,
2808 excess_data: Vec::new()
2811 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2812 assert_eq!(route.paths[0].len(), 4);
2814 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2815 assert_eq!(route.paths[0][0].short_channel_id, 2);
2816 assert_eq!(route.paths[0][0].fee_msat, 200);
2817 assert_eq!(route.paths[0][0].cltv_expiry_delta, 65);
2818 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2819 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2821 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2822 assert_eq!(route.paths[0][1].short_channel_id, 4);
2823 assert_eq!(route.paths[0][1].fee_msat, 100);
2824 assert_eq!(route.paths[0][1].cltv_expiry_delta, 81);
2825 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2826 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2828 assert_eq!(route.paths[0][2].pubkey, nodes[3]);
2829 assert_eq!(route.paths[0][2].short_channel_id, last_hops[0].0[0].short_channel_id);
2830 assert_eq!(route.paths[0][2].fee_msat, 0);
2831 assert_eq!(route.paths[0][2].cltv_expiry_delta, 129);
2832 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(4));
2833 assert_eq!(route.paths[0][2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2835 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2836 assert_eq!(route.paths[0][3].short_channel_id, last_hops[0].0[1].short_channel_id);
2837 assert_eq!(route.paths[0][3].fee_msat, 100);
2838 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2839 assert_eq!(route.paths[0][3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
2840 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2844 fn private_multi_hint_last_hops_test() {
2845 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2846 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2848 let non_announced_privkey = SecretKey::from_slice(&hex::decode(format!("{:02x}", 0xf0).repeat(32)).unwrap()[..]).unwrap();
2849 let non_announced_pubkey = PublicKey::from_secret_key(&secp_ctx, &non_announced_privkey);
2851 let last_hops = multi_hop_last_hops_hint([nodes[2], non_announced_pubkey]);
2852 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops.clone());
2853 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2854 // Test through channels 2, 3, 0xff00, 0xff01.
2855 // Test shows that multiple hop hints are considered.
2857 // Disabling channels 6 & 7 by flags=2
2858 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2859 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2860 short_channel_id: 6,
2862 flags: 2, // to disable
2863 cltv_expiry_delta: 0,
2864 htlc_minimum_msat: 0,
2865 htlc_maximum_msat: MAX_VALUE_MSAT,
2867 fee_proportional_millionths: 0,
2868 excess_data: Vec::new()
2870 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2871 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2872 short_channel_id: 7,
2874 flags: 2, // to disable
2875 cltv_expiry_delta: 0,
2876 htlc_minimum_msat: 0,
2877 htlc_maximum_msat: MAX_VALUE_MSAT,
2879 fee_proportional_millionths: 0,
2880 excess_data: Vec::new()
2883 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &[42u8; 32]).unwrap();
2884 assert_eq!(route.paths[0].len(), 4);
2886 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2887 assert_eq!(route.paths[0][0].short_channel_id, 2);
2888 assert_eq!(route.paths[0][0].fee_msat, 200);
2889 assert_eq!(route.paths[0][0].cltv_expiry_delta, 65);
2890 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2891 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2893 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2894 assert_eq!(route.paths[0][1].short_channel_id, 4);
2895 assert_eq!(route.paths[0][1].fee_msat, 100);
2896 assert_eq!(route.paths[0][1].cltv_expiry_delta, 81);
2897 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2898 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2900 assert_eq!(route.paths[0][2].pubkey, non_announced_pubkey);
2901 assert_eq!(route.paths[0][2].short_channel_id, last_hops[0].0[0].short_channel_id);
2902 assert_eq!(route.paths[0][2].fee_msat, 0);
2903 assert_eq!(route.paths[0][2].cltv_expiry_delta, 129);
2904 assert_eq!(route.paths[0][2].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
2905 assert_eq!(route.paths[0][2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2907 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2908 assert_eq!(route.paths[0][3].short_channel_id, last_hops[0].0[1].short_channel_id);
2909 assert_eq!(route.paths[0][3].fee_msat, 100);
2910 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2911 assert_eq!(route.paths[0][3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
2912 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2915 fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2916 let zero_fees = RoutingFees {
2918 proportional_millionths: 0,
2920 vec![RouteHint(vec![RouteHintHop {
2921 src_node_id: nodes[4],
2922 short_channel_id: 11,
2924 cltv_expiry_delta: (11 << 4) | 1,
2925 htlc_minimum_msat: None,
2926 htlc_maximum_msat: None,
2928 src_node_id: nodes[3],
2929 short_channel_id: 8,
2931 cltv_expiry_delta: (8 << 4) | 1,
2932 htlc_minimum_msat: None,
2933 htlc_maximum_msat: None,
2934 }]), RouteHint(vec![RouteHintHop {
2935 src_node_id: nodes[4],
2936 short_channel_id: 9,
2939 proportional_millionths: 0,
2941 cltv_expiry_delta: (9 << 4) | 1,
2942 htlc_minimum_msat: None,
2943 htlc_maximum_msat: None,
2944 }]), RouteHint(vec![RouteHintHop {
2945 src_node_id: nodes[5],
2946 short_channel_id: 10,
2948 cltv_expiry_delta: (10 << 4) | 1,
2949 htlc_minimum_msat: None,
2950 htlc_maximum_msat: None,
2955 fn last_hops_with_public_channel_test() {
2956 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2957 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2958 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops_with_public_channel(&nodes));
2959 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2960 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2961 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2962 // This test shows that public routes can be present in the invoice
2963 // which would be handled in the same manner.
2965 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2966 assert_eq!(route.paths[0].len(), 5);
2968 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2969 assert_eq!(route.paths[0][0].short_channel_id, 2);
2970 assert_eq!(route.paths[0][0].fee_msat, 100);
2971 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2972 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2973 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2975 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2976 assert_eq!(route.paths[0][1].short_channel_id, 4);
2977 assert_eq!(route.paths[0][1].fee_msat, 0);
2978 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
2979 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2980 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2982 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2983 assert_eq!(route.paths[0][2].short_channel_id, 6);
2984 assert_eq!(route.paths[0][2].fee_msat, 0);
2985 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
2986 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2987 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2989 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2990 assert_eq!(route.paths[0][3].short_channel_id, 11);
2991 assert_eq!(route.paths[0][3].fee_msat, 0);
2992 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
2993 // If we have a peer in the node map, we'll use their features here since we don't have
2994 // a way of figuring out their features from the invoice:
2995 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2996 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2998 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2999 assert_eq!(route.paths[0][4].short_channel_id, 8);
3000 assert_eq!(route.paths[0][4].fee_msat, 100);
3001 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
3002 assert_eq!(route.paths[0][4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3003 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3007 fn our_chans_last_hop_connect_test() {
3008 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3009 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3010 let scorer = ln_test_utils::TestScorer::with_penalty(0);
3011 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3012 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3014 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
3015 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3016 let mut last_hops = last_hops(&nodes);
3017 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops.clone());
3018 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();
3019 assert_eq!(route.paths[0].len(), 2);
3021 assert_eq!(route.paths[0][0].pubkey, nodes[3]);
3022 assert_eq!(route.paths[0][0].short_channel_id, 42);
3023 assert_eq!(route.paths[0][0].fee_msat, 0);
3024 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 4) | 1);
3025 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
3026 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3028 assert_eq!(route.paths[0][1].pubkey, nodes[6]);
3029 assert_eq!(route.paths[0][1].short_channel_id, 8);
3030 assert_eq!(route.paths[0][1].fee_msat, 100);
3031 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
3032 assert_eq!(route.paths[0][1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3033 assert_eq!(route.paths[0][1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3035 last_hops[0].0[0].fees.base_msat = 1000;
3037 // Revert to via 6 as the fee on 8 goes up
3038 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops);
3039 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3040 assert_eq!(route.paths[0].len(), 4);
3042 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3043 assert_eq!(route.paths[0][0].short_channel_id, 2);
3044 assert_eq!(route.paths[0][0].fee_msat, 200); // fee increased as its % of value transferred across node
3045 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
3046 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3047 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3049 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3050 assert_eq!(route.paths[0][1].short_channel_id, 4);
3051 assert_eq!(route.paths[0][1].fee_msat, 100);
3052 assert_eq!(route.paths[0][1].cltv_expiry_delta, (7 << 4) | 1);
3053 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3054 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3056 assert_eq!(route.paths[0][2].pubkey, nodes[5]);
3057 assert_eq!(route.paths[0][2].short_channel_id, 7);
3058 assert_eq!(route.paths[0][2].fee_msat, 0);
3059 assert_eq!(route.paths[0][2].cltv_expiry_delta, (10 << 4) | 1);
3060 // If we have a peer in the node map, we'll use their features here since we don't have
3061 // a way of figuring out their features from the invoice:
3062 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
3063 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(7));
3065 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
3066 assert_eq!(route.paths[0][3].short_channel_id, 10);
3067 assert_eq!(route.paths[0][3].fee_msat, 100);
3068 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
3069 assert_eq!(route.paths[0][3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3070 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3072 // ...but still use 8 for larger payments as 6 has a variable feerate
3073 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 2000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3074 assert_eq!(route.paths[0].len(), 5);
3076 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3077 assert_eq!(route.paths[0][0].short_channel_id, 2);
3078 assert_eq!(route.paths[0][0].fee_msat, 3000);
3079 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
3080 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3081 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3083 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3084 assert_eq!(route.paths[0][1].short_channel_id, 4);
3085 assert_eq!(route.paths[0][1].fee_msat, 0);
3086 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
3087 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3088 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3090 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
3091 assert_eq!(route.paths[0][2].short_channel_id, 6);
3092 assert_eq!(route.paths[0][2].fee_msat, 0);
3093 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
3094 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
3095 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
3097 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
3098 assert_eq!(route.paths[0][3].short_channel_id, 11);
3099 assert_eq!(route.paths[0][3].fee_msat, 1000);
3100 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
3101 // If we have a peer in the node map, we'll use their features here since we don't have
3102 // a way of figuring out their features from the invoice:
3103 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
3104 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
3106 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
3107 assert_eq!(route.paths[0][4].short_channel_id, 8);
3108 assert_eq!(route.paths[0][4].fee_msat, 2000);
3109 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
3110 assert_eq!(route.paths[0][4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3111 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3114 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> {
3115 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
3116 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3117 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3119 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
3120 let last_hops = RouteHint(vec![RouteHintHop {
3121 src_node_id: middle_node_id,
3122 short_channel_id: 8,
3125 proportional_millionths: last_hop_fee_prop,
3127 cltv_expiry_delta: (8 << 4) | 1,
3128 htlc_minimum_msat: None,
3129 htlc_maximum_msat: last_hop_htlc_max,
3131 let payment_params = PaymentParameters::from_node_id(target_node_id).with_route_hints(vec![last_hops]);
3132 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
3133 let scorer = ln_test_utils::TestScorer::with_penalty(0);
3134 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3135 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3136 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
3137 let logger = ln_test_utils::TestLogger::new();
3138 let network_graph = NetworkGraph::new(genesis_hash, &logger);
3139 let route = get_route(&source_node_id, &payment_params, &network_graph.read_only(),
3140 Some(&our_chans.iter().collect::<Vec<_>>()), route_val, 42, &logger, &scorer, &random_seed_bytes);
3145 fn unannounced_path_test() {
3146 // We should be able to send a payment to a destination without any help of a routing graph
3147 // if we have a channel with a common counterparty that appears in the first and last hop
3149 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
3151 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3152 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3153 assert_eq!(route.paths[0].len(), 2);
3155 assert_eq!(route.paths[0][0].pubkey, middle_node_id);
3156 assert_eq!(route.paths[0][0].short_channel_id, 42);
3157 assert_eq!(route.paths[0][0].fee_msat, 1001);
3158 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 4) | 1);
3159 assert_eq!(route.paths[0][0].node_features.le_flags(), &[0b11]);
3160 assert_eq!(route.paths[0][0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3162 assert_eq!(route.paths[0][1].pubkey, target_node_id);
3163 assert_eq!(route.paths[0][1].short_channel_id, 8);
3164 assert_eq!(route.paths[0][1].fee_msat, 1000000);
3165 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
3166 assert_eq!(route.paths[0][1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3167 assert_eq!(route.paths[0][1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3171 fn overflow_unannounced_path_test_liquidity_underflow() {
3172 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
3173 // the last-hop had a fee which overflowed a u64, we'd panic.
3174 // This was due to us adding the first-hop from us unconditionally, causing us to think
3175 // we'd built a path (as our node is in the "best candidate" set), when we had not.
3176 // In this test, we previously hit a subtraction underflow due to having less available
3177 // liquidity at the last hop than 0.
3178 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());
3182 fn overflow_unannounced_path_test_feerate_overflow() {
3183 // This tests for the same case as above, except instead of hitting a subtraction
3184 // underflow, we hit a case where the fee charged at a hop overflowed.
3185 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());
3189 fn available_amount_while_routing_test() {
3190 // Tests whether we choose the correct available channel amount while routing.
3192 let (secp_ctx, network_graph, mut gossip_sync, chain_monitor, logger) = build_graph();
3193 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3194 let scorer = ln_test_utils::TestScorer::with_penalty(0);
3195 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3196 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3197 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(channelmanager::provided_invoice_features());
3199 // We will use a simple single-path route from
3200 // our node to node2 via node0: channels {1, 3}.
3202 // First disable all other paths.
3203 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3204 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3205 short_channel_id: 2,
3208 cltv_expiry_delta: 0,
3209 htlc_minimum_msat: 0,
3210 htlc_maximum_msat: 100_000,
3212 fee_proportional_millionths: 0,
3213 excess_data: Vec::new()
3215 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3216 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3217 short_channel_id: 12,
3220 cltv_expiry_delta: 0,
3221 htlc_minimum_msat: 0,
3222 htlc_maximum_msat: 100_000,
3224 fee_proportional_millionths: 0,
3225 excess_data: Vec::new()
3228 // Make the first channel (#1) very permissive,
3229 // and we will be testing all limits on the second channel.
3230 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3231 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3232 short_channel_id: 1,
3235 cltv_expiry_delta: 0,
3236 htlc_minimum_msat: 0,
3237 htlc_maximum_msat: 1_000_000_000,
3239 fee_proportional_millionths: 0,
3240 excess_data: Vec::new()
3243 // First, let's see if routing works if we have absolutely no idea about the available amount.
3244 // In this case, it should be set to 250_000 sats.
3245 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3246 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3247 short_channel_id: 3,
3250 cltv_expiry_delta: 0,
3251 htlc_minimum_msat: 0,
3252 htlc_maximum_msat: 250_000_000,
3254 fee_proportional_millionths: 0,
3255 excess_data: Vec::new()
3259 // Attempt to route more than available results in a failure.
3260 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3261 &our_id, &payment_params, &network_graph.read_only(), None, 250_000_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3262 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3263 } else { panic!(); }
3267 // Now, attempt to route an exact amount we have should be fine.
3268 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();
3269 assert_eq!(route.paths.len(), 1);
3270 let path = route.paths.last().unwrap();
3271 assert_eq!(path.len(), 2);
3272 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3273 assert_eq!(path.last().unwrap().fee_msat, 250_000_000);
3276 // Check that setting next_outbound_htlc_limit_msat in first_hops limits the channels.
3277 // Disable channel #1 and use another first hop.
3278 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3279 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3280 short_channel_id: 1,
3283 cltv_expiry_delta: 0,
3284 htlc_minimum_msat: 0,
3285 htlc_maximum_msat: 1_000_000_000,
3287 fee_proportional_millionths: 0,
3288 excess_data: Vec::new()
3291 // Now, limit the first_hop by the next_outbound_htlc_limit_msat of 200_000 sats.
3292 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
3295 // Attempt to route more than available results in a failure.
3296 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3297 &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) {
3298 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3299 } else { panic!(); }
3303 // Now, attempt to route an exact amount we have should be fine.
3304 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();
3305 assert_eq!(route.paths.len(), 1);
3306 let path = route.paths.last().unwrap();
3307 assert_eq!(path.len(), 2);
3308 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3309 assert_eq!(path.last().unwrap().fee_msat, 200_000_000);
3312 // Enable channel #1 back.
3313 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3314 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3315 short_channel_id: 1,
3318 cltv_expiry_delta: 0,
3319 htlc_minimum_msat: 0,
3320 htlc_maximum_msat: 1_000_000_000,
3322 fee_proportional_millionths: 0,
3323 excess_data: Vec::new()
3327 // Now let's see if routing works if we know only htlc_maximum_msat.
3328 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3329 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3330 short_channel_id: 3,
3333 cltv_expiry_delta: 0,
3334 htlc_minimum_msat: 0,
3335 htlc_maximum_msat: 15_000,
3337 fee_proportional_millionths: 0,
3338 excess_data: Vec::new()
3342 // Attempt to route more than available results in a failure.
3343 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3344 &our_id, &payment_params, &network_graph.read_only(), None, 15_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3345 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3346 } else { panic!(); }
3350 // Now, attempt to route an exact amount we have should be fine.
3351 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 15_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3352 assert_eq!(route.paths.len(), 1);
3353 let path = route.paths.last().unwrap();
3354 assert_eq!(path.len(), 2);
3355 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3356 assert_eq!(path.last().unwrap().fee_msat, 15_000);
3359 // Now let's see if routing works if we know only capacity from the UTXO.
3361 // We can't change UTXO capacity on the fly, so we'll disable
3362 // the existing channel and add another one with the capacity we need.
3363 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3364 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3365 short_channel_id: 3,
3368 cltv_expiry_delta: 0,
3369 htlc_minimum_msat: 0,
3370 htlc_maximum_msat: MAX_VALUE_MSAT,
3372 fee_proportional_millionths: 0,
3373 excess_data: Vec::new()
3376 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
3377 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
3378 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
3379 .push_opcode(opcodes::all::OP_PUSHNUM_2)
3380 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
3382 *chain_monitor.utxo_ret.lock().unwrap() = Ok(TxOut { value: 15, script_pubkey: good_script.clone() });
3383 gossip_sync.add_chain_access(Some(chain_monitor));
3385 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
3386 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3387 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3388 short_channel_id: 333,
3391 cltv_expiry_delta: (3 << 4) | 1,
3392 htlc_minimum_msat: 0,
3393 htlc_maximum_msat: 15_000,
3395 fee_proportional_millionths: 0,
3396 excess_data: Vec::new()
3398 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3399 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3400 short_channel_id: 333,
3403 cltv_expiry_delta: (3 << 4) | 2,
3404 htlc_minimum_msat: 0,
3405 htlc_maximum_msat: 15_000,
3407 fee_proportional_millionths: 0,
3408 excess_data: Vec::new()
3412 // Attempt to route more than available results in a failure.
3413 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3414 &our_id, &payment_params, &network_graph.read_only(), None, 15_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3415 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3416 } else { panic!(); }
3420 // Now, attempt to route an exact amount we have should be fine.
3421 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 15_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3422 assert_eq!(route.paths.len(), 1);
3423 let path = route.paths.last().unwrap();
3424 assert_eq!(path.len(), 2);
3425 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3426 assert_eq!(path.last().unwrap().fee_msat, 15_000);
3429 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
3430 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3431 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3432 short_channel_id: 333,
3435 cltv_expiry_delta: 0,
3436 htlc_minimum_msat: 0,
3437 htlc_maximum_msat: 10_000,
3439 fee_proportional_millionths: 0,
3440 excess_data: Vec::new()
3444 // Attempt to route more than available results in a failure.
3445 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3446 &our_id, &payment_params, &network_graph.read_only(), None, 10_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3447 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3448 } else { panic!(); }
3452 // Now, attempt to route an exact amount we have should be fine.
3453 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 10_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3454 assert_eq!(route.paths.len(), 1);
3455 let path = route.paths.last().unwrap();
3456 assert_eq!(path.len(), 2);
3457 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3458 assert_eq!(path.last().unwrap().fee_msat, 10_000);
3463 fn available_liquidity_last_hop_test() {
3464 // Check that available liquidity properly limits the path even when only
3465 // one of the latter hops is limited.
3466 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3467 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3468 let scorer = ln_test_utils::TestScorer::with_penalty(0);
3469 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3470 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3471 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(channelmanager::provided_invoice_features());
3473 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3474 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
3475 // Total capacity: 50 sats.
3477 // Disable other potential paths.
3478 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3479 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3480 short_channel_id: 2,
3483 cltv_expiry_delta: 0,
3484 htlc_minimum_msat: 0,
3485 htlc_maximum_msat: 100_000,
3487 fee_proportional_millionths: 0,
3488 excess_data: Vec::new()
3490 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3491 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3492 short_channel_id: 7,
3495 cltv_expiry_delta: 0,
3496 htlc_minimum_msat: 0,
3497 htlc_maximum_msat: 100_000,
3499 fee_proportional_millionths: 0,
3500 excess_data: Vec::new()
3505 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3506 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3507 short_channel_id: 12,
3510 cltv_expiry_delta: 0,
3511 htlc_minimum_msat: 0,
3512 htlc_maximum_msat: 100_000,
3514 fee_proportional_millionths: 0,
3515 excess_data: Vec::new()
3517 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3518 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3519 short_channel_id: 13,
3522 cltv_expiry_delta: 0,
3523 htlc_minimum_msat: 0,
3524 htlc_maximum_msat: 100_000,
3526 fee_proportional_millionths: 0,
3527 excess_data: Vec::new()
3530 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3531 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3532 short_channel_id: 6,
3535 cltv_expiry_delta: 0,
3536 htlc_minimum_msat: 0,
3537 htlc_maximum_msat: 50_000,
3539 fee_proportional_millionths: 0,
3540 excess_data: Vec::new()
3542 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3543 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3544 short_channel_id: 11,
3547 cltv_expiry_delta: 0,
3548 htlc_minimum_msat: 0,
3549 htlc_maximum_msat: 100_000,
3551 fee_proportional_millionths: 0,
3552 excess_data: Vec::new()
3555 // Attempt to route more than available results in a failure.
3556 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3557 &our_id, &payment_params, &network_graph.read_only(), None, 60_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3558 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3559 } else { panic!(); }
3563 // Now, attempt to route 49 sats (just a bit below the capacity).
3564 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 49_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3565 assert_eq!(route.paths.len(), 1);
3566 let mut total_amount_paid_msat = 0;
3567 for path in &route.paths {
3568 assert_eq!(path.len(), 4);
3569 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3570 total_amount_paid_msat += path.last().unwrap().fee_msat;
3572 assert_eq!(total_amount_paid_msat, 49_000);
3576 // Attempt to route an exact amount is also fine
3577 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3578 assert_eq!(route.paths.len(), 1);
3579 let mut total_amount_paid_msat = 0;
3580 for path in &route.paths {
3581 assert_eq!(path.len(), 4);
3582 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3583 total_amount_paid_msat += path.last().unwrap().fee_msat;
3585 assert_eq!(total_amount_paid_msat, 50_000);
3590 fn ignore_fee_first_hop_test() {
3591 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3592 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3593 let scorer = ln_test_utils::TestScorer::with_penalty(0);
3594 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3595 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3596 let payment_params = PaymentParameters::from_node_id(nodes[2]);
3598 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3599 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3600 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3601 short_channel_id: 1,
3604 cltv_expiry_delta: 0,
3605 htlc_minimum_msat: 0,
3606 htlc_maximum_msat: 100_000,
3607 fee_base_msat: 1_000_000,
3608 fee_proportional_millionths: 0,
3609 excess_data: Vec::new()
3611 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3612 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3613 short_channel_id: 3,
3616 cltv_expiry_delta: 0,
3617 htlc_minimum_msat: 0,
3618 htlc_maximum_msat: 50_000,
3620 fee_proportional_millionths: 0,
3621 excess_data: Vec::new()
3625 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3626 assert_eq!(route.paths.len(), 1);
3627 let mut total_amount_paid_msat = 0;
3628 for path in &route.paths {
3629 assert_eq!(path.len(), 2);
3630 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3631 total_amount_paid_msat += path.last().unwrap().fee_msat;
3633 assert_eq!(total_amount_paid_msat, 50_000);
3638 fn simple_mpp_route_test() {
3639 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3640 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3641 let scorer = ln_test_utils::TestScorer::with_penalty(0);
3642 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3643 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3644 let payment_params = PaymentParameters::from_node_id(nodes[2])
3645 .with_features(channelmanager::provided_invoice_features());
3647 // We need a route consisting of 3 paths:
3648 // From our node to node2 via node0, node7, node1 (three paths one hop each).
3649 // To achieve this, the amount being transferred should be around
3650 // the total capacity of these 3 paths.
3652 // First, we set limits on these (previously unlimited) channels.
3653 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
3655 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3656 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3657 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3658 short_channel_id: 1,
3661 cltv_expiry_delta: 0,
3662 htlc_minimum_msat: 0,
3663 htlc_maximum_msat: 100_000,
3665 fee_proportional_millionths: 0,
3666 excess_data: Vec::new()
3668 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3669 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3670 short_channel_id: 3,
3673 cltv_expiry_delta: 0,
3674 htlc_minimum_msat: 0,
3675 htlc_maximum_msat: 50_000,
3677 fee_proportional_millionths: 0,
3678 excess_data: Vec::new()
3681 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
3682 // (total limit 60).
3683 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3684 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3685 short_channel_id: 12,
3688 cltv_expiry_delta: 0,
3689 htlc_minimum_msat: 0,
3690 htlc_maximum_msat: 60_000,
3692 fee_proportional_millionths: 0,
3693 excess_data: Vec::new()
3695 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3696 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3697 short_channel_id: 13,
3700 cltv_expiry_delta: 0,
3701 htlc_minimum_msat: 0,
3702 htlc_maximum_msat: 60_000,
3704 fee_proportional_millionths: 0,
3705 excess_data: Vec::new()
3708 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
3709 // (total capacity 180 sats).
3710 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3711 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3712 short_channel_id: 2,
3715 cltv_expiry_delta: 0,
3716 htlc_minimum_msat: 0,
3717 htlc_maximum_msat: 200_000,
3719 fee_proportional_millionths: 0,
3720 excess_data: Vec::new()
3722 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3723 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3724 short_channel_id: 4,
3727 cltv_expiry_delta: 0,
3728 htlc_minimum_msat: 0,
3729 htlc_maximum_msat: 180_000,
3731 fee_proportional_millionths: 0,
3732 excess_data: Vec::new()
3736 // Attempt to route more than available results in a failure.
3737 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3738 &our_id, &payment_params, &network_graph.read_only(), None, 300_000, 42,
3739 Arc::clone(&logger), &scorer, &random_seed_bytes) {
3740 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3741 } else { panic!(); }
3745 // Attempt to route while setting max_path_count to 0 results in a failure.
3746 let zero_payment_params = payment_params.clone().with_max_path_count(0);
3747 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3748 &our_id, &zero_payment_params, &network_graph.read_only(), None, 100, 42,
3749 Arc::clone(&logger), &scorer, &random_seed_bytes) {
3750 assert_eq!(err, "Can't find a route with no paths allowed.");
3751 } else { panic!(); }
3755 // Attempt to route while setting max_path_count to 3 results in a failure.
3756 // This is the case because the minimal_value_contribution_msat would require each path
3757 // to account for 1/3 of the total value, which is violated by 2 out of 3 paths.
3758 let fail_payment_params = payment_params.clone().with_max_path_count(3);
3759 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3760 &our_id, &fail_payment_params, &network_graph.read_only(), None, 250_000, 42,
3761 Arc::clone(&logger), &scorer, &random_seed_bytes) {
3762 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3763 } else { panic!(); }
3767 // Now, attempt to route 250 sats (just a bit below the capacity).
3768 // Our algorithm should provide us with these 3 paths.
3769 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None,
3770 250_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3771 assert_eq!(route.paths.len(), 3);
3772 let mut total_amount_paid_msat = 0;
3773 for path in &route.paths {
3774 assert_eq!(path.len(), 2);
3775 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3776 total_amount_paid_msat += path.last().unwrap().fee_msat;
3778 assert_eq!(total_amount_paid_msat, 250_000);
3782 // Attempt to route an exact amount is also fine
3783 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None,
3784 290_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3785 assert_eq!(route.paths.len(), 3);
3786 let mut total_amount_paid_msat = 0;
3787 for path in &route.paths {
3788 assert_eq!(path.len(), 2);
3789 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3790 total_amount_paid_msat += path.last().unwrap().fee_msat;
3792 assert_eq!(total_amount_paid_msat, 290_000);
3797 fn long_mpp_route_test() {
3798 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3799 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3800 let scorer = ln_test_utils::TestScorer::with_penalty(0);
3801 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3802 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3803 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(channelmanager::provided_invoice_features());
3805 // We need a route consisting of 3 paths:
3806 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3807 // Note that these paths overlap (channels 5, 12, 13).
3808 // We will route 300 sats.
3809 // Each path will have 100 sats capacity, those channels which
3810 // are used twice will have 200 sats capacity.
3812 // Disable other potential paths.
3813 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3814 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3815 short_channel_id: 2,
3818 cltv_expiry_delta: 0,
3819 htlc_minimum_msat: 0,
3820 htlc_maximum_msat: 100_000,
3822 fee_proportional_millionths: 0,
3823 excess_data: Vec::new()
3825 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3826 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3827 short_channel_id: 7,
3830 cltv_expiry_delta: 0,
3831 htlc_minimum_msat: 0,
3832 htlc_maximum_msat: 100_000,
3834 fee_proportional_millionths: 0,
3835 excess_data: Vec::new()
3838 // Path via {node0, node2} is channels {1, 3, 5}.
3839 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3840 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3841 short_channel_id: 1,
3844 cltv_expiry_delta: 0,
3845 htlc_minimum_msat: 0,
3846 htlc_maximum_msat: 100_000,
3848 fee_proportional_millionths: 0,
3849 excess_data: Vec::new()
3851 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3852 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3853 short_channel_id: 3,
3856 cltv_expiry_delta: 0,
3857 htlc_minimum_msat: 0,
3858 htlc_maximum_msat: 100_000,
3860 fee_proportional_millionths: 0,
3861 excess_data: Vec::new()
3864 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3865 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3866 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3867 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3868 short_channel_id: 5,
3871 cltv_expiry_delta: 0,
3872 htlc_minimum_msat: 0,
3873 htlc_maximum_msat: 200_000,
3875 fee_proportional_millionths: 0,
3876 excess_data: Vec::new()
3879 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3880 // Add 100 sats to the capacities of {12, 13}, because these channels
3881 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3882 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3883 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3884 short_channel_id: 12,
3887 cltv_expiry_delta: 0,
3888 htlc_minimum_msat: 0,
3889 htlc_maximum_msat: 200_000,
3891 fee_proportional_millionths: 0,
3892 excess_data: Vec::new()
3894 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3895 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3896 short_channel_id: 13,
3899 cltv_expiry_delta: 0,
3900 htlc_minimum_msat: 0,
3901 htlc_maximum_msat: 200_000,
3903 fee_proportional_millionths: 0,
3904 excess_data: Vec::new()
3907 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3908 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3909 short_channel_id: 6,
3912 cltv_expiry_delta: 0,
3913 htlc_minimum_msat: 0,
3914 htlc_maximum_msat: 100_000,
3916 fee_proportional_millionths: 0,
3917 excess_data: Vec::new()
3919 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3920 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3921 short_channel_id: 11,
3924 cltv_expiry_delta: 0,
3925 htlc_minimum_msat: 0,
3926 htlc_maximum_msat: 100_000,
3928 fee_proportional_millionths: 0,
3929 excess_data: Vec::new()
3932 // Path via {node7, node2} is channels {12, 13, 5}.
3933 // We already limited them to 200 sats (they are used twice for 100 sats).
3934 // Nothing to do here.
3937 // Attempt to route more than available results in a failure.
3938 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3939 &our_id, &payment_params, &network_graph.read_only(), None, 350_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3940 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3941 } else { panic!(); }
3945 // Now, attempt to route 300 sats (exact amount we can route).
3946 // Our algorithm should provide us with these 3 paths, 100 sats each.
3947 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 300_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3948 assert_eq!(route.paths.len(), 3);
3950 let mut total_amount_paid_msat = 0;
3951 for path in &route.paths {
3952 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3953 total_amount_paid_msat += path.last().unwrap().fee_msat;
3955 assert_eq!(total_amount_paid_msat, 300_000);
3961 fn mpp_cheaper_route_test() {
3962 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3963 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3964 let scorer = ln_test_utils::TestScorer::with_penalty(0);
3965 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3966 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3967 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(channelmanager::provided_invoice_features());
3969 // This test checks that if we have two cheaper paths and one more expensive path,
3970 // so that liquidity-wise any 2 of 3 combination is sufficient,
3971 // two cheaper paths will be taken.
3972 // These paths have equal available liquidity.
3974 // We need a combination of 3 paths:
3975 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3976 // Note that these paths overlap (channels 5, 12, 13).
3977 // Each path will have 100 sats capacity, those channels which
3978 // are used twice will have 200 sats capacity.
3980 // Disable other potential paths.
3981 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3982 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3983 short_channel_id: 2,
3986 cltv_expiry_delta: 0,
3987 htlc_minimum_msat: 0,
3988 htlc_maximum_msat: 100_000,
3990 fee_proportional_millionths: 0,
3991 excess_data: Vec::new()
3993 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3994 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3995 short_channel_id: 7,
3998 cltv_expiry_delta: 0,
3999 htlc_minimum_msat: 0,
4000 htlc_maximum_msat: 100_000,
4002 fee_proportional_millionths: 0,
4003 excess_data: Vec::new()
4006 // Path via {node0, node2} is channels {1, 3, 5}.
4007 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4008 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4009 short_channel_id: 1,
4012 cltv_expiry_delta: 0,
4013 htlc_minimum_msat: 0,
4014 htlc_maximum_msat: 100_000,
4016 fee_proportional_millionths: 0,
4017 excess_data: Vec::new()
4019 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4020 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4021 short_channel_id: 3,
4024 cltv_expiry_delta: 0,
4025 htlc_minimum_msat: 0,
4026 htlc_maximum_msat: 100_000,
4028 fee_proportional_millionths: 0,
4029 excess_data: Vec::new()
4032 // Capacity of 200 sats because this channel will be used by 3rd path as well.
4033 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4034 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4035 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4036 short_channel_id: 5,
4039 cltv_expiry_delta: 0,
4040 htlc_minimum_msat: 0,
4041 htlc_maximum_msat: 200_000,
4043 fee_proportional_millionths: 0,
4044 excess_data: Vec::new()
4047 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4048 // Add 100 sats to the capacities of {12, 13}, because these channels
4049 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
4050 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4051 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4052 short_channel_id: 12,
4055 cltv_expiry_delta: 0,
4056 htlc_minimum_msat: 0,
4057 htlc_maximum_msat: 200_000,
4059 fee_proportional_millionths: 0,
4060 excess_data: Vec::new()
4062 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4063 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4064 short_channel_id: 13,
4067 cltv_expiry_delta: 0,
4068 htlc_minimum_msat: 0,
4069 htlc_maximum_msat: 200_000,
4071 fee_proportional_millionths: 0,
4072 excess_data: Vec::new()
4075 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4076 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4077 short_channel_id: 6,
4080 cltv_expiry_delta: 0,
4081 htlc_minimum_msat: 0,
4082 htlc_maximum_msat: 100_000,
4083 fee_base_msat: 1_000,
4084 fee_proportional_millionths: 0,
4085 excess_data: Vec::new()
4087 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4088 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4089 short_channel_id: 11,
4092 cltv_expiry_delta: 0,
4093 htlc_minimum_msat: 0,
4094 htlc_maximum_msat: 100_000,
4096 fee_proportional_millionths: 0,
4097 excess_data: Vec::new()
4100 // Path via {node7, node2} is channels {12, 13, 5}.
4101 // We already limited them to 200 sats (they are used twice for 100 sats).
4102 // Nothing to do here.
4105 // Now, attempt to route 180 sats.
4106 // Our algorithm should provide us with these 2 paths.
4107 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 180_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4108 assert_eq!(route.paths.len(), 2);
4110 let mut total_value_transferred_msat = 0;
4111 let mut total_paid_msat = 0;
4112 for path in &route.paths {
4113 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
4114 total_value_transferred_msat += path.last().unwrap().fee_msat;
4116 total_paid_msat += hop.fee_msat;
4119 // If we paid fee, this would be higher.
4120 assert_eq!(total_value_transferred_msat, 180_000);
4121 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
4122 assert_eq!(total_fees_paid, 0);
4127 fn fees_on_mpp_route_test() {
4128 // This test makes sure that MPP algorithm properly takes into account
4129 // fees charged on the channels, by making the fees impactful:
4130 // if the fee is not properly accounted for, the behavior is different.
4131 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4132 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4133 let scorer = ln_test_utils::TestScorer::with_penalty(0);
4134 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4135 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4136 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(channelmanager::provided_invoice_features());
4138 // We need a route consisting of 2 paths:
4139 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
4140 // We will route 200 sats, Each path will have 100 sats capacity.
4142 // This test is not particularly stable: e.g.,
4143 // there's a way to route via {node0, node2, node4}.
4144 // It works while pathfinding is deterministic, but can be broken otherwise.
4145 // It's fine to ignore this concern for now.
4147 // Disable other potential paths.
4148 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4149 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4150 short_channel_id: 2,
4153 cltv_expiry_delta: 0,
4154 htlc_minimum_msat: 0,
4155 htlc_maximum_msat: 100_000,
4157 fee_proportional_millionths: 0,
4158 excess_data: Vec::new()
4161 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4162 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4163 short_channel_id: 7,
4166 cltv_expiry_delta: 0,
4167 htlc_minimum_msat: 0,
4168 htlc_maximum_msat: 100_000,
4170 fee_proportional_millionths: 0,
4171 excess_data: Vec::new()
4174 // Path via {node0, node2} is channels {1, 3, 5}.
4175 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4176 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4177 short_channel_id: 1,
4180 cltv_expiry_delta: 0,
4181 htlc_minimum_msat: 0,
4182 htlc_maximum_msat: 100_000,
4184 fee_proportional_millionths: 0,
4185 excess_data: Vec::new()
4187 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4188 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4189 short_channel_id: 3,
4192 cltv_expiry_delta: 0,
4193 htlc_minimum_msat: 0,
4194 htlc_maximum_msat: 100_000,
4196 fee_proportional_millionths: 0,
4197 excess_data: Vec::new()
4200 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4201 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4202 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4203 short_channel_id: 5,
4206 cltv_expiry_delta: 0,
4207 htlc_minimum_msat: 0,
4208 htlc_maximum_msat: 100_000,
4210 fee_proportional_millionths: 0,
4211 excess_data: Vec::new()
4214 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4215 // All channels should be 100 sats capacity. But for the fee experiment,
4216 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
4217 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
4218 // 100 sats (and pay 150 sats in fees for the use of channel 6),
4219 // so no matter how large are other channels,
4220 // the whole path will be limited by 100 sats with just these 2 conditions:
4221 // - channel 12 capacity is 250 sats
4222 // - fee for channel 6 is 150 sats
4223 // Let's test this by enforcing these 2 conditions and removing other limits.
4224 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4225 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4226 short_channel_id: 12,
4229 cltv_expiry_delta: 0,
4230 htlc_minimum_msat: 0,
4231 htlc_maximum_msat: 250_000,
4233 fee_proportional_millionths: 0,
4234 excess_data: Vec::new()
4236 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4237 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4238 short_channel_id: 13,
4241 cltv_expiry_delta: 0,
4242 htlc_minimum_msat: 0,
4243 htlc_maximum_msat: MAX_VALUE_MSAT,
4245 fee_proportional_millionths: 0,
4246 excess_data: Vec::new()
4249 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4250 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4251 short_channel_id: 6,
4254 cltv_expiry_delta: 0,
4255 htlc_minimum_msat: 0,
4256 htlc_maximum_msat: MAX_VALUE_MSAT,
4257 fee_base_msat: 150_000,
4258 fee_proportional_millionths: 0,
4259 excess_data: Vec::new()
4261 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4262 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4263 short_channel_id: 11,
4266 cltv_expiry_delta: 0,
4267 htlc_minimum_msat: 0,
4268 htlc_maximum_msat: MAX_VALUE_MSAT,
4270 fee_proportional_millionths: 0,
4271 excess_data: Vec::new()
4275 // Attempt to route more than available results in a failure.
4276 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4277 &our_id, &payment_params, &network_graph.read_only(), None, 210_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
4278 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4279 } else { panic!(); }
4283 // Now, attempt to route 200 sats (exact amount we can route).
4284 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 200_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4285 assert_eq!(route.paths.len(), 2);
4287 let mut total_amount_paid_msat = 0;
4288 for path in &route.paths {
4289 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
4290 total_amount_paid_msat += path.last().unwrap().fee_msat;
4292 assert_eq!(total_amount_paid_msat, 200_000);
4293 assert_eq!(route.get_total_fees(), 150_000);
4298 fn mpp_with_last_hops() {
4299 // Previously, if we tried to send an MPP payment to a destination which was only reachable
4300 // via a single last-hop route hint, we'd fail to route if we first collected routes
4301 // totaling close but not quite enough to fund the full payment.
4303 // This was because we considered last-hop hints to have exactly the sought payment amount
4304 // instead of the amount we were trying to collect, needlessly limiting our path searching
4305 // at the very first hop.
4307 // Specifically, this interacted with our "all paths must fund at least 5% of total target"
4308 // criterion to cause us to refuse all routes at the last hop hint which would be considered
4309 // to only have the remaining to-collect amount in available liquidity.
4311 // This bug appeared in production in some specific channel configurations.
4312 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4313 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4314 let scorer = ln_test_utils::TestScorer::with_penalty(0);
4315 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4316 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4317 let payment_params = PaymentParameters::from_node_id(PublicKey::from_slice(&[02; 33]).unwrap()).with_features(channelmanager::provided_invoice_features())
4318 .with_route_hints(vec![RouteHint(vec![RouteHintHop {
4319 src_node_id: nodes[2],
4320 short_channel_id: 42,
4321 fees: RoutingFees { base_msat: 0, proportional_millionths: 0 },
4322 cltv_expiry_delta: 42,
4323 htlc_minimum_msat: None,
4324 htlc_maximum_msat: None,
4325 }])]).with_max_channel_saturation_power_of_half(0);
4327 // Keep only two paths from us to nodes[2], both with a 99sat HTLC maximum, with one with
4328 // no fee and one with a 1msat fee. Previously, trying to route 100 sats to nodes[2] here
4329 // would first use the no-fee route and then fail to find a path along the second route as
4330 // we think we can only send up to 1 additional sat over the last-hop but refuse to as its
4331 // under 5% of our payment amount.
4332 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4333 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4334 short_channel_id: 1,
4337 cltv_expiry_delta: (5 << 4) | 5,
4338 htlc_minimum_msat: 0,
4339 htlc_maximum_msat: 99_000,
4340 fee_base_msat: u32::max_value(),
4341 fee_proportional_millionths: u32::max_value(),
4342 excess_data: Vec::new()
4344 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4345 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4346 short_channel_id: 2,
4349 cltv_expiry_delta: (5 << 4) | 3,
4350 htlc_minimum_msat: 0,
4351 htlc_maximum_msat: 99_000,
4352 fee_base_msat: u32::max_value(),
4353 fee_proportional_millionths: u32::max_value(),
4354 excess_data: Vec::new()
4356 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4357 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4358 short_channel_id: 4,
4361 cltv_expiry_delta: (4 << 4) | 1,
4362 htlc_minimum_msat: 0,
4363 htlc_maximum_msat: MAX_VALUE_MSAT,
4365 fee_proportional_millionths: 0,
4366 excess_data: Vec::new()
4368 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4369 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4370 short_channel_id: 13,
4372 flags: 0|2, // Channel disabled
4373 cltv_expiry_delta: (13 << 4) | 1,
4374 htlc_minimum_msat: 0,
4375 htlc_maximum_msat: MAX_VALUE_MSAT,
4377 fee_proportional_millionths: 2000000,
4378 excess_data: Vec::new()
4381 // Get a route for 100 sats and check that we found the MPP route no problem and didn't
4383 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();
4384 assert_eq!(route.paths.len(), 2);
4385 route.paths.sort_by_key(|path| path[0].short_channel_id);
4386 // Paths are manually ordered ordered by SCID, so:
4387 // * the first is channel 1 (0 fee, but 99 sat maximum) -> channel 3 -> channel 42
4388 // * the second is channel 2 (1 msat fee) -> channel 4 -> channel 42
4389 assert_eq!(route.paths[0][0].short_channel_id, 1);
4390 assert_eq!(route.paths[0][0].fee_msat, 0);
4391 assert_eq!(route.paths[0][2].fee_msat, 99_000);
4392 assert_eq!(route.paths[1][0].short_channel_id, 2);
4393 assert_eq!(route.paths[1][0].fee_msat, 1);
4394 assert_eq!(route.paths[1][2].fee_msat, 1_000);
4395 assert_eq!(route.get_total_fees(), 1);
4396 assert_eq!(route.get_total_amount(), 100_000);
4400 fn drop_lowest_channel_mpp_route_test() {
4401 // This test checks that low-capacity channel is dropped when after
4402 // path finding we realize that we found more capacity than we need.
4403 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4404 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4405 let scorer = ln_test_utils::TestScorer::with_penalty(0);
4406 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4407 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4408 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(channelmanager::provided_invoice_features())
4409 .with_max_channel_saturation_power_of_half(0);
4411 // We need a route consisting of 3 paths:
4412 // From our node to node2 via node0, node7, node1 (three paths one hop each).
4414 // The first and the second paths should be sufficient, but the third should be
4415 // cheaper, so that we select it but drop later.
4417 // First, we set limits on these (previously unlimited) channels.
4418 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
4420 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
4421 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4422 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4423 short_channel_id: 1,
4426 cltv_expiry_delta: 0,
4427 htlc_minimum_msat: 0,
4428 htlc_maximum_msat: 100_000,
4430 fee_proportional_millionths: 0,
4431 excess_data: Vec::new()
4433 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4434 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4435 short_channel_id: 3,
4438 cltv_expiry_delta: 0,
4439 htlc_minimum_msat: 0,
4440 htlc_maximum_msat: 50_000,
4442 fee_proportional_millionths: 0,
4443 excess_data: Vec::new()
4446 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
4447 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4448 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4449 short_channel_id: 12,
4452 cltv_expiry_delta: 0,
4453 htlc_minimum_msat: 0,
4454 htlc_maximum_msat: 60_000,
4456 fee_proportional_millionths: 0,
4457 excess_data: Vec::new()
4459 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4460 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4461 short_channel_id: 13,
4464 cltv_expiry_delta: 0,
4465 htlc_minimum_msat: 0,
4466 htlc_maximum_msat: 60_000,
4468 fee_proportional_millionths: 0,
4469 excess_data: Vec::new()
4472 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
4473 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4474 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4475 short_channel_id: 2,
4478 cltv_expiry_delta: 0,
4479 htlc_minimum_msat: 0,
4480 htlc_maximum_msat: 20_000,
4482 fee_proportional_millionths: 0,
4483 excess_data: Vec::new()
4485 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4486 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4487 short_channel_id: 4,
4490 cltv_expiry_delta: 0,
4491 htlc_minimum_msat: 0,
4492 htlc_maximum_msat: 20_000,
4494 fee_proportional_millionths: 0,
4495 excess_data: Vec::new()
4499 // Attempt to route more than available results in a failure.
4500 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4501 &our_id, &payment_params, &network_graph.read_only(), None, 150_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
4502 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4503 } else { panic!(); }
4507 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
4508 // Our algorithm should provide us with these 3 paths.
4509 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 125_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4510 assert_eq!(route.paths.len(), 3);
4511 let mut total_amount_paid_msat = 0;
4512 for path in &route.paths {
4513 assert_eq!(path.len(), 2);
4514 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4515 total_amount_paid_msat += path.last().unwrap().fee_msat;
4517 assert_eq!(total_amount_paid_msat, 125_000);
4521 // Attempt to route without the last small cheap channel
4522 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4523 assert_eq!(route.paths.len(), 2);
4524 let mut total_amount_paid_msat = 0;
4525 for path in &route.paths {
4526 assert_eq!(path.len(), 2);
4527 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4528 total_amount_paid_msat += path.last().unwrap().fee_msat;
4530 assert_eq!(total_amount_paid_msat, 90_000);
4535 fn min_criteria_consistency() {
4536 // Test that we don't use an inconsistent metric between updating and walking nodes during
4537 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
4538 // was updated with a different criterion from the heap sorting, resulting in loops in
4539 // calculated paths. We test for that specific case here.
4541 // We construct a network that looks like this:
4543 // node2 -1(3)2- node3
4547 // node1 -1(5)2- node4 -1(1)2- node6
4553 // We create a loop on the side of our real path - our destination is node 6, with a
4554 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
4555 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
4556 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
4557 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
4558 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
4559 // "previous hop" being set to node 3, creating a loop in the path.
4560 let secp_ctx = Secp256k1::new();
4561 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
4562 let logger = Arc::new(ln_test_utils::TestLogger::new());
4563 let network = Arc::new(NetworkGraph::new(genesis_hash, Arc::clone(&logger)));
4564 let gossip_sync = P2PGossipSync::new(Arc::clone(&network), None, Arc::clone(&logger));
4565 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4566 let scorer = ln_test_utils::TestScorer::with_penalty(0);
4567 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4568 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4569 let payment_params = PaymentParameters::from_node_id(nodes[6]);
4571 add_channel(&gossip_sync, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
4572 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4573 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4574 short_channel_id: 6,
4577 cltv_expiry_delta: (6 << 4) | 0,
4578 htlc_minimum_msat: 0,
4579 htlc_maximum_msat: MAX_VALUE_MSAT,
4581 fee_proportional_millionths: 0,
4582 excess_data: Vec::new()
4584 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
4586 add_channel(&gossip_sync, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4587 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4588 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4589 short_channel_id: 5,
4592 cltv_expiry_delta: (5 << 4) | 0,
4593 htlc_minimum_msat: 0,
4594 htlc_maximum_msat: MAX_VALUE_MSAT,
4596 fee_proportional_millionths: 0,
4597 excess_data: Vec::new()
4599 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
4601 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
4602 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4603 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4604 short_channel_id: 4,
4607 cltv_expiry_delta: (4 << 4) | 0,
4608 htlc_minimum_msat: 0,
4609 htlc_maximum_msat: MAX_VALUE_MSAT,
4611 fee_proportional_millionths: 0,
4612 excess_data: Vec::new()
4614 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
4616 add_channel(&gossip_sync, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
4617 update_channel(&gossip_sync, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
4618 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4619 short_channel_id: 3,
4622 cltv_expiry_delta: (3 << 4) | 0,
4623 htlc_minimum_msat: 0,
4624 htlc_maximum_msat: MAX_VALUE_MSAT,
4626 fee_proportional_millionths: 0,
4627 excess_data: Vec::new()
4629 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
4631 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
4632 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4633 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4634 short_channel_id: 2,
4637 cltv_expiry_delta: (2 << 4) | 0,
4638 htlc_minimum_msat: 0,
4639 htlc_maximum_msat: MAX_VALUE_MSAT,
4641 fee_proportional_millionths: 0,
4642 excess_data: Vec::new()
4645 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
4646 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4647 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4648 short_channel_id: 1,
4651 cltv_expiry_delta: (1 << 4) | 0,
4652 htlc_minimum_msat: 100,
4653 htlc_maximum_msat: MAX_VALUE_MSAT,
4655 fee_proportional_millionths: 0,
4656 excess_data: Vec::new()
4658 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
4661 // Now ensure the route flows simply over nodes 1 and 4 to 6.
4662 let route = get_route(&our_id, &payment_params, &network.read_only(), None, 10_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4663 assert_eq!(route.paths.len(), 1);
4664 assert_eq!(route.paths[0].len(), 3);
4666 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
4667 assert_eq!(route.paths[0][0].short_channel_id, 6);
4668 assert_eq!(route.paths[0][0].fee_msat, 100);
4669 assert_eq!(route.paths[0][0].cltv_expiry_delta, (5 << 4) | 0);
4670 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(1));
4671 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(6));
4673 assert_eq!(route.paths[0][1].pubkey, nodes[4]);
4674 assert_eq!(route.paths[0][1].short_channel_id, 5);
4675 assert_eq!(route.paths[0][1].fee_msat, 0);
4676 assert_eq!(route.paths[0][1].cltv_expiry_delta, (1 << 4) | 0);
4677 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(4));
4678 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(5));
4680 assert_eq!(route.paths[0][2].pubkey, nodes[6]);
4681 assert_eq!(route.paths[0][2].short_channel_id, 1);
4682 assert_eq!(route.paths[0][2].fee_msat, 10_000);
4683 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
4684 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
4685 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(1));
4691 fn exact_fee_liquidity_limit() {
4692 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
4693 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
4694 // we calculated fees on a higher value, resulting in us ignoring such paths.
4695 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4696 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
4697 let scorer = ln_test_utils::TestScorer::with_penalty(0);
4698 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4699 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4700 let payment_params = PaymentParameters::from_node_id(nodes[2]);
4702 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
4704 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4705 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4706 short_channel_id: 2,
4709 cltv_expiry_delta: 0,
4710 htlc_minimum_msat: 0,
4711 htlc_maximum_msat: 85_000,
4713 fee_proportional_millionths: 0,
4714 excess_data: Vec::new()
4717 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4718 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4719 short_channel_id: 12,
4722 cltv_expiry_delta: (4 << 4) | 1,
4723 htlc_minimum_msat: 0,
4724 htlc_maximum_msat: 270_000,
4726 fee_proportional_millionths: 1000000,
4727 excess_data: Vec::new()
4731 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
4732 // 200% fee charged channel 13 in the 1-to-2 direction.
4733 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4734 assert_eq!(route.paths.len(), 1);
4735 assert_eq!(route.paths[0].len(), 2);
4737 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
4738 assert_eq!(route.paths[0][0].short_channel_id, 12);
4739 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
4740 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
4741 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
4742 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
4744 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
4745 assert_eq!(route.paths[0][1].short_channel_id, 13);
4746 assert_eq!(route.paths[0][1].fee_msat, 90_000);
4747 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
4748 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
4749 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
4754 fn htlc_max_reduction_below_min() {
4755 // Test that if, while walking the graph, we reduce the value being sent to meet an
4756 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
4757 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
4758 // resulting in us thinking there is no possible path, even if other paths exist.
4759 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4760 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4761 let scorer = ln_test_utils::TestScorer::with_penalty(0);
4762 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4763 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4764 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(channelmanager::provided_invoice_features());
4766 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
4767 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
4768 // then try to send 90_000.
4769 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4770 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4771 short_channel_id: 2,
4774 cltv_expiry_delta: 0,
4775 htlc_minimum_msat: 0,
4776 htlc_maximum_msat: 80_000,
4778 fee_proportional_millionths: 0,
4779 excess_data: Vec::new()
4781 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4782 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4783 short_channel_id: 4,
4786 cltv_expiry_delta: (4 << 4) | 1,
4787 htlc_minimum_msat: 90_000,
4788 htlc_maximum_msat: MAX_VALUE_MSAT,
4790 fee_proportional_millionths: 0,
4791 excess_data: Vec::new()
4795 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
4796 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
4797 // expensive) channels 12-13 path.
4798 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4799 assert_eq!(route.paths.len(), 1);
4800 assert_eq!(route.paths[0].len(), 2);
4802 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
4803 assert_eq!(route.paths[0][0].short_channel_id, 12);
4804 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
4805 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
4806 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
4807 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
4809 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
4810 assert_eq!(route.paths[0][1].short_channel_id, 13);
4811 assert_eq!(route.paths[0][1].fee_msat, 90_000);
4812 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
4813 assert_eq!(route.paths[0][1].node_features.le_flags(), channelmanager::provided_invoice_features().le_flags());
4814 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
4819 fn multiple_direct_first_hops() {
4820 // Previously we'd only ever considered one first hop path per counterparty.
4821 // However, as we don't restrict users to one channel per peer, we really need to support
4822 // looking at all first hop paths.
4823 // Here we test that we do not ignore all-but-the-last first hop paths per counterparty (as
4824 // we used to do by overwriting the `first_hop_targets` hashmap entry) and that we can MPP
4825 // route over multiple channels with the same first hop.
4826 let secp_ctx = Secp256k1::new();
4827 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4828 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
4829 let logger = Arc::new(ln_test_utils::TestLogger::new());
4830 let network_graph = NetworkGraph::new(genesis_hash, Arc::clone(&logger));
4831 let scorer = ln_test_utils::TestScorer::with_penalty(0);
4832 let payment_params = PaymentParameters::from_node_id(nodes[0]).with_features(channelmanager::provided_invoice_features());
4833 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4834 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4837 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
4838 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(), 200_000),
4839 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(), 10_000),
4840 ]), 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4841 assert_eq!(route.paths.len(), 1);
4842 assert_eq!(route.paths[0].len(), 1);
4844 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
4845 assert_eq!(route.paths[0][0].short_channel_id, 3);
4846 assert_eq!(route.paths[0][0].fee_msat, 100_000);
4849 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
4850 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(), 50_000),
4851 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(), 50_000),
4852 ]), 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4853 assert_eq!(route.paths.len(), 2);
4854 assert_eq!(route.paths[0].len(), 1);
4855 assert_eq!(route.paths[1].len(), 1);
4857 assert!((route.paths[0][0].short_channel_id == 3 && route.paths[1][0].short_channel_id == 2) ||
4858 (route.paths[0][0].short_channel_id == 2 && route.paths[1][0].short_channel_id == 3));
4860 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
4861 assert_eq!(route.paths[0][0].fee_msat, 50_000);
4863 assert_eq!(route.paths[1][0].pubkey, nodes[0]);
4864 assert_eq!(route.paths[1][0].fee_msat, 50_000);
4868 // If we have a bunch of outbound channels to the same node, where most are not
4869 // sufficient to pay the full payment, but one is, we should default to just using the
4870 // one single channel that has sufficient balance, avoiding MPP.
4872 // If we have several options above the 3xpayment value threshold, we should pick the
4873 // smallest of them, avoiding further fragmenting our available outbound balance to
4875 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
4876 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(), 50_000),
4877 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(), 50_000),
4878 &get_channel_details(Some(5), nodes[0], channelmanager::provided_init_features(), 50_000),
4879 &get_channel_details(Some(6), nodes[0], channelmanager::provided_init_features(), 300_000),
4880 &get_channel_details(Some(7), nodes[0], channelmanager::provided_init_features(), 50_000),
4881 &get_channel_details(Some(8), nodes[0], channelmanager::provided_init_features(), 50_000),
4882 &get_channel_details(Some(9), nodes[0], channelmanager::provided_init_features(), 50_000),
4883 &get_channel_details(Some(4), nodes[0], channelmanager::provided_init_features(), 1_000_000),
4884 ]), 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4885 assert_eq!(route.paths.len(), 1);
4886 assert_eq!(route.paths[0].len(), 1);
4888 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
4889 assert_eq!(route.paths[0][0].short_channel_id, 6);
4890 assert_eq!(route.paths[0][0].fee_msat, 100_000);
4895 fn prefers_shorter_route_with_higher_fees() {
4896 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4897 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4898 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
4900 // Without penalizing each hop 100 msats, a longer path with lower fees is chosen.
4901 let scorer = ln_test_utils::TestScorer::with_penalty(0);
4902 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4903 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4904 let route = get_route(
4905 &our_id, &payment_params, &network_graph.read_only(), None, 100, 42,
4906 Arc::clone(&logger), &scorer, &random_seed_bytes
4908 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4910 assert_eq!(route.get_total_fees(), 100);
4911 assert_eq!(route.get_total_amount(), 100);
4912 assert_eq!(path, vec![2, 4, 6, 11, 8]);
4914 // Applying a 100 msat penalty to each hop results in taking channels 7 and 10 to nodes[6]
4915 // from nodes[2] rather than channel 6, 11, and 8, even though the longer path is cheaper.
4916 let scorer = ln_test_utils::TestScorer::with_penalty(100);
4917 let route = get_route(
4918 &our_id, &payment_params, &network_graph.read_only(), None, 100, 42,
4919 Arc::clone(&logger), &scorer, &random_seed_bytes
4921 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4923 assert_eq!(route.get_total_fees(), 300);
4924 assert_eq!(route.get_total_amount(), 100);
4925 assert_eq!(path, vec![2, 4, 7, 10]);
4928 struct BadChannelScorer {
4929 short_channel_id: u64,
4933 impl Writeable for BadChannelScorer {
4934 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
4936 impl Score for BadChannelScorer {
4937 fn channel_penalty_msat(&self, short_channel_id: u64, _: &NodeId, _: &NodeId, _: ChannelUsage) -> u64 {
4938 if short_channel_id == self.short_channel_id { u64::max_value() } else { 0 }
4941 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
4942 fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
4943 fn probe_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
4944 fn probe_successful(&mut self, _path: &[&RouteHop]) {}
4947 struct BadNodeScorer {
4952 impl Writeable for BadNodeScorer {
4953 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
4956 impl Score for BadNodeScorer {
4957 fn channel_penalty_msat(&self, _: u64, _: &NodeId, target: &NodeId, _: ChannelUsage) -> u64 {
4958 if *target == self.node_id { u64::max_value() } else { 0 }
4961 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
4962 fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
4963 fn probe_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
4964 fn probe_successful(&mut self, _path: &[&RouteHop]) {}
4968 fn avoids_routing_through_bad_channels_and_nodes() {
4969 let (secp_ctx, network, _, _, logger) = build_graph();
4970 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4971 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
4972 let network_graph = network.read_only();
4974 // A path to nodes[6] exists when no penalties are applied to any channel.
4975 let scorer = ln_test_utils::TestScorer::with_penalty(0);
4976 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4977 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4978 let route = get_route(
4979 &our_id, &payment_params, &network_graph, None, 100, 42,
4980 Arc::clone(&logger), &scorer, &random_seed_bytes
4982 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4984 assert_eq!(route.get_total_fees(), 100);
4985 assert_eq!(route.get_total_amount(), 100);
4986 assert_eq!(path, vec![2, 4, 6, 11, 8]);
4988 // A different path to nodes[6] exists if channel 6 cannot be routed over.
4989 let scorer = BadChannelScorer { short_channel_id: 6 };
4990 let route = get_route(
4991 &our_id, &payment_params, &network_graph, None, 100, 42,
4992 Arc::clone(&logger), &scorer, &random_seed_bytes
4994 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4996 assert_eq!(route.get_total_fees(), 300);
4997 assert_eq!(route.get_total_amount(), 100);
4998 assert_eq!(path, vec![2, 4, 7, 10]);
5000 // A path to nodes[6] does not exist if nodes[2] cannot be routed through.
5001 let scorer = BadNodeScorer { node_id: NodeId::from_pubkey(&nodes[2]) };
5003 &our_id, &payment_params, &network_graph, None, 100, 42,
5004 Arc::clone(&logger), &scorer, &random_seed_bytes
5006 Err(LightningError { err, .. } ) => {
5007 assert_eq!(err, "Failed to find a path to the given destination");
5009 Ok(_) => panic!("Expected error"),
5014 fn total_fees_single_path() {
5018 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5019 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5020 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5023 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5024 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5025 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5028 pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
5029 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5030 short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0
5033 payment_params: None,
5036 assert_eq!(route.get_total_fees(), 250);
5037 assert_eq!(route.get_total_amount(), 225);
5041 fn total_fees_multi_path() {
5045 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5046 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5047 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5050 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5051 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5052 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5056 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5057 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5058 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5061 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5062 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5063 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5066 payment_params: None,
5069 assert_eq!(route.get_total_fees(), 200);
5070 assert_eq!(route.get_total_amount(), 300);
5074 fn total_empty_route_no_panic() {
5075 // In an earlier version of `Route::get_total_fees` and `Route::get_total_amount`, they
5076 // would both panic if the route was completely empty. We test to ensure they return 0
5077 // here, even though its somewhat nonsensical as a route.
5078 let route = Route { paths: Vec::new(), payment_params: None };
5080 assert_eq!(route.get_total_fees(), 0);
5081 assert_eq!(route.get_total_amount(), 0);
5085 fn limits_total_cltv_delta() {
5086 let (secp_ctx, network, _, _, logger) = build_graph();
5087 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5088 let network_graph = network.read_only();
5090 let scorer = ln_test_utils::TestScorer::with_penalty(0);
5092 // Make sure that generally there is at least one route available
5093 let feasible_max_total_cltv_delta = 1008;
5094 let feasible_payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes))
5095 .with_max_total_cltv_expiry_delta(feasible_max_total_cltv_delta);
5096 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5097 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5098 let route = get_route(&our_id, &feasible_payment_params, &network_graph, None, 100, 0, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5099 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5100 assert_ne!(path.len(), 0);
5102 // But not if we exclude all paths on the basis of their accumulated CLTV delta
5103 let fail_max_total_cltv_delta = 23;
5104 let fail_payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes))
5105 .with_max_total_cltv_expiry_delta(fail_max_total_cltv_delta);
5106 match get_route(&our_id, &fail_payment_params, &network_graph, None, 100, 0, Arc::clone(&logger), &scorer, &random_seed_bytes)
5108 Err(LightningError { err, .. } ) => {
5109 assert_eq!(err, "Failed to find a path to the given destination");
5111 Ok(_) => panic!("Expected error"),
5116 fn avoids_recently_failed_paths() {
5117 // Ensure that the router always avoids all of the `previously_failed_channels` channels by
5118 // randomly inserting channels into it until we can't find a route anymore.
5119 let (secp_ctx, network, _, _, logger) = build_graph();
5120 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5121 let network_graph = network.read_only();
5123 let scorer = ln_test_utils::TestScorer::with_penalty(0);
5124 let mut payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes))
5125 .with_max_path_count(1);
5126 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5127 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5129 // We should be able to find a route initially, and then after we fail a few random
5130 // channels eventually we won't be able to any longer.
5131 assert!(get_route(&our_id, &payment_params, &network_graph, None, 100, 0, Arc::clone(&logger), &scorer, &random_seed_bytes).is_ok());
5133 if let Ok(route) = get_route(&our_id, &payment_params, &network_graph, None, 100, 0, Arc::clone(&logger), &scorer, &random_seed_bytes) {
5134 for chan in route.paths[0].iter() {
5135 assert!(!payment_params.previously_failed_channels.contains(&chan.short_channel_id));
5137 let victim = (u64::from_ne_bytes(random_seed_bytes[0..8].try_into().unwrap()) as usize)
5138 % route.paths[0].len();
5139 payment_params.previously_failed_channels.push(route.paths[0][victim].short_channel_id);
5145 fn limits_path_length() {
5146 let (secp_ctx, network, _, _, logger) = build_line_graph();
5147 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5148 let network_graph = network.read_only();
5150 let scorer = ln_test_utils::TestScorer::with_penalty(0);
5151 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5152 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5154 // First check we can actually create a long route on this graph.
5155 let feasible_payment_params = PaymentParameters::from_node_id(nodes[18]);
5156 let route = get_route(&our_id, &feasible_payment_params, &network_graph, None, 100, 0,
5157 Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5158 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5159 assert!(path.len() == MAX_PATH_LENGTH_ESTIMATE.into());
5161 // But we can't create a path surpassing the MAX_PATH_LENGTH_ESTIMATE limit.
5162 let fail_payment_params = PaymentParameters::from_node_id(nodes[19]);
5163 match get_route(&our_id, &fail_payment_params, &network_graph, None, 100, 0,
5164 Arc::clone(&logger), &scorer, &random_seed_bytes)
5166 Err(LightningError { err, .. } ) => {
5167 assert_eq!(err, "Failed to find a path to the given destination");
5169 Ok(_) => panic!("Expected error"),
5174 fn adds_and_limits_cltv_offset() {
5175 let (secp_ctx, network_graph, _, _, logger) = build_graph();
5176 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5178 let scorer = ln_test_utils::TestScorer::with_penalty(0);
5180 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
5181 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5182 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5183 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5184 assert_eq!(route.paths.len(), 1);
5186 let cltv_expiry_deltas_before = route.paths[0].iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5188 // Check whether the offset added to the last hop by default is in [1 .. DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA]
5189 let mut route_default = route.clone();
5190 add_random_cltv_offset(&mut route_default, &payment_params, &network_graph.read_only(), &random_seed_bytes);
5191 let cltv_expiry_deltas_default = route_default.paths[0].iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5192 assert_eq!(cltv_expiry_deltas_before.split_last().unwrap().1, cltv_expiry_deltas_default.split_last().unwrap().1);
5193 assert!(cltv_expiry_deltas_default.last() > cltv_expiry_deltas_before.last());
5194 assert!(cltv_expiry_deltas_default.last().unwrap() <= &DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA);
5196 // Check that no offset is added when we restrict the max_total_cltv_expiry_delta
5197 let mut route_limited = route.clone();
5198 let limited_max_total_cltv_expiry_delta = cltv_expiry_deltas_before.iter().sum();
5199 let limited_payment_params = payment_params.with_max_total_cltv_expiry_delta(limited_max_total_cltv_expiry_delta);
5200 add_random_cltv_offset(&mut route_limited, &limited_payment_params, &network_graph.read_only(), &random_seed_bytes);
5201 let cltv_expiry_deltas_limited = route_limited.paths[0].iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5202 assert_eq!(cltv_expiry_deltas_before, cltv_expiry_deltas_limited);
5206 fn adds_plausible_cltv_offset() {
5207 let (secp_ctx, network, _, _, logger) = build_graph();
5208 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5209 let network_graph = network.read_only();
5210 let network_nodes = network_graph.nodes();
5211 let network_channels = network_graph.channels();
5212 let scorer = ln_test_utils::TestScorer::with_penalty(0);
5213 let payment_params = PaymentParameters::from_node_id(nodes[3]);
5214 let keys_manager = ln_test_utils::TestKeysInterface::new(&[4u8; 32], Network::Testnet);
5215 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5217 let mut route = get_route(&our_id, &payment_params, &network_graph, None, 100, 0,
5218 Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5219 add_random_cltv_offset(&mut route, &payment_params, &network_graph, &random_seed_bytes);
5221 let mut path_plausibility = vec![];
5223 for p in route.paths {
5224 // 1. Select random observation point
5225 let mut prng = ChaCha20::new(&random_seed_bytes, &[0u8; 12]);
5226 let mut random_bytes = [0u8; ::core::mem::size_of::<usize>()];
5228 prng.process_in_place(&mut random_bytes);
5229 let random_path_index = usize::from_be_bytes(random_bytes).wrapping_rem(p.len());
5230 let observation_point = NodeId::from_pubkey(&p.get(random_path_index).unwrap().pubkey);
5232 // 2. Calculate what CLTV expiry delta we would observe there
5233 let observed_cltv_expiry_delta: u32 = p[random_path_index..].iter().map(|h| h.cltv_expiry_delta).sum();
5235 // 3. Starting from the observation point, find candidate paths
5236 let mut candidates: VecDeque<(NodeId, Vec<u32>)> = VecDeque::new();
5237 candidates.push_back((observation_point, vec![]));
5239 let mut found_plausible_candidate = false;
5241 'candidate_loop: while let Some((cur_node_id, cur_path_cltv_deltas)) = candidates.pop_front() {
5242 if let Some(remaining) = observed_cltv_expiry_delta.checked_sub(cur_path_cltv_deltas.iter().sum::<u32>()) {
5243 if remaining == 0 || remaining.wrapping_rem(40) == 0 || remaining.wrapping_rem(144) == 0 {
5244 found_plausible_candidate = true;
5245 break 'candidate_loop;
5249 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
5250 for channel_id in &cur_node.channels {
5251 if let Some(channel_info) = network_channels.get(&channel_id) {
5252 if let Some((dir_info, next_id)) = channel_info.as_directed_from(&cur_node_id) {
5253 let next_cltv_expiry_delta = dir_info.direction().cltv_expiry_delta as u32;
5254 if cur_path_cltv_deltas.iter().sum::<u32>()
5255 .saturating_add(next_cltv_expiry_delta) <= observed_cltv_expiry_delta {
5256 let mut new_path_cltv_deltas = cur_path_cltv_deltas.clone();
5257 new_path_cltv_deltas.push(next_cltv_expiry_delta);
5258 candidates.push_back((*next_id, new_path_cltv_deltas));
5266 path_plausibility.push(found_plausible_candidate);
5268 assert!(path_plausibility.iter().all(|x| *x));
5272 fn builds_correct_path_from_hops() {
5273 let (secp_ctx, network, _, _, logger) = build_graph();
5274 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5275 let network_graph = network.read_only();
5277 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5278 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5280 let payment_params = PaymentParameters::from_node_id(nodes[3]);
5281 let hops = [nodes[1], nodes[2], nodes[4], nodes[3]];
5282 let route = build_route_from_hops_internal(&our_id, &hops, &payment_params,
5283 &network_graph, 100, 0, Arc::clone(&logger), &random_seed_bytes).unwrap();
5284 let route_hop_pubkeys = route.paths[0].iter().map(|hop| hop.pubkey).collect::<Vec<_>>();
5285 assert_eq!(hops.len(), route.paths[0].len());
5286 for (idx, hop_pubkey) in hops.iter().enumerate() {
5287 assert!(*hop_pubkey == route_hop_pubkeys[idx]);
5292 fn avoids_saturating_channels() {
5293 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5294 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5296 let scorer = ProbabilisticScorer::new(Default::default(), &*network_graph, Arc::clone(&logger));
5298 // Set the fee on channel 13 to 100% to match channel 4 giving us two equivalent paths (us
5299 // -> node 7 -> node2 and us -> node 1 -> node 2) which we should balance over.
5300 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5301 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5302 short_channel_id: 4,
5305 cltv_expiry_delta: (4 << 4) | 1,
5306 htlc_minimum_msat: 0,
5307 htlc_maximum_msat: 250_000_000,
5309 fee_proportional_millionths: 0,
5310 excess_data: Vec::new()
5312 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5313 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5314 short_channel_id: 13,
5317 cltv_expiry_delta: (13 << 4) | 1,
5318 htlc_minimum_msat: 0,
5319 htlc_maximum_msat: 250_000_000,
5321 fee_proportional_millionths: 0,
5322 excess_data: Vec::new()
5325 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(channelmanager::provided_invoice_features());
5326 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5327 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5328 // 100,000 sats is less than the available liquidity on each channel, set above.
5329 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();
5330 assert_eq!(route.paths.len(), 2);
5331 assert!((route.paths[0][1].short_channel_id == 4 && route.paths[1][1].short_channel_id == 13) ||
5332 (route.paths[1][1].short_channel_id == 4 && route.paths[0][1].short_channel_id == 13));
5335 #[cfg(not(feature = "no-std"))]
5336 pub(super) fn random_init_seed() -> u64 {
5337 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
5338 use core::hash::{BuildHasher, Hasher};
5339 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
5340 println!("Using seed of {}", seed);
5343 #[cfg(not(feature = "no-std"))]
5344 use crate::util::ser::ReadableArgs;
5347 #[cfg(not(feature = "no-std"))]
5348 fn generate_routes() {
5349 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringParameters};
5351 let mut d = match super::bench_utils::get_route_file() {
5358 let logger = ln_test_utils::TestLogger::new();
5359 let graph = NetworkGraph::read(&mut d, &logger).unwrap();
5360 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5361 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5363 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
5364 let mut seed = random_init_seed() as usize;
5365 let nodes = graph.read_only().nodes().clone();
5366 'load_endpoints: for _ in 0..10 {
5368 seed = seed.overflowing_mul(0xdeadbeef).0;
5369 let src = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5370 seed = seed.overflowing_mul(0xdeadbeef).0;
5371 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5372 let payment_params = PaymentParameters::from_node_id(dst);
5373 let amt = seed as u64 % 200_000_000;
5374 let params = ProbabilisticScoringParameters::default();
5375 let scorer = ProbabilisticScorer::new(params, &graph, &logger);
5376 if get_route(src, &payment_params, &graph.read_only(), None, amt, 42, &logger, &scorer, &random_seed_bytes).is_ok() {
5377 continue 'load_endpoints;
5384 #[cfg(not(feature = "no-std"))]
5385 fn generate_routes_mpp() {
5386 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringParameters};
5388 let mut d = match super::bench_utils::get_route_file() {
5395 let logger = ln_test_utils::TestLogger::new();
5396 let graph = NetworkGraph::read(&mut d, &logger).unwrap();
5397 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5398 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5400 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
5401 let mut seed = random_init_seed() as usize;
5402 let nodes = graph.read_only().nodes().clone();
5403 'load_endpoints: for _ in 0..10 {
5405 seed = seed.overflowing_mul(0xdeadbeef).0;
5406 let src = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5407 seed = seed.overflowing_mul(0xdeadbeef).0;
5408 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5409 let payment_params = PaymentParameters::from_node_id(dst).with_features(channelmanager::provided_invoice_features());
5410 let amt = seed as u64 % 200_000_000;
5411 let params = ProbabilisticScoringParameters::default();
5412 let scorer = ProbabilisticScorer::new(params, &graph, &logger);
5413 if get_route(src, &payment_params, &graph.read_only(), None, amt, 42, &logger, &scorer, &random_seed_bytes).is_ok() {
5414 continue 'load_endpoints;
5421 fn honors_manual_penalties() {
5422 let (secp_ctx, network_graph, _, _, logger) = build_line_graph();
5423 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5425 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5426 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5428 let scorer_params = ProbabilisticScoringParameters::default();
5429 let mut scorer = ProbabilisticScorer::new(scorer_params, Arc::clone(&network_graph), Arc::clone(&logger));
5431 // First check set manual penalties are returned by the scorer.
5432 let usage = ChannelUsage {
5434 inflight_htlc_msat: 0,
5435 effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_024_000, htlc_maximum_msat: 1_000 },
5437 scorer.set_manual_penalty(&NodeId::from_pubkey(&nodes[3]), 123);
5438 scorer.set_manual_penalty(&NodeId::from_pubkey(&nodes[4]), 456);
5439 assert_eq!(scorer.channel_penalty_msat(42, &NodeId::from_pubkey(&nodes[3]), &NodeId::from_pubkey(&nodes[4]), usage), 456);
5441 // Then check we can get a normal route
5442 let payment_params = PaymentParameters::from_node_id(nodes[10]);
5443 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes);
5444 assert!(route.is_ok());
5446 // Then check that we can't get a route if we ban an intermediate node.
5447 scorer.add_banned(&NodeId::from_pubkey(&nodes[3]));
5448 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes);
5449 assert!(route.is_err());
5451 // Finally make sure we can route again, when we remove the ban.
5452 scorer.remove_banned(&NodeId::from_pubkey(&nodes[3]));
5453 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes);
5454 assert!(route.is_ok());
5458 #[cfg(all(test, not(feature = "no-std")))]
5459 pub(crate) mod bench_utils {
5461 /// Tries to open a network graph file, or panics with a URL to fetch it.
5462 pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
5463 let res = File::open("net_graph-2021-05-31.bin") // By default we're run in RL/lightning
5464 .or_else(|_| File::open("lightning/net_graph-2021-05-31.bin")) // We may be run manually in RL/
5465 .or_else(|_| { // Fall back to guessing based on the binary location
5466 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
5467 let mut path = std::env::current_exe().unwrap();
5468 path.pop(); // lightning-...
5470 path.pop(); // debug
5471 path.pop(); // target
5472 path.push("lightning");
5473 path.push("net_graph-2021-05-31.bin");
5474 eprintln!("{}", path.to_str().unwrap());
5477 .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");
5478 #[cfg(require_route_graph_test)]
5479 return Ok(res.unwrap());
5480 #[cfg(not(require_route_graph_test))]
5485 #[cfg(all(test, feature = "_bench_unstable", not(feature = "no-std")))]
5488 use bitcoin::hashes::Hash;
5489 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
5490 use crate::chain::transaction::OutPoint;
5491 use crate::chain::keysinterface::{KeysManager,KeysInterface};
5492 use crate::ln::channelmanager::{self, ChannelCounterparty, ChannelDetails};
5493 use crate::ln::features::InvoiceFeatures;
5494 use crate::routing::gossip::NetworkGraph;
5495 use crate::routing::scoring::{FixedPenaltyScorer, ProbabilisticScorer, ProbabilisticScoringParameters};
5496 use crate::util::logger::{Logger, Record};
5497 use crate::util::ser::ReadableArgs;
5501 struct DummyLogger {}
5502 impl Logger for DummyLogger {
5503 fn log(&self, _record: &Record) {}
5506 fn read_network_graph(logger: &DummyLogger) -> NetworkGraph<&DummyLogger> {
5507 let mut d = bench_utils::get_route_file().unwrap();
5508 NetworkGraph::read(&mut d, logger).unwrap()
5511 fn payer_pubkey() -> PublicKey {
5512 let secp_ctx = Secp256k1::new();
5513 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
5517 fn first_hop(node_id: PublicKey) -> ChannelDetails {
5519 channel_id: [0; 32],
5520 counterparty: ChannelCounterparty {
5521 features: channelmanager::provided_init_features(),
5523 unspendable_punishment_reserve: 0,
5524 forwarding_info: None,
5525 outbound_htlc_minimum_msat: None,
5526 outbound_htlc_maximum_msat: None,
5528 funding_txo: Some(OutPoint {
5529 txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0
5532 short_channel_id: Some(1),
5533 inbound_scid_alias: None,
5534 outbound_scid_alias: None,
5535 channel_value_satoshis: 10_000_000,
5537 balance_msat: 10_000_000,
5538 outbound_capacity_msat: 10_000_000,
5539 next_outbound_htlc_limit_msat: 10_000_000,
5540 inbound_capacity_msat: 0,
5541 unspendable_punishment_reserve: None,
5542 confirmations_required: None,
5543 force_close_spend_delay: None,
5545 is_channel_ready: true,
5548 inbound_htlc_minimum_msat: None,
5549 inbound_htlc_maximum_msat: None,
5555 fn generate_routes_with_zero_penalty_scorer(bench: &mut Bencher) {
5556 let logger = DummyLogger {};
5557 let network_graph = read_network_graph(&logger);
5558 let scorer = FixedPenaltyScorer::with_penalty(0);
5559 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::empty());
5563 fn generate_mpp_routes_with_zero_penalty_scorer(bench: &mut Bencher) {
5564 let logger = DummyLogger {};
5565 let network_graph = read_network_graph(&logger);
5566 let scorer = FixedPenaltyScorer::with_penalty(0);
5567 generate_routes(bench, &network_graph, scorer, channelmanager::provided_invoice_features());
5571 fn generate_routes_with_probabilistic_scorer(bench: &mut Bencher) {
5572 let logger = DummyLogger {};
5573 let network_graph = read_network_graph(&logger);
5574 let params = ProbabilisticScoringParameters::default();
5575 let scorer = ProbabilisticScorer::new(params, &network_graph, &logger);
5576 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::empty());
5580 fn generate_mpp_routes_with_probabilistic_scorer(bench: &mut Bencher) {
5581 let logger = DummyLogger {};
5582 let network_graph = read_network_graph(&logger);
5583 let params = ProbabilisticScoringParameters::default();
5584 let scorer = ProbabilisticScorer::new(params, &network_graph, &logger);
5585 generate_routes(bench, &network_graph, scorer, channelmanager::provided_invoice_features());
5588 fn generate_routes<S: Score>(
5589 bench: &mut Bencher, graph: &NetworkGraph<&DummyLogger>, mut scorer: S,
5590 features: InvoiceFeatures
5592 let nodes = graph.read_only().nodes().clone();
5593 let payer = payer_pubkey();
5594 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
5595 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5597 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
5598 let mut routes = Vec::new();
5599 let mut route_endpoints = Vec::new();
5600 let mut seed: usize = 0xdeadbeef;
5601 'load_endpoints: for _ in 0..150 {
5604 let src = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5606 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5607 let params = PaymentParameters::from_node_id(dst).with_features(features.clone());
5608 let first_hop = first_hop(src);
5609 let amt = seed as u64 % 1_000_000;
5610 if let Ok(route) = get_route(&payer, ¶ms, &graph.read_only(), Some(&[&first_hop]), amt, 42, &DummyLogger{}, &scorer, &random_seed_bytes) {
5612 route_endpoints.push((first_hop, params, amt));
5613 continue 'load_endpoints;
5618 // ...and seed the scorer with success and failure data...
5619 for route in routes {
5620 let amount = route.get_total_amount();
5621 if amount < 250_000 {
5622 for path in route.paths {
5623 scorer.payment_path_successful(&path.iter().collect::<Vec<_>>());
5625 } else if amount > 750_000 {
5626 for path in route.paths {
5627 let short_channel_id = path[path.len() / 2].short_channel_id;
5628 scorer.payment_path_failed(&path.iter().collect::<Vec<_>>(), short_channel_id);
5633 // Because we've changed channel scores, its possible we'll take different routes to the
5634 // selected destinations, possibly causing us to fail because, eg, the newly-selected path
5635 // requires a too-high CLTV delta.
5636 route_endpoints.retain(|(first_hop, params, amt)| {
5637 get_route(&payer, params, &graph.read_only(), Some(&[first_hop]), *amt, 42, &DummyLogger{}, &scorer, &random_seed_bytes).is_ok()
5639 route_endpoints.truncate(100);
5640 assert_eq!(route_endpoints.len(), 100);
5642 // ...then benchmark finding paths between the nodes we learned.
5645 let (first_hop, params, amt) = &route_endpoints[idx % route_endpoints.len()];
5646 assert!(get_route(&payer, params, &graph.read_only(), Some(&[first_hop]), *amt, 42, &DummyLogger{}, &scorer, &random_seed_bytes).is_ok());