1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! The top-level routing/network map tracking logic lives here.
12 //! You probably want to create a P2PGossipSync and use that as your RoutingMessageHandler and then
13 //! interrogate it to get routes for your own payments.
15 use bitcoin::secp256k1::PublicKey;
17 use crate::ln::channelmanager::ChannelDetails;
18 use crate::ln::features::{ChannelFeatures, InvoiceFeatures, NodeFeatures};
19 use crate::ln::msgs::{DecodeError, ErrorAction, LightningError, MAX_VALUE_MSAT};
20 use crate::routing::gossip::{DirectedChannelInfoWithUpdate, EffectiveCapacity, ReadOnlyNetworkGraph, NetworkGraph, NodeId, RoutingFees};
21 use crate::routing::scoring::{ChannelUsage, Score};
22 use crate::util::ser::{Writeable, Readable, Writer};
23 use crate::util::logger::{Level, Logger};
24 use crate::util::chacha20::ChaCha20;
27 use crate::prelude::*;
28 use alloc::collections::BinaryHeap;
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: DirectedChannelInfoWithUpdate<'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: None } =>
541 capacity_msat.checked_shr(saturation_shift).unwrap_or(0),
542 EffectiveCapacity::Total { capacity_msat, htlc_maximum_msat: Some(htlc_max) } =>
543 cmp::min(capacity_msat.checked_shr(saturation_shift).unwrap_or(0), htlc_max),
547 fn iter_equal<I1: Iterator, I2: Iterator>(mut iter_a: I1, mut iter_b: I2)
548 -> bool where I1::Item: PartialEq<I2::Item> {
550 let a = iter_a.next();
551 let b = iter_b.next();
552 if a.is_none() && b.is_none() { return true; }
553 if a.is_none() || b.is_none() { return false; }
554 if a.unwrap().ne(&b.unwrap()) { return false; }
558 /// It's useful to keep track of the hops associated with the fees required to use them,
559 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
560 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
561 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
563 struct PathBuildingHop<'a> {
564 // Note that this should be dropped in favor of loading it from CandidateRouteHop, but doing so
565 // is a larger refactor and will require careful performance analysis.
567 candidate: CandidateRouteHop<'a>,
570 /// Minimal fees required to route to the source node of the current hop via any of its inbound channels.
571 src_lowest_inbound_fees: RoutingFees,
572 /// All the fees paid *after* this channel on the way to the destination
573 next_hops_fee_msat: u64,
574 /// Fee paid for the use of the current channel (see candidate.fees()).
575 /// The value will be actually deducted from the counterparty balance on the previous link.
576 hop_use_fee_msat: u64,
577 /// Used to compare channels when choosing the for routing.
578 /// Includes paying for the use of a hop and the following hops, as well as
579 /// an estimated cost of reaching this hop.
580 /// Might get stale when fees are recomputed. Primarily for internal use.
582 /// A mirror of the same field in RouteGraphNode. Note that this is only used during the graph
583 /// walk and may be invalid thereafter.
584 path_htlc_minimum_msat: u64,
585 /// All penalties incurred from this channel on the way to the destination, as calculated using
587 path_penalty_msat: u64,
588 /// If we've already processed a node as the best node, we shouldn't process it again. Normally
589 /// we'd just ignore it if we did as all channels would have a higher new fee, but because we
590 /// may decrease the amounts in use as we walk the graph, the actual calculated fee may
591 /// decrease as well. Thus, we have to explicitly track which nodes have been processed and
592 /// avoid processing them again.
594 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
595 // In tests, we apply further sanity checks on cases where we skip nodes we already processed
596 // to ensure it is specifically in cases where the fee has gone down because of a decrease in
597 // value_contribution_msat, which requires tracking it here. See comments below where it is
598 // used for more info.
599 value_contribution_msat: u64,
602 impl<'a> core::fmt::Debug for PathBuildingHop<'a> {
603 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
604 let mut debug_struct = f.debug_struct("PathBuildingHop");
606 .field("node_id", &self.node_id)
607 .field("short_channel_id", &self.candidate.short_channel_id())
608 .field("total_fee_msat", &self.total_fee_msat)
609 .field("next_hops_fee_msat", &self.next_hops_fee_msat)
610 .field("hop_use_fee_msat", &self.hop_use_fee_msat)
611 .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)))
612 .field("path_penalty_msat", &self.path_penalty_msat)
613 .field("path_htlc_minimum_msat", &self.path_htlc_minimum_msat)
614 .field("cltv_expiry_delta", &self.candidate.cltv_expiry_delta());
615 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
616 let debug_struct = debug_struct
617 .field("value_contribution_msat", &self.value_contribution_msat);
618 debug_struct.finish()
622 // Instantiated with a list of hops with correct data in them collected during path finding,
623 // an instance of this struct should be further modified only via given methods.
625 struct PaymentPath<'a> {
626 hops: Vec<(PathBuildingHop<'a>, NodeFeatures)>,
629 impl<'a> PaymentPath<'a> {
630 // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
631 fn get_value_msat(&self) -> u64 {
632 self.hops.last().unwrap().0.fee_msat
635 fn get_path_penalty_msat(&self) -> u64 {
636 self.hops.first().map(|h| h.0.path_penalty_msat).unwrap_or(u64::max_value())
639 fn get_total_fee_paid_msat(&self) -> u64 {
640 if self.hops.len() < 1 {
644 // Can't use next_hops_fee_msat because it gets outdated.
645 for (i, (hop, _)) in self.hops.iter().enumerate() {
646 if i != self.hops.len() - 1 {
647 result += hop.fee_msat;
653 fn get_cost_msat(&self) -> u64 {
654 self.get_total_fee_paid_msat().saturating_add(self.get_path_penalty_msat())
657 // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
658 // to change fees may result in an inconsistency.
660 // Sometimes we call this function right after constructing a path which is inconsistent in
661 // that it the value being transferred has decreased while we were doing path finding, leading
662 // to the fees being paid not lining up with the actual limits.
664 // Note that this function is not aware of the available_liquidity limit, and thus does not
665 // support increasing the value being transferred beyond what was selected during the initial
667 fn update_value_and_recompute_fees(&mut self, value_msat: u64) {
668 let mut total_fee_paid_msat = 0 as u64;
669 for i in (0..self.hops.len()).rev() {
670 let last_hop = i == self.hops.len() - 1;
672 // For non-last-hop, this value will represent the fees paid on the current hop. It
673 // will consist of the fees for the use of the next hop, and extra fees to match
674 // htlc_minimum_msat of the current channel. Last hop is handled separately.
675 let mut cur_hop_fees_msat = 0;
677 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().0.hop_use_fee_msat;
680 let mut cur_hop = &mut self.hops.get_mut(i).unwrap().0;
681 cur_hop.next_hops_fee_msat = total_fee_paid_msat;
682 // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
683 // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
684 // set it too high just to maliciously take more fees by exploiting this
685 // match htlc_minimum_msat logic.
686 let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
687 if let Some(extra_fees_msat) = cur_hop.candidate.htlc_minimum_msat().checked_sub(cur_hop_transferred_amount_msat) {
688 // Note that there is a risk that *previous hops* (those closer to us, as we go
689 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
691 // This might make us end up with a broken route, although this should be super-rare
692 // in practice, both because of how healthy channels look like, and how we pick
693 // channels in add_entry.
694 // Also, this can't be exploited more heavily than *announce a free path and fail
696 cur_hop_transferred_amount_msat += extra_fees_msat;
697 total_fee_paid_msat += extra_fees_msat;
698 cur_hop_fees_msat += extra_fees_msat;
702 // Final hop is a special case: it usually has just value_msat (by design), but also
703 // it still could overpay for the htlc_minimum_msat.
704 cur_hop.fee_msat = cur_hop_transferred_amount_msat;
706 // Propagate updated fees for the use of the channels to one hop back, where they
707 // will be actually paid (fee_msat). The last hop is handled above separately.
708 cur_hop.fee_msat = cur_hop_fees_msat;
711 // Fee for the use of the current hop which will be deducted on the previous hop.
712 // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
713 // this channel is free for us.
715 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.candidate.fees()) {
716 cur_hop.hop_use_fee_msat = new_fee;
717 total_fee_paid_msat += new_fee;
719 // It should not be possible because this function is called only to reduce the
720 // value. In that case, compute_fee was already called with the same fees for
721 // larger amount and there was no overflow.
729 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
730 let proportional_fee_millions =
731 amount_msat.checked_mul(channel_fees.proportional_millionths as u64);
732 if let Some(new_fee) = proportional_fee_millions.and_then(|part| {
733 (channel_fees.base_msat as u64).checked_add(part / 1_000_000) }) {
737 // This function may be (indirectly) called without any verification,
738 // with channel_fees provided by a caller. We should handle it gracefully.
743 /// The default `features` we assume for a node in a route, when no `features` are known about that
746 /// Default features are:
747 /// * variable_length_onion_optional
748 fn default_node_features() -> NodeFeatures {
749 let mut features = NodeFeatures::empty();
750 features.set_variable_length_onion_optional();
754 /// Finds a route from us (payer) to the given target node (payee).
756 /// If the payee provided features in their invoice, they should be provided via `params.payee`.
757 /// Without this, MPP will only be used if the payee's features are available in the network graph.
759 /// Private routing paths between a public node and the target may be included in `params.payee`.
761 /// If some channels aren't announced, it may be useful to fill in `first_hops` with the results
762 /// from [`ChannelManager::list_usable_channels`]. If it is filled in, the view of these channels
763 /// from `network_graph` will be ignored, and only those in `first_hops` will be used.
765 /// The fees on channels from us to the next hop are ignored as they are assumed to all be equal.
766 /// However, the enabled/disabled bit on such channels as well as the `htlc_minimum_msat` /
767 /// `htlc_maximum_msat` *are* checked as they may change based on the receiving node.
771 /// May be used to re-compute a [`Route`] when handling a [`Event::PaymentPathFailed`]. Any
772 /// adjustments to the [`NetworkGraph`] and channel scores should be made prior to calling this
777 /// Panics if first_hops contains channels without short_channel_ids;
778 /// [`ChannelManager::list_usable_channels`] will never include such channels.
780 /// [`ChannelManager::list_usable_channels`]: crate::ln::channelmanager::ChannelManager::list_usable_channels
781 /// [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed
782 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
783 pub fn find_route<L: Deref, GL: Deref, S: Score>(
784 our_node_pubkey: &PublicKey, route_params: &RouteParameters,
785 network_graph: &NetworkGraph<GL>, first_hops: Option<&[&ChannelDetails]>, logger: L,
786 scorer: &S, random_seed_bytes: &[u8; 32]
787 ) -> Result<Route, LightningError>
788 where L::Target: Logger, GL::Target: Logger {
789 let graph_lock = network_graph.read_only();
790 let mut route = get_route(our_node_pubkey, &route_params.payment_params, &graph_lock, first_hops,
791 route_params.final_value_msat, route_params.final_cltv_expiry_delta, logger, scorer,
793 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
797 pub(crate) fn get_route<L: Deref, S: Score>(
798 our_node_pubkey: &PublicKey, payment_params: &PaymentParameters, network_graph: &ReadOnlyNetworkGraph,
799 first_hops: Option<&[&ChannelDetails]>, final_value_msat: u64, final_cltv_expiry_delta: u32,
800 logger: L, scorer: &S, _random_seed_bytes: &[u8; 32]
801 ) -> Result<Route, LightningError>
802 where L::Target: Logger {
803 let payee_node_id = NodeId::from_pubkey(&payment_params.payee_pubkey);
804 let our_node_id = NodeId::from_pubkey(&our_node_pubkey);
806 if payee_node_id == our_node_id {
807 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
810 if final_value_msat > MAX_VALUE_MSAT {
811 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
814 if final_value_msat == 0 {
815 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
818 for route in payment_params.route_hints.iter() {
819 for hop in &route.0 {
820 if hop.src_node_id == payment_params.payee_pubkey {
821 return Err(LightningError{err: "Route hint cannot have the payee as the source.".to_owned(), action: ErrorAction::IgnoreError});
825 if payment_params.max_total_cltv_expiry_delta <= final_cltv_expiry_delta {
826 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});
829 // The general routing idea is the following:
830 // 1. Fill first/last hops communicated by the caller.
831 // 2. Attempt to construct a path from payer to payee for transferring
832 // any ~sufficient (described later) value.
833 // If succeed, remember which channels were used and how much liquidity they have available,
834 // so that future paths don't rely on the same liquidity.
835 // 3. Proceed to the next step if:
836 // - we hit the recommended target value;
837 // - OR if we could not construct a new path. Any next attempt will fail too.
838 // Otherwise, repeat step 2.
839 // 4. See if we managed to collect paths which aggregately are able to transfer target value
840 // (not recommended value).
841 // 5. If yes, proceed. If not, fail routing.
842 // 6. Select the paths which have the lowest cost (fee plus scorer penalty) per amount
843 // transferred up to the transfer target value.
844 // 7. Reduce the value of the last path until we are sending only the target value.
845 // 8. If our maximum channel saturation limit caused us to pick two identical paths, combine
846 // them so that we're not sending two HTLCs along the same path.
848 // As for the actual search algorithm,
849 // we do a payee-to-payer pseudo-Dijkstra's sorting by each node's distance from the payee
850 // plus the minimum per-HTLC fee to get from it to another node (aka "shitty pseudo-A*").
852 // We are not a faithful Dijkstra's implementation because we can change values which impact
853 // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
854 // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) than
855 // the value we are currently attempting to send over a path, we simply reduce the value being
856 // sent along the path for any hops after that channel. This may imply that later fees (which
857 // we've already tabulated) are lower because a smaller value is passing through the channels
858 // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
859 // channels which were selected earlier (and which may still be used for other paths without a
860 // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
863 // One potentially problematic case for this algorithm would be if there are many
864 // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
865 // graph walking), we may never find a path which is not liquidity-limited and has lower
866 // proportional fee (and only lower absolute fee when considering the ultimate value sent).
867 // Because we only consider paths with at least 5% of the total value being sent, the damage
868 // from such a case should be limited, however this could be further reduced in the future by
869 // calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
870 // limits for the purposes of fee calculation.
872 // Alternatively, we could store more detailed path information in the heap (targets, below)
873 // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
874 // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
875 // and practically (as we would need to store dynamically-allocated path information in heap
876 // objects, increasing malloc traffic and indirect memory access significantly). Further, the
877 // results of such an algorithm would likely be biased towards lower-value paths.
879 // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
880 // outside of our current search value, running a path search more times to gather candidate
881 // paths at different values. While this may be acceptable, further path searches may increase
882 // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
883 // graph for candidate paths, calculating the maximum value which can realistically be sent at
884 // the same time, remaining generic across different payment values.
886 // TODO: There are a few tweaks we could do, including possibly pre-calculating more stuff
887 // to use as the A* heuristic beyond just the cost to get one node further than the current
890 let network_channels = network_graph.channels();
891 let network_nodes = network_graph.nodes();
893 if payment_params.max_path_count == 0 {
894 return Err(LightningError{err: "Can't find a route with no paths allowed.".to_owned(), action: ErrorAction::IgnoreError});
897 // Allow MPP only if we have a features set from somewhere that indicates the payee supports
898 // it. If the payee supports it they're supposed to include it in the invoice, so that should
900 let allow_mpp = if payment_params.max_path_count == 1 {
902 } else if let Some(features) = &payment_params.features {
903 features.supports_basic_mpp()
904 } else if let Some(node) = network_nodes.get(&payee_node_id) {
905 if let Some(node_info) = node.announcement_info.as_ref() {
906 node_info.features.supports_basic_mpp()
910 log_trace!(logger, "Searching for a route from payer {} to payee {} {} MPP and {} first hops {}overriding the network graph", our_node_pubkey,
911 payment_params.payee_pubkey, if allow_mpp { "with" } else { "without" },
912 first_hops.map(|hops| hops.len()).unwrap_or(0), if first_hops.is_some() { "" } else { "not " });
915 // Prepare the data we'll use for payee-to-payer search by
916 // inserting first hops suggested by the caller as targets.
917 // Our search will then attempt to reach them while traversing from the payee node.
918 let mut first_hop_targets: HashMap<_, Vec<&ChannelDetails>> =
919 HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
920 if let Some(hops) = first_hops {
922 if chan.get_outbound_payment_scid().is_none() {
923 panic!("first_hops should be filled in with usable channels, not pending ones");
925 if chan.counterparty.node_id == *our_node_pubkey {
926 return Err(LightningError{err: "First hop cannot have our_node_pubkey as a destination.".to_owned(), action: ErrorAction::IgnoreError});
929 .entry(NodeId::from_pubkey(&chan.counterparty.node_id))
930 .or_insert(Vec::new())
933 if first_hop_targets.is_empty() {
934 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
938 // The main heap containing all candidate next-hops sorted by their score (max(A* fee,
939 // htlc_minimum)). Ideally this would be a heap which allowed cheap score reduction instead of
940 // adding duplicate entries when we find a better path to a given node.
941 let mut targets: BinaryHeap<RouteGraphNode> = BinaryHeap::new();
943 // Map from node_id to information about the best current path to that node, including feerate
945 let mut dist: HashMap<NodeId, PathBuildingHop> = HashMap::with_capacity(network_nodes.len());
947 // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
948 // indicating that we may wish to try again with a higher value, potentially paying to meet an
949 // htlc_minimum with extra fees while still finding a cheaper path.
950 let mut hit_minimum_limit;
952 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
953 // We start with a path_value of the exact amount we want, and if that generates a route we may
954 // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
955 // amount we want in total across paths, selecting the best subset at the end.
956 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
957 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
958 let mut path_value_msat = final_value_msat;
960 // Routing Fragmentation Mitigation heuristic:
962 // Routing fragmentation across many payment paths increases the overall routing
963 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
964 // Taking too many smaller paths also increases the chance of payment failure.
965 // Thus to avoid this effect, we require from our collected links to provide
966 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
967 // This requirement is currently set to be 1/max_path_count of the payment
968 // value to ensure we only ever return routes that do not violate this limit.
969 let minimal_value_contribution_msat: u64 = if allow_mpp {
970 (final_value_msat + (payment_params.max_path_count as u64 - 1)) / payment_params.max_path_count as u64
975 // When we start collecting routes we enforce the max_channel_saturation_power_of_half
976 // requirement strictly. After we've collected enough (or if we fail to find new routes) we
977 // drop the requirement by setting this to 0.
978 let mut channel_saturation_pow_half = payment_params.max_channel_saturation_power_of_half;
980 // Keep track of how much liquidity has been used in selected channels. Used to determine
981 // if the channel can be used by additional MPP paths or to inform path finding decisions. It is
982 // aware of direction *only* to ensure that the correct htlc_maximum_msat value is used. Hence,
983 // liquidity used in one direction will not offset any used in the opposite direction.
984 let mut used_channel_liquidities: HashMap<(u64, bool), u64> =
985 HashMap::with_capacity(network_nodes.len());
987 // Keeping track of how much value we already collected across other paths. Helps to decide
988 // when we want to stop looking for new paths.
989 let mut already_collected_value_msat = 0;
991 for (_, channels) in first_hop_targets.iter_mut() {
992 // Sort the first_hops channels to the same node(s) in priority order of which channel we'd
995 // First, if channels are below `recommended_value_msat`, sort them in descending order,
996 // preferring larger channels to avoid splitting the payment into more MPP parts than is
999 // Second, because simply always sorting in descending order would always use our largest
1000 // available outbound capacity, needlessly fragmenting our available channel capacities,
1001 // sort channels above `recommended_value_msat` in ascending order, preferring channels
1002 // which have enough, but not too much, capacity for the payment.
1003 channels.sort_unstable_by(|chan_a, chan_b| {
1004 if chan_b.next_outbound_htlc_limit_msat < recommended_value_msat || chan_a.next_outbound_htlc_limit_msat < recommended_value_msat {
1005 // Sort in descending order
1006 chan_b.next_outbound_htlc_limit_msat.cmp(&chan_a.next_outbound_htlc_limit_msat)
1008 // Sort in ascending order
1009 chan_a.next_outbound_htlc_limit_msat.cmp(&chan_b.next_outbound_htlc_limit_msat)
1014 log_trace!(logger, "Building path from {} (payee) to {} (us/payer) for value {} msat.", payment_params.payee_pubkey, our_node_pubkey, final_value_msat);
1016 macro_rules! add_entry {
1017 // Adds entry which goes from $src_node_id to $dest_node_id over the $candidate hop.
1018 // $next_hops_fee_msat represents the fees paid for using all the channels *after* this one,
1019 // since that value has to be transferred over this channel.
1020 // Returns whether this channel caused an update to `targets`.
1021 ( $candidate: expr, $src_node_id: expr, $dest_node_id: expr, $next_hops_fee_msat: expr,
1022 $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr,
1023 $next_hops_path_penalty_msat: expr, $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => { {
1024 // We "return" whether we updated the path at the end, via this:
1025 let mut did_add_update_path_to_src_node = false;
1026 // Channels to self should not be used. This is more of belt-and-suspenders, because in
1027 // practice these cases should be caught earlier:
1028 // - for regular channels at channel announcement (TODO)
1029 // - for first and last hops early in get_route
1030 if $src_node_id != $dest_node_id {
1031 let short_channel_id = $candidate.short_channel_id();
1032 let effective_capacity = $candidate.effective_capacity();
1033 let htlc_maximum_msat = max_htlc_from_capacity(effective_capacity, channel_saturation_pow_half);
1035 // It is tricky to subtract $next_hops_fee_msat from available liquidity here.
1036 // It may be misleading because we might later choose to reduce the value transferred
1037 // over these channels, and the channel which was insufficient might become sufficient.
1038 // Worst case: we drop a good channel here because it can't cover the high following
1039 // fees caused by one expensive channel, but then this channel could have been used
1040 // if the amount being transferred over this path is lower.
1041 // We do this for now, but this is a subject for removal.
1042 if let Some(mut available_value_contribution_msat) = htlc_maximum_msat.checked_sub($next_hops_fee_msat) {
1043 let used_liquidity_msat = used_channel_liquidities
1044 .get(&(short_channel_id, $src_node_id < $dest_node_id))
1045 .map_or(0, |used_liquidity_msat| {
1046 available_value_contribution_msat = available_value_contribution_msat
1047 .saturating_sub(*used_liquidity_msat);
1048 *used_liquidity_msat
1051 // Verify the liquidity offered by this channel complies to the minimal contribution.
1052 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
1053 // Do not consider candidate hops that would exceed the maximum path length.
1054 let path_length_to_node = $next_hops_path_length + 1;
1055 let exceeds_max_path_length = path_length_to_node > MAX_PATH_LENGTH_ESTIMATE;
1057 // Do not consider candidates that exceed the maximum total cltv expiry limit.
1058 // In order to already account for some of the privacy enhancing random CLTV
1059 // expiry delta offset we add on top later, we subtract a rough estimate
1060 // (2*MEDIAN_HOP_CLTV_EXPIRY_DELTA) here.
1061 let max_total_cltv_expiry_delta = (payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta)
1062 .checked_sub(2*MEDIAN_HOP_CLTV_EXPIRY_DELTA)
1063 .unwrap_or(payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta);
1064 let hop_total_cltv_delta = ($next_hops_cltv_delta as u32)
1065 .saturating_add($candidate.cltv_expiry_delta());
1066 let exceeds_cltv_delta_limit = hop_total_cltv_delta > max_total_cltv_expiry_delta;
1068 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
1069 // Includes paying fees for the use of the following channels.
1070 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
1071 Some(result) => result,
1072 // Can't overflow due to how the values were computed right above.
1073 None => unreachable!(),
1075 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
1076 let over_path_minimum_msat = amount_to_transfer_over_msat >= $candidate.htlc_minimum_msat() &&
1077 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
1079 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
1080 let may_overpay_to_meet_path_minimum_msat =
1081 ((amount_to_transfer_over_msat < $candidate.htlc_minimum_msat() &&
1082 recommended_value_msat > $candidate.htlc_minimum_msat()) ||
1083 (amount_to_transfer_over_msat < $next_hops_path_htlc_minimum_msat &&
1084 recommended_value_msat > $next_hops_path_htlc_minimum_msat));
1086 let payment_failed_on_this_channel =
1087 payment_params.previously_failed_channels.contains(&short_channel_id);
1089 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
1090 // bother considering this channel. If retrying with recommended_value_msat may
1091 // allow us to hit the HTLC minimum limit, set htlc_minimum_limit so that we go
1092 // around again with a higher amount.
1093 if !contributes_sufficient_value || exceeds_max_path_length ||
1094 exceeds_cltv_delta_limit || payment_failed_on_this_channel {
1095 // Path isn't useful, ignore it and move on.
1096 } else if may_overpay_to_meet_path_minimum_msat {
1097 hit_minimum_limit = true;
1098 } else if over_path_minimum_msat {
1099 // Note that low contribution here (limited by available_liquidity_msat)
1100 // might violate htlc_minimum_msat on the hops which are next along the
1101 // payment path (upstream to the payee). To avoid that, we recompute
1102 // path fees knowing the final path contribution after constructing it.
1103 let path_htlc_minimum_msat = compute_fees($next_hops_path_htlc_minimum_msat, $candidate.fees())
1104 .and_then(|fee_msat| fee_msat.checked_add($next_hops_path_htlc_minimum_msat))
1105 .map(|fee_msat| cmp::max(fee_msat, $candidate.htlc_minimum_msat()))
1106 .unwrap_or_else(|| u64::max_value());
1107 let hm_entry = dist.entry($src_node_id);
1108 let old_entry = hm_entry.or_insert_with(|| {
1109 // If there was previously no known way to access the source node
1110 // (recall it goes payee-to-payer) of short_channel_id, first add a
1111 // semi-dummy record just to compute the fees to reach the source node.
1112 // This will affect our decision on selecting short_channel_id
1113 // as a way to reach the $dest_node_id.
1114 let mut fee_base_msat = 0;
1115 let mut fee_proportional_millionths = 0;
1116 if let Some(Some(fees)) = network_nodes.get(&$src_node_id).map(|node| node.lowest_inbound_channel_fees) {
1117 fee_base_msat = fees.base_msat;
1118 fee_proportional_millionths = fees.proportional_millionths;
1121 node_id: $dest_node_id.clone(),
1122 candidate: $candidate.clone(),
1124 src_lowest_inbound_fees: RoutingFees {
1125 base_msat: fee_base_msat,
1126 proportional_millionths: fee_proportional_millionths,
1128 next_hops_fee_msat: u64::max_value(),
1129 hop_use_fee_msat: u64::max_value(),
1130 total_fee_msat: u64::max_value(),
1131 path_htlc_minimum_msat,
1132 path_penalty_msat: u64::max_value(),
1133 was_processed: false,
1134 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
1135 value_contribution_msat,
1139 #[allow(unused_mut)] // We only use the mut in cfg(test)
1140 let mut should_process = !old_entry.was_processed;
1141 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
1143 // In test/fuzzing builds, we do extra checks to make sure the skipping
1144 // of already-seen nodes only happens in cases we expect (see below).
1145 if !should_process { should_process = true; }
1149 let mut hop_use_fee_msat = 0;
1150 let mut total_fee_msat = $next_hops_fee_msat;
1152 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
1153 // will have the same effective-fee
1154 if $src_node_id != our_node_id {
1155 match compute_fees(amount_to_transfer_over_msat, $candidate.fees()) {
1156 // max_value means we'll always fail
1157 // the old_entry.total_fee_msat > total_fee_msat check
1158 None => total_fee_msat = u64::max_value(),
1160 hop_use_fee_msat = fee_msat;
1161 total_fee_msat += hop_use_fee_msat;
1162 // When calculating the lowest inbound fees to a node, we
1163 // calculate fees here not based on the actual value we think
1164 // will flow over this channel, but on the minimum value that
1165 // we'll accept flowing over it. The minimum accepted value
1166 // is a constant through each path collection run, ensuring
1167 // consistent basis. Otherwise we may later find a
1168 // different path to the source node that is more expensive,
1169 // but which we consider to be cheaper because we are capacity
1170 // constrained and the relative fee becomes lower.
1171 match compute_fees(minimal_value_contribution_msat, old_entry.src_lowest_inbound_fees)
1172 .map(|a| a.checked_add(total_fee_msat)) {
1177 total_fee_msat = u64::max_value();
1184 let channel_usage = ChannelUsage {
1185 amount_msat: amount_to_transfer_over_msat,
1186 inflight_htlc_msat: used_liquidity_msat,
1189 let channel_penalty_msat = scorer.channel_penalty_msat(
1190 short_channel_id, &$src_node_id, &$dest_node_id, channel_usage
1192 let path_penalty_msat = $next_hops_path_penalty_msat
1193 .saturating_add(channel_penalty_msat);
1194 let new_graph_node = RouteGraphNode {
1195 node_id: $src_node_id,
1196 lowest_fee_to_peer_through_node: total_fee_msat,
1197 lowest_fee_to_node: $next_hops_fee_msat as u64 + hop_use_fee_msat,
1198 total_cltv_delta: hop_total_cltv_delta,
1199 value_contribution_msat,
1200 path_htlc_minimum_msat,
1202 path_length_to_node,
1205 // Update the way of reaching $src_node_id with the given short_channel_id (from $dest_node_id),
1206 // if this way is cheaper than the already known
1207 // (considering the cost to "reach" this channel from the route destination,
1208 // the cost of using this channel,
1209 // and the cost of routing to the source node of this channel).
1210 // Also, consider that htlc_minimum_msat_difference, because we might end up
1211 // paying it. Consider the following exploit:
1212 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
1213 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
1214 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
1215 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
1217 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
1218 // but it may require additional tracking - we don't want to double-count
1219 // the fees included in $next_hops_path_htlc_minimum_msat, but also
1220 // can't use something that may decrease on future hops.
1221 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat)
1222 .saturating_add(old_entry.path_penalty_msat);
1223 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat)
1224 .saturating_add(path_penalty_msat);
1226 if !old_entry.was_processed && new_cost < old_cost {
1227 targets.push(new_graph_node);
1228 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
1229 old_entry.hop_use_fee_msat = hop_use_fee_msat;
1230 old_entry.total_fee_msat = total_fee_msat;
1231 old_entry.node_id = $dest_node_id.clone();
1232 old_entry.candidate = $candidate.clone();
1233 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
1234 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
1235 old_entry.path_penalty_msat = path_penalty_msat;
1236 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
1238 old_entry.value_contribution_msat = value_contribution_msat;
1240 did_add_update_path_to_src_node = true;
1241 } else if old_entry.was_processed && new_cost < old_cost {
1242 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
1244 // If we're skipping processing a node which was previously
1245 // processed even though we found another path to it with a
1246 // cheaper fee, check that it was because the second path we
1247 // found (which we are processing now) has a lower value
1248 // contribution due to an HTLC minimum limit.
1250 // e.g. take a graph with two paths from node 1 to node 2, one
1251 // through channel A, and one through channel B. Channel A and
1252 // B are both in the to-process heap, with their scores set by
1253 // a higher htlc_minimum than fee.
1254 // Channel A is processed first, and the channels onwards from
1255 // node 1 are added to the to-process heap. Thereafter, we pop
1256 // Channel B off of the heap, note that it has a much more
1257 // restrictive htlc_maximum_msat, and recalculate the fees for
1258 // all of node 1's channels using the new, reduced, amount.
1260 // This would be bogus - we'd be selecting a higher-fee path
1261 // with a lower htlc_maximum_msat instead of the one we'd
1262 // already decided to use.
1263 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
1265 value_contribution_msat + path_penalty_msat <
1266 old_entry.value_contribution_msat + old_entry.path_penalty_msat
1274 did_add_update_path_to_src_node
1278 let default_node_features = default_node_features();
1280 // Find ways (channels with destination) to reach a given node and store them
1281 // in the corresponding data structures (routing graph etc).
1282 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
1283 // meaning how much will be paid in fees after this node (to the best of our knowledge).
1284 // This data can later be helpful to optimize routing (pay lower fees).
1285 macro_rules! add_entries_to_cheapest_to_target_node {
1286 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr, $next_hops_value_contribution: expr,
1287 $next_hops_path_htlc_minimum_msat: expr, $next_hops_path_penalty_msat: expr,
1288 $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => {
1289 let skip_node = if let Some(elem) = dist.get_mut(&$node_id) {
1290 let was_processed = elem.was_processed;
1291 elem.was_processed = true;
1294 // Entries are added to dist in add_entry!() when there is a channel from a node.
1295 // Because there are no channels from payee, it will not have a dist entry at this point.
1296 // If we're processing any other node, it is always be the result of a channel from it.
1297 assert_eq!($node_id, payee_node_id);
1302 if let Some(first_channels) = first_hop_targets.get(&$node_id) {
1303 for details in first_channels {
1304 let candidate = CandidateRouteHop::FirstHop { details };
1305 add_entry!(candidate, our_node_id, $node_id, $fee_to_target_msat,
1306 $next_hops_value_contribution,
1307 $next_hops_path_htlc_minimum_msat, $next_hops_path_penalty_msat,
1308 $next_hops_cltv_delta, $next_hops_path_length);
1312 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
1315 &default_node_features
1318 if !features.requires_unknown_bits() {
1319 for chan_id in $node.channels.iter() {
1320 let chan = network_channels.get(chan_id).unwrap();
1321 if !chan.features.requires_unknown_bits() {
1322 let (directed_channel, source) =
1323 chan.as_directed_to(&$node_id).expect("inconsistent NetworkGraph");
1324 if first_hops.is_none() || *source != our_node_id {
1325 if let Some(direction) = directed_channel.direction() {
1326 if direction.enabled {
1327 let candidate = CandidateRouteHop::PublicHop {
1328 info: directed_channel.with_update().unwrap(),
1329 short_channel_id: *chan_id,
1331 add_entry!(candidate, *source, $node_id,
1332 $fee_to_target_msat,
1333 $next_hops_value_contribution,
1334 $next_hops_path_htlc_minimum_msat,
1335 $next_hops_path_penalty_msat,
1336 $next_hops_cltv_delta, $next_hops_path_length);
1347 let mut payment_paths = Vec::<PaymentPath>::new();
1349 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
1350 'paths_collection: loop {
1351 // For every new path, start from scratch, except for used_channel_liquidities, which
1352 // helps to avoid reusing previously selected paths in future iterations.
1355 hit_minimum_limit = false;
1357 // If first hop is a private channel and the only way to reach the payee, this is the only
1358 // place where it could be added.
1359 if let Some(first_channels) = first_hop_targets.get(&payee_node_id) {
1360 for details in first_channels {
1361 let candidate = CandidateRouteHop::FirstHop { details };
1362 let added = add_entry!(candidate, our_node_id, payee_node_id, 0, path_value_msat,
1364 log_trace!(logger, "{} direct route to payee via SCID {}",
1365 if added { "Added" } else { "Skipped" }, candidate.short_channel_id());
1369 // Add the payee as a target, so that the payee-to-payer
1370 // search algorithm knows what to start with.
1371 match network_nodes.get(&payee_node_id) {
1372 // The payee is not in our network graph, so nothing to add here.
1373 // There is still a chance of reaching them via last_hops though,
1374 // so don't yet fail the payment here.
1375 // If not, targets.pop() will not even let us enter the loop in step 2.
1378 add_entries_to_cheapest_to_target_node!(node, payee_node_id, 0, path_value_msat, 0, 0u64, 0, 0);
1383 // If a caller provided us with last hops, add them to routing targets. Since this happens
1384 // earlier than general path finding, they will be somewhat prioritized, although currently
1385 // it matters only if the fees are exactly the same.
1386 for route in payment_params.route_hints.iter().filter(|route| !route.0.is_empty()) {
1387 let first_hop_in_route = &(route.0)[0];
1388 let have_hop_src_in_graph =
1389 // Only add the hops in this route to our candidate set if either
1390 // we have a direct channel to the first hop or the first hop is
1391 // in the regular network graph.
1392 first_hop_targets.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some() ||
1393 network_nodes.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some();
1394 if have_hop_src_in_graph {
1395 // We start building the path from reverse, i.e., from payee
1396 // to the first RouteHintHop in the path.
1397 let hop_iter = route.0.iter().rev();
1398 let prev_hop_iter = core::iter::once(&payment_params.payee_pubkey).chain(
1399 route.0.iter().skip(1).rev().map(|hop| &hop.src_node_id));
1400 let mut hop_used = true;
1401 let mut aggregate_next_hops_fee_msat: u64 = 0;
1402 let mut aggregate_next_hops_path_htlc_minimum_msat: u64 = 0;
1403 let mut aggregate_next_hops_path_penalty_msat: u64 = 0;
1404 let mut aggregate_next_hops_cltv_delta: u32 = 0;
1405 let mut aggregate_next_hops_path_length: u8 = 0;
1407 for (idx, (hop, prev_hop_id)) in hop_iter.zip(prev_hop_iter).enumerate() {
1408 let source = NodeId::from_pubkey(&hop.src_node_id);
1409 let target = NodeId::from_pubkey(&prev_hop_id);
1410 let candidate = network_channels
1411 .get(&hop.short_channel_id)
1412 .and_then(|channel| channel.as_directed_to(&target))
1413 .and_then(|(channel, _)| channel.with_update())
1414 .map(|info| CandidateRouteHop::PublicHop {
1416 short_channel_id: hop.short_channel_id,
1418 .unwrap_or_else(|| CandidateRouteHop::PrivateHop { hint: hop });
1420 if !add_entry!(candidate, source, target, aggregate_next_hops_fee_msat,
1421 path_value_msat, aggregate_next_hops_path_htlc_minimum_msat,
1422 aggregate_next_hops_path_penalty_msat,
1423 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length) {
1424 // If this hop was not used then there is no use checking the preceding
1425 // hops in the RouteHint. We can break by just searching for a direct
1426 // channel between last checked hop and first_hop_targets.
1430 let used_liquidity_msat = used_channel_liquidities
1431 .get(&(hop.short_channel_id, source < target)).copied().unwrap_or(0);
1432 let channel_usage = ChannelUsage {
1433 amount_msat: final_value_msat + aggregate_next_hops_fee_msat,
1434 inflight_htlc_msat: used_liquidity_msat,
1435 effective_capacity: candidate.effective_capacity(),
1437 let channel_penalty_msat = scorer.channel_penalty_msat(
1438 hop.short_channel_id, &source, &target, channel_usage
1440 aggregate_next_hops_path_penalty_msat = aggregate_next_hops_path_penalty_msat
1441 .saturating_add(channel_penalty_msat);
1443 aggregate_next_hops_cltv_delta = aggregate_next_hops_cltv_delta
1444 .saturating_add(hop.cltv_expiry_delta as u32);
1446 aggregate_next_hops_path_length = aggregate_next_hops_path_length
1449 // Searching for a direct channel between last checked hop and first_hop_targets
1450 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&prev_hop_id)) {
1451 for details in first_channels {
1452 let candidate = CandidateRouteHop::FirstHop { details };
1453 add_entry!(candidate, our_node_id, NodeId::from_pubkey(&prev_hop_id),
1454 aggregate_next_hops_fee_msat, path_value_msat,
1455 aggregate_next_hops_path_htlc_minimum_msat,
1456 aggregate_next_hops_path_penalty_msat, aggregate_next_hops_cltv_delta,
1457 aggregate_next_hops_path_length);
1465 // In the next values of the iterator, the aggregate fees already reflects
1466 // the sum of value sent from payer (final_value_msat) and routing fees
1467 // for the last node in the RouteHint. We need to just add the fees to
1468 // route through the current node so that the preceding node (next iteration)
1470 let hops_fee = compute_fees(aggregate_next_hops_fee_msat + final_value_msat, hop.fees)
1471 .map_or(None, |inc| inc.checked_add(aggregate_next_hops_fee_msat));
1472 aggregate_next_hops_fee_msat = if let Some(val) = hops_fee { val } else { break; };
1474 let hop_htlc_minimum_msat = candidate.htlc_minimum_msat();
1475 let hop_htlc_minimum_msat_inc = if let Some(val) = compute_fees(aggregate_next_hops_path_htlc_minimum_msat, hop.fees) { val } else { break; };
1476 let hops_path_htlc_minimum = aggregate_next_hops_path_htlc_minimum_msat
1477 .checked_add(hop_htlc_minimum_msat_inc);
1478 aggregate_next_hops_path_htlc_minimum_msat = if let Some(val) = hops_path_htlc_minimum { cmp::max(hop_htlc_minimum_msat, val) } else { break; };
1480 if idx == route.0.len() - 1 {
1481 // The last hop in this iterator is the first hop in
1482 // overall RouteHint.
1483 // If this hop connects to a node with which we have a direct channel,
1484 // ignore the network graph and, if the last hop was added, add our
1485 // direct channel to the candidate set.
1487 // Note that we *must* check if the last hop was added as `add_entry`
1488 // always assumes that the third argument is a node to which we have a
1490 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&hop.src_node_id)) {
1491 for details in first_channels {
1492 let candidate = CandidateRouteHop::FirstHop { details };
1493 add_entry!(candidate, our_node_id,
1494 NodeId::from_pubkey(&hop.src_node_id),
1495 aggregate_next_hops_fee_msat, path_value_msat,
1496 aggregate_next_hops_path_htlc_minimum_msat,
1497 aggregate_next_hops_path_penalty_msat,
1498 aggregate_next_hops_cltv_delta,
1499 aggregate_next_hops_path_length);
1507 log_trace!(logger, "Starting main path collection loop with {} nodes pre-filled from first/last hops.", targets.len());
1509 // At this point, targets are filled with the data from first and
1510 // last hops communicated by the caller, and the payment receiver.
1511 let mut found_new_path = false;
1514 // If this loop terminates due the exhaustion of targets, two situations are possible:
1515 // - not enough outgoing liquidity:
1516 // 0 < already_collected_value_msat < final_value_msat
1517 // - enough outgoing liquidity:
1518 // final_value_msat <= already_collected_value_msat < recommended_value_msat
1519 // Both these cases (and other cases except reaching recommended_value_msat) mean that
1520 // paths_collection will be stopped because found_new_path==false.
1521 // This is not necessarily a routing failure.
1522 '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() {
1524 // Since we're going payee-to-payer, hitting our node as a target means we should stop
1525 // traversing the graph and arrange the path out of what we found.
1526 if node_id == our_node_id {
1527 let mut new_entry = dist.remove(&our_node_id).unwrap();
1528 let mut ordered_hops: Vec<(PathBuildingHop, NodeFeatures)> = vec!((new_entry.clone(), default_node_features.clone()));
1531 let mut features_set = false;
1532 if let Some(first_channels) = first_hop_targets.get(&ordered_hops.last().unwrap().0.node_id) {
1533 for details in first_channels {
1534 if details.get_outbound_payment_scid().unwrap() == ordered_hops.last().unwrap().0.candidate.short_channel_id() {
1535 ordered_hops.last_mut().unwrap().1 = details.counterparty.features.to_context();
1536 features_set = true;
1542 if let Some(node) = network_nodes.get(&ordered_hops.last().unwrap().0.node_id) {
1543 if let Some(node_info) = node.announcement_info.as_ref() {
1544 ordered_hops.last_mut().unwrap().1 = node_info.features.clone();
1546 ordered_hops.last_mut().unwrap().1 = default_node_features.clone();
1549 // We can fill in features for everything except hops which were
1550 // provided via the invoice we're paying. We could guess based on the
1551 // recipient's features but for now we simply avoid guessing at all.
1555 // Means we succesfully traversed from the payer to the payee, now
1556 // save this path for the payment route. Also, update the liquidity
1557 // remaining on the used hops, so that we take them into account
1558 // while looking for more paths.
1559 if ordered_hops.last().unwrap().0.node_id == payee_node_id {
1563 new_entry = match dist.remove(&ordered_hops.last().unwrap().0.node_id) {
1564 Some(payment_hop) => payment_hop,
1565 // We can't arrive at None because, if we ever add an entry to targets,
1566 // we also fill in the entry in dist (see add_entry!).
1567 None => unreachable!(),
1569 // We "propagate" the fees one hop backward (topologically) here,
1570 // so that fees paid for a HTLC forwarding on the current channel are
1571 // associated with the previous channel (where they will be subtracted).
1572 ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
1573 ordered_hops.push((new_entry.clone(), default_node_features.clone()));
1575 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
1576 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
1578 log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: \n {:#?}",
1579 ordered_hops.len(), value_contribution_msat, ordered_hops.iter().map(|h| &(h.0)).collect::<Vec<&PathBuildingHop>>());
1581 let mut payment_path = PaymentPath {hops: ordered_hops};
1583 // We could have possibly constructed a slightly inconsistent path: since we reduce
1584 // value being transferred along the way, we could have violated htlc_minimum_msat
1585 // on some channels we already passed (assuming dest->source direction). Here, we
1586 // recompute the fees again, so that if that's the case, we match the currently
1587 // underpaid htlc_minimum_msat with fees.
1588 debug_assert_eq!(payment_path.get_value_msat(), value_contribution_msat);
1589 value_contribution_msat = cmp::min(value_contribution_msat, final_value_msat);
1590 payment_path.update_value_and_recompute_fees(value_contribution_msat);
1592 // Since a path allows to transfer as much value as
1593 // the smallest channel it has ("bottleneck"), we should recompute
1594 // the fees so sender HTLC don't overpay fees when traversing
1595 // larger channels than the bottleneck. This may happen because
1596 // when we were selecting those channels we were not aware how much value
1597 // this path will transfer, and the relative fee for them
1598 // might have been computed considering a larger value.
1599 // Remember that we used these channels so that we don't rely
1600 // on the same liquidity in future paths.
1601 let mut prevented_redundant_path_selection = false;
1602 let prev_hop_iter = core::iter::once(&our_node_id)
1603 .chain(payment_path.hops.iter().map(|(hop, _)| &hop.node_id));
1604 for (prev_hop, (hop, _)) in prev_hop_iter.zip(payment_path.hops.iter()) {
1605 let spent_on_hop_msat = value_contribution_msat + hop.next_hops_fee_msat;
1606 let used_liquidity_msat = used_channel_liquidities
1607 .entry((hop.candidate.short_channel_id(), *prev_hop < hop.node_id))
1608 .and_modify(|used_liquidity_msat| *used_liquidity_msat += spent_on_hop_msat)
1609 .or_insert(spent_on_hop_msat);
1610 let hop_capacity = hop.candidate.effective_capacity();
1611 let hop_max_msat = max_htlc_from_capacity(hop_capacity, channel_saturation_pow_half);
1612 if *used_liquidity_msat == hop_max_msat {
1613 // If this path used all of this channel's available liquidity, we know
1614 // this path will not be selected again in the next loop iteration.
1615 prevented_redundant_path_selection = true;
1617 debug_assert!(*used_liquidity_msat <= hop_max_msat);
1619 if !prevented_redundant_path_selection {
1620 // If we weren't capped by hitting a liquidity limit on a channel in the path,
1621 // we'll probably end up picking the same path again on the next iteration.
1622 // Decrease the available liquidity of a hop in the middle of the path.
1623 let victim_scid = payment_path.hops[(payment_path.hops.len()) / 2].0.candidate.short_channel_id();
1624 let exhausted = u64::max_value();
1625 log_trace!(logger, "Disabling channel {} for future path building iterations to avoid duplicates.", victim_scid);
1626 *used_channel_liquidities.entry((victim_scid, false)).or_default() = exhausted;
1627 *used_channel_liquidities.entry((victim_scid, true)).or_default() = exhausted;
1630 // Track the total amount all our collected paths allow to send so that we know
1631 // when to stop looking for more paths
1632 already_collected_value_msat += value_contribution_msat;
1634 payment_paths.push(payment_path);
1635 found_new_path = true;
1636 break 'path_construction;
1639 // If we found a path back to the payee, we shouldn't try to process it again. This is
1640 // the equivalent of the `elem.was_processed` check in
1641 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
1642 if node_id == payee_node_id { continue 'path_construction; }
1644 // Otherwise, since the current target node is not us,
1645 // keep "unrolling" the payment graph from payee to payer by
1646 // finding a way to reach the current target from the payer side.
1647 match network_nodes.get(&node_id) {
1650 add_entries_to_cheapest_to_target_node!(node, node_id, lowest_fee_to_node,
1651 value_contribution_msat, path_htlc_minimum_msat, path_penalty_msat,
1652 total_cltv_delta, path_length_to_node);
1658 if !found_new_path && channel_saturation_pow_half != 0 {
1659 channel_saturation_pow_half = 0;
1660 continue 'paths_collection;
1662 // If we don't support MPP, no use trying to gather more value ever.
1663 break 'paths_collection;
1667 // Stop either when the recommended value is reached or if no new path was found in this
1669 // In the latter case, making another path finding attempt won't help,
1670 // because we deterministically terminated the search due to low liquidity.
1671 if !found_new_path && channel_saturation_pow_half != 0 {
1672 channel_saturation_pow_half = 0;
1673 } else if already_collected_value_msat >= recommended_value_msat || !found_new_path {
1674 log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
1675 already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
1676 break 'paths_collection;
1677 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
1678 // Further, if this was our first walk of the graph, and we weren't limited by an
1679 // htlc_minimum_msat, return immediately because this path should suffice. If we were
1680 // limited by an htlc_minimum_msat value, find another path with a higher value,
1681 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
1682 // still keeping a lower total fee than this path.
1683 if !hit_minimum_limit {
1684 log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
1685 break 'paths_collection;
1687 log_trace!(logger, "Collected our payment amount on the first pass, but running again to collect extra paths with a potentially higher limit.");
1688 path_value_msat = recommended_value_msat;
1693 if payment_paths.len() == 0 {
1694 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1697 if already_collected_value_msat < final_value_msat {
1698 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1702 let mut selected_route = payment_paths;
1704 debug_assert_eq!(selected_route.iter().map(|p| p.get_value_msat()).sum::<u64>(), already_collected_value_msat);
1705 let mut overpaid_value_msat = already_collected_value_msat - final_value_msat;
1707 // First, sort by the cost-per-value of the path, dropping the paths that cost the most for
1708 // the value they contribute towards the payment amount.
1709 // We sort in descending order as we will remove from the front in `retain`, next.
1710 selected_route.sort_unstable_by(|a, b|
1711 (((b.get_cost_msat() as u128) << 64) / (b.get_value_msat() as u128))
1712 .cmp(&(((a.get_cost_msat() as u128) << 64) / (a.get_value_msat() as u128)))
1715 // We should make sure that at least 1 path left.
1716 let mut paths_left = selected_route.len();
1717 selected_route.retain(|path| {
1718 if paths_left == 1 {
1721 let path_value_msat = path.get_value_msat();
1722 if path_value_msat <= overpaid_value_msat {
1723 overpaid_value_msat -= path_value_msat;
1729 debug_assert!(selected_route.len() > 0);
1731 if overpaid_value_msat != 0 {
1733 // Now, subtract the remaining overpaid value from the most-expensive path.
1734 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1735 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1736 selected_route.sort_unstable_by(|a, b| {
1737 let a_f = a.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
1738 let b_f = b.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
1739 a_f.cmp(&b_f).then_with(|| b.get_cost_msat().cmp(&a.get_cost_msat()))
1741 let expensive_payment_path = selected_route.first_mut().unwrap();
1743 // We already dropped all the paths with value below `overpaid_value_msat` above, thus this
1744 // can't go negative.
1745 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
1746 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
1750 // Sort by the path itself and combine redundant paths.
1751 // Note that we sort by SCIDs alone as its simpler but when combining we have to ensure we
1752 // compare both SCIDs and NodeIds as individual nodes may use random aliases causing collisions
1754 selected_route.sort_unstable_by_key(|path| {
1755 let mut key = [0u64; MAX_PATH_LENGTH_ESTIMATE as usize];
1756 debug_assert!(path.hops.len() <= key.len());
1757 for (scid, key) in path.hops.iter().map(|h| h.0.candidate.short_channel_id()).zip(key.iter_mut()) {
1762 for idx in 0..(selected_route.len() - 1) {
1763 if idx + 1 >= selected_route.len() { break; }
1764 if iter_equal(selected_route[idx ].hops.iter().map(|h| (h.0.candidate.short_channel_id(), h.0.node_id)),
1765 selected_route[idx + 1].hops.iter().map(|h| (h.0.candidate.short_channel_id(), h.0.node_id))) {
1766 let new_value = selected_route[idx].get_value_msat() + selected_route[idx + 1].get_value_msat();
1767 selected_route[idx].update_value_and_recompute_fees(new_value);
1768 selected_route.remove(idx + 1);
1772 let mut selected_paths = Vec::<Vec<Result<RouteHop, LightningError>>>::new();
1773 for payment_path in selected_route {
1774 let mut path = payment_path.hops.iter().map(|(payment_hop, node_features)| {
1776 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)})?,
1777 node_features: node_features.clone(),
1778 short_channel_id: payment_hop.candidate.short_channel_id(),
1779 channel_features: payment_hop.candidate.features(),
1780 fee_msat: payment_hop.fee_msat,
1781 cltv_expiry_delta: payment_hop.candidate.cltv_expiry_delta(),
1783 }).collect::<Vec<_>>();
1784 // Propagate the cltv_expiry_delta one hop backwards since the delta from the current hop is
1785 // applicable for the previous hop.
1786 path.iter_mut().rev().fold(final_cltv_expiry_delta, |prev_cltv_expiry_delta, hop| {
1787 core::mem::replace(&mut hop.as_mut().unwrap().cltv_expiry_delta, prev_cltv_expiry_delta)
1789 selected_paths.push(path);
1791 // Make sure we would never create a route with more paths than we allow.
1792 debug_assert!(selected_paths.len() <= payment_params.max_path_count.into());
1794 if let Some(features) = &payment_params.features {
1795 for path in selected_paths.iter_mut() {
1796 if let Ok(route_hop) = path.last_mut().unwrap() {
1797 route_hop.node_features = features.to_context();
1803 paths: selected_paths.into_iter().map(|path| path.into_iter().collect()).collect::<Result<Vec<_>, _>>()?,
1804 payment_params: Some(payment_params.clone()),
1806 log_info!(logger, "Got route to {}: {}", payment_params.payee_pubkey, log_route!(route));
1810 // When an adversarial intermediary node observes a payment, it may be able to infer its
1811 // destination, if the remaining CLTV expiry delta exactly matches a feasible path in the network
1812 // graph. In order to improve privacy, this method obfuscates the CLTV expiry deltas along the
1813 // payment path by adding a randomized 'shadow route' offset to the final hop.
1814 fn add_random_cltv_offset(route: &mut Route, payment_params: &PaymentParameters,
1815 network_graph: &ReadOnlyNetworkGraph, random_seed_bytes: &[u8; 32]
1817 let network_channels = network_graph.channels();
1818 let network_nodes = network_graph.nodes();
1820 for path in route.paths.iter_mut() {
1821 let mut shadow_ctlv_expiry_delta_offset: u32 = 0;
1823 // Remember the last three nodes of the random walk and avoid looping back on them.
1824 // Init with the last three nodes from the actual path, if possible.
1825 let mut nodes_to_avoid: [NodeId; 3] = [NodeId::from_pubkey(&path.last().unwrap().pubkey),
1826 NodeId::from_pubkey(&path.get(path.len().saturating_sub(2)).unwrap().pubkey),
1827 NodeId::from_pubkey(&path.get(path.len().saturating_sub(3)).unwrap().pubkey)];
1829 // Choose the last publicly known node as the starting point for the random walk.
1830 let mut cur_hop: Option<NodeId> = None;
1831 let mut path_nonce = [0u8; 12];
1832 if let Some(starting_hop) = path.iter().rev()
1833 .find(|h| network_nodes.contains_key(&NodeId::from_pubkey(&h.pubkey))) {
1834 cur_hop = Some(NodeId::from_pubkey(&starting_hop.pubkey));
1835 path_nonce.copy_from_slice(&cur_hop.unwrap().as_slice()[..12]);
1838 // Init PRNG with the path-dependant nonce, which is static for private paths.
1839 let mut prng = ChaCha20::new(random_seed_bytes, &path_nonce);
1840 let mut random_path_bytes = [0u8; ::core::mem::size_of::<usize>()];
1842 // Pick a random path length in [1 .. 3]
1843 prng.process_in_place(&mut random_path_bytes);
1844 let random_walk_length = usize::from_be_bytes(random_path_bytes).wrapping_rem(3).wrapping_add(1);
1846 for random_hop in 0..random_walk_length {
1847 // If we don't find a suitable offset in the public network graph, we default to
1848 // MEDIAN_HOP_CLTV_EXPIRY_DELTA.
1849 let mut random_hop_offset = MEDIAN_HOP_CLTV_EXPIRY_DELTA;
1851 if let Some(cur_node_id) = cur_hop {
1852 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
1853 // Randomly choose the next unvisited hop.
1854 prng.process_in_place(&mut random_path_bytes);
1855 if let Some(random_channel) = usize::from_be_bytes(random_path_bytes)
1856 .checked_rem(cur_node.channels.len())
1857 .and_then(|index| cur_node.channels.get(index))
1858 .and_then(|id| network_channels.get(id)) {
1859 random_channel.as_directed_from(&cur_node_id).map(|(dir_info, next_id)| {
1860 if !nodes_to_avoid.iter().any(|x| x == next_id) {
1861 nodes_to_avoid[random_hop] = *next_id;
1862 dir_info.direction().map(|channel_update_info| {
1863 random_hop_offset = channel_update_info.cltv_expiry_delta.into();
1864 cur_hop = Some(*next_id);
1872 shadow_ctlv_expiry_delta_offset = shadow_ctlv_expiry_delta_offset
1873 .checked_add(random_hop_offset)
1874 .unwrap_or(shadow_ctlv_expiry_delta_offset);
1877 // Limit the total offset to reduce the worst-case locked liquidity timevalue
1878 const MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET: u32 = 3*144;
1879 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET);
1881 // Limit the offset so we never exceed the max_total_cltv_expiry_delta. To improve plausibility,
1882 // we choose the limit to be the largest possible multiple of MEDIAN_HOP_CLTV_EXPIRY_DELTA.
1883 let path_total_cltv_expiry_delta: u32 = path.iter().map(|h| h.cltv_expiry_delta).sum();
1884 let mut max_path_offset = payment_params.max_total_cltv_expiry_delta - path_total_cltv_expiry_delta;
1885 max_path_offset = cmp::max(
1886 max_path_offset - (max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA),
1887 max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA);
1888 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, max_path_offset);
1890 // Add 'shadow' CLTV offset to the final hop
1891 if let Some(last_hop) = path.last_mut() {
1892 last_hop.cltv_expiry_delta = last_hop.cltv_expiry_delta
1893 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(last_hop.cltv_expiry_delta);
1898 /// Construct a route from us (payer) to the target node (payee) via the given hops (which should
1899 /// exclude the payer, but include the payee). This may be useful, e.g., for probing the chosen path.
1901 /// Re-uses logic from `find_route`, so the restrictions described there also apply here.
1902 pub fn build_route_from_hops<L: Deref, GL: Deref>(
1903 our_node_pubkey: &PublicKey, hops: &[PublicKey], route_params: &RouteParameters,
1904 network_graph: &NetworkGraph<GL>, logger: L, random_seed_bytes: &[u8; 32]
1905 ) -> Result<Route, LightningError>
1906 where L::Target: Logger, GL::Target: Logger {
1907 let graph_lock = network_graph.read_only();
1908 let mut route = build_route_from_hops_internal(
1909 our_node_pubkey, hops, &route_params.payment_params, &graph_lock,
1910 route_params.final_value_msat, route_params.final_cltv_expiry_delta, logger, random_seed_bytes)?;
1911 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
1915 fn build_route_from_hops_internal<L: Deref>(
1916 our_node_pubkey: &PublicKey, hops: &[PublicKey], payment_params: &PaymentParameters,
1917 network_graph: &ReadOnlyNetworkGraph, final_value_msat: u64, final_cltv_expiry_delta: u32,
1918 logger: L, random_seed_bytes: &[u8; 32]
1919 ) -> Result<Route, LightningError> where L::Target: Logger {
1922 our_node_id: NodeId,
1923 hop_ids: [Option<NodeId>; MAX_PATH_LENGTH_ESTIMATE as usize],
1926 impl Score for HopScorer {
1927 fn channel_penalty_msat(&self, _short_channel_id: u64, source: &NodeId, target: &NodeId,
1928 _usage: ChannelUsage) -> u64
1930 let mut cur_id = self.our_node_id;
1931 for i in 0..self.hop_ids.len() {
1932 if let Some(next_id) = self.hop_ids[i] {
1933 if cur_id == *source && next_id == *target {
1944 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
1946 fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
1948 fn probe_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
1950 fn probe_successful(&mut self, _path: &[&RouteHop]) {}
1953 impl<'a> Writeable for HopScorer {
1955 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), io::Error> {
1960 if hops.len() > MAX_PATH_LENGTH_ESTIMATE.into() {
1961 return Err(LightningError{err: "Cannot build a route exceeding the maximum path length.".to_owned(), action: ErrorAction::IgnoreError});
1964 let our_node_id = NodeId::from_pubkey(our_node_pubkey);
1965 let mut hop_ids = [None; MAX_PATH_LENGTH_ESTIMATE as usize];
1966 for i in 0..hops.len() {
1967 hop_ids[i] = Some(NodeId::from_pubkey(&hops[i]));
1970 let scorer = HopScorer { our_node_id, hop_ids };
1972 get_route(our_node_pubkey, payment_params, network_graph, None, final_value_msat,
1973 final_cltv_expiry_delta, logger, &scorer, random_seed_bytes)
1978 use crate::routing::gossip::{NetworkGraph, P2PGossipSync, NodeId, EffectiveCapacity};
1979 use crate::routing::router::{get_route, build_route_from_hops_internal, add_random_cltv_offset, default_node_features,
1980 PaymentParameters, Route, RouteHint, RouteHintHop, RouteHop, RoutingFees,
1981 DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA, MAX_PATH_LENGTH_ESTIMATE};
1982 use crate::routing::scoring::{ChannelUsage, Score, ProbabilisticScorer, ProbabilisticScoringParameters};
1983 use crate::routing::test_utils::{add_channel, add_or_update_node, build_graph, build_line_graph, id_to_feature_flags, get_nodes, update_channel};
1984 use crate::chain::transaction::OutPoint;
1985 use crate::chain::keysinterface::KeysInterface;
1986 use crate::ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
1987 use crate::ln::msgs::{ErrorAction, LightningError, UnsignedChannelUpdate, MAX_VALUE_MSAT};
1988 use crate::ln::channelmanager;
1989 use crate::util::test_utils as ln_test_utils;
1990 use crate::util::chacha20::ChaCha20;
1992 use crate::util::ser::{Writeable, Writer};
1994 use bitcoin::hashes::Hash;
1995 use bitcoin::network::constants::Network;
1996 use bitcoin::blockdata::constants::genesis_block;
1997 use bitcoin::blockdata::script::Builder;
1998 use bitcoin::blockdata::opcodes;
1999 use bitcoin::blockdata::transaction::TxOut;
2003 use bitcoin::secp256k1::{PublicKey,SecretKey};
2004 use bitcoin::secp256k1::Secp256k1;
2006 use crate::prelude::*;
2007 use crate::sync::Arc;
2009 use core::convert::TryInto;
2011 fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
2012 features: InitFeatures, outbound_capacity_msat: u64) -> channelmanager::ChannelDetails {
2013 channelmanager::ChannelDetails {
2014 channel_id: [0; 32],
2015 counterparty: channelmanager::ChannelCounterparty {
2018 unspendable_punishment_reserve: 0,
2019 forwarding_info: None,
2020 outbound_htlc_minimum_msat: None,
2021 outbound_htlc_maximum_msat: None,
2023 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
2026 outbound_scid_alias: None,
2027 inbound_scid_alias: None,
2028 channel_value_satoshis: 0,
2031 outbound_capacity_msat,
2032 next_outbound_htlc_limit_msat: outbound_capacity_msat,
2033 inbound_capacity_msat: 42,
2034 unspendable_punishment_reserve: None,
2035 confirmations_required: None,
2036 force_close_spend_delay: None,
2037 is_outbound: true, is_channel_ready: true,
2038 is_usable: true, is_public: true,
2039 inbound_htlc_minimum_msat: None,
2040 inbound_htlc_maximum_msat: None,
2046 fn simple_route_test() {
2047 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2048 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2049 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2050 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2051 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2052 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2054 // Simple route to 2 via 1
2056 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) {
2057 assert_eq!(err, "Cannot send a payment of 0 msat");
2058 } else { panic!(); }
2060 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2061 assert_eq!(route.paths[0].len(), 2);
2063 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2064 assert_eq!(route.paths[0][0].short_channel_id, 2);
2065 assert_eq!(route.paths[0][0].fee_msat, 100);
2066 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2067 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2068 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2070 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2071 assert_eq!(route.paths[0][1].short_channel_id, 4);
2072 assert_eq!(route.paths[0][1].fee_msat, 100);
2073 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2074 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2075 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2079 fn invalid_first_hop_test() {
2080 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2081 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2082 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2083 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2084 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2085 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2087 // Simple route to 2 via 1
2089 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
2091 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) =
2092 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) {
2093 assert_eq!(err, "First hop cannot have our_node_pubkey as a destination.");
2094 } else { panic!(); }
2096 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2097 assert_eq!(route.paths[0].len(), 2);
2101 fn htlc_minimum_test() {
2102 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2103 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2104 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2105 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2106 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2107 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2109 // Simple route to 2 via 1
2111 // Disable other paths
2112 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2113 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2114 short_channel_id: 12,
2116 flags: 2, // to disable
2117 cltv_expiry_delta: 0,
2118 htlc_minimum_msat: 0,
2119 htlc_maximum_msat: MAX_VALUE_MSAT,
2121 fee_proportional_millionths: 0,
2122 excess_data: Vec::new()
2124 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2125 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2126 short_channel_id: 3,
2128 flags: 2, // to disable
2129 cltv_expiry_delta: 0,
2130 htlc_minimum_msat: 0,
2131 htlc_maximum_msat: MAX_VALUE_MSAT,
2133 fee_proportional_millionths: 0,
2134 excess_data: Vec::new()
2136 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2137 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2138 short_channel_id: 13,
2140 flags: 2, // to disable
2141 cltv_expiry_delta: 0,
2142 htlc_minimum_msat: 0,
2143 htlc_maximum_msat: MAX_VALUE_MSAT,
2145 fee_proportional_millionths: 0,
2146 excess_data: Vec::new()
2148 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2149 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2150 short_channel_id: 6,
2152 flags: 2, // to disable
2153 cltv_expiry_delta: 0,
2154 htlc_minimum_msat: 0,
2155 htlc_maximum_msat: MAX_VALUE_MSAT,
2157 fee_proportional_millionths: 0,
2158 excess_data: Vec::new()
2160 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2161 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2162 short_channel_id: 7,
2164 flags: 2, // to disable
2165 cltv_expiry_delta: 0,
2166 htlc_minimum_msat: 0,
2167 htlc_maximum_msat: MAX_VALUE_MSAT,
2169 fee_proportional_millionths: 0,
2170 excess_data: Vec::new()
2173 // Check against amount_to_transfer_over_msat.
2174 // Set minimal HTLC of 200_000_000 msat.
2175 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2176 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2177 short_channel_id: 2,
2180 cltv_expiry_delta: 0,
2181 htlc_minimum_msat: 200_000_000,
2182 htlc_maximum_msat: MAX_VALUE_MSAT,
2184 fee_proportional_millionths: 0,
2185 excess_data: Vec::new()
2188 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
2190 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2191 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2192 short_channel_id: 4,
2195 cltv_expiry_delta: 0,
2196 htlc_minimum_msat: 0,
2197 htlc_maximum_msat: 199_999_999,
2199 fee_proportional_millionths: 0,
2200 excess_data: Vec::new()
2203 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
2204 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) {
2205 assert_eq!(err, "Failed to find a path to the given destination");
2206 } else { panic!(); }
2208 // Lift the restriction on the first hop.
2209 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2210 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2211 short_channel_id: 2,
2214 cltv_expiry_delta: 0,
2215 htlc_minimum_msat: 0,
2216 htlc_maximum_msat: MAX_VALUE_MSAT,
2218 fee_proportional_millionths: 0,
2219 excess_data: Vec::new()
2222 // A payment above the minimum should pass
2223 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();
2224 assert_eq!(route.paths[0].len(), 2);
2228 fn htlc_minimum_overpay_test() {
2229 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2230 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2231 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(channelmanager::provided_invoice_features());
2232 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2233 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2234 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2236 // A route to node#2 via two paths.
2237 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
2238 // Thus, they can't send 60 without overpaying.
2239 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2240 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2241 short_channel_id: 2,
2244 cltv_expiry_delta: 0,
2245 htlc_minimum_msat: 35_000,
2246 htlc_maximum_msat: 40_000,
2248 fee_proportional_millionths: 0,
2249 excess_data: Vec::new()
2251 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2252 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2253 short_channel_id: 12,
2256 cltv_expiry_delta: 0,
2257 htlc_minimum_msat: 35_000,
2258 htlc_maximum_msat: 40_000,
2260 fee_proportional_millionths: 0,
2261 excess_data: Vec::new()
2265 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2266 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2267 short_channel_id: 13,
2270 cltv_expiry_delta: 0,
2271 htlc_minimum_msat: 0,
2272 htlc_maximum_msat: MAX_VALUE_MSAT,
2274 fee_proportional_millionths: 0,
2275 excess_data: Vec::new()
2277 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2278 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2279 short_channel_id: 4,
2282 cltv_expiry_delta: 0,
2283 htlc_minimum_msat: 0,
2284 htlc_maximum_msat: MAX_VALUE_MSAT,
2286 fee_proportional_millionths: 0,
2287 excess_data: Vec::new()
2290 // Disable other paths
2291 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2292 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2293 short_channel_id: 1,
2295 flags: 2, // to disable
2296 cltv_expiry_delta: 0,
2297 htlc_minimum_msat: 0,
2298 htlc_maximum_msat: MAX_VALUE_MSAT,
2300 fee_proportional_millionths: 0,
2301 excess_data: Vec::new()
2304 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 60_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2305 // Overpay fees to hit htlc_minimum_msat.
2306 let overpaid_fees = route.paths[0][0].fee_msat + route.paths[1][0].fee_msat;
2307 // TODO: this could be better balanced to overpay 10k and not 15k.
2308 assert_eq!(overpaid_fees, 15_000);
2310 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
2311 // while taking even more fee to match htlc_minimum_msat.
2312 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2313 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2314 short_channel_id: 12,
2317 cltv_expiry_delta: 0,
2318 htlc_minimum_msat: 65_000,
2319 htlc_maximum_msat: 80_000,
2321 fee_proportional_millionths: 0,
2322 excess_data: Vec::new()
2324 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2325 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2326 short_channel_id: 2,
2329 cltv_expiry_delta: 0,
2330 htlc_minimum_msat: 0,
2331 htlc_maximum_msat: MAX_VALUE_MSAT,
2333 fee_proportional_millionths: 0,
2334 excess_data: Vec::new()
2336 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2337 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2338 short_channel_id: 4,
2341 cltv_expiry_delta: 0,
2342 htlc_minimum_msat: 0,
2343 htlc_maximum_msat: MAX_VALUE_MSAT,
2345 fee_proportional_millionths: 100_000,
2346 excess_data: Vec::new()
2349 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 60_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2350 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
2351 assert_eq!(route.paths.len(), 1);
2352 assert_eq!(route.paths[0][0].short_channel_id, 12);
2353 let fees = route.paths[0][0].fee_msat;
2354 assert_eq!(fees, 5_000);
2356 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2357 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
2358 // the other channel.
2359 assert_eq!(route.paths.len(), 1);
2360 assert_eq!(route.paths[0][0].short_channel_id, 2);
2361 let fees = route.paths[0][0].fee_msat;
2362 assert_eq!(fees, 5_000);
2366 fn disable_channels_test() {
2367 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2368 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2369 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2370 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2371 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2372 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2374 // // Disable channels 4 and 12 by flags=2
2375 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2376 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2377 short_channel_id: 4,
2379 flags: 2, // to disable
2380 cltv_expiry_delta: 0,
2381 htlc_minimum_msat: 0,
2382 htlc_maximum_msat: MAX_VALUE_MSAT,
2384 fee_proportional_millionths: 0,
2385 excess_data: Vec::new()
2387 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2388 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2389 short_channel_id: 12,
2391 flags: 2, // to disable
2392 cltv_expiry_delta: 0,
2393 htlc_minimum_msat: 0,
2394 htlc_maximum_msat: MAX_VALUE_MSAT,
2396 fee_proportional_millionths: 0,
2397 excess_data: Vec::new()
2400 // If all the channels require some features we don't understand, route should fail
2401 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) {
2402 assert_eq!(err, "Failed to find a path to the given destination");
2403 } else { panic!(); }
2405 // If we specify a channel to node7, that overrides our local channel view and that gets used
2406 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2407 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();
2408 assert_eq!(route.paths[0].len(), 2);
2410 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2411 assert_eq!(route.paths[0][0].short_channel_id, 42);
2412 assert_eq!(route.paths[0][0].fee_msat, 200);
2413 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2414 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2415 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2417 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2418 assert_eq!(route.paths[0][1].short_channel_id, 13);
2419 assert_eq!(route.paths[0][1].fee_msat, 100);
2420 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2421 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2422 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2426 fn disable_node_test() {
2427 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2428 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2429 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2430 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2431 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2432 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2434 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
2435 let mut unknown_features = NodeFeatures::empty();
2436 unknown_features.set_unknown_feature_required();
2437 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
2438 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
2439 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
2441 // If all nodes require some features we don't understand, route should fail
2442 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) {
2443 assert_eq!(err, "Failed to find a path to the given destination");
2444 } else { panic!(); }
2446 // If we specify a channel to node7, that overrides our local channel view and that gets used
2447 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2448 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();
2449 assert_eq!(route.paths[0].len(), 2);
2451 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2452 assert_eq!(route.paths[0][0].short_channel_id, 42);
2453 assert_eq!(route.paths[0][0].fee_msat, 200);
2454 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2455 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2456 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2458 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2459 assert_eq!(route.paths[0][1].short_channel_id, 13);
2460 assert_eq!(route.paths[0][1].fee_msat, 100);
2461 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2462 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2463 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2465 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
2466 // naively) assume that the user checked the feature bits on the invoice, which override
2467 // the node_announcement.
2471 fn our_chans_test() {
2472 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2473 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2474 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2475 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2476 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2478 // Route to 1 via 2 and 3 because our channel to 1 is disabled
2479 let payment_params = PaymentParameters::from_node_id(nodes[0]);
2480 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2481 assert_eq!(route.paths[0].len(), 3);
2483 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2484 assert_eq!(route.paths[0][0].short_channel_id, 2);
2485 assert_eq!(route.paths[0][0].fee_msat, 200);
2486 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2487 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2488 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2490 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2491 assert_eq!(route.paths[0][1].short_channel_id, 4);
2492 assert_eq!(route.paths[0][1].fee_msat, 100);
2493 assert_eq!(route.paths[0][1].cltv_expiry_delta, (3 << 4) | 2);
2494 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2495 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2497 assert_eq!(route.paths[0][2].pubkey, nodes[0]);
2498 assert_eq!(route.paths[0][2].short_channel_id, 3);
2499 assert_eq!(route.paths[0][2].fee_msat, 100);
2500 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
2501 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(1));
2502 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(3));
2504 // If we specify a channel to node7, that overrides our local channel view and that gets used
2505 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2506 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2507 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();
2508 assert_eq!(route.paths[0].len(), 2);
2510 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2511 assert_eq!(route.paths[0][0].short_channel_id, 42);
2512 assert_eq!(route.paths[0][0].fee_msat, 200);
2513 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2514 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2515 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2517 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2518 assert_eq!(route.paths[0][1].short_channel_id, 13);
2519 assert_eq!(route.paths[0][1].fee_msat, 100);
2520 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2521 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2522 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2525 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2526 let zero_fees = RoutingFees {
2528 proportional_millionths: 0,
2530 vec![RouteHint(vec![RouteHintHop {
2531 src_node_id: nodes[3],
2532 short_channel_id: 8,
2534 cltv_expiry_delta: (8 << 4) | 1,
2535 htlc_minimum_msat: None,
2536 htlc_maximum_msat: None,
2538 ]), RouteHint(vec![RouteHintHop {
2539 src_node_id: nodes[4],
2540 short_channel_id: 9,
2543 proportional_millionths: 0,
2545 cltv_expiry_delta: (9 << 4) | 1,
2546 htlc_minimum_msat: None,
2547 htlc_maximum_msat: None,
2548 }]), RouteHint(vec![RouteHintHop {
2549 src_node_id: nodes[5],
2550 short_channel_id: 10,
2552 cltv_expiry_delta: (10 << 4) | 1,
2553 htlc_minimum_msat: None,
2554 htlc_maximum_msat: None,
2558 fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2559 let zero_fees = RoutingFees {
2561 proportional_millionths: 0,
2563 vec![RouteHint(vec![RouteHintHop {
2564 src_node_id: nodes[2],
2565 short_channel_id: 5,
2568 proportional_millionths: 0,
2570 cltv_expiry_delta: (5 << 4) | 1,
2571 htlc_minimum_msat: None,
2572 htlc_maximum_msat: None,
2574 src_node_id: nodes[3],
2575 short_channel_id: 8,
2577 cltv_expiry_delta: (8 << 4) | 1,
2578 htlc_minimum_msat: None,
2579 htlc_maximum_msat: None,
2581 ]), RouteHint(vec![RouteHintHop {
2582 src_node_id: nodes[4],
2583 short_channel_id: 9,
2586 proportional_millionths: 0,
2588 cltv_expiry_delta: (9 << 4) | 1,
2589 htlc_minimum_msat: None,
2590 htlc_maximum_msat: None,
2591 }]), RouteHint(vec![RouteHintHop {
2592 src_node_id: nodes[5],
2593 short_channel_id: 10,
2595 cltv_expiry_delta: (10 << 4) | 1,
2596 htlc_minimum_msat: None,
2597 htlc_maximum_msat: None,
2602 fn partial_route_hint_test() {
2603 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2604 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2605 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2606 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2607 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2609 // Simple test across 2, 3, 5, and 4 via a last_hop channel
2610 // Tests the behaviour when the RouteHint contains a suboptimal hop.
2611 // RouteHint may be partially used by the algo to build the best path.
2613 // First check that last hop can't have its source as the payee.
2614 let invalid_last_hop = RouteHint(vec![RouteHintHop {
2615 src_node_id: nodes[6],
2616 short_channel_id: 8,
2619 proportional_millionths: 0,
2621 cltv_expiry_delta: (8 << 4) | 1,
2622 htlc_minimum_msat: None,
2623 htlc_maximum_msat: None,
2626 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
2627 invalid_last_hops.push(invalid_last_hop);
2629 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(invalid_last_hops);
2630 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) {
2631 assert_eq!(err, "Route hint cannot have the payee as the source.");
2632 } else { panic!(); }
2635 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops_multi_private_channels(&nodes));
2636 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2637 assert_eq!(route.paths[0].len(), 5);
2639 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2640 assert_eq!(route.paths[0][0].short_channel_id, 2);
2641 assert_eq!(route.paths[0][0].fee_msat, 100);
2642 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2643 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2644 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2646 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2647 assert_eq!(route.paths[0][1].short_channel_id, 4);
2648 assert_eq!(route.paths[0][1].fee_msat, 0);
2649 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
2650 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2651 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2653 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2654 assert_eq!(route.paths[0][2].short_channel_id, 6);
2655 assert_eq!(route.paths[0][2].fee_msat, 0);
2656 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
2657 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2658 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2660 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2661 assert_eq!(route.paths[0][3].short_channel_id, 11);
2662 assert_eq!(route.paths[0][3].fee_msat, 0);
2663 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
2664 // If we have a peer in the node map, we'll use their features here since we don't have
2665 // a way of figuring out their features from the invoice:
2666 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2667 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2669 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2670 assert_eq!(route.paths[0][4].short_channel_id, 8);
2671 assert_eq!(route.paths[0][4].fee_msat, 100);
2672 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2673 assert_eq!(route.paths[0][4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
2674 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2677 fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2678 let zero_fees = RoutingFees {
2680 proportional_millionths: 0,
2682 vec![RouteHint(vec![RouteHintHop {
2683 src_node_id: nodes[3],
2684 short_channel_id: 8,
2686 cltv_expiry_delta: (8 << 4) | 1,
2687 htlc_minimum_msat: None,
2688 htlc_maximum_msat: None,
2689 }]), RouteHint(vec![
2691 ]), RouteHint(vec![RouteHintHop {
2692 src_node_id: nodes[5],
2693 short_channel_id: 10,
2695 cltv_expiry_delta: (10 << 4) | 1,
2696 htlc_minimum_msat: None,
2697 htlc_maximum_msat: None,
2702 fn ignores_empty_last_hops_test() {
2703 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2704 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2705 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(empty_last_hop(&nodes));
2706 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2707 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2708 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2710 // Test handling of an empty RouteHint passed in Invoice.
2712 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2713 assert_eq!(route.paths[0].len(), 5);
2715 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2716 assert_eq!(route.paths[0][0].short_channel_id, 2);
2717 assert_eq!(route.paths[0][0].fee_msat, 100);
2718 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2719 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2720 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2722 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2723 assert_eq!(route.paths[0][1].short_channel_id, 4);
2724 assert_eq!(route.paths[0][1].fee_msat, 0);
2725 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
2726 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2727 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2729 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2730 assert_eq!(route.paths[0][2].short_channel_id, 6);
2731 assert_eq!(route.paths[0][2].fee_msat, 0);
2732 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
2733 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2734 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2736 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2737 assert_eq!(route.paths[0][3].short_channel_id, 11);
2738 assert_eq!(route.paths[0][3].fee_msat, 0);
2739 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
2740 // If we have a peer in the node map, we'll use their features here since we don't have
2741 // a way of figuring out their features from the invoice:
2742 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2743 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2745 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2746 assert_eq!(route.paths[0][4].short_channel_id, 8);
2747 assert_eq!(route.paths[0][4].fee_msat, 100);
2748 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2749 assert_eq!(route.paths[0][4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
2750 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2753 /// Builds a trivial last-hop hint that passes through the two nodes given, with channel 0xff00
2755 fn multi_hop_last_hops_hint(hint_hops: [PublicKey; 2]) -> Vec<RouteHint> {
2756 let zero_fees = RoutingFees {
2758 proportional_millionths: 0,
2760 vec![RouteHint(vec![RouteHintHop {
2761 src_node_id: hint_hops[0],
2762 short_channel_id: 0xff00,
2765 proportional_millionths: 0,
2767 cltv_expiry_delta: (5 << 4) | 1,
2768 htlc_minimum_msat: None,
2769 htlc_maximum_msat: None,
2771 src_node_id: hint_hops[1],
2772 short_channel_id: 0xff01,
2774 cltv_expiry_delta: (8 << 4) | 1,
2775 htlc_minimum_msat: None,
2776 htlc_maximum_msat: None,
2781 fn multi_hint_last_hops_test() {
2782 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2783 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2784 let last_hops = multi_hop_last_hops_hint([nodes[2], nodes[3]]);
2785 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops.clone());
2786 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2787 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2788 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2789 // Test through channels 2, 3, 0xff00, 0xff01.
2790 // Test shows that multiple hop hints are considered.
2792 // Disabling channels 6 & 7 by flags=2
2793 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2794 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2795 short_channel_id: 6,
2797 flags: 2, // to disable
2798 cltv_expiry_delta: 0,
2799 htlc_minimum_msat: 0,
2800 htlc_maximum_msat: MAX_VALUE_MSAT,
2802 fee_proportional_millionths: 0,
2803 excess_data: Vec::new()
2805 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2806 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2807 short_channel_id: 7,
2809 flags: 2, // to disable
2810 cltv_expiry_delta: 0,
2811 htlc_minimum_msat: 0,
2812 htlc_maximum_msat: MAX_VALUE_MSAT,
2814 fee_proportional_millionths: 0,
2815 excess_data: Vec::new()
2818 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2819 assert_eq!(route.paths[0].len(), 4);
2821 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2822 assert_eq!(route.paths[0][0].short_channel_id, 2);
2823 assert_eq!(route.paths[0][0].fee_msat, 200);
2824 assert_eq!(route.paths[0][0].cltv_expiry_delta, 65);
2825 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2826 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2828 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2829 assert_eq!(route.paths[0][1].short_channel_id, 4);
2830 assert_eq!(route.paths[0][1].fee_msat, 100);
2831 assert_eq!(route.paths[0][1].cltv_expiry_delta, 81);
2832 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2833 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2835 assert_eq!(route.paths[0][2].pubkey, nodes[3]);
2836 assert_eq!(route.paths[0][2].short_channel_id, last_hops[0].0[0].short_channel_id);
2837 assert_eq!(route.paths[0][2].fee_msat, 0);
2838 assert_eq!(route.paths[0][2].cltv_expiry_delta, 129);
2839 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(4));
2840 assert_eq!(route.paths[0][2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2842 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2843 assert_eq!(route.paths[0][3].short_channel_id, last_hops[0].0[1].short_channel_id);
2844 assert_eq!(route.paths[0][3].fee_msat, 100);
2845 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2846 assert_eq!(route.paths[0][3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
2847 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2851 fn private_multi_hint_last_hops_test() {
2852 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2853 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2855 let non_announced_privkey = SecretKey::from_slice(&hex::decode(format!("{:02x}", 0xf0).repeat(32)).unwrap()[..]).unwrap();
2856 let non_announced_pubkey = PublicKey::from_secret_key(&secp_ctx, &non_announced_privkey);
2858 let last_hops = multi_hop_last_hops_hint([nodes[2], non_announced_pubkey]);
2859 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops.clone());
2860 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2861 // Test through channels 2, 3, 0xff00, 0xff01.
2862 // Test shows that multiple hop hints are considered.
2864 // Disabling channels 6 & 7 by flags=2
2865 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2866 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2867 short_channel_id: 6,
2869 flags: 2, // to disable
2870 cltv_expiry_delta: 0,
2871 htlc_minimum_msat: 0,
2872 htlc_maximum_msat: MAX_VALUE_MSAT,
2874 fee_proportional_millionths: 0,
2875 excess_data: Vec::new()
2877 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2878 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2879 short_channel_id: 7,
2881 flags: 2, // to disable
2882 cltv_expiry_delta: 0,
2883 htlc_minimum_msat: 0,
2884 htlc_maximum_msat: MAX_VALUE_MSAT,
2886 fee_proportional_millionths: 0,
2887 excess_data: Vec::new()
2890 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &[42u8; 32]).unwrap();
2891 assert_eq!(route.paths[0].len(), 4);
2893 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2894 assert_eq!(route.paths[0][0].short_channel_id, 2);
2895 assert_eq!(route.paths[0][0].fee_msat, 200);
2896 assert_eq!(route.paths[0][0].cltv_expiry_delta, 65);
2897 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2898 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2900 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2901 assert_eq!(route.paths[0][1].short_channel_id, 4);
2902 assert_eq!(route.paths[0][1].fee_msat, 100);
2903 assert_eq!(route.paths[0][1].cltv_expiry_delta, 81);
2904 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2905 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2907 assert_eq!(route.paths[0][2].pubkey, non_announced_pubkey);
2908 assert_eq!(route.paths[0][2].short_channel_id, last_hops[0].0[0].short_channel_id);
2909 assert_eq!(route.paths[0][2].fee_msat, 0);
2910 assert_eq!(route.paths[0][2].cltv_expiry_delta, 129);
2911 assert_eq!(route.paths[0][2].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
2912 assert_eq!(route.paths[0][2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2914 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2915 assert_eq!(route.paths[0][3].short_channel_id, last_hops[0].0[1].short_channel_id);
2916 assert_eq!(route.paths[0][3].fee_msat, 100);
2917 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2918 assert_eq!(route.paths[0][3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
2919 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2922 fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2923 let zero_fees = RoutingFees {
2925 proportional_millionths: 0,
2927 vec![RouteHint(vec![RouteHintHop {
2928 src_node_id: nodes[4],
2929 short_channel_id: 11,
2931 cltv_expiry_delta: (11 << 4) | 1,
2932 htlc_minimum_msat: None,
2933 htlc_maximum_msat: None,
2935 src_node_id: nodes[3],
2936 short_channel_id: 8,
2938 cltv_expiry_delta: (8 << 4) | 1,
2939 htlc_minimum_msat: None,
2940 htlc_maximum_msat: None,
2941 }]), RouteHint(vec![RouteHintHop {
2942 src_node_id: nodes[4],
2943 short_channel_id: 9,
2946 proportional_millionths: 0,
2948 cltv_expiry_delta: (9 << 4) | 1,
2949 htlc_minimum_msat: None,
2950 htlc_maximum_msat: None,
2951 }]), RouteHint(vec![RouteHintHop {
2952 src_node_id: nodes[5],
2953 short_channel_id: 10,
2955 cltv_expiry_delta: (10 << 4) | 1,
2956 htlc_minimum_msat: None,
2957 htlc_maximum_msat: None,
2962 fn last_hops_with_public_channel_test() {
2963 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2964 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2965 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops_with_public_channel(&nodes));
2966 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2967 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2968 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2969 // This test shows that public routes can be present in the invoice
2970 // which would be handled in the same manner.
2972 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2973 assert_eq!(route.paths[0].len(), 5);
2975 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2976 assert_eq!(route.paths[0][0].short_channel_id, 2);
2977 assert_eq!(route.paths[0][0].fee_msat, 100);
2978 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2979 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2980 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2982 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2983 assert_eq!(route.paths[0][1].short_channel_id, 4);
2984 assert_eq!(route.paths[0][1].fee_msat, 0);
2985 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
2986 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2987 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2989 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2990 assert_eq!(route.paths[0][2].short_channel_id, 6);
2991 assert_eq!(route.paths[0][2].fee_msat, 0);
2992 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
2993 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2994 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2996 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2997 assert_eq!(route.paths[0][3].short_channel_id, 11);
2998 assert_eq!(route.paths[0][3].fee_msat, 0);
2999 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
3000 // If we have a peer in the node map, we'll use their features here since we don't have
3001 // a way of figuring out their features from the invoice:
3002 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
3003 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
3005 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
3006 assert_eq!(route.paths[0][4].short_channel_id, 8);
3007 assert_eq!(route.paths[0][4].fee_msat, 100);
3008 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
3009 assert_eq!(route.paths[0][4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3010 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3014 fn our_chans_last_hop_connect_test() {
3015 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3016 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3017 let scorer = ln_test_utils::TestScorer::with_penalty(0);
3018 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3019 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3021 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
3022 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3023 let mut last_hops = last_hops(&nodes);
3024 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops.clone());
3025 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();
3026 assert_eq!(route.paths[0].len(), 2);
3028 assert_eq!(route.paths[0][0].pubkey, nodes[3]);
3029 assert_eq!(route.paths[0][0].short_channel_id, 42);
3030 assert_eq!(route.paths[0][0].fee_msat, 0);
3031 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 4) | 1);
3032 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
3033 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3035 assert_eq!(route.paths[0][1].pubkey, nodes[6]);
3036 assert_eq!(route.paths[0][1].short_channel_id, 8);
3037 assert_eq!(route.paths[0][1].fee_msat, 100);
3038 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
3039 assert_eq!(route.paths[0][1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3040 assert_eq!(route.paths[0][1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3042 last_hops[0].0[0].fees.base_msat = 1000;
3044 // Revert to via 6 as the fee on 8 goes up
3045 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops);
3046 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3047 assert_eq!(route.paths[0].len(), 4);
3049 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3050 assert_eq!(route.paths[0][0].short_channel_id, 2);
3051 assert_eq!(route.paths[0][0].fee_msat, 200); // fee increased as its % of value transferred across node
3052 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
3053 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3054 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3056 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3057 assert_eq!(route.paths[0][1].short_channel_id, 4);
3058 assert_eq!(route.paths[0][1].fee_msat, 100);
3059 assert_eq!(route.paths[0][1].cltv_expiry_delta, (7 << 4) | 1);
3060 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3061 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3063 assert_eq!(route.paths[0][2].pubkey, nodes[5]);
3064 assert_eq!(route.paths[0][2].short_channel_id, 7);
3065 assert_eq!(route.paths[0][2].fee_msat, 0);
3066 assert_eq!(route.paths[0][2].cltv_expiry_delta, (10 << 4) | 1);
3067 // If we have a peer in the node map, we'll use their features here since we don't have
3068 // a way of figuring out their features from the invoice:
3069 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
3070 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(7));
3072 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
3073 assert_eq!(route.paths[0][3].short_channel_id, 10);
3074 assert_eq!(route.paths[0][3].fee_msat, 100);
3075 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
3076 assert_eq!(route.paths[0][3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3077 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3079 // ...but still use 8 for larger payments as 6 has a variable feerate
3080 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 2000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3081 assert_eq!(route.paths[0].len(), 5);
3083 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3084 assert_eq!(route.paths[0][0].short_channel_id, 2);
3085 assert_eq!(route.paths[0][0].fee_msat, 3000);
3086 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
3087 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3088 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3090 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3091 assert_eq!(route.paths[0][1].short_channel_id, 4);
3092 assert_eq!(route.paths[0][1].fee_msat, 0);
3093 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
3094 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3095 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3097 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
3098 assert_eq!(route.paths[0][2].short_channel_id, 6);
3099 assert_eq!(route.paths[0][2].fee_msat, 0);
3100 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
3101 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
3102 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
3104 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
3105 assert_eq!(route.paths[0][3].short_channel_id, 11);
3106 assert_eq!(route.paths[0][3].fee_msat, 1000);
3107 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
3108 // If we have a peer in the node map, we'll use their features here since we don't have
3109 // a way of figuring out their features from the invoice:
3110 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
3111 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
3113 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
3114 assert_eq!(route.paths[0][4].short_channel_id, 8);
3115 assert_eq!(route.paths[0][4].fee_msat, 2000);
3116 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
3117 assert_eq!(route.paths[0][4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3118 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3121 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> {
3122 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
3123 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3124 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3126 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
3127 let last_hops = RouteHint(vec![RouteHintHop {
3128 src_node_id: middle_node_id,
3129 short_channel_id: 8,
3132 proportional_millionths: last_hop_fee_prop,
3134 cltv_expiry_delta: (8 << 4) | 1,
3135 htlc_minimum_msat: None,
3136 htlc_maximum_msat: last_hop_htlc_max,
3138 let payment_params = PaymentParameters::from_node_id(target_node_id).with_route_hints(vec![last_hops]);
3139 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
3140 let scorer = ln_test_utils::TestScorer::with_penalty(0);
3141 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3142 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3143 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
3144 let logger = ln_test_utils::TestLogger::new();
3145 let network_graph = NetworkGraph::new(genesis_hash, &logger);
3146 let route = get_route(&source_node_id, &payment_params, &network_graph.read_only(),
3147 Some(&our_chans.iter().collect::<Vec<_>>()), route_val, 42, &logger, &scorer, &random_seed_bytes);
3152 fn unannounced_path_test() {
3153 // We should be able to send a payment to a destination without any help of a routing graph
3154 // if we have a channel with a common counterparty that appears in the first and last hop
3156 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
3158 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3159 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3160 assert_eq!(route.paths[0].len(), 2);
3162 assert_eq!(route.paths[0][0].pubkey, middle_node_id);
3163 assert_eq!(route.paths[0][0].short_channel_id, 42);
3164 assert_eq!(route.paths[0][0].fee_msat, 1001);
3165 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 4) | 1);
3166 assert_eq!(route.paths[0][0].node_features.le_flags(), &[0b11]);
3167 assert_eq!(route.paths[0][0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3169 assert_eq!(route.paths[0][1].pubkey, target_node_id);
3170 assert_eq!(route.paths[0][1].short_channel_id, 8);
3171 assert_eq!(route.paths[0][1].fee_msat, 1000000);
3172 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
3173 assert_eq!(route.paths[0][1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3174 assert_eq!(route.paths[0][1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3178 fn overflow_unannounced_path_test_liquidity_underflow() {
3179 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
3180 // the last-hop had a fee which overflowed a u64, we'd panic.
3181 // This was due to us adding the first-hop from us unconditionally, causing us to think
3182 // we'd built a path (as our node is in the "best candidate" set), when we had not.
3183 // In this test, we previously hit a subtraction underflow due to having less available
3184 // liquidity at the last hop than 0.
3185 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());
3189 fn overflow_unannounced_path_test_feerate_overflow() {
3190 // This tests for the same case as above, except instead of hitting a subtraction
3191 // underflow, we hit a case where the fee charged at a hop overflowed.
3192 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());
3196 fn available_amount_while_routing_test() {
3197 // Tests whether we choose the correct available channel amount while routing.
3199 let (secp_ctx, network_graph, mut gossip_sync, chain_monitor, logger) = build_graph();
3200 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3201 let scorer = ln_test_utils::TestScorer::with_penalty(0);
3202 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3203 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3204 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(channelmanager::provided_invoice_features());
3206 // We will use a simple single-path route from
3207 // our node to node2 via node0: channels {1, 3}.
3209 // First disable all other paths.
3210 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3211 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3212 short_channel_id: 2,
3215 cltv_expiry_delta: 0,
3216 htlc_minimum_msat: 0,
3217 htlc_maximum_msat: 100_000,
3219 fee_proportional_millionths: 0,
3220 excess_data: Vec::new()
3222 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3223 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3224 short_channel_id: 12,
3227 cltv_expiry_delta: 0,
3228 htlc_minimum_msat: 0,
3229 htlc_maximum_msat: 100_000,
3231 fee_proportional_millionths: 0,
3232 excess_data: Vec::new()
3235 // Make the first channel (#1) very permissive,
3236 // and we will be testing all limits on the second channel.
3237 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3238 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3239 short_channel_id: 1,
3242 cltv_expiry_delta: 0,
3243 htlc_minimum_msat: 0,
3244 htlc_maximum_msat: 1_000_000_000,
3246 fee_proportional_millionths: 0,
3247 excess_data: Vec::new()
3250 // First, let's see if routing works if we have absolutely no idea about the available amount.
3251 // In this case, it should be set to 250_000 sats.
3252 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3253 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3254 short_channel_id: 3,
3257 cltv_expiry_delta: 0,
3258 htlc_minimum_msat: 0,
3259 htlc_maximum_msat: 250_000_000,
3261 fee_proportional_millionths: 0,
3262 excess_data: Vec::new()
3266 // Attempt to route more than available results in a failure.
3267 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3268 &our_id, &payment_params, &network_graph.read_only(), None, 250_000_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3269 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3270 } else { panic!(); }
3274 // Now, attempt to route an exact amount we have should be fine.
3275 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();
3276 assert_eq!(route.paths.len(), 1);
3277 let path = route.paths.last().unwrap();
3278 assert_eq!(path.len(), 2);
3279 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3280 assert_eq!(path.last().unwrap().fee_msat, 250_000_000);
3283 // Check that setting next_outbound_htlc_limit_msat in first_hops limits the channels.
3284 // Disable channel #1 and use another first hop.
3285 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3286 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3287 short_channel_id: 1,
3290 cltv_expiry_delta: 0,
3291 htlc_minimum_msat: 0,
3292 htlc_maximum_msat: 1_000_000_000,
3294 fee_proportional_millionths: 0,
3295 excess_data: Vec::new()
3298 // Now, limit the first_hop by the next_outbound_htlc_limit_msat of 200_000 sats.
3299 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
3302 // Attempt to route more than available results in a failure.
3303 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3304 &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) {
3305 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3306 } else { panic!(); }
3310 // Now, attempt to route an exact amount we have should be fine.
3311 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();
3312 assert_eq!(route.paths.len(), 1);
3313 let path = route.paths.last().unwrap();
3314 assert_eq!(path.len(), 2);
3315 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3316 assert_eq!(path.last().unwrap().fee_msat, 200_000_000);
3319 // Enable channel #1 back.
3320 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3321 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3322 short_channel_id: 1,
3325 cltv_expiry_delta: 0,
3326 htlc_minimum_msat: 0,
3327 htlc_maximum_msat: 1_000_000_000,
3329 fee_proportional_millionths: 0,
3330 excess_data: Vec::new()
3334 // Now let's see if routing works if we know only htlc_maximum_msat.
3335 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3336 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3337 short_channel_id: 3,
3340 cltv_expiry_delta: 0,
3341 htlc_minimum_msat: 0,
3342 htlc_maximum_msat: 15_000,
3344 fee_proportional_millionths: 0,
3345 excess_data: Vec::new()
3349 // Attempt to route more than available results in a failure.
3350 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3351 &our_id, &payment_params, &network_graph.read_only(), None, 15_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3352 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3353 } else { panic!(); }
3357 // Now, attempt to route an exact amount we have should be fine.
3358 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 15_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3359 assert_eq!(route.paths.len(), 1);
3360 let path = route.paths.last().unwrap();
3361 assert_eq!(path.len(), 2);
3362 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3363 assert_eq!(path.last().unwrap().fee_msat, 15_000);
3366 // Now let's see if routing works if we know only capacity from the UTXO.
3368 // We can't change UTXO capacity on the fly, so we'll disable
3369 // the existing channel and add another one with the capacity we need.
3370 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3371 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3372 short_channel_id: 3,
3375 cltv_expiry_delta: 0,
3376 htlc_minimum_msat: 0,
3377 htlc_maximum_msat: MAX_VALUE_MSAT,
3379 fee_proportional_millionths: 0,
3380 excess_data: Vec::new()
3383 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
3384 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
3385 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
3386 .push_opcode(opcodes::all::OP_PUSHNUM_2)
3387 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
3389 *chain_monitor.utxo_ret.lock().unwrap() = Ok(TxOut { value: 15, script_pubkey: good_script.clone() });
3390 gossip_sync.add_chain_access(Some(chain_monitor));
3392 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
3393 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3394 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3395 short_channel_id: 333,
3398 cltv_expiry_delta: (3 << 4) | 1,
3399 htlc_minimum_msat: 0,
3400 htlc_maximum_msat: 15_000,
3402 fee_proportional_millionths: 0,
3403 excess_data: Vec::new()
3405 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3406 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3407 short_channel_id: 333,
3410 cltv_expiry_delta: (3 << 4) | 2,
3411 htlc_minimum_msat: 0,
3412 htlc_maximum_msat: 15_000,
3414 fee_proportional_millionths: 0,
3415 excess_data: Vec::new()
3419 // Attempt to route more than available results in a failure.
3420 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3421 &our_id, &payment_params, &network_graph.read_only(), None, 15_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3422 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3423 } else { panic!(); }
3427 // Now, attempt to route an exact amount we have should be fine.
3428 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 15_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3429 assert_eq!(route.paths.len(), 1);
3430 let path = route.paths.last().unwrap();
3431 assert_eq!(path.len(), 2);
3432 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3433 assert_eq!(path.last().unwrap().fee_msat, 15_000);
3436 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
3437 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3438 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3439 short_channel_id: 333,
3442 cltv_expiry_delta: 0,
3443 htlc_minimum_msat: 0,
3444 htlc_maximum_msat: 10_000,
3446 fee_proportional_millionths: 0,
3447 excess_data: Vec::new()
3451 // Attempt to route more than available results in a failure.
3452 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3453 &our_id, &payment_params, &network_graph.read_only(), None, 10_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3454 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3455 } else { panic!(); }
3459 // Now, attempt to route an exact amount we have should be fine.
3460 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 10_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3461 assert_eq!(route.paths.len(), 1);
3462 let path = route.paths.last().unwrap();
3463 assert_eq!(path.len(), 2);
3464 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3465 assert_eq!(path.last().unwrap().fee_msat, 10_000);
3470 fn available_liquidity_last_hop_test() {
3471 // Check that available liquidity properly limits the path even when only
3472 // one of the latter hops is limited.
3473 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3474 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3475 let scorer = ln_test_utils::TestScorer::with_penalty(0);
3476 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3477 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3478 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(channelmanager::provided_invoice_features());
3480 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3481 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
3482 // Total capacity: 50 sats.
3484 // Disable other potential paths.
3485 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3486 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3487 short_channel_id: 2,
3490 cltv_expiry_delta: 0,
3491 htlc_minimum_msat: 0,
3492 htlc_maximum_msat: 100_000,
3494 fee_proportional_millionths: 0,
3495 excess_data: Vec::new()
3497 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3498 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3499 short_channel_id: 7,
3502 cltv_expiry_delta: 0,
3503 htlc_minimum_msat: 0,
3504 htlc_maximum_msat: 100_000,
3506 fee_proportional_millionths: 0,
3507 excess_data: Vec::new()
3512 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3513 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3514 short_channel_id: 12,
3517 cltv_expiry_delta: 0,
3518 htlc_minimum_msat: 0,
3519 htlc_maximum_msat: 100_000,
3521 fee_proportional_millionths: 0,
3522 excess_data: Vec::new()
3524 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3525 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3526 short_channel_id: 13,
3529 cltv_expiry_delta: 0,
3530 htlc_minimum_msat: 0,
3531 htlc_maximum_msat: 100_000,
3533 fee_proportional_millionths: 0,
3534 excess_data: Vec::new()
3537 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3538 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3539 short_channel_id: 6,
3542 cltv_expiry_delta: 0,
3543 htlc_minimum_msat: 0,
3544 htlc_maximum_msat: 50_000,
3546 fee_proportional_millionths: 0,
3547 excess_data: Vec::new()
3549 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3550 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3551 short_channel_id: 11,
3554 cltv_expiry_delta: 0,
3555 htlc_minimum_msat: 0,
3556 htlc_maximum_msat: 100_000,
3558 fee_proportional_millionths: 0,
3559 excess_data: Vec::new()
3562 // Attempt to route more than available results in a failure.
3563 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3564 &our_id, &payment_params, &network_graph.read_only(), None, 60_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3565 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3566 } else { panic!(); }
3570 // Now, attempt to route 49 sats (just a bit below the capacity).
3571 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 49_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3572 assert_eq!(route.paths.len(), 1);
3573 let mut total_amount_paid_msat = 0;
3574 for path in &route.paths {
3575 assert_eq!(path.len(), 4);
3576 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3577 total_amount_paid_msat += path.last().unwrap().fee_msat;
3579 assert_eq!(total_amount_paid_msat, 49_000);
3583 // Attempt to route an exact amount is also fine
3584 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3585 assert_eq!(route.paths.len(), 1);
3586 let mut total_amount_paid_msat = 0;
3587 for path in &route.paths {
3588 assert_eq!(path.len(), 4);
3589 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3590 total_amount_paid_msat += path.last().unwrap().fee_msat;
3592 assert_eq!(total_amount_paid_msat, 50_000);
3597 fn ignore_fee_first_hop_test() {
3598 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3599 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3600 let scorer = ln_test_utils::TestScorer::with_penalty(0);
3601 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3602 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3603 let payment_params = PaymentParameters::from_node_id(nodes[2]);
3605 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3606 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3607 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3608 short_channel_id: 1,
3611 cltv_expiry_delta: 0,
3612 htlc_minimum_msat: 0,
3613 htlc_maximum_msat: 100_000,
3614 fee_base_msat: 1_000_000,
3615 fee_proportional_millionths: 0,
3616 excess_data: Vec::new()
3618 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3619 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3620 short_channel_id: 3,
3623 cltv_expiry_delta: 0,
3624 htlc_minimum_msat: 0,
3625 htlc_maximum_msat: 50_000,
3627 fee_proportional_millionths: 0,
3628 excess_data: Vec::new()
3632 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3633 assert_eq!(route.paths.len(), 1);
3634 let mut total_amount_paid_msat = 0;
3635 for path in &route.paths {
3636 assert_eq!(path.len(), 2);
3637 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3638 total_amount_paid_msat += path.last().unwrap().fee_msat;
3640 assert_eq!(total_amount_paid_msat, 50_000);
3645 fn simple_mpp_route_test() {
3646 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3647 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3648 let scorer = ln_test_utils::TestScorer::with_penalty(0);
3649 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3650 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3651 let payment_params = PaymentParameters::from_node_id(nodes[2])
3652 .with_features(channelmanager::provided_invoice_features());
3654 // We need a route consisting of 3 paths:
3655 // From our node to node2 via node0, node7, node1 (three paths one hop each).
3656 // To achieve this, the amount being transferred should be around
3657 // the total capacity of these 3 paths.
3659 // First, we set limits on these (previously unlimited) channels.
3660 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
3662 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3663 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3664 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3665 short_channel_id: 1,
3668 cltv_expiry_delta: 0,
3669 htlc_minimum_msat: 0,
3670 htlc_maximum_msat: 100_000,
3672 fee_proportional_millionths: 0,
3673 excess_data: Vec::new()
3675 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3676 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3677 short_channel_id: 3,
3680 cltv_expiry_delta: 0,
3681 htlc_minimum_msat: 0,
3682 htlc_maximum_msat: 50_000,
3684 fee_proportional_millionths: 0,
3685 excess_data: Vec::new()
3688 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
3689 // (total limit 60).
3690 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3691 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3692 short_channel_id: 12,
3695 cltv_expiry_delta: 0,
3696 htlc_minimum_msat: 0,
3697 htlc_maximum_msat: 60_000,
3699 fee_proportional_millionths: 0,
3700 excess_data: Vec::new()
3702 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3703 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3704 short_channel_id: 13,
3707 cltv_expiry_delta: 0,
3708 htlc_minimum_msat: 0,
3709 htlc_maximum_msat: 60_000,
3711 fee_proportional_millionths: 0,
3712 excess_data: Vec::new()
3715 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
3716 // (total capacity 180 sats).
3717 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3718 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3719 short_channel_id: 2,
3722 cltv_expiry_delta: 0,
3723 htlc_minimum_msat: 0,
3724 htlc_maximum_msat: 200_000,
3726 fee_proportional_millionths: 0,
3727 excess_data: Vec::new()
3729 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3730 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3731 short_channel_id: 4,
3734 cltv_expiry_delta: 0,
3735 htlc_minimum_msat: 0,
3736 htlc_maximum_msat: 180_000,
3738 fee_proportional_millionths: 0,
3739 excess_data: Vec::new()
3743 // Attempt to route more than available results in a failure.
3744 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3745 &our_id, &payment_params, &network_graph.read_only(), None, 300_000, 42,
3746 Arc::clone(&logger), &scorer, &random_seed_bytes) {
3747 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3748 } else { panic!(); }
3752 // Attempt to route while setting max_path_count to 0 results in a failure.
3753 let zero_payment_params = payment_params.clone().with_max_path_count(0);
3754 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3755 &our_id, &zero_payment_params, &network_graph.read_only(), None, 100, 42,
3756 Arc::clone(&logger), &scorer, &random_seed_bytes) {
3757 assert_eq!(err, "Can't find a route with no paths allowed.");
3758 } else { panic!(); }
3762 // Attempt to route while setting max_path_count to 3 results in a failure.
3763 // This is the case because the minimal_value_contribution_msat would require each path
3764 // to account for 1/3 of the total value, which is violated by 2 out of 3 paths.
3765 let fail_payment_params = payment_params.clone().with_max_path_count(3);
3766 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3767 &our_id, &fail_payment_params, &network_graph.read_only(), None, 250_000, 42,
3768 Arc::clone(&logger), &scorer, &random_seed_bytes) {
3769 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3770 } else { panic!(); }
3774 // Now, attempt to route 250 sats (just a bit below the capacity).
3775 // Our algorithm should provide us with these 3 paths.
3776 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None,
3777 250_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3778 assert_eq!(route.paths.len(), 3);
3779 let mut total_amount_paid_msat = 0;
3780 for path in &route.paths {
3781 assert_eq!(path.len(), 2);
3782 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3783 total_amount_paid_msat += path.last().unwrap().fee_msat;
3785 assert_eq!(total_amount_paid_msat, 250_000);
3789 // Attempt to route an exact amount is also fine
3790 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None,
3791 290_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3792 assert_eq!(route.paths.len(), 3);
3793 let mut total_amount_paid_msat = 0;
3794 for path in &route.paths {
3795 assert_eq!(path.len(), 2);
3796 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3797 total_amount_paid_msat += path.last().unwrap().fee_msat;
3799 assert_eq!(total_amount_paid_msat, 290_000);
3804 fn long_mpp_route_test() {
3805 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3806 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3807 let scorer = ln_test_utils::TestScorer::with_penalty(0);
3808 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3809 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3810 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(channelmanager::provided_invoice_features());
3812 // We need a route consisting of 3 paths:
3813 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3814 // Note that these paths overlap (channels 5, 12, 13).
3815 // We will route 300 sats.
3816 // Each path will have 100 sats capacity, those channels which
3817 // are used twice will have 200 sats capacity.
3819 // Disable other potential paths.
3820 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3821 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3822 short_channel_id: 2,
3825 cltv_expiry_delta: 0,
3826 htlc_minimum_msat: 0,
3827 htlc_maximum_msat: 100_000,
3829 fee_proportional_millionths: 0,
3830 excess_data: Vec::new()
3832 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3833 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3834 short_channel_id: 7,
3837 cltv_expiry_delta: 0,
3838 htlc_minimum_msat: 0,
3839 htlc_maximum_msat: 100_000,
3841 fee_proportional_millionths: 0,
3842 excess_data: Vec::new()
3845 // Path via {node0, node2} is channels {1, 3, 5}.
3846 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3847 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3848 short_channel_id: 1,
3851 cltv_expiry_delta: 0,
3852 htlc_minimum_msat: 0,
3853 htlc_maximum_msat: 100_000,
3855 fee_proportional_millionths: 0,
3856 excess_data: Vec::new()
3858 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3859 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3860 short_channel_id: 3,
3863 cltv_expiry_delta: 0,
3864 htlc_minimum_msat: 0,
3865 htlc_maximum_msat: 100_000,
3867 fee_proportional_millionths: 0,
3868 excess_data: Vec::new()
3871 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3872 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3873 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3874 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3875 short_channel_id: 5,
3878 cltv_expiry_delta: 0,
3879 htlc_minimum_msat: 0,
3880 htlc_maximum_msat: 200_000,
3882 fee_proportional_millionths: 0,
3883 excess_data: Vec::new()
3886 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3887 // Add 100 sats to the capacities of {12, 13}, because these channels
3888 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3889 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3890 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3891 short_channel_id: 12,
3894 cltv_expiry_delta: 0,
3895 htlc_minimum_msat: 0,
3896 htlc_maximum_msat: 200_000,
3898 fee_proportional_millionths: 0,
3899 excess_data: Vec::new()
3901 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3902 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3903 short_channel_id: 13,
3906 cltv_expiry_delta: 0,
3907 htlc_minimum_msat: 0,
3908 htlc_maximum_msat: 200_000,
3910 fee_proportional_millionths: 0,
3911 excess_data: Vec::new()
3914 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3915 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3916 short_channel_id: 6,
3919 cltv_expiry_delta: 0,
3920 htlc_minimum_msat: 0,
3921 htlc_maximum_msat: 100_000,
3923 fee_proportional_millionths: 0,
3924 excess_data: Vec::new()
3926 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3927 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3928 short_channel_id: 11,
3931 cltv_expiry_delta: 0,
3932 htlc_minimum_msat: 0,
3933 htlc_maximum_msat: 100_000,
3935 fee_proportional_millionths: 0,
3936 excess_data: Vec::new()
3939 // Path via {node7, node2} is channels {12, 13, 5}.
3940 // We already limited them to 200 sats (they are used twice for 100 sats).
3941 // Nothing to do here.
3944 // Attempt to route more than available results in a failure.
3945 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3946 &our_id, &payment_params, &network_graph.read_only(), None, 350_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3947 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3948 } else { panic!(); }
3952 // Now, attempt to route 300 sats (exact amount we can route).
3953 // Our algorithm should provide us with these 3 paths, 100 sats each.
3954 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 300_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3955 assert_eq!(route.paths.len(), 3);
3957 let mut total_amount_paid_msat = 0;
3958 for path in &route.paths {
3959 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3960 total_amount_paid_msat += path.last().unwrap().fee_msat;
3962 assert_eq!(total_amount_paid_msat, 300_000);
3968 fn mpp_cheaper_route_test() {
3969 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3970 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3971 let scorer = ln_test_utils::TestScorer::with_penalty(0);
3972 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3973 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3974 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(channelmanager::provided_invoice_features());
3976 // This test checks that if we have two cheaper paths and one more expensive path,
3977 // so that liquidity-wise any 2 of 3 combination is sufficient,
3978 // two cheaper paths will be taken.
3979 // These paths have equal available liquidity.
3981 // We need a combination of 3 paths:
3982 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3983 // Note that these paths overlap (channels 5, 12, 13).
3984 // Each path will have 100 sats capacity, those channels which
3985 // are used twice will have 200 sats capacity.
3987 // Disable other potential paths.
3988 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3989 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3990 short_channel_id: 2,
3993 cltv_expiry_delta: 0,
3994 htlc_minimum_msat: 0,
3995 htlc_maximum_msat: 100_000,
3997 fee_proportional_millionths: 0,
3998 excess_data: Vec::new()
4000 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4001 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4002 short_channel_id: 7,
4005 cltv_expiry_delta: 0,
4006 htlc_minimum_msat: 0,
4007 htlc_maximum_msat: 100_000,
4009 fee_proportional_millionths: 0,
4010 excess_data: Vec::new()
4013 // Path via {node0, node2} is channels {1, 3, 5}.
4014 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4015 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4016 short_channel_id: 1,
4019 cltv_expiry_delta: 0,
4020 htlc_minimum_msat: 0,
4021 htlc_maximum_msat: 100_000,
4023 fee_proportional_millionths: 0,
4024 excess_data: Vec::new()
4026 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4027 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4028 short_channel_id: 3,
4031 cltv_expiry_delta: 0,
4032 htlc_minimum_msat: 0,
4033 htlc_maximum_msat: 100_000,
4035 fee_proportional_millionths: 0,
4036 excess_data: Vec::new()
4039 // Capacity of 200 sats because this channel will be used by 3rd path as well.
4040 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4041 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4042 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4043 short_channel_id: 5,
4046 cltv_expiry_delta: 0,
4047 htlc_minimum_msat: 0,
4048 htlc_maximum_msat: 200_000,
4050 fee_proportional_millionths: 0,
4051 excess_data: Vec::new()
4054 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4055 // Add 100 sats to the capacities of {12, 13}, because these channels
4056 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
4057 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4058 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4059 short_channel_id: 12,
4062 cltv_expiry_delta: 0,
4063 htlc_minimum_msat: 0,
4064 htlc_maximum_msat: 200_000,
4066 fee_proportional_millionths: 0,
4067 excess_data: Vec::new()
4069 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4070 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4071 short_channel_id: 13,
4074 cltv_expiry_delta: 0,
4075 htlc_minimum_msat: 0,
4076 htlc_maximum_msat: 200_000,
4078 fee_proportional_millionths: 0,
4079 excess_data: Vec::new()
4082 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4083 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4084 short_channel_id: 6,
4087 cltv_expiry_delta: 0,
4088 htlc_minimum_msat: 0,
4089 htlc_maximum_msat: 100_000,
4090 fee_base_msat: 1_000,
4091 fee_proportional_millionths: 0,
4092 excess_data: Vec::new()
4094 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4095 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4096 short_channel_id: 11,
4099 cltv_expiry_delta: 0,
4100 htlc_minimum_msat: 0,
4101 htlc_maximum_msat: 100_000,
4103 fee_proportional_millionths: 0,
4104 excess_data: Vec::new()
4107 // Path via {node7, node2} is channels {12, 13, 5}.
4108 // We already limited them to 200 sats (they are used twice for 100 sats).
4109 // Nothing to do here.
4112 // Now, attempt to route 180 sats.
4113 // Our algorithm should provide us with these 2 paths.
4114 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 180_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4115 assert_eq!(route.paths.len(), 2);
4117 let mut total_value_transferred_msat = 0;
4118 let mut total_paid_msat = 0;
4119 for path in &route.paths {
4120 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
4121 total_value_transferred_msat += path.last().unwrap().fee_msat;
4123 total_paid_msat += hop.fee_msat;
4126 // If we paid fee, this would be higher.
4127 assert_eq!(total_value_transferred_msat, 180_000);
4128 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
4129 assert_eq!(total_fees_paid, 0);
4134 fn fees_on_mpp_route_test() {
4135 // This test makes sure that MPP algorithm properly takes into account
4136 // fees charged on the channels, by making the fees impactful:
4137 // if the fee is not properly accounted for, the behavior is different.
4138 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4139 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4140 let scorer = ln_test_utils::TestScorer::with_penalty(0);
4141 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4142 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4143 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(channelmanager::provided_invoice_features());
4145 // We need a route consisting of 2 paths:
4146 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
4147 // We will route 200 sats, Each path will have 100 sats capacity.
4149 // This test is not particularly stable: e.g.,
4150 // there's a way to route via {node0, node2, node4}.
4151 // It works while pathfinding is deterministic, but can be broken otherwise.
4152 // It's fine to ignore this concern for now.
4154 // Disable other potential paths.
4155 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4156 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4157 short_channel_id: 2,
4160 cltv_expiry_delta: 0,
4161 htlc_minimum_msat: 0,
4162 htlc_maximum_msat: 100_000,
4164 fee_proportional_millionths: 0,
4165 excess_data: Vec::new()
4168 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4169 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4170 short_channel_id: 7,
4173 cltv_expiry_delta: 0,
4174 htlc_minimum_msat: 0,
4175 htlc_maximum_msat: 100_000,
4177 fee_proportional_millionths: 0,
4178 excess_data: Vec::new()
4181 // Path via {node0, node2} is channels {1, 3, 5}.
4182 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4183 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4184 short_channel_id: 1,
4187 cltv_expiry_delta: 0,
4188 htlc_minimum_msat: 0,
4189 htlc_maximum_msat: 100_000,
4191 fee_proportional_millionths: 0,
4192 excess_data: Vec::new()
4194 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4195 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4196 short_channel_id: 3,
4199 cltv_expiry_delta: 0,
4200 htlc_minimum_msat: 0,
4201 htlc_maximum_msat: 100_000,
4203 fee_proportional_millionths: 0,
4204 excess_data: Vec::new()
4207 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4208 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4209 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4210 short_channel_id: 5,
4213 cltv_expiry_delta: 0,
4214 htlc_minimum_msat: 0,
4215 htlc_maximum_msat: 100_000,
4217 fee_proportional_millionths: 0,
4218 excess_data: Vec::new()
4221 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4222 // All channels should be 100 sats capacity. But for the fee experiment,
4223 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
4224 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
4225 // 100 sats (and pay 150 sats in fees for the use of channel 6),
4226 // so no matter how large are other channels,
4227 // the whole path will be limited by 100 sats with just these 2 conditions:
4228 // - channel 12 capacity is 250 sats
4229 // - fee for channel 6 is 150 sats
4230 // Let's test this by enforcing these 2 conditions and removing other limits.
4231 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4232 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4233 short_channel_id: 12,
4236 cltv_expiry_delta: 0,
4237 htlc_minimum_msat: 0,
4238 htlc_maximum_msat: 250_000,
4240 fee_proportional_millionths: 0,
4241 excess_data: Vec::new()
4243 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4244 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4245 short_channel_id: 13,
4248 cltv_expiry_delta: 0,
4249 htlc_minimum_msat: 0,
4250 htlc_maximum_msat: MAX_VALUE_MSAT,
4252 fee_proportional_millionths: 0,
4253 excess_data: Vec::new()
4256 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4257 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4258 short_channel_id: 6,
4261 cltv_expiry_delta: 0,
4262 htlc_minimum_msat: 0,
4263 htlc_maximum_msat: MAX_VALUE_MSAT,
4264 fee_base_msat: 150_000,
4265 fee_proportional_millionths: 0,
4266 excess_data: Vec::new()
4268 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4269 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4270 short_channel_id: 11,
4273 cltv_expiry_delta: 0,
4274 htlc_minimum_msat: 0,
4275 htlc_maximum_msat: MAX_VALUE_MSAT,
4277 fee_proportional_millionths: 0,
4278 excess_data: Vec::new()
4282 // Attempt to route more than available results in a failure.
4283 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4284 &our_id, &payment_params, &network_graph.read_only(), None, 210_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
4285 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4286 } else { panic!(); }
4290 // Now, attempt to route 200 sats (exact amount we can route).
4291 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 200_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4292 assert_eq!(route.paths.len(), 2);
4294 let mut total_amount_paid_msat = 0;
4295 for path in &route.paths {
4296 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
4297 total_amount_paid_msat += path.last().unwrap().fee_msat;
4299 assert_eq!(total_amount_paid_msat, 200_000);
4300 assert_eq!(route.get_total_fees(), 150_000);
4305 fn mpp_with_last_hops() {
4306 // Previously, if we tried to send an MPP payment to a destination which was only reachable
4307 // via a single last-hop route hint, we'd fail to route if we first collected routes
4308 // totaling close but not quite enough to fund the full payment.
4310 // This was because we considered last-hop hints to have exactly the sought payment amount
4311 // instead of the amount we were trying to collect, needlessly limiting our path searching
4312 // at the very first hop.
4314 // Specifically, this interacted with our "all paths must fund at least 5% of total target"
4315 // criterion to cause us to refuse all routes at the last hop hint which would be considered
4316 // to only have the remaining to-collect amount in available liquidity.
4318 // This bug appeared in production in some specific channel configurations.
4319 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4320 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4321 let scorer = ln_test_utils::TestScorer::with_penalty(0);
4322 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4323 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4324 let payment_params = PaymentParameters::from_node_id(PublicKey::from_slice(&[02; 33]).unwrap()).with_features(channelmanager::provided_invoice_features())
4325 .with_route_hints(vec![RouteHint(vec![RouteHintHop {
4326 src_node_id: nodes[2],
4327 short_channel_id: 42,
4328 fees: RoutingFees { base_msat: 0, proportional_millionths: 0 },
4329 cltv_expiry_delta: 42,
4330 htlc_minimum_msat: None,
4331 htlc_maximum_msat: None,
4332 }])]).with_max_channel_saturation_power_of_half(0);
4334 // Keep only two paths from us to nodes[2], both with a 99sat HTLC maximum, with one with
4335 // no fee and one with a 1msat fee. Previously, trying to route 100 sats to nodes[2] here
4336 // would first use the no-fee route and then fail to find a path along the second route as
4337 // we think we can only send up to 1 additional sat over the last-hop but refuse to as its
4338 // under 5% of our payment amount.
4339 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4340 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4341 short_channel_id: 1,
4344 cltv_expiry_delta: (5 << 4) | 5,
4345 htlc_minimum_msat: 0,
4346 htlc_maximum_msat: 99_000,
4347 fee_base_msat: u32::max_value(),
4348 fee_proportional_millionths: u32::max_value(),
4349 excess_data: Vec::new()
4351 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4352 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4353 short_channel_id: 2,
4356 cltv_expiry_delta: (5 << 4) | 3,
4357 htlc_minimum_msat: 0,
4358 htlc_maximum_msat: 99_000,
4359 fee_base_msat: u32::max_value(),
4360 fee_proportional_millionths: u32::max_value(),
4361 excess_data: Vec::new()
4363 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4364 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4365 short_channel_id: 4,
4368 cltv_expiry_delta: (4 << 4) | 1,
4369 htlc_minimum_msat: 0,
4370 htlc_maximum_msat: MAX_VALUE_MSAT,
4372 fee_proportional_millionths: 0,
4373 excess_data: Vec::new()
4375 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4376 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4377 short_channel_id: 13,
4379 flags: 0|2, // Channel disabled
4380 cltv_expiry_delta: (13 << 4) | 1,
4381 htlc_minimum_msat: 0,
4382 htlc_maximum_msat: MAX_VALUE_MSAT,
4384 fee_proportional_millionths: 2000000,
4385 excess_data: Vec::new()
4388 // Get a route for 100 sats and check that we found the MPP route no problem and didn't
4390 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();
4391 assert_eq!(route.paths.len(), 2);
4392 route.paths.sort_by_key(|path| path[0].short_channel_id);
4393 // Paths are manually ordered ordered by SCID, so:
4394 // * the first is channel 1 (0 fee, but 99 sat maximum) -> channel 3 -> channel 42
4395 // * the second is channel 2 (1 msat fee) -> channel 4 -> channel 42
4396 assert_eq!(route.paths[0][0].short_channel_id, 1);
4397 assert_eq!(route.paths[0][0].fee_msat, 0);
4398 assert_eq!(route.paths[0][2].fee_msat, 99_000);
4399 assert_eq!(route.paths[1][0].short_channel_id, 2);
4400 assert_eq!(route.paths[1][0].fee_msat, 1);
4401 assert_eq!(route.paths[1][2].fee_msat, 1_000);
4402 assert_eq!(route.get_total_fees(), 1);
4403 assert_eq!(route.get_total_amount(), 100_000);
4407 fn drop_lowest_channel_mpp_route_test() {
4408 // This test checks that low-capacity channel is dropped when after
4409 // path finding we realize that we found more capacity than we need.
4410 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4411 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4412 let scorer = ln_test_utils::TestScorer::with_penalty(0);
4413 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4414 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4415 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(channelmanager::provided_invoice_features())
4416 .with_max_channel_saturation_power_of_half(0);
4418 // We need a route consisting of 3 paths:
4419 // From our node to node2 via node0, node7, node1 (three paths one hop each).
4421 // The first and the second paths should be sufficient, but the third should be
4422 // cheaper, so that we select it but drop later.
4424 // First, we set limits on these (previously unlimited) channels.
4425 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
4427 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
4428 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4429 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4430 short_channel_id: 1,
4433 cltv_expiry_delta: 0,
4434 htlc_minimum_msat: 0,
4435 htlc_maximum_msat: 100_000,
4437 fee_proportional_millionths: 0,
4438 excess_data: Vec::new()
4440 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4441 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4442 short_channel_id: 3,
4445 cltv_expiry_delta: 0,
4446 htlc_minimum_msat: 0,
4447 htlc_maximum_msat: 50_000,
4449 fee_proportional_millionths: 0,
4450 excess_data: Vec::new()
4453 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
4454 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4455 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4456 short_channel_id: 12,
4459 cltv_expiry_delta: 0,
4460 htlc_minimum_msat: 0,
4461 htlc_maximum_msat: 60_000,
4463 fee_proportional_millionths: 0,
4464 excess_data: Vec::new()
4466 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4467 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4468 short_channel_id: 13,
4471 cltv_expiry_delta: 0,
4472 htlc_minimum_msat: 0,
4473 htlc_maximum_msat: 60_000,
4475 fee_proportional_millionths: 0,
4476 excess_data: Vec::new()
4479 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
4480 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4481 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4482 short_channel_id: 2,
4485 cltv_expiry_delta: 0,
4486 htlc_minimum_msat: 0,
4487 htlc_maximum_msat: 20_000,
4489 fee_proportional_millionths: 0,
4490 excess_data: Vec::new()
4492 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4493 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4494 short_channel_id: 4,
4497 cltv_expiry_delta: 0,
4498 htlc_minimum_msat: 0,
4499 htlc_maximum_msat: 20_000,
4501 fee_proportional_millionths: 0,
4502 excess_data: Vec::new()
4506 // Attempt to route more than available results in a failure.
4507 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4508 &our_id, &payment_params, &network_graph.read_only(), None, 150_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
4509 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4510 } else { panic!(); }
4514 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
4515 // Our algorithm should provide us with these 3 paths.
4516 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 125_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4517 assert_eq!(route.paths.len(), 3);
4518 let mut total_amount_paid_msat = 0;
4519 for path in &route.paths {
4520 assert_eq!(path.len(), 2);
4521 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4522 total_amount_paid_msat += path.last().unwrap().fee_msat;
4524 assert_eq!(total_amount_paid_msat, 125_000);
4528 // Attempt to route without the last small cheap channel
4529 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4530 assert_eq!(route.paths.len(), 2);
4531 let mut total_amount_paid_msat = 0;
4532 for path in &route.paths {
4533 assert_eq!(path.len(), 2);
4534 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4535 total_amount_paid_msat += path.last().unwrap().fee_msat;
4537 assert_eq!(total_amount_paid_msat, 90_000);
4542 fn min_criteria_consistency() {
4543 // Test that we don't use an inconsistent metric between updating and walking nodes during
4544 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
4545 // was updated with a different criterion from the heap sorting, resulting in loops in
4546 // calculated paths. We test for that specific case here.
4548 // We construct a network that looks like this:
4550 // node2 -1(3)2- node3
4554 // node1 -1(5)2- node4 -1(1)2- node6
4560 // We create a loop on the side of our real path - our destination is node 6, with a
4561 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
4562 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
4563 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
4564 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
4565 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
4566 // "previous hop" being set to node 3, creating a loop in the path.
4567 let secp_ctx = Secp256k1::new();
4568 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
4569 let logger = Arc::new(ln_test_utils::TestLogger::new());
4570 let network = Arc::new(NetworkGraph::new(genesis_hash, Arc::clone(&logger)));
4571 let gossip_sync = P2PGossipSync::new(Arc::clone(&network), None, Arc::clone(&logger));
4572 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4573 let scorer = ln_test_utils::TestScorer::with_penalty(0);
4574 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4575 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4576 let payment_params = PaymentParameters::from_node_id(nodes[6]);
4578 add_channel(&gossip_sync, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
4579 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4580 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4581 short_channel_id: 6,
4584 cltv_expiry_delta: (6 << 4) | 0,
4585 htlc_minimum_msat: 0,
4586 htlc_maximum_msat: MAX_VALUE_MSAT,
4588 fee_proportional_millionths: 0,
4589 excess_data: Vec::new()
4591 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
4593 add_channel(&gossip_sync, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4594 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4595 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4596 short_channel_id: 5,
4599 cltv_expiry_delta: (5 << 4) | 0,
4600 htlc_minimum_msat: 0,
4601 htlc_maximum_msat: MAX_VALUE_MSAT,
4603 fee_proportional_millionths: 0,
4604 excess_data: Vec::new()
4606 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
4608 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
4609 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4610 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4611 short_channel_id: 4,
4614 cltv_expiry_delta: (4 << 4) | 0,
4615 htlc_minimum_msat: 0,
4616 htlc_maximum_msat: MAX_VALUE_MSAT,
4618 fee_proportional_millionths: 0,
4619 excess_data: Vec::new()
4621 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
4623 add_channel(&gossip_sync, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
4624 update_channel(&gossip_sync, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
4625 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4626 short_channel_id: 3,
4629 cltv_expiry_delta: (3 << 4) | 0,
4630 htlc_minimum_msat: 0,
4631 htlc_maximum_msat: MAX_VALUE_MSAT,
4633 fee_proportional_millionths: 0,
4634 excess_data: Vec::new()
4636 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
4638 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
4639 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4640 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4641 short_channel_id: 2,
4644 cltv_expiry_delta: (2 << 4) | 0,
4645 htlc_minimum_msat: 0,
4646 htlc_maximum_msat: MAX_VALUE_MSAT,
4648 fee_proportional_millionths: 0,
4649 excess_data: Vec::new()
4652 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
4653 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4654 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4655 short_channel_id: 1,
4658 cltv_expiry_delta: (1 << 4) | 0,
4659 htlc_minimum_msat: 100,
4660 htlc_maximum_msat: MAX_VALUE_MSAT,
4662 fee_proportional_millionths: 0,
4663 excess_data: Vec::new()
4665 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
4668 // Now ensure the route flows simply over nodes 1 and 4 to 6.
4669 let route = get_route(&our_id, &payment_params, &network.read_only(), None, 10_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4670 assert_eq!(route.paths.len(), 1);
4671 assert_eq!(route.paths[0].len(), 3);
4673 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
4674 assert_eq!(route.paths[0][0].short_channel_id, 6);
4675 assert_eq!(route.paths[0][0].fee_msat, 100);
4676 assert_eq!(route.paths[0][0].cltv_expiry_delta, (5 << 4) | 0);
4677 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(1));
4678 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(6));
4680 assert_eq!(route.paths[0][1].pubkey, nodes[4]);
4681 assert_eq!(route.paths[0][1].short_channel_id, 5);
4682 assert_eq!(route.paths[0][1].fee_msat, 0);
4683 assert_eq!(route.paths[0][1].cltv_expiry_delta, (1 << 4) | 0);
4684 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(4));
4685 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(5));
4687 assert_eq!(route.paths[0][2].pubkey, nodes[6]);
4688 assert_eq!(route.paths[0][2].short_channel_id, 1);
4689 assert_eq!(route.paths[0][2].fee_msat, 10_000);
4690 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
4691 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
4692 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(1));
4698 fn exact_fee_liquidity_limit() {
4699 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
4700 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
4701 // we calculated fees on a higher value, resulting in us ignoring such paths.
4702 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4703 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
4704 let scorer = ln_test_utils::TestScorer::with_penalty(0);
4705 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4706 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4707 let payment_params = PaymentParameters::from_node_id(nodes[2]);
4709 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
4711 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4712 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4713 short_channel_id: 2,
4716 cltv_expiry_delta: 0,
4717 htlc_minimum_msat: 0,
4718 htlc_maximum_msat: 85_000,
4720 fee_proportional_millionths: 0,
4721 excess_data: Vec::new()
4724 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4725 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4726 short_channel_id: 12,
4729 cltv_expiry_delta: (4 << 4) | 1,
4730 htlc_minimum_msat: 0,
4731 htlc_maximum_msat: 270_000,
4733 fee_proportional_millionths: 1000000,
4734 excess_data: Vec::new()
4738 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
4739 // 200% fee charged channel 13 in the 1-to-2 direction.
4740 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4741 assert_eq!(route.paths.len(), 1);
4742 assert_eq!(route.paths[0].len(), 2);
4744 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
4745 assert_eq!(route.paths[0][0].short_channel_id, 12);
4746 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
4747 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
4748 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
4749 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
4751 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
4752 assert_eq!(route.paths[0][1].short_channel_id, 13);
4753 assert_eq!(route.paths[0][1].fee_msat, 90_000);
4754 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
4755 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
4756 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
4761 fn htlc_max_reduction_below_min() {
4762 // Test that if, while walking the graph, we reduce the value being sent to meet an
4763 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
4764 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
4765 // resulting in us thinking there is no possible path, even if other paths exist.
4766 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4767 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4768 let scorer = ln_test_utils::TestScorer::with_penalty(0);
4769 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4770 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4771 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(channelmanager::provided_invoice_features());
4773 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
4774 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
4775 // then try to send 90_000.
4776 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4777 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4778 short_channel_id: 2,
4781 cltv_expiry_delta: 0,
4782 htlc_minimum_msat: 0,
4783 htlc_maximum_msat: 80_000,
4785 fee_proportional_millionths: 0,
4786 excess_data: Vec::new()
4788 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4789 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4790 short_channel_id: 4,
4793 cltv_expiry_delta: (4 << 4) | 1,
4794 htlc_minimum_msat: 90_000,
4795 htlc_maximum_msat: MAX_VALUE_MSAT,
4797 fee_proportional_millionths: 0,
4798 excess_data: Vec::new()
4802 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
4803 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
4804 // expensive) channels 12-13 path.
4805 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4806 assert_eq!(route.paths.len(), 1);
4807 assert_eq!(route.paths[0].len(), 2);
4809 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
4810 assert_eq!(route.paths[0][0].short_channel_id, 12);
4811 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
4812 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
4813 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
4814 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
4816 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
4817 assert_eq!(route.paths[0][1].short_channel_id, 13);
4818 assert_eq!(route.paths[0][1].fee_msat, 90_000);
4819 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
4820 assert_eq!(route.paths[0][1].node_features.le_flags(), channelmanager::provided_invoice_features().le_flags());
4821 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
4826 fn multiple_direct_first_hops() {
4827 // Previously we'd only ever considered one first hop path per counterparty.
4828 // However, as we don't restrict users to one channel per peer, we really need to support
4829 // looking at all first hop paths.
4830 // Here we test that we do not ignore all-but-the-last first hop paths per counterparty (as
4831 // we used to do by overwriting the `first_hop_targets` hashmap entry) and that we can MPP
4832 // route over multiple channels with the same first hop.
4833 let secp_ctx = Secp256k1::new();
4834 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4835 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
4836 let logger = Arc::new(ln_test_utils::TestLogger::new());
4837 let network_graph = NetworkGraph::new(genesis_hash, Arc::clone(&logger));
4838 let scorer = ln_test_utils::TestScorer::with_penalty(0);
4839 let payment_params = PaymentParameters::from_node_id(nodes[0]).with_features(channelmanager::provided_invoice_features());
4840 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4841 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4844 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
4845 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(), 200_000),
4846 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(), 10_000),
4847 ]), 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4848 assert_eq!(route.paths.len(), 1);
4849 assert_eq!(route.paths[0].len(), 1);
4851 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
4852 assert_eq!(route.paths[0][0].short_channel_id, 3);
4853 assert_eq!(route.paths[0][0].fee_msat, 100_000);
4856 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
4857 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(), 50_000),
4858 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(), 50_000),
4859 ]), 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4860 assert_eq!(route.paths.len(), 2);
4861 assert_eq!(route.paths[0].len(), 1);
4862 assert_eq!(route.paths[1].len(), 1);
4864 assert!((route.paths[0][0].short_channel_id == 3 && route.paths[1][0].short_channel_id == 2) ||
4865 (route.paths[0][0].short_channel_id == 2 && route.paths[1][0].short_channel_id == 3));
4867 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
4868 assert_eq!(route.paths[0][0].fee_msat, 50_000);
4870 assert_eq!(route.paths[1][0].pubkey, nodes[0]);
4871 assert_eq!(route.paths[1][0].fee_msat, 50_000);
4875 // If we have a bunch of outbound channels to the same node, where most are not
4876 // sufficient to pay the full payment, but one is, we should default to just using the
4877 // one single channel that has sufficient balance, avoiding MPP.
4879 // If we have several options above the 3xpayment value threshold, we should pick the
4880 // smallest of them, avoiding further fragmenting our available outbound balance to
4882 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
4883 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(), 50_000),
4884 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(), 50_000),
4885 &get_channel_details(Some(5), nodes[0], channelmanager::provided_init_features(), 50_000),
4886 &get_channel_details(Some(6), nodes[0], channelmanager::provided_init_features(), 300_000),
4887 &get_channel_details(Some(7), nodes[0], channelmanager::provided_init_features(), 50_000),
4888 &get_channel_details(Some(8), nodes[0], channelmanager::provided_init_features(), 50_000),
4889 &get_channel_details(Some(9), nodes[0], channelmanager::provided_init_features(), 50_000),
4890 &get_channel_details(Some(4), nodes[0], channelmanager::provided_init_features(), 1_000_000),
4891 ]), 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4892 assert_eq!(route.paths.len(), 1);
4893 assert_eq!(route.paths[0].len(), 1);
4895 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
4896 assert_eq!(route.paths[0][0].short_channel_id, 6);
4897 assert_eq!(route.paths[0][0].fee_msat, 100_000);
4902 fn prefers_shorter_route_with_higher_fees() {
4903 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4904 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4905 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
4907 // Without penalizing each hop 100 msats, a longer path with lower fees is chosen.
4908 let scorer = ln_test_utils::TestScorer::with_penalty(0);
4909 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4910 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4911 let route = get_route(
4912 &our_id, &payment_params, &network_graph.read_only(), None, 100, 42,
4913 Arc::clone(&logger), &scorer, &random_seed_bytes
4915 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4917 assert_eq!(route.get_total_fees(), 100);
4918 assert_eq!(route.get_total_amount(), 100);
4919 assert_eq!(path, vec![2, 4, 6, 11, 8]);
4921 // Applying a 100 msat penalty to each hop results in taking channels 7 and 10 to nodes[6]
4922 // from nodes[2] rather than channel 6, 11, and 8, even though the longer path is cheaper.
4923 let scorer = ln_test_utils::TestScorer::with_penalty(100);
4924 let route = get_route(
4925 &our_id, &payment_params, &network_graph.read_only(), None, 100, 42,
4926 Arc::clone(&logger), &scorer, &random_seed_bytes
4928 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4930 assert_eq!(route.get_total_fees(), 300);
4931 assert_eq!(route.get_total_amount(), 100);
4932 assert_eq!(path, vec![2, 4, 7, 10]);
4935 struct BadChannelScorer {
4936 short_channel_id: u64,
4940 impl Writeable for BadChannelScorer {
4941 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
4943 impl Score for BadChannelScorer {
4944 fn channel_penalty_msat(&self, short_channel_id: u64, _: &NodeId, _: &NodeId, _: ChannelUsage) -> u64 {
4945 if short_channel_id == self.short_channel_id { u64::max_value() } else { 0 }
4948 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
4949 fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
4950 fn probe_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
4951 fn probe_successful(&mut self, _path: &[&RouteHop]) {}
4954 struct BadNodeScorer {
4959 impl Writeable for BadNodeScorer {
4960 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
4963 impl Score for BadNodeScorer {
4964 fn channel_penalty_msat(&self, _: u64, _: &NodeId, target: &NodeId, _: ChannelUsage) -> u64 {
4965 if *target == self.node_id { u64::max_value() } else { 0 }
4968 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
4969 fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
4970 fn probe_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
4971 fn probe_successful(&mut self, _path: &[&RouteHop]) {}
4975 fn avoids_routing_through_bad_channels_and_nodes() {
4976 let (secp_ctx, network, _, _, logger) = build_graph();
4977 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4978 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
4979 let network_graph = network.read_only();
4981 // A path to nodes[6] exists when no penalties are applied to any channel.
4982 let scorer = ln_test_utils::TestScorer::with_penalty(0);
4983 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4984 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4985 let route = get_route(
4986 &our_id, &payment_params, &network_graph, None, 100, 42,
4987 Arc::clone(&logger), &scorer, &random_seed_bytes
4989 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4991 assert_eq!(route.get_total_fees(), 100);
4992 assert_eq!(route.get_total_amount(), 100);
4993 assert_eq!(path, vec![2, 4, 6, 11, 8]);
4995 // A different path to nodes[6] exists if channel 6 cannot be routed over.
4996 let scorer = BadChannelScorer { short_channel_id: 6 };
4997 let route = get_route(
4998 &our_id, &payment_params, &network_graph, None, 100, 42,
4999 Arc::clone(&logger), &scorer, &random_seed_bytes
5001 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5003 assert_eq!(route.get_total_fees(), 300);
5004 assert_eq!(route.get_total_amount(), 100);
5005 assert_eq!(path, vec![2, 4, 7, 10]);
5007 // A path to nodes[6] does not exist if nodes[2] cannot be routed through.
5008 let scorer = BadNodeScorer { node_id: NodeId::from_pubkey(&nodes[2]) };
5010 &our_id, &payment_params, &network_graph, None, 100, 42,
5011 Arc::clone(&logger), &scorer, &random_seed_bytes
5013 Err(LightningError { err, .. } ) => {
5014 assert_eq!(err, "Failed to find a path to the given destination");
5016 Ok(_) => panic!("Expected error"),
5021 fn total_fees_single_path() {
5025 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5026 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5027 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5030 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5031 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5032 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5035 pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
5036 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5037 short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0
5040 payment_params: None,
5043 assert_eq!(route.get_total_fees(), 250);
5044 assert_eq!(route.get_total_amount(), 225);
5048 fn total_fees_multi_path() {
5052 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5053 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5054 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5057 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5058 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5059 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5063 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5064 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5065 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5068 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5069 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5070 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5073 payment_params: None,
5076 assert_eq!(route.get_total_fees(), 200);
5077 assert_eq!(route.get_total_amount(), 300);
5081 fn total_empty_route_no_panic() {
5082 // In an earlier version of `Route::get_total_fees` and `Route::get_total_amount`, they
5083 // would both panic if the route was completely empty. We test to ensure they return 0
5084 // here, even though its somewhat nonsensical as a route.
5085 let route = Route { paths: Vec::new(), payment_params: None };
5087 assert_eq!(route.get_total_fees(), 0);
5088 assert_eq!(route.get_total_amount(), 0);
5092 fn limits_total_cltv_delta() {
5093 let (secp_ctx, network, _, _, logger) = build_graph();
5094 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5095 let network_graph = network.read_only();
5097 let scorer = ln_test_utils::TestScorer::with_penalty(0);
5099 // Make sure that generally there is at least one route available
5100 let feasible_max_total_cltv_delta = 1008;
5101 let feasible_payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes))
5102 .with_max_total_cltv_expiry_delta(feasible_max_total_cltv_delta);
5103 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5104 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5105 let route = get_route(&our_id, &feasible_payment_params, &network_graph, None, 100, 0, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5106 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5107 assert_ne!(path.len(), 0);
5109 // But not if we exclude all paths on the basis of their accumulated CLTV delta
5110 let fail_max_total_cltv_delta = 23;
5111 let fail_payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes))
5112 .with_max_total_cltv_expiry_delta(fail_max_total_cltv_delta);
5113 match get_route(&our_id, &fail_payment_params, &network_graph, None, 100, 0, Arc::clone(&logger), &scorer, &random_seed_bytes)
5115 Err(LightningError { err, .. } ) => {
5116 assert_eq!(err, "Failed to find a path to the given destination");
5118 Ok(_) => panic!("Expected error"),
5123 fn avoids_recently_failed_paths() {
5124 // Ensure that the router always avoids all of the `previously_failed_channels` channels by
5125 // randomly inserting channels into it until we can't find a route anymore.
5126 let (secp_ctx, network, _, _, logger) = build_graph();
5127 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5128 let network_graph = network.read_only();
5130 let scorer = ln_test_utils::TestScorer::with_penalty(0);
5131 let mut payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes))
5132 .with_max_path_count(1);
5133 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5134 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5136 // We should be able to find a route initially, and then after we fail a few random
5137 // channels eventually we won't be able to any longer.
5138 assert!(get_route(&our_id, &payment_params, &network_graph, None, 100, 0, Arc::clone(&logger), &scorer, &random_seed_bytes).is_ok());
5140 if let Ok(route) = get_route(&our_id, &payment_params, &network_graph, None, 100, 0, Arc::clone(&logger), &scorer, &random_seed_bytes) {
5141 for chan in route.paths[0].iter() {
5142 assert!(!payment_params.previously_failed_channels.contains(&chan.short_channel_id));
5144 let victim = (u64::from_ne_bytes(random_seed_bytes[0..8].try_into().unwrap()) as usize)
5145 % route.paths[0].len();
5146 payment_params.previously_failed_channels.push(route.paths[0][victim].short_channel_id);
5152 fn limits_path_length() {
5153 let (secp_ctx, network, _, _, logger) = build_line_graph();
5154 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5155 let network_graph = network.read_only();
5157 let scorer = ln_test_utils::TestScorer::with_penalty(0);
5158 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5159 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5161 // First check we can actually create a long route on this graph.
5162 let feasible_payment_params = PaymentParameters::from_node_id(nodes[18]);
5163 let route = get_route(&our_id, &feasible_payment_params, &network_graph, None, 100, 0,
5164 Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5165 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5166 assert!(path.len() == MAX_PATH_LENGTH_ESTIMATE.into());
5168 // But we can't create a path surpassing the MAX_PATH_LENGTH_ESTIMATE limit.
5169 let fail_payment_params = PaymentParameters::from_node_id(nodes[19]);
5170 match get_route(&our_id, &fail_payment_params, &network_graph, None, 100, 0,
5171 Arc::clone(&logger), &scorer, &random_seed_bytes)
5173 Err(LightningError { err, .. } ) => {
5174 assert_eq!(err, "Failed to find a path to the given destination");
5176 Ok(_) => panic!("Expected error"),
5181 fn adds_and_limits_cltv_offset() {
5182 let (secp_ctx, network_graph, _, _, logger) = build_graph();
5183 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5185 let scorer = ln_test_utils::TestScorer::with_penalty(0);
5187 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
5188 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5189 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5190 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5191 assert_eq!(route.paths.len(), 1);
5193 let cltv_expiry_deltas_before = route.paths[0].iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5195 // Check whether the offset added to the last hop by default is in [1 .. DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA]
5196 let mut route_default = route.clone();
5197 add_random_cltv_offset(&mut route_default, &payment_params, &network_graph.read_only(), &random_seed_bytes);
5198 let cltv_expiry_deltas_default = route_default.paths[0].iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5199 assert_eq!(cltv_expiry_deltas_before.split_last().unwrap().1, cltv_expiry_deltas_default.split_last().unwrap().1);
5200 assert!(cltv_expiry_deltas_default.last() > cltv_expiry_deltas_before.last());
5201 assert!(cltv_expiry_deltas_default.last().unwrap() <= &DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA);
5203 // Check that no offset is added when we restrict the max_total_cltv_expiry_delta
5204 let mut route_limited = route.clone();
5205 let limited_max_total_cltv_expiry_delta = cltv_expiry_deltas_before.iter().sum();
5206 let limited_payment_params = payment_params.with_max_total_cltv_expiry_delta(limited_max_total_cltv_expiry_delta);
5207 add_random_cltv_offset(&mut route_limited, &limited_payment_params, &network_graph.read_only(), &random_seed_bytes);
5208 let cltv_expiry_deltas_limited = route_limited.paths[0].iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5209 assert_eq!(cltv_expiry_deltas_before, cltv_expiry_deltas_limited);
5213 fn adds_plausible_cltv_offset() {
5214 let (secp_ctx, network, _, _, logger) = build_graph();
5215 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5216 let network_graph = network.read_only();
5217 let network_nodes = network_graph.nodes();
5218 let network_channels = network_graph.channels();
5219 let scorer = ln_test_utils::TestScorer::with_penalty(0);
5220 let payment_params = PaymentParameters::from_node_id(nodes[3]);
5221 let keys_manager = ln_test_utils::TestKeysInterface::new(&[4u8; 32], Network::Testnet);
5222 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5224 let mut route = get_route(&our_id, &payment_params, &network_graph, None, 100, 0,
5225 Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5226 add_random_cltv_offset(&mut route, &payment_params, &network_graph, &random_seed_bytes);
5228 let mut path_plausibility = vec![];
5230 for p in route.paths {
5231 // 1. Select random observation point
5232 let mut prng = ChaCha20::new(&random_seed_bytes, &[0u8; 12]);
5233 let mut random_bytes = [0u8; ::core::mem::size_of::<usize>()];
5235 prng.process_in_place(&mut random_bytes);
5236 let random_path_index = usize::from_be_bytes(random_bytes).wrapping_rem(p.len());
5237 let observation_point = NodeId::from_pubkey(&p.get(random_path_index).unwrap().pubkey);
5239 // 2. Calculate what CLTV expiry delta we would observe there
5240 let observed_cltv_expiry_delta: u32 = p[random_path_index..].iter().map(|h| h.cltv_expiry_delta).sum();
5242 // 3. Starting from the observation point, find candidate paths
5243 let mut candidates: VecDeque<(NodeId, Vec<u32>)> = VecDeque::new();
5244 candidates.push_back((observation_point, vec![]));
5246 let mut found_plausible_candidate = false;
5248 'candidate_loop: while let Some((cur_node_id, cur_path_cltv_deltas)) = candidates.pop_front() {
5249 if let Some(remaining) = observed_cltv_expiry_delta.checked_sub(cur_path_cltv_deltas.iter().sum::<u32>()) {
5250 if remaining == 0 || remaining.wrapping_rem(40) == 0 || remaining.wrapping_rem(144) == 0 {
5251 found_plausible_candidate = true;
5252 break 'candidate_loop;
5256 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
5257 for channel_id in &cur_node.channels {
5258 if let Some(channel_info) = network_channels.get(&channel_id) {
5259 if let Some((dir_info, next_id)) = channel_info.as_directed_from(&cur_node_id) {
5260 if let Some(channel_update_info) = dir_info.direction() {
5261 let next_cltv_expiry_delta = channel_update_info.cltv_expiry_delta as u32;
5262 if cur_path_cltv_deltas.iter().sum::<u32>()
5263 .saturating_add(next_cltv_expiry_delta) <= observed_cltv_expiry_delta {
5264 let mut new_path_cltv_deltas = cur_path_cltv_deltas.clone();
5265 new_path_cltv_deltas.push(next_cltv_expiry_delta);
5266 candidates.push_back((*next_id, new_path_cltv_deltas));
5275 path_plausibility.push(found_plausible_candidate);
5277 assert!(path_plausibility.iter().all(|x| *x));
5281 fn builds_correct_path_from_hops() {
5282 let (secp_ctx, network, _, _, logger) = build_graph();
5283 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5284 let network_graph = network.read_only();
5286 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5287 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5289 let payment_params = PaymentParameters::from_node_id(nodes[3]);
5290 let hops = [nodes[1], nodes[2], nodes[4], nodes[3]];
5291 let route = build_route_from_hops_internal(&our_id, &hops, &payment_params,
5292 &network_graph, 100, 0, Arc::clone(&logger), &random_seed_bytes).unwrap();
5293 let route_hop_pubkeys = route.paths[0].iter().map(|hop| hop.pubkey).collect::<Vec<_>>();
5294 assert_eq!(hops.len(), route.paths[0].len());
5295 for (idx, hop_pubkey) in hops.iter().enumerate() {
5296 assert!(*hop_pubkey == route_hop_pubkeys[idx]);
5301 fn avoids_saturating_channels() {
5302 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5303 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5305 let scorer = ProbabilisticScorer::new(Default::default(), &*network_graph, Arc::clone(&logger));
5307 // Set the fee on channel 13 to 100% to match channel 4 giving us two equivalent paths (us
5308 // -> node 7 -> node2 and us -> node 1 -> node 2) which we should balance over.
5309 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5310 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5311 short_channel_id: 4,
5314 cltv_expiry_delta: (4 << 4) | 1,
5315 htlc_minimum_msat: 0,
5316 htlc_maximum_msat: 250_000_000,
5318 fee_proportional_millionths: 0,
5319 excess_data: Vec::new()
5321 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5322 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5323 short_channel_id: 13,
5326 cltv_expiry_delta: (13 << 4) | 1,
5327 htlc_minimum_msat: 0,
5328 htlc_maximum_msat: 250_000_000,
5330 fee_proportional_millionths: 0,
5331 excess_data: Vec::new()
5334 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(channelmanager::provided_invoice_features());
5335 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5336 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5337 // 100,000 sats is less than the available liquidity on each channel, set above.
5338 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();
5339 assert_eq!(route.paths.len(), 2);
5340 assert!((route.paths[0][1].short_channel_id == 4 && route.paths[1][1].short_channel_id == 13) ||
5341 (route.paths[1][1].short_channel_id == 4 && route.paths[0][1].short_channel_id == 13));
5344 #[cfg(not(feature = "no-std"))]
5345 pub(super) fn random_init_seed() -> u64 {
5346 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
5347 use core::hash::{BuildHasher, Hasher};
5348 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
5349 println!("Using seed of {}", seed);
5352 #[cfg(not(feature = "no-std"))]
5353 use crate::util::ser::ReadableArgs;
5356 #[cfg(not(feature = "no-std"))]
5357 fn generate_routes() {
5358 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringParameters};
5360 let mut d = match super::bench_utils::get_route_file() {
5367 let logger = ln_test_utils::TestLogger::new();
5368 let graph = NetworkGraph::read(&mut d, &logger).unwrap();
5369 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5370 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5372 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
5373 let mut seed = random_init_seed() as usize;
5374 let nodes = graph.read_only().nodes().clone();
5375 'load_endpoints: for _ in 0..10 {
5377 seed = seed.overflowing_mul(0xdeadbeef).0;
5378 let src = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5379 seed = seed.overflowing_mul(0xdeadbeef).0;
5380 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5381 let payment_params = PaymentParameters::from_node_id(dst);
5382 let amt = seed as u64 % 200_000_000;
5383 let params = ProbabilisticScoringParameters::default();
5384 let scorer = ProbabilisticScorer::new(params, &graph, &logger);
5385 if get_route(src, &payment_params, &graph.read_only(), None, amt, 42, &logger, &scorer, &random_seed_bytes).is_ok() {
5386 continue 'load_endpoints;
5393 #[cfg(not(feature = "no-std"))]
5394 fn generate_routes_mpp() {
5395 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringParameters};
5397 let mut d = match super::bench_utils::get_route_file() {
5404 let logger = ln_test_utils::TestLogger::new();
5405 let graph = NetworkGraph::read(&mut d, &logger).unwrap();
5406 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5407 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5409 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
5410 let mut seed = random_init_seed() as usize;
5411 let nodes = graph.read_only().nodes().clone();
5412 'load_endpoints: for _ in 0..10 {
5414 seed = seed.overflowing_mul(0xdeadbeef).0;
5415 let src = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5416 seed = seed.overflowing_mul(0xdeadbeef).0;
5417 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5418 let payment_params = PaymentParameters::from_node_id(dst).with_features(channelmanager::provided_invoice_features());
5419 let amt = seed as u64 % 200_000_000;
5420 let params = ProbabilisticScoringParameters::default();
5421 let scorer = ProbabilisticScorer::new(params, &graph, &logger);
5422 if get_route(src, &payment_params, &graph.read_only(), None, amt, 42, &logger, &scorer, &random_seed_bytes).is_ok() {
5423 continue 'load_endpoints;
5430 fn honors_manual_penalties() {
5431 let (secp_ctx, network_graph, _, _, logger) = build_line_graph();
5432 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5434 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5435 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5437 let scorer_params = ProbabilisticScoringParameters::default();
5438 let mut scorer = ProbabilisticScorer::new(scorer_params, Arc::clone(&network_graph), Arc::clone(&logger));
5440 // First check set manual penalties are returned by the scorer.
5441 let usage = ChannelUsage {
5443 inflight_htlc_msat: 0,
5444 effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_024_000, htlc_maximum_msat: Some(1_000) },
5446 scorer.set_manual_penalty(&NodeId::from_pubkey(&nodes[3]), 123);
5447 scorer.set_manual_penalty(&NodeId::from_pubkey(&nodes[4]), 456);
5448 assert_eq!(scorer.channel_penalty_msat(42, &NodeId::from_pubkey(&nodes[3]), &NodeId::from_pubkey(&nodes[4]), usage), 456);
5450 // Then check we can get a normal route
5451 let payment_params = PaymentParameters::from_node_id(nodes[10]);
5452 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes);
5453 assert!(route.is_ok());
5455 // Then check that we can't get a route if we ban an intermediate node.
5456 scorer.add_banned(&NodeId::from_pubkey(&nodes[3]));
5457 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes);
5458 assert!(route.is_err());
5460 // Finally make sure we can route again, when we remove the ban.
5461 scorer.remove_banned(&NodeId::from_pubkey(&nodes[3]));
5462 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes);
5463 assert!(route.is_ok());
5467 #[cfg(all(test, not(feature = "no-std")))]
5468 pub(crate) mod bench_utils {
5470 /// Tries to open a network graph file, or panics with a URL to fetch it.
5471 pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
5472 let res = File::open("net_graph-2021-05-31.bin") // By default we're run in RL/lightning
5473 .or_else(|_| File::open("lightning/net_graph-2021-05-31.bin")) // We may be run manually in RL/
5474 .or_else(|_| { // Fall back to guessing based on the binary location
5475 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
5476 let mut path = std::env::current_exe().unwrap();
5477 path.pop(); // lightning-...
5479 path.pop(); // debug
5480 path.pop(); // target
5481 path.push("lightning");
5482 path.push("net_graph-2021-05-31.bin");
5483 eprintln!("{}", path.to_str().unwrap());
5486 .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");
5487 #[cfg(require_route_graph_test)]
5488 return Ok(res.unwrap());
5489 #[cfg(not(require_route_graph_test))]
5494 #[cfg(all(test, feature = "_bench_unstable", not(feature = "no-std")))]
5497 use bitcoin::hashes::Hash;
5498 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
5499 use crate::chain::transaction::OutPoint;
5500 use crate::chain::keysinterface::{KeysManager,KeysInterface};
5501 use crate::ln::channelmanager::{self, ChannelCounterparty, ChannelDetails};
5502 use crate::ln::features::InvoiceFeatures;
5503 use crate::routing::gossip::NetworkGraph;
5504 use crate::routing::scoring::{FixedPenaltyScorer, ProbabilisticScorer, ProbabilisticScoringParameters};
5505 use crate::util::logger::{Logger, Record};
5506 use crate::util::ser::ReadableArgs;
5510 struct DummyLogger {}
5511 impl Logger for DummyLogger {
5512 fn log(&self, _record: &Record) {}
5515 fn read_network_graph(logger: &DummyLogger) -> NetworkGraph<&DummyLogger> {
5516 let mut d = bench_utils::get_route_file().unwrap();
5517 NetworkGraph::read(&mut d, logger).unwrap()
5520 fn payer_pubkey() -> PublicKey {
5521 let secp_ctx = Secp256k1::new();
5522 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
5526 fn first_hop(node_id: PublicKey) -> ChannelDetails {
5528 channel_id: [0; 32],
5529 counterparty: ChannelCounterparty {
5530 features: channelmanager::provided_init_features(),
5532 unspendable_punishment_reserve: 0,
5533 forwarding_info: None,
5534 outbound_htlc_minimum_msat: None,
5535 outbound_htlc_maximum_msat: None,
5537 funding_txo: Some(OutPoint {
5538 txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0
5541 short_channel_id: Some(1),
5542 inbound_scid_alias: None,
5543 outbound_scid_alias: None,
5544 channel_value_satoshis: 10_000_000,
5546 balance_msat: 10_000_000,
5547 outbound_capacity_msat: 10_000_000,
5548 next_outbound_htlc_limit_msat: 10_000_000,
5549 inbound_capacity_msat: 0,
5550 unspendable_punishment_reserve: None,
5551 confirmations_required: None,
5552 force_close_spend_delay: None,
5554 is_channel_ready: true,
5557 inbound_htlc_minimum_msat: None,
5558 inbound_htlc_maximum_msat: None,
5564 fn generate_routes_with_zero_penalty_scorer(bench: &mut Bencher) {
5565 let logger = DummyLogger {};
5566 let network_graph = read_network_graph(&logger);
5567 let scorer = FixedPenaltyScorer::with_penalty(0);
5568 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::empty());
5572 fn generate_mpp_routes_with_zero_penalty_scorer(bench: &mut Bencher) {
5573 let logger = DummyLogger {};
5574 let network_graph = read_network_graph(&logger);
5575 let scorer = FixedPenaltyScorer::with_penalty(0);
5576 generate_routes(bench, &network_graph, scorer, channelmanager::provided_invoice_features());
5580 fn generate_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, InvoiceFeatures::empty());
5589 fn generate_mpp_routes_with_probabilistic_scorer(bench: &mut Bencher) {
5590 let logger = DummyLogger {};
5591 let network_graph = read_network_graph(&logger);
5592 let params = ProbabilisticScoringParameters::default();
5593 let scorer = ProbabilisticScorer::new(params, &network_graph, &logger);
5594 generate_routes(bench, &network_graph, scorer, channelmanager::provided_invoice_features());
5597 fn generate_routes<S: Score>(
5598 bench: &mut Bencher, graph: &NetworkGraph<&DummyLogger>, mut scorer: S,
5599 features: InvoiceFeatures
5601 let nodes = graph.read_only().nodes().clone();
5602 let payer = payer_pubkey();
5603 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
5604 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5606 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
5607 let mut routes = Vec::new();
5608 let mut route_endpoints = Vec::new();
5609 let mut seed: usize = 0xdeadbeef;
5610 'load_endpoints: for _ in 0..150 {
5613 let src = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5615 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5616 let params = PaymentParameters::from_node_id(dst).with_features(features.clone());
5617 let first_hop = first_hop(src);
5618 let amt = seed as u64 % 1_000_000;
5619 if let Ok(route) = get_route(&payer, ¶ms, &graph.read_only(), Some(&[&first_hop]), amt, 42, &DummyLogger{}, &scorer, &random_seed_bytes) {
5621 route_endpoints.push((first_hop, params, amt));
5622 continue 'load_endpoints;
5627 // ...and seed the scorer with success and failure data...
5628 for route in routes {
5629 let amount = route.get_total_amount();
5630 if amount < 250_000 {
5631 for path in route.paths {
5632 scorer.payment_path_successful(&path.iter().collect::<Vec<_>>());
5634 } else if amount > 750_000 {
5635 for path in route.paths {
5636 let short_channel_id = path[path.len() / 2].short_channel_id;
5637 scorer.payment_path_failed(&path.iter().collect::<Vec<_>>(), short_channel_id);
5642 // Because we've changed channel scores, its possible we'll take different routes to the
5643 // selected destinations, possibly causing us to fail because, eg, the newly-selected path
5644 // requires a too-high CLTV delta.
5645 route_endpoints.retain(|(first_hop, params, amt)| {
5646 get_route(&payer, params, &graph.read_only(), Some(&[first_hop]), *amt, 42, &DummyLogger{}, &scorer, &random_seed_bytes).is_ok()
5648 route_endpoints.truncate(100);
5649 assert_eq!(route_endpoints.len(), 100);
5651 // ...then benchmark finding paths between the nodes we learned.
5654 let (first_hop, params, amt) = &route_endpoints[idx % route_endpoints.len()];
5655 assert!(get_route(&payer, params, &graph.read_only(), Some(&[first_hop]), *amt, 42, &DummyLogger{}, &scorer, &random_seed_bytes).is_ok());