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 ln::channelmanager::ChannelDetails;
18 use ln::features::{ChannelFeatures, InvoiceFeatures, NodeFeatures};
19 use ln::msgs::{DecodeError, ErrorAction, LightningError, MAX_VALUE_MSAT};
20 use routing::gossip::{DirectedChannelInfoWithUpdate, EffectiveCapacity, ReadOnlyNetworkGraph, NetworkGraph, NodeId, RoutingFees};
21 use routing::scoring::{ChannelUsage, Score};
22 use util::ser::{Writeable, Readable, Writer};
23 use util::logger::{Level, Logger};
24 use util::chacha20::ChaCha20;
28 use alloc::collections::BinaryHeap;
33 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
35 /// The node_id of the node at this hop.
36 pub pubkey: PublicKey,
37 /// The node_announcement features of the node at this hop. For the last hop, these may be
38 /// amended to match the features present in the invoice this node generated.
39 pub node_features: NodeFeatures,
40 /// The channel that should be used from the previous hop to reach this node.
41 pub short_channel_id: u64,
42 /// The channel_announcement features of the channel that should be used from the previous hop
43 /// to reach this node.
44 pub channel_features: ChannelFeatures,
45 /// The fee taken on this hop (for paying for the use of the *next* channel in the path).
46 /// For the last hop, this should be the full value of the payment (might be more than
47 /// requested if we had to match htlc_minimum_msat).
49 /// The CLTV delta added for this hop. For the last hop, this should be the full CLTV value
50 /// expected at the destination, in excess of the current block height.
51 pub cltv_expiry_delta: u32,
54 impl_writeable_tlv_based!(RouteHop, {
55 (0, pubkey, required),
56 (2, node_features, required),
57 (4, short_channel_id, required),
58 (6, channel_features, required),
59 (8, fee_msat, required),
60 (10, cltv_expiry_delta, required),
63 /// A route directs a payment from the sender (us) to the recipient. If the recipient supports MPP,
64 /// it can take multiple paths. Each path is composed of one or more hops through the network.
65 #[derive(Clone, Hash, PartialEq, Eq)]
67 /// The list of routes taken for a single (potentially-)multi-part payment. The pubkey of the
68 /// last RouteHop in each path must be the same. Each entry represents a list of hops, NOT
69 /// INCLUDING our own, where the last hop is the destination. Thus, this must always be at
70 /// least length one. While the maximum length of any given path is variable, keeping the length
71 /// of any path less or equal to 19 should currently ensure it is viable.
72 pub paths: Vec<Vec<RouteHop>>,
73 /// The `payment_params` parameter passed to [`find_route`].
74 /// This is used by `ChannelManager` to track information which may be required for retries,
75 /// provided back to you via [`Event::PaymentPathFailed`].
77 /// [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed
78 pub payment_params: Option<PaymentParameters>,
81 pub(crate) trait RoutePath {
82 /// Gets the fees for a given path, excluding any excess paid to the recipient.
83 fn get_path_fees(&self) -> u64;
85 impl RoutePath for Vec<RouteHop> {
86 fn get_path_fees(&self) -> u64 {
87 // Do not count last hop of each path since that's the full value of the payment
88 self.split_last().map(|(_, path_prefix)| path_prefix).unwrap_or(&[])
89 .iter().map(|hop| &hop.fee_msat)
95 /// Returns the total amount of fees paid on this [`Route`].
97 /// This doesn't include any extra payment made to the recipient, which can happen in excess of
98 /// the amount passed to [`find_route`]'s `params.final_value_msat`.
99 pub fn get_total_fees(&self) -> u64 {
100 self.paths.iter().map(|path| path.get_path_fees()).sum()
103 /// Returns the total amount paid on this [`Route`], excluding the fees.
104 pub fn get_total_amount(&self) -> u64 {
105 return self.paths.iter()
106 .map(|path| path.split_last().map(|(hop, _)| hop.fee_msat).unwrap_or(0))
111 const SERIALIZATION_VERSION: u8 = 1;
112 const MIN_SERIALIZATION_VERSION: u8 = 1;
114 impl Writeable for Route {
115 fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
116 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
117 (self.paths.len() as u64).write(writer)?;
118 for hops in self.paths.iter() {
119 (hops.len() as u8).write(writer)?;
120 for hop in hops.iter() {
124 write_tlv_fields!(writer, {
125 (1, self.payment_params, option),
131 impl Readable for Route {
132 fn read<R: io::Read>(reader: &mut R) -> Result<Route, DecodeError> {
133 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
134 let path_count: u64 = Readable::read(reader)?;
135 let mut paths = Vec::with_capacity(cmp::min(path_count, 128) as usize);
136 for _ in 0..path_count {
137 let hop_count: u8 = Readable::read(reader)?;
138 let mut hops = Vec::with_capacity(hop_count as usize);
139 for _ in 0..hop_count {
140 hops.push(Readable::read(reader)?);
144 let mut payment_params = None;
145 read_tlv_fields!(reader, {
146 (1, payment_params, option),
148 Ok(Route { paths, payment_params })
152 /// Parameters needed to find a [`Route`].
154 /// Passed to [`find_route`] and [`build_route_from_hops`], but also provided in
155 /// [`Event::PaymentPathFailed`] for retrying a failed payment path.
157 /// [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed
158 #[derive(Clone, Debug)]
159 pub struct RouteParameters {
160 /// The parameters of the failed payment path.
161 pub payment_params: PaymentParameters,
163 /// The amount in msats sent on the failed payment path.
164 pub final_value_msat: u64,
166 /// The CLTV on the final hop of the failed payment path.
167 pub final_cltv_expiry_delta: u32,
170 impl_writeable_tlv_based!(RouteParameters, {
171 (0, payment_params, required),
172 (2, final_value_msat, required),
173 (4, final_cltv_expiry_delta, required),
176 /// Maximum total CTLV difference we allow for a full payment path.
177 pub const DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA: u32 = 1008;
179 /// Maximum number of paths we allow an (MPP) payment to have.
180 // The default limit is currently set rather arbitrary - there aren't any real fundamental path-count
181 // limits, but for now more than 10 paths likely carries too much one-path failure.
182 pub const DEFAULT_MAX_PATH_COUNT: u8 = 10;
184 // The median hop CLTV expiry delta currently seen in the network.
185 const MEDIAN_HOP_CLTV_EXPIRY_DELTA: u32 = 40;
187 // During routing, we only consider paths shorter than our maximum length estimate.
188 // In the legacy onion format, the maximum number of hops used to be a fixed value of 20.
189 // However, in the TLV onion format, there is no fixed maximum length, but the `hop_payloads`
190 // field is always 1300 bytes. As the `tlv_payload` for each hop may vary in length, we have to
191 // estimate how many hops the route may have so that it actually fits the `hop_payloads` field.
193 // We estimate 3+32 (payload length and HMAC) + 2+8 (amt_to_forward) + 2+4 (outgoing_cltv_value) +
194 // 2+8 (short_channel_id) = 61 bytes for each intermediate hop and 3+32
195 // (payload length and HMAC) + 2+8 (amt_to_forward) + 2+4 (outgoing_cltv_value) + 2+32+8
196 // (payment_secret and total_msat) = 93 bytes for the final hop.
197 // Since the length of the potentially included `payment_metadata` is unknown to us, we round
198 // down from (1300-93) / 61 = 19.78... to arrive at a conservative estimate of 19.
199 const MAX_PATH_LENGTH_ESTIMATE: u8 = 19;
201 /// The recipient of a payment.
202 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
203 pub struct PaymentParameters {
204 /// The node id of the payee.
205 pub payee_pubkey: PublicKey,
207 /// Features supported by the payee.
209 /// May be set from the payee's invoice or via [`for_keysend`]. May be `None` if the invoice
210 /// does not contain any features.
212 /// [`for_keysend`]: Self::for_keysend
213 pub features: Option<InvoiceFeatures>,
215 /// Hints for routing to the payee, containing channels connecting the payee to public nodes.
216 pub route_hints: Vec<RouteHint>,
218 /// Expiration of a payment to the payee, in seconds relative to the UNIX epoch.
219 pub expiry_time: Option<u64>,
221 /// The maximum total CLTV delta we accept for the route.
222 /// Defaults to [`DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA`].
223 pub max_total_cltv_expiry_delta: u32,
225 /// The maximum number of paths that may be used by (MPP) payments.
226 /// Defaults to [`DEFAULT_MAX_PATH_COUNT`].
227 pub max_path_count: u8,
229 /// Selects the maximum share of a channel's total capacity which will be sent over a channel,
230 /// as a power of 1/2. A higher value prefers to send the payment using more MPP parts whereas
231 /// a lower value prefers to send larger MPP parts, potentially saturating channels and
232 /// increasing failure probability for those paths.
234 /// Note that this restriction will be relaxed during pathfinding after paths which meet this
235 /// restriction have been found. While paths which meet this criteria will be searched for, it
236 /// is ultimately up to the scorer to select them over other paths.
238 /// A value of 0 will allow payments up to and including a channel's total announced usable
239 /// capacity, a value of one will only use up to half its capacity, two 1/4, etc.
242 pub max_channel_saturation_power_of_half: u8,
245 impl_writeable_tlv_based!(PaymentParameters, {
246 (0, payee_pubkey, required),
247 (1, max_total_cltv_expiry_delta, (default_value, DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA)),
248 (2, features, option),
249 (3, max_path_count, (default_value, DEFAULT_MAX_PATH_COUNT)),
250 (4, route_hints, vec_type),
251 (5, max_channel_saturation_power_of_half, (default_value, 1)),
252 (6, expiry_time, option),
255 impl PaymentParameters {
256 /// Creates a payee with the node id of the given `pubkey`.
257 pub fn from_node_id(payee_pubkey: PublicKey) -> Self {
263 max_total_cltv_expiry_delta: DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA,
264 max_path_count: DEFAULT_MAX_PATH_COUNT,
265 max_channel_saturation_power_of_half: 1,
269 /// Creates a payee with the node id of the given `pubkey` to use for keysend payments.
270 pub fn for_keysend(payee_pubkey: PublicKey) -> Self {
271 Self::from_node_id(payee_pubkey).with_features(InvoiceFeatures::for_keysend())
274 /// Includes the payee's features.
276 /// (C-not exported) since bindings don't support move semantics
277 pub fn with_features(self, features: InvoiceFeatures) -> Self {
278 Self { features: Some(features), ..self }
281 /// Includes hints for routing to the payee.
283 /// (C-not exported) since bindings don't support move semantics
284 pub fn with_route_hints(self, route_hints: Vec<RouteHint>) -> Self {
285 Self { route_hints, ..self }
288 /// Includes a payment expiration in seconds relative to the UNIX epoch.
290 /// (C-not exported) since bindings don't support move semantics
291 pub fn with_expiry_time(self, expiry_time: u64) -> Self {
292 Self { expiry_time: Some(expiry_time), ..self }
295 /// Includes a limit for the total CLTV expiry delta which is considered during routing
297 /// (C-not exported) since bindings don't support move semantics
298 pub fn with_max_total_cltv_expiry_delta(self, max_total_cltv_expiry_delta: u32) -> Self {
299 Self { max_total_cltv_expiry_delta, ..self }
302 /// Includes a limit for the maximum number of payment paths that may be used.
304 /// (C-not exported) since bindings don't support move semantics
305 pub fn with_max_path_count(self, max_path_count: u8) -> Self {
306 Self { max_path_count, ..self }
309 /// Includes a limit for the maximum number of payment paths that may be used.
311 /// (C-not exported) since bindings don't support move semantics
312 pub fn with_max_channel_saturation_power_of_half(self, max_channel_saturation_power_of_half: u8) -> Self {
313 Self { max_channel_saturation_power_of_half, ..self }
317 /// A list of hops along a payment path terminating with a channel to the recipient.
318 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
319 pub struct RouteHint(pub Vec<RouteHintHop>);
321 impl Writeable for RouteHint {
322 fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
323 (self.0.len() as u64).write(writer)?;
324 for hop in self.0.iter() {
331 impl Readable for RouteHint {
332 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
333 let hop_count: u64 = Readable::read(reader)?;
334 let mut hops = Vec::with_capacity(cmp::min(hop_count, 16) as usize);
335 for _ in 0..hop_count {
336 hops.push(Readable::read(reader)?);
342 /// A channel descriptor for a hop along a payment path.
343 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
344 pub struct RouteHintHop {
345 /// The node_id of the non-target end of the route
346 pub src_node_id: PublicKey,
347 /// The short_channel_id of this channel
348 pub short_channel_id: u64,
349 /// The fees which must be paid to use this channel
350 pub fees: RoutingFees,
351 /// The difference in CLTV values between this node and the next node.
352 pub cltv_expiry_delta: u16,
353 /// The minimum value, in msat, which must be relayed to the next hop.
354 pub htlc_minimum_msat: Option<u64>,
355 /// The maximum value in msat available for routing with a single HTLC.
356 pub htlc_maximum_msat: Option<u64>,
359 impl_writeable_tlv_based!(RouteHintHop, {
360 (0, src_node_id, required),
361 (1, htlc_minimum_msat, option),
362 (2, short_channel_id, required),
363 (3, htlc_maximum_msat, option),
365 (6, cltv_expiry_delta, required),
368 #[derive(Eq, PartialEq)]
369 struct RouteGraphNode {
371 lowest_fee_to_peer_through_node: u64,
372 lowest_fee_to_node: u64,
373 total_cltv_delta: u32,
374 // The maximum value a yet-to-be-constructed payment path might flow through this node.
375 // This value is upper-bounded by us by:
376 // - how much is needed for a path being constructed
377 // - how much value can channels following this node (up to the destination) can contribute,
378 // considering their capacity and fees
379 value_contribution_msat: u64,
380 /// The effective htlc_minimum_msat at this hop. If a later hop on the path had a higher HTLC
381 /// minimum, we use it, plus the fees required at each earlier hop to meet it.
382 path_htlc_minimum_msat: u64,
383 /// All penalties incurred from this hop on the way to the destination, as calculated using
385 path_penalty_msat: u64,
386 /// The number of hops walked up to this node.
387 path_length_to_node: u8,
390 impl cmp::Ord for RouteGraphNode {
391 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
392 let other_score = cmp::max(other.lowest_fee_to_peer_through_node, other.path_htlc_minimum_msat)
393 .saturating_add(other.path_penalty_msat);
394 let self_score = cmp::max(self.lowest_fee_to_peer_through_node, self.path_htlc_minimum_msat)
395 .saturating_add(self.path_penalty_msat);
396 other_score.cmp(&self_score).then_with(|| other.node_id.cmp(&self.node_id))
400 impl cmp::PartialOrd for RouteGraphNode {
401 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
402 Some(self.cmp(other))
406 /// A wrapper around the various hop representations.
408 /// Used to construct a [`PathBuildingHop`] and to estimate [`EffectiveCapacity`].
409 #[derive(Clone, Debug)]
410 enum CandidateRouteHop<'a> {
411 /// A hop from the payer, where the outbound liquidity is known.
413 details: &'a ChannelDetails,
415 /// A hop found in the [`ReadOnlyNetworkGraph`], where the channel capacity may be unknown.
417 info: DirectedChannelInfoWithUpdate<'a>,
418 short_channel_id: u64,
420 /// A hop to the payee found in the payment invoice, though not necessarily a direct channel.
422 hint: &'a RouteHintHop,
426 impl<'a> CandidateRouteHop<'a> {
427 fn short_channel_id(&self) -> u64 {
429 CandidateRouteHop::FirstHop { details } => details.get_outbound_payment_scid().unwrap(),
430 CandidateRouteHop::PublicHop { short_channel_id, .. } => *short_channel_id,
431 CandidateRouteHop::PrivateHop { hint } => hint.short_channel_id,
435 // NOTE: This may alloc memory so avoid calling it in a hot code path.
436 fn features(&self) -> ChannelFeatures {
438 CandidateRouteHop::FirstHop { details } => details.counterparty.features.to_context(),
439 CandidateRouteHop::PublicHop { info, .. } => info.channel().features.clone(),
440 CandidateRouteHop::PrivateHop { .. } => ChannelFeatures::empty(),
444 fn cltv_expiry_delta(&self) -> u32 {
446 CandidateRouteHop::FirstHop { .. } => 0,
447 CandidateRouteHop::PublicHop { info, .. } => info.direction().cltv_expiry_delta as u32,
448 CandidateRouteHop::PrivateHop { hint } => hint.cltv_expiry_delta as u32,
452 fn htlc_minimum_msat(&self) -> u64 {
454 CandidateRouteHop::FirstHop { .. } => 0,
455 CandidateRouteHop::PublicHop { info, .. } => info.direction().htlc_minimum_msat,
456 CandidateRouteHop::PrivateHop { hint } => hint.htlc_minimum_msat.unwrap_or(0),
460 fn fees(&self) -> RoutingFees {
462 CandidateRouteHop::FirstHop { .. } => RoutingFees {
463 base_msat: 0, proportional_millionths: 0,
465 CandidateRouteHop::PublicHop { info, .. } => info.direction().fees,
466 CandidateRouteHop::PrivateHop { hint } => hint.fees,
470 fn effective_capacity(&self) -> EffectiveCapacity {
472 CandidateRouteHop::FirstHop { details } => EffectiveCapacity::ExactLiquidity {
473 liquidity_msat: details.next_outbound_htlc_limit_msat,
475 CandidateRouteHop::PublicHop { info, .. } => info.effective_capacity(),
476 CandidateRouteHop::PrivateHop { .. } => EffectiveCapacity::Infinite,
482 fn max_htlc_from_capacity(capacity: EffectiveCapacity, max_channel_saturation_power_of_half: u8) -> u64 {
483 let saturation_shift: u32 = max_channel_saturation_power_of_half as u32;
485 EffectiveCapacity::ExactLiquidity { liquidity_msat } => liquidity_msat,
486 EffectiveCapacity::Infinite => u64::max_value(),
487 EffectiveCapacity::Unknown => EffectiveCapacity::Unknown.as_msat(),
488 EffectiveCapacity::MaximumHTLC { amount_msat } =>
489 amount_msat.checked_shr(saturation_shift).unwrap_or(0),
490 EffectiveCapacity::Total { capacity_msat, htlc_maximum_msat: None } =>
491 capacity_msat.checked_shr(saturation_shift).unwrap_or(0),
492 EffectiveCapacity::Total { capacity_msat, htlc_maximum_msat: Some(htlc_max) } =>
493 cmp::min(capacity_msat.checked_shr(saturation_shift).unwrap_or(0), htlc_max),
497 fn iter_equal<I1: Iterator, I2: Iterator>(mut iter_a: I1, mut iter_b: I2)
498 -> bool where I1::Item: PartialEq<I2::Item> {
500 let a = iter_a.next();
501 let b = iter_b.next();
502 if a.is_none() && b.is_none() { return true; }
503 if a.is_none() || b.is_none() { return false; }
504 if a.unwrap().ne(&b.unwrap()) { return false; }
508 /// It's useful to keep track of the hops associated with the fees required to use them,
509 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
510 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
511 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
513 struct PathBuildingHop<'a> {
514 // Note that this should be dropped in favor of loading it from CandidateRouteHop, but doing so
515 // is a larger refactor and will require careful performance analysis.
517 candidate: CandidateRouteHop<'a>,
520 /// Minimal fees required to route to the source node of the current hop via any of its inbound channels.
521 src_lowest_inbound_fees: RoutingFees,
522 /// All the fees paid *after* this channel on the way to the destination
523 next_hops_fee_msat: u64,
524 /// Fee paid for the use of the current channel (see candidate.fees()).
525 /// The value will be actually deducted from the counterparty balance on the previous link.
526 hop_use_fee_msat: u64,
527 /// Used to compare channels when choosing the for routing.
528 /// Includes paying for the use of a hop and the following hops, as well as
529 /// an estimated cost of reaching this hop.
530 /// Might get stale when fees are recomputed. Primarily for internal use.
532 /// A mirror of the same field in RouteGraphNode. Note that this is only used during the graph
533 /// walk and may be invalid thereafter.
534 path_htlc_minimum_msat: u64,
535 /// All penalties incurred from this channel on the way to the destination, as calculated using
537 path_penalty_msat: u64,
538 /// If we've already processed a node as the best node, we shouldn't process it again. Normally
539 /// we'd just ignore it if we did as all channels would have a higher new fee, but because we
540 /// may decrease the amounts in use as we walk the graph, the actual calculated fee may
541 /// decrease as well. Thus, we have to explicitly track which nodes have been processed and
542 /// avoid processing them again.
544 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
545 // In tests, we apply further sanity checks on cases where we skip nodes we already processed
546 // to ensure it is specifically in cases where the fee has gone down because of a decrease in
547 // value_contribution_msat, which requires tracking it here. See comments below where it is
548 // used for more info.
549 value_contribution_msat: u64,
552 impl<'a> core::fmt::Debug for PathBuildingHop<'a> {
553 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
554 let mut debug_struct = f.debug_struct("PathBuildingHop");
556 .field("node_id", &self.node_id)
557 .field("short_channel_id", &self.candidate.short_channel_id())
558 .field("total_fee_msat", &self.total_fee_msat)
559 .field("next_hops_fee_msat", &self.next_hops_fee_msat)
560 .field("hop_use_fee_msat", &self.hop_use_fee_msat)
561 .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)))
562 .field("path_penalty_msat", &self.path_penalty_msat)
563 .field("path_htlc_minimum_msat", &self.path_htlc_minimum_msat)
564 .field("cltv_expiry_delta", &self.candidate.cltv_expiry_delta());
565 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
566 let debug_struct = debug_struct
567 .field("value_contribution_msat", &self.value_contribution_msat);
568 debug_struct.finish()
572 // Instantiated with a list of hops with correct data in them collected during path finding,
573 // an instance of this struct should be further modified only via given methods.
575 struct PaymentPath<'a> {
576 hops: Vec<(PathBuildingHop<'a>, NodeFeatures)>,
579 impl<'a> PaymentPath<'a> {
580 // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
581 fn get_value_msat(&self) -> u64 {
582 self.hops.last().unwrap().0.fee_msat
585 fn get_path_penalty_msat(&self) -> u64 {
586 self.hops.first().map(|h| h.0.path_penalty_msat).unwrap_or(u64::max_value())
589 fn get_total_fee_paid_msat(&self) -> u64 {
590 if self.hops.len() < 1 {
594 // Can't use next_hops_fee_msat because it gets outdated.
595 for (i, (hop, _)) in self.hops.iter().enumerate() {
596 if i != self.hops.len() - 1 {
597 result += hop.fee_msat;
603 fn get_cost_msat(&self) -> u64 {
604 self.get_total_fee_paid_msat().saturating_add(self.get_path_penalty_msat())
607 // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
608 // to change fees may result in an inconsistency.
610 // Sometimes we call this function right after constructing a path which is inconsistent in
611 // that it the value being transferred has decreased while we were doing path finding, leading
612 // to the fees being paid not lining up with the actual limits.
614 // Note that this function is not aware of the available_liquidity limit, and thus does not
615 // support increasing the value being transferred beyond what was selected during the initial
617 fn update_value_and_recompute_fees(&mut self, value_msat: u64) {
618 let mut total_fee_paid_msat = 0 as u64;
619 for i in (0..self.hops.len()).rev() {
620 let last_hop = i == self.hops.len() - 1;
622 // For non-last-hop, this value will represent the fees paid on the current hop. It
623 // will consist of the fees for the use of the next hop, and extra fees to match
624 // htlc_minimum_msat of the current channel. Last hop is handled separately.
625 let mut cur_hop_fees_msat = 0;
627 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().0.hop_use_fee_msat;
630 let mut cur_hop = &mut self.hops.get_mut(i).unwrap().0;
631 cur_hop.next_hops_fee_msat = total_fee_paid_msat;
632 // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
633 // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
634 // set it too high just to maliciously take more fees by exploiting this
635 // match htlc_minimum_msat logic.
636 let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
637 if let Some(extra_fees_msat) = cur_hop.candidate.htlc_minimum_msat().checked_sub(cur_hop_transferred_amount_msat) {
638 // Note that there is a risk that *previous hops* (those closer to us, as we go
639 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
641 // This might make us end up with a broken route, although this should be super-rare
642 // in practice, both because of how healthy channels look like, and how we pick
643 // channels in add_entry.
644 // Also, this can't be exploited more heavily than *announce a free path and fail
646 cur_hop_transferred_amount_msat += extra_fees_msat;
647 total_fee_paid_msat += extra_fees_msat;
648 cur_hop_fees_msat += extra_fees_msat;
652 // Final hop is a special case: it usually has just value_msat (by design), but also
653 // it still could overpay for the htlc_minimum_msat.
654 cur_hop.fee_msat = cur_hop_transferred_amount_msat;
656 // Propagate updated fees for the use of the channels to one hop back, where they
657 // will be actually paid (fee_msat). The last hop is handled above separately.
658 cur_hop.fee_msat = cur_hop_fees_msat;
661 // Fee for the use of the current hop which will be deducted on the previous hop.
662 // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
663 // this channel is free for us.
665 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.candidate.fees()) {
666 cur_hop.hop_use_fee_msat = new_fee;
667 total_fee_paid_msat += new_fee;
669 // It should not be possible because this function is called only to reduce the
670 // value. In that case, compute_fee was already called with the same fees for
671 // larger amount and there was no overflow.
679 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
680 let proportional_fee_millions =
681 amount_msat.checked_mul(channel_fees.proportional_millionths as u64);
682 if let Some(new_fee) = proportional_fee_millions.and_then(|part| {
683 (channel_fees.base_msat as u64).checked_add(part / 1_000_000) }) {
687 // This function may be (indirectly) called without any verification,
688 // with channel_fees provided by a caller. We should handle it gracefully.
693 /// The default `features` we assume for a node in a route, when no `features` are known about that
696 /// Default features are:
697 /// * variable_length_onion_optional
698 fn default_node_features() -> NodeFeatures {
699 let mut features = NodeFeatures::empty();
700 features.set_variable_length_onion_optional();
704 /// Finds a route from us (payer) to the given target node (payee).
706 /// If the payee provided features in their invoice, they should be provided via `params.payee`.
707 /// Without this, MPP will only be used if the payee's features are available in the network graph.
709 /// Private routing paths between a public node and the target may be included in `params.payee`.
711 /// If some channels aren't announced, it may be useful to fill in `first_hops` with the results
712 /// from [`ChannelManager::list_usable_channels`]. If it is filled in, the view of these channels
713 /// from `network_graph` will be ignored, and only those in `first_hops` will be used.
715 /// The fees on channels from us to the next hop are ignored as they are assumed to all be equal.
716 /// However, the enabled/disabled bit on such channels as well as the `htlc_minimum_msat` /
717 /// `htlc_maximum_msat` *are* checked as they may change based on the receiving node.
721 /// May be used to re-compute a [`Route`] when handling a [`Event::PaymentPathFailed`]. Any
722 /// adjustments to the [`NetworkGraph`] and channel scores should be made prior to calling this
727 /// Panics if first_hops contains channels without short_channel_ids;
728 /// [`ChannelManager::list_usable_channels`] will never include such channels.
730 /// [`ChannelManager::list_usable_channels`]: crate::ln::channelmanager::ChannelManager::list_usable_channels
731 /// [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed
732 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
733 pub fn find_route<L: Deref, GL: Deref, S: Score>(
734 our_node_pubkey: &PublicKey, route_params: &RouteParameters,
735 network_graph: &NetworkGraph<GL>, first_hops: Option<&[&ChannelDetails]>, logger: L,
736 scorer: &S, random_seed_bytes: &[u8; 32]
737 ) -> Result<Route, LightningError>
738 where L::Target: Logger, GL::Target: Logger {
739 let graph_lock = network_graph.read_only();
740 let mut route = get_route(our_node_pubkey, &route_params.payment_params, &graph_lock, first_hops,
741 route_params.final_value_msat, route_params.final_cltv_expiry_delta, logger, scorer,
743 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
747 pub(crate) fn get_route<L: Deref, S: Score>(
748 our_node_pubkey: &PublicKey, payment_params: &PaymentParameters, network_graph: &ReadOnlyNetworkGraph,
749 first_hops: Option<&[&ChannelDetails]>, final_value_msat: u64, final_cltv_expiry_delta: u32,
750 logger: L, scorer: &S, random_seed_bytes: &[u8; 32]
751 ) -> Result<Route, LightningError>
752 where L::Target: Logger {
753 let payee_node_id = NodeId::from_pubkey(&payment_params.payee_pubkey);
754 let our_node_id = NodeId::from_pubkey(&our_node_pubkey);
756 if payee_node_id == our_node_id {
757 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
760 if final_value_msat > MAX_VALUE_MSAT {
761 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
764 if final_value_msat == 0 {
765 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
768 for route in payment_params.route_hints.iter() {
769 for hop in &route.0 {
770 if hop.src_node_id == payment_params.payee_pubkey {
771 return Err(LightningError{err: "Route hint cannot have the payee as the source.".to_owned(), action: ErrorAction::IgnoreError});
775 if payment_params.max_total_cltv_expiry_delta <= final_cltv_expiry_delta {
776 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});
779 // The general routing idea is the following:
780 // 1. Fill first/last hops communicated by the caller.
781 // 2. Attempt to construct a path from payer to payee for transferring
782 // any ~sufficient (described later) value.
783 // If succeed, remember which channels were used and how much liquidity they have available,
784 // so that future paths don't rely on the same liquidity.
785 // 3. Proceed to the next step if:
786 // - we hit the recommended target value;
787 // - OR if we could not construct a new path. Any next attempt will fail too.
788 // Otherwise, repeat step 2.
789 // 4. See if we managed to collect paths which aggregately are able to transfer target value
790 // (not recommended value).
791 // 5. If yes, proceed. If not, fail routing.
792 // 6. Randomly combine paths into routes having enough to fulfill the payment. (TODO: knapsack)
793 // 7. Of all the found paths, select only those with the lowest total fee.
794 // 8. The last path in every selected route is likely to be more than we need.
795 // Reduce its value-to-transfer and recompute fees.
796 // 9. Choose the best route by the lowest total fee.
798 // As for the actual search algorithm,
799 // we do a payee-to-payer pseudo-Dijkstra's sorting by each node's distance from the payee
800 // plus the minimum per-HTLC fee to get from it to another node (aka "shitty pseudo-A*").
802 // We are not a faithful Dijkstra's implementation because we can change values which impact
803 // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
804 // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) than
805 // the value we are currently attempting to send over a path, we simply reduce the value being
806 // sent along the path for any hops after that channel. This may imply that later fees (which
807 // we've already tabulated) are lower because a smaller value is passing through the channels
808 // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
809 // channels which were selected earlier (and which may still be used for other paths without a
810 // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
813 // One potentially problematic case for this algorithm would be if there are many
814 // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
815 // graph walking), we may never find a path which is not liquidity-limited and has lower
816 // proportional fee (and only lower absolute fee when considering the ultimate value sent).
817 // Because we only consider paths with at least 5% of the total value being sent, the damage
818 // from such a case should be limited, however this could be further reduced in the future by
819 // calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
820 // limits for the purposes of fee calculation.
822 // Alternatively, we could store more detailed path information in the heap (targets, below)
823 // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
824 // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
825 // and practically (as we would need to store dynamically-allocated path information in heap
826 // objects, increasing malloc traffic and indirect memory access significantly). Further, the
827 // results of such an algorithm would likely be biased towards lower-value paths.
829 // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
830 // outside of our current search value, running a path search more times to gather candidate
831 // paths at different values. While this may be acceptable, further path searches may increase
832 // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
833 // graph for candidate paths, calculating the maximum value which can realistically be sent at
834 // the same time, remaining generic across different payment values.
836 // TODO: There are a few tweaks we could do, including possibly pre-calculating more stuff
837 // to use as the A* heuristic beyond just the cost to get one node further than the current
840 let network_channels = network_graph.channels();
841 let network_nodes = network_graph.nodes();
843 if payment_params.max_path_count == 0 {
844 return Err(LightningError{err: "Can't find a route with no paths allowed.".to_owned(), action: ErrorAction::IgnoreError});
847 // Allow MPP only if we have a features set from somewhere that indicates the payee supports
848 // it. If the payee supports it they're supposed to include it in the invoice, so that should
850 let allow_mpp = if payment_params.max_path_count == 1 {
852 } else if let Some(features) = &payment_params.features {
853 features.supports_basic_mpp()
854 } else if let Some(node) = network_nodes.get(&payee_node_id) {
855 if let Some(node_info) = node.announcement_info.as_ref() {
856 node_info.features.supports_basic_mpp()
860 log_trace!(logger, "Searching for a route from payer {} to payee {} {} MPP and {} first hops {}overriding the network graph", our_node_pubkey,
861 payment_params.payee_pubkey, if allow_mpp { "with" } else { "without" },
862 first_hops.map(|hops| hops.len()).unwrap_or(0), if first_hops.is_some() { "" } else { "not " });
865 // Prepare the data we'll use for payee-to-payer search by
866 // inserting first hops suggested by the caller as targets.
867 // Our search will then attempt to reach them while traversing from the payee node.
868 let mut first_hop_targets: HashMap<_, Vec<&ChannelDetails>> =
869 HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
870 if let Some(hops) = first_hops {
872 if chan.get_outbound_payment_scid().is_none() {
873 panic!("first_hops should be filled in with usable channels, not pending ones");
875 if chan.counterparty.node_id == *our_node_pubkey {
876 return Err(LightningError{err: "First hop cannot have our_node_pubkey as a destination.".to_owned(), action: ErrorAction::IgnoreError});
879 .entry(NodeId::from_pubkey(&chan.counterparty.node_id))
880 .or_insert(Vec::new())
883 if first_hop_targets.is_empty() {
884 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
888 // The main heap containing all candidate next-hops sorted by their score (max(A* fee,
889 // htlc_minimum)). Ideally this would be a heap which allowed cheap score reduction instead of
890 // adding duplicate entries when we find a better path to a given node.
891 let mut targets: BinaryHeap<RouteGraphNode> = BinaryHeap::new();
893 // Map from node_id to information about the best current path to that node, including feerate
895 let mut dist: HashMap<NodeId, PathBuildingHop> = HashMap::with_capacity(network_nodes.len());
897 // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
898 // indicating that we may wish to try again with a higher value, potentially paying to meet an
899 // htlc_minimum with extra fees while still finding a cheaper path.
900 let mut hit_minimum_limit;
902 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
903 // We start with a path_value of the exact amount we want, and if that generates a route we may
904 // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
905 // amount we want in total across paths, selecting the best subset at the end.
906 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
907 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
908 let mut path_value_msat = final_value_msat;
910 // Routing Fragmentation Mitigation heuristic:
912 // Routing fragmentation across many payment paths increases the overall routing
913 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
914 // Taking too many smaller paths also increases the chance of payment failure.
915 // Thus to avoid this effect, we require from our collected links to provide
916 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
917 // This requirement is currently set to be 1/max_path_count of the payment
918 // value to ensure we only ever return routes that do not violate this limit.
919 let minimal_value_contribution_msat: u64 = if allow_mpp {
920 (final_value_msat + (payment_params.max_path_count as u64 - 1)) / payment_params.max_path_count as u64
925 // When we start collecting routes we enforce the max_channel_saturation_power_of_half
926 // requirement strictly. After we've collected enough (or if we fail to find new routes) we
927 // drop the requirement by setting this to 0.
928 let mut channel_saturation_pow_half = payment_params.max_channel_saturation_power_of_half;
930 // Keep track of how much liquidity has been used in selected channels. Used to determine
931 // if the channel can be used by additional MPP paths or to inform path finding decisions. It is
932 // aware of direction *only* to ensure that the correct htlc_maximum_msat value is used. Hence,
933 // liquidity used in one direction will not offset any used in the opposite direction.
934 let mut used_channel_liquidities: HashMap<(u64, bool), u64> =
935 HashMap::with_capacity(network_nodes.len());
937 // Keeping track of how much value we already collected across other paths. Helps to decide
938 // when we want to stop looking for new paths.
939 let mut already_collected_value_msat = 0;
941 for (_, channels) in first_hop_targets.iter_mut() {
942 // Sort the first_hops channels to the same node(s) in priority order of which channel we'd
945 // First, if channels are below `recommended_value_msat`, sort them in descending order,
946 // preferring larger channels to avoid splitting the payment into more MPP parts than is
949 // Second, because simply always sorting in descending order would always use our largest
950 // available outbound capacity, needlessly fragmenting our available channel capacities,
951 // sort channels above `recommended_value_msat` in ascending order, preferring channels
952 // which have enough, but not too much, capacity for the payment.
953 channels.sort_unstable_by(|chan_a, chan_b| {
954 if chan_b.next_outbound_htlc_limit_msat < recommended_value_msat || chan_a.next_outbound_htlc_limit_msat < recommended_value_msat {
955 // Sort in descending order
956 chan_b.next_outbound_htlc_limit_msat.cmp(&chan_a.next_outbound_htlc_limit_msat)
958 // Sort in ascending order
959 chan_a.next_outbound_htlc_limit_msat.cmp(&chan_b.next_outbound_htlc_limit_msat)
964 log_trace!(logger, "Building path from {} (payee) to {} (us/payer) for value {} msat.", payment_params.payee_pubkey, our_node_pubkey, final_value_msat);
966 macro_rules! add_entry {
967 // Adds entry which goes from $src_node_id to $dest_node_id over the $candidate hop.
968 // $next_hops_fee_msat represents the fees paid for using all the channels *after* this one,
969 // since that value has to be transferred over this channel.
970 // Returns whether this channel caused an update to `targets`.
971 ( $candidate: expr, $src_node_id: expr, $dest_node_id: expr, $next_hops_fee_msat: expr,
972 $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr,
973 $next_hops_path_penalty_msat: expr, $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => { {
974 // We "return" whether we updated the path at the end, via this:
975 let mut did_add_update_path_to_src_node = false;
976 // Channels to self should not be used. This is more of belt-and-suspenders, because in
977 // practice these cases should be caught earlier:
978 // - for regular channels at channel announcement (TODO)
979 // - for first and last hops early in get_route
980 if $src_node_id != $dest_node_id {
981 let short_channel_id = $candidate.short_channel_id();
982 let effective_capacity = $candidate.effective_capacity();
983 let htlc_maximum_msat = max_htlc_from_capacity(effective_capacity, channel_saturation_pow_half);
985 // It is tricky to subtract $next_hops_fee_msat from available liquidity here.
986 // It may be misleading because we might later choose to reduce the value transferred
987 // over these channels, and the channel which was insufficient might become sufficient.
988 // Worst case: we drop a good channel here because it can't cover the high following
989 // fees caused by one expensive channel, but then this channel could have been used
990 // if the amount being transferred over this path is lower.
991 // We do this for now, but this is a subject for removal.
992 if let Some(mut available_value_contribution_msat) = htlc_maximum_msat.checked_sub($next_hops_fee_msat) {
993 let used_liquidity_msat = used_channel_liquidities
994 .get(&(short_channel_id, $src_node_id < $dest_node_id))
995 .map_or(0, |used_liquidity_msat| {
996 available_value_contribution_msat = available_value_contribution_msat
997 .saturating_sub(*used_liquidity_msat);
1001 // Verify the liquidity offered by this channel complies to the minimal contribution.
1002 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
1003 // Do not consider candidate hops that would exceed the maximum path length.
1004 let path_length_to_node = $next_hops_path_length + 1;
1005 let doesnt_exceed_max_path_length = path_length_to_node <= MAX_PATH_LENGTH_ESTIMATE;
1007 // Do not consider candidates that exceed the maximum total cltv expiry limit.
1008 // In order to already account for some of the privacy enhancing random CLTV
1009 // expiry delta offset we add on top later, we subtract a rough estimate
1010 // (2*MEDIAN_HOP_CLTV_EXPIRY_DELTA) here.
1011 let max_total_cltv_expiry_delta = (payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta)
1012 .checked_sub(2*MEDIAN_HOP_CLTV_EXPIRY_DELTA)
1013 .unwrap_or(payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta);
1014 let hop_total_cltv_delta = ($next_hops_cltv_delta as u32)
1015 .saturating_add($candidate.cltv_expiry_delta());
1016 let doesnt_exceed_cltv_delta_limit = hop_total_cltv_delta <= max_total_cltv_expiry_delta;
1018 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
1019 // Includes paying fees for the use of the following channels.
1020 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
1021 Some(result) => result,
1022 // Can't overflow due to how the values were computed right above.
1023 None => unreachable!(),
1025 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
1026 let over_path_minimum_msat = amount_to_transfer_over_msat >= $candidate.htlc_minimum_msat() &&
1027 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
1029 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
1030 let may_overpay_to_meet_path_minimum_msat =
1031 ((amount_to_transfer_over_msat < $candidate.htlc_minimum_msat() &&
1032 recommended_value_msat > $candidate.htlc_minimum_msat()) ||
1033 (amount_to_transfer_over_msat < $next_hops_path_htlc_minimum_msat &&
1034 recommended_value_msat > $next_hops_path_htlc_minimum_msat));
1036 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
1037 // bother considering this channel. If retrying with recommended_value_msat may
1038 // allow us to hit the HTLC minimum limit, set htlc_minimum_limit so that we go
1039 // around again with a higher amount.
1040 if contributes_sufficient_value && doesnt_exceed_max_path_length &&
1041 doesnt_exceed_cltv_delta_limit && may_overpay_to_meet_path_minimum_msat {
1042 hit_minimum_limit = true;
1043 } else if contributes_sufficient_value && doesnt_exceed_max_path_length &&
1044 doesnt_exceed_cltv_delta_limit && over_path_minimum_msat {
1045 // Note that low contribution here (limited by available_liquidity_msat)
1046 // might violate htlc_minimum_msat on the hops which are next along the
1047 // payment path (upstream to the payee). To avoid that, we recompute
1048 // path fees knowing the final path contribution after constructing it.
1049 let path_htlc_minimum_msat = compute_fees($next_hops_path_htlc_minimum_msat, $candidate.fees())
1050 .and_then(|fee_msat| fee_msat.checked_add($next_hops_path_htlc_minimum_msat))
1051 .map(|fee_msat| cmp::max(fee_msat, $candidate.htlc_minimum_msat()))
1052 .unwrap_or_else(|| u64::max_value());
1053 let hm_entry = dist.entry($src_node_id);
1054 let old_entry = hm_entry.or_insert_with(|| {
1055 // If there was previously no known way to access the source node
1056 // (recall it goes payee-to-payer) of short_channel_id, first add a
1057 // semi-dummy record just to compute the fees to reach the source node.
1058 // This will affect our decision on selecting short_channel_id
1059 // as a way to reach the $dest_node_id.
1060 let mut fee_base_msat = 0;
1061 let mut fee_proportional_millionths = 0;
1062 if let Some(Some(fees)) = network_nodes.get(&$src_node_id).map(|node| node.lowest_inbound_channel_fees) {
1063 fee_base_msat = fees.base_msat;
1064 fee_proportional_millionths = fees.proportional_millionths;
1067 node_id: $dest_node_id.clone(),
1068 candidate: $candidate.clone(),
1070 src_lowest_inbound_fees: RoutingFees {
1071 base_msat: fee_base_msat,
1072 proportional_millionths: fee_proportional_millionths,
1074 next_hops_fee_msat: u64::max_value(),
1075 hop_use_fee_msat: u64::max_value(),
1076 total_fee_msat: u64::max_value(),
1077 path_htlc_minimum_msat,
1078 path_penalty_msat: u64::max_value(),
1079 was_processed: false,
1080 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
1081 value_contribution_msat,
1085 #[allow(unused_mut)] // We only use the mut in cfg(test)
1086 let mut should_process = !old_entry.was_processed;
1087 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
1089 // In test/fuzzing builds, we do extra checks to make sure the skipping
1090 // of already-seen nodes only happens in cases we expect (see below).
1091 if !should_process { should_process = true; }
1095 let mut hop_use_fee_msat = 0;
1096 let mut total_fee_msat = $next_hops_fee_msat;
1098 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
1099 // will have the same effective-fee
1100 if $src_node_id != our_node_id {
1101 match compute_fees(amount_to_transfer_over_msat, $candidate.fees()) {
1102 // max_value means we'll always fail
1103 // the old_entry.total_fee_msat > total_fee_msat check
1104 None => total_fee_msat = u64::max_value(),
1106 hop_use_fee_msat = fee_msat;
1107 total_fee_msat += hop_use_fee_msat;
1108 // When calculating the lowest inbound fees to a node, we
1109 // calculate fees here not based on the actual value we think
1110 // will flow over this channel, but on the minimum value that
1111 // we'll accept flowing over it. The minimum accepted value
1112 // is a constant through each path collection run, ensuring
1113 // consistent basis. Otherwise we may later find a
1114 // different path to the source node that is more expensive,
1115 // but which we consider to be cheaper because we are capacity
1116 // constrained and the relative fee becomes lower.
1117 match compute_fees(minimal_value_contribution_msat, old_entry.src_lowest_inbound_fees)
1118 .map(|a| a.checked_add(total_fee_msat)) {
1123 total_fee_msat = u64::max_value();
1130 let channel_usage = ChannelUsage {
1131 amount_msat: amount_to_transfer_over_msat,
1132 inflight_htlc_msat: used_liquidity_msat,
1135 let channel_penalty_msat = scorer.channel_penalty_msat(
1136 short_channel_id, &$src_node_id, &$dest_node_id, channel_usage
1138 let path_penalty_msat = $next_hops_path_penalty_msat
1139 .saturating_add(channel_penalty_msat);
1140 let new_graph_node = RouteGraphNode {
1141 node_id: $src_node_id,
1142 lowest_fee_to_peer_through_node: total_fee_msat,
1143 lowest_fee_to_node: $next_hops_fee_msat as u64 + hop_use_fee_msat,
1144 total_cltv_delta: hop_total_cltv_delta,
1145 value_contribution_msat: value_contribution_msat,
1146 path_htlc_minimum_msat,
1148 path_length_to_node,
1151 // Update the way of reaching $src_node_id with the given short_channel_id (from $dest_node_id),
1152 // if this way is cheaper than the already known
1153 // (considering the cost to "reach" this channel from the route destination,
1154 // the cost of using this channel,
1155 // and the cost of routing to the source node of this channel).
1156 // Also, consider that htlc_minimum_msat_difference, because we might end up
1157 // paying it. Consider the following exploit:
1158 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
1159 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
1160 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
1161 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
1163 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
1164 // but it may require additional tracking - we don't want to double-count
1165 // the fees included in $next_hops_path_htlc_minimum_msat, but also
1166 // can't use something that may decrease on future hops.
1167 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat)
1168 .saturating_add(old_entry.path_penalty_msat);
1169 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat)
1170 .saturating_add(path_penalty_msat);
1172 if !old_entry.was_processed && new_cost < old_cost {
1173 targets.push(new_graph_node);
1174 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
1175 old_entry.hop_use_fee_msat = hop_use_fee_msat;
1176 old_entry.total_fee_msat = total_fee_msat;
1177 old_entry.node_id = $dest_node_id.clone();
1178 old_entry.candidate = $candidate.clone();
1179 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
1180 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
1181 old_entry.path_penalty_msat = path_penalty_msat;
1182 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
1184 old_entry.value_contribution_msat = value_contribution_msat;
1186 did_add_update_path_to_src_node = true;
1187 } else if old_entry.was_processed && new_cost < old_cost {
1188 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
1190 // If we're skipping processing a node which was previously
1191 // processed even though we found another path to it with a
1192 // cheaper fee, check that it was because the second path we
1193 // found (which we are processing now) has a lower value
1194 // contribution due to an HTLC minimum limit.
1196 // e.g. take a graph with two paths from node 1 to node 2, one
1197 // through channel A, and one through channel B. Channel A and
1198 // B are both in the to-process heap, with their scores set by
1199 // a higher htlc_minimum than fee.
1200 // Channel A is processed first, and the channels onwards from
1201 // node 1 are added to the to-process heap. Thereafter, we pop
1202 // Channel B off of the heap, note that it has a much more
1203 // restrictive htlc_maximum_msat, and recalculate the fees for
1204 // all of node 1's channels using the new, reduced, amount.
1206 // This would be bogus - we'd be selecting a higher-fee path
1207 // with a lower htlc_maximum_msat instead of the one we'd
1208 // already decided to use.
1209 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
1211 value_contribution_msat + path_penalty_msat <
1212 old_entry.value_contribution_msat + old_entry.path_penalty_msat
1220 did_add_update_path_to_src_node
1224 let default_node_features = default_node_features();
1226 // Find ways (channels with destination) to reach a given node and store them
1227 // in the corresponding data structures (routing graph etc).
1228 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
1229 // meaning how much will be paid in fees after this node (to the best of our knowledge).
1230 // This data can later be helpful to optimize routing (pay lower fees).
1231 macro_rules! add_entries_to_cheapest_to_target_node {
1232 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr, $next_hops_value_contribution: expr,
1233 $next_hops_path_htlc_minimum_msat: expr, $next_hops_path_penalty_msat: expr,
1234 $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => {
1235 let skip_node = if let Some(elem) = dist.get_mut(&$node_id) {
1236 let was_processed = elem.was_processed;
1237 elem.was_processed = true;
1240 // Entries are added to dist in add_entry!() when there is a channel from a node.
1241 // Because there are no channels from payee, it will not have a dist entry at this point.
1242 // If we're processing any other node, it is always be the result of a channel from it.
1243 assert_eq!($node_id, payee_node_id);
1248 if let Some(first_channels) = first_hop_targets.get(&$node_id) {
1249 for details in first_channels {
1250 let candidate = CandidateRouteHop::FirstHop { details };
1251 add_entry!(candidate, our_node_id, $node_id, $fee_to_target_msat,
1252 $next_hops_value_contribution,
1253 $next_hops_path_htlc_minimum_msat, $next_hops_path_penalty_msat,
1254 $next_hops_cltv_delta, $next_hops_path_length);
1258 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
1261 &default_node_features
1264 if !features.requires_unknown_bits() {
1265 for chan_id in $node.channels.iter() {
1266 let chan = network_channels.get(chan_id).unwrap();
1267 if !chan.features.requires_unknown_bits() {
1268 let (directed_channel, source) =
1269 chan.as_directed_to(&$node_id).expect("inconsistent NetworkGraph");
1270 if first_hops.is_none() || *source != our_node_id {
1271 if let Some(direction) = directed_channel.direction() {
1272 if direction.enabled {
1273 let candidate = CandidateRouteHop::PublicHop {
1274 info: directed_channel.with_update().unwrap(),
1275 short_channel_id: *chan_id,
1277 add_entry!(candidate, *source, $node_id,
1278 $fee_to_target_msat,
1279 $next_hops_value_contribution,
1280 $next_hops_path_htlc_minimum_msat,
1281 $next_hops_path_penalty_msat,
1282 $next_hops_cltv_delta, $next_hops_path_length);
1293 let mut payment_paths = Vec::<PaymentPath>::new();
1295 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
1296 'paths_collection: loop {
1297 // For every new path, start from scratch, except for used_channel_liquidities, which
1298 // helps to avoid reusing previously selected paths in future iterations.
1301 hit_minimum_limit = false;
1303 // If first hop is a private channel and the only way to reach the payee, this is the only
1304 // place where it could be added.
1305 if let Some(first_channels) = first_hop_targets.get(&payee_node_id) {
1306 for details in first_channels {
1307 let candidate = CandidateRouteHop::FirstHop { details };
1308 let added = add_entry!(candidate, our_node_id, payee_node_id, 0, path_value_msat,
1310 log_trace!(logger, "{} direct route to payee via SCID {}",
1311 if added { "Added" } else { "Skipped" }, candidate.short_channel_id());
1315 // Add the payee as a target, so that the payee-to-payer
1316 // search algorithm knows what to start with.
1317 match network_nodes.get(&payee_node_id) {
1318 // The payee is not in our network graph, so nothing to add here.
1319 // There is still a chance of reaching them via last_hops though,
1320 // so don't yet fail the payment here.
1321 // If not, targets.pop() will not even let us enter the loop in step 2.
1324 add_entries_to_cheapest_to_target_node!(node, payee_node_id, 0, path_value_msat, 0, 0u64, 0, 0);
1329 // If a caller provided us with last hops, add them to routing targets. Since this happens
1330 // earlier than general path finding, they will be somewhat prioritized, although currently
1331 // it matters only if the fees are exactly the same.
1332 for route in payment_params.route_hints.iter().filter(|route| !route.0.is_empty()) {
1333 let first_hop_in_route = &(route.0)[0];
1334 let have_hop_src_in_graph =
1335 // Only add the hops in this route to our candidate set if either
1336 // we have a direct channel to the first hop or the first hop is
1337 // in the regular network graph.
1338 first_hop_targets.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some() ||
1339 network_nodes.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some();
1340 if have_hop_src_in_graph {
1341 // We start building the path from reverse, i.e., from payee
1342 // to the first RouteHintHop in the path.
1343 let hop_iter = route.0.iter().rev();
1344 let prev_hop_iter = core::iter::once(&payment_params.payee_pubkey).chain(
1345 route.0.iter().skip(1).rev().map(|hop| &hop.src_node_id));
1346 let mut hop_used = true;
1347 let mut aggregate_next_hops_fee_msat: u64 = 0;
1348 let mut aggregate_next_hops_path_htlc_minimum_msat: u64 = 0;
1349 let mut aggregate_next_hops_path_penalty_msat: u64 = 0;
1350 let mut aggregate_next_hops_cltv_delta: u32 = 0;
1351 let mut aggregate_next_hops_path_length: u8 = 0;
1353 for (idx, (hop, prev_hop_id)) in hop_iter.zip(prev_hop_iter).enumerate() {
1354 let source = NodeId::from_pubkey(&hop.src_node_id);
1355 let target = NodeId::from_pubkey(&prev_hop_id);
1356 let candidate = network_channels
1357 .get(&hop.short_channel_id)
1358 .and_then(|channel| channel.as_directed_to(&target))
1359 .and_then(|(channel, _)| channel.with_update())
1360 .map(|info| CandidateRouteHop::PublicHop {
1362 short_channel_id: hop.short_channel_id,
1364 .unwrap_or_else(|| CandidateRouteHop::PrivateHop { hint: hop });
1366 if !add_entry!(candidate, source, target, aggregate_next_hops_fee_msat,
1367 path_value_msat, aggregate_next_hops_path_htlc_minimum_msat,
1368 aggregate_next_hops_path_penalty_msat,
1369 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length) {
1370 // If this hop was not used then there is no use checking the preceding
1371 // hops in the RouteHint. We can break by just searching for a direct
1372 // channel between last checked hop and first_hop_targets.
1376 let used_liquidity_msat = used_channel_liquidities
1377 .get(&(hop.short_channel_id, source < target)).copied().unwrap_or(0);
1378 let channel_usage = ChannelUsage {
1379 amount_msat: final_value_msat + aggregate_next_hops_fee_msat,
1380 inflight_htlc_msat: used_liquidity_msat,
1381 effective_capacity: candidate.effective_capacity(),
1383 let channel_penalty_msat = scorer.channel_penalty_msat(
1384 hop.short_channel_id, &source, &target, channel_usage
1386 aggregate_next_hops_path_penalty_msat = aggregate_next_hops_path_penalty_msat
1387 .saturating_add(channel_penalty_msat);
1389 aggregate_next_hops_cltv_delta = aggregate_next_hops_cltv_delta
1390 .saturating_add(hop.cltv_expiry_delta as u32);
1392 aggregate_next_hops_path_length = aggregate_next_hops_path_length
1395 // Searching for a direct channel between last checked hop and first_hop_targets
1396 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&prev_hop_id)) {
1397 for details in first_channels {
1398 let candidate = CandidateRouteHop::FirstHop { details };
1399 add_entry!(candidate, our_node_id, NodeId::from_pubkey(&prev_hop_id),
1400 aggregate_next_hops_fee_msat, path_value_msat,
1401 aggregate_next_hops_path_htlc_minimum_msat,
1402 aggregate_next_hops_path_penalty_msat, aggregate_next_hops_cltv_delta,
1403 aggregate_next_hops_path_length);
1411 // In the next values of the iterator, the aggregate fees already reflects
1412 // the sum of value sent from payer (final_value_msat) and routing fees
1413 // for the last node in the RouteHint. We need to just add the fees to
1414 // route through the current node so that the preceding node (next iteration)
1416 let hops_fee = compute_fees(aggregate_next_hops_fee_msat + final_value_msat, hop.fees)
1417 .map_or(None, |inc| inc.checked_add(aggregate_next_hops_fee_msat));
1418 aggregate_next_hops_fee_msat = if let Some(val) = hops_fee { val } else { break; };
1420 let hop_htlc_minimum_msat = candidate.htlc_minimum_msat();
1421 let hop_htlc_minimum_msat_inc = if let Some(val) = compute_fees(aggregate_next_hops_path_htlc_minimum_msat, hop.fees) { val } else { break; };
1422 let hops_path_htlc_minimum = aggregate_next_hops_path_htlc_minimum_msat
1423 .checked_add(hop_htlc_minimum_msat_inc);
1424 aggregate_next_hops_path_htlc_minimum_msat = if let Some(val) = hops_path_htlc_minimum { cmp::max(hop_htlc_minimum_msat, val) } else { break; };
1426 if idx == route.0.len() - 1 {
1427 // The last hop in this iterator is the first hop in
1428 // overall RouteHint.
1429 // If this hop connects to a node with which we have a direct channel,
1430 // ignore the network graph and, if the last hop was added, add our
1431 // direct channel to the candidate set.
1433 // Note that we *must* check if the last hop was added as `add_entry`
1434 // always assumes that the third argument is a node to which we have a
1436 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&hop.src_node_id)) {
1437 for details in first_channels {
1438 let candidate = CandidateRouteHop::FirstHop { details };
1439 add_entry!(candidate, our_node_id,
1440 NodeId::from_pubkey(&hop.src_node_id),
1441 aggregate_next_hops_fee_msat, path_value_msat,
1442 aggregate_next_hops_path_htlc_minimum_msat,
1443 aggregate_next_hops_path_penalty_msat,
1444 aggregate_next_hops_cltv_delta,
1445 aggregate_next_hops_path_length);
1453 log_trace!(logger, "Starting main path collection loop with {} nodes pre-filled from first/last hops.", targets.len());
1455 // At this point, targets are filled with the data from first and
1456 // last hops communicated by the caller, and the payment receiver.
1457 let mut found_new_path = false;
1460 // If this loop terminates due the exhaustion of targets, two situations are possible:
1461 // - not enough outgoing liquidity:
1462 // 0 < already_collected_value_msat < final_value_msat
1463 // - enough outgoing liquidity:
1464 // final_value_msat <= already_collected_value_msat < recommended_value_msat
1465 // Both these cases (and other cases except reaching recommended_value_msat) mean that
1466 // paths_collection will be stopped because found_new_path==false.
1467 // This is not necessarily a routing failure.
1468 'path_construction: while let Some(RouteGraphNode { node_id, lowest_fee_to_node, total_cltv_delta, value_contribution_msat, path_htlc_minimum_msat, path_penalty_msat, path_length_to_node, .. }) = targets.pop() {
1470 // Since we're going payee-to-payer, hitting our node as a target means we should stop
1471 // traversing the graph and arrange the path out of what we found.
1472 if node_id == our_node_id {
1473 let mut new_entry = dist.remove(&our_node_id).unwrap();
1474 let mut ordered_hops: Vec<(PathBuildingHop, NodeFeatures)> = vec!((new_entry.clone(), default_node_features.clone()));
1477 let mut features_set = false;
1478 if let Some(first_channels) = first_hop_targets.get(&ordered_hops.last().unwrap().0.node_id) {
1479 for details in first_channels {
1480 if details.get_outbound_payment_scid().unwrap() == ordered_hops.last().unwrap().0.candidate.short_channel_id() {
1481 ordered_hops.last_mut().unwrap().1 = details.counterparty.features.to_context();
1482 features_set = true;
1488 if let Some(node) = network_nodes.get(&ordered_hops.last().unwrap().0.node_id) {
1489 if let Some(node_info) = node.announcement_info.as_ref() {
1490 ordered_hops.last_mut().unwrap().1 = node_info.features.clone();
1492 ordered_hops.last_mut().unwrap().1 = default_node_features.clone();
1495 // We can fill in features for everything except hops which were
1496 // provided via the invoice we're paying. We could guess based on the
1497 // recipient's features but for now we simply avoid guessing at all.
1501 // Means we succesfully traversed from the payer to the payee, now
1502 // save this path for the payment route. Also, update the liquidity
1503 // remaining on the used hops, so that we take them into account
1504 // while looking for more paths.
1505 if ordered_hops.last().unwrap().0.node_id == payee_node_id {
1509 new_entry = match dist.remove(&ordered_hops.last().unwrap().0.node_id) {
1510 Some(payment_hop) => payment_hop,
1511 // We can't arrive at None because, if we ever add an entry to targets,
1512 // we also fill in the entry in dist (see add_entry!).
1513 None => unreachable!(),
1515 // We "propagate" the fees one hop backward (topologically) here,
1516 // so that fees paid for a HTLC forwarding on the current channel are
1517 // associated with the previous channel (where they will be subtracted).
1518 ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
1519 ordered_hops.push((new_entry.clone(), default_node_features.clone()));
1521 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
1522 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
1524 log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: \n {:#?}",
1525 ordered_hops.len(), value_contribution_msat, ordered_hops.iter().map(|h| &(h.0)).collect::<Vec<&PathBuildingHop>>());
1527 let mut payment_path = PaymentPath {hops: ordered_hops};
1529 // We could have possibly constructed a slightly inconsistent path: since we reduce
1530 // value being transferred along the way, we could have violated htlc_minimum_msat
1531 // on some channels we already passed (assuming dest->source direction). Here, we
1532 // recompute the fees again, so that if that's the case, we match the currently
1533 // underpaid htlc_minimum_msat with fees.
1534 payment_path.update_value_and_recompute_fees(cmp::min(value_contribution_msat, final_value_msat));
1536 // Since a path allows to transfer as much value as
1537 // the smallest channel it has ("bottleneck"), we should recompute
1538 // the fees so sender HTLC don't overpay fees when traversing
1539 // larger channels than the bottleneck. This may happen because
1540 // when we were selecting those channels we were not aware how much value
1541 // this path will transfer, and the relative fee for them
1542 // might have been computed considering a larger value.
1543 // Remember that we used these channels so that we don't rely
1544 // on the same liquidity in future paths.
1545 let mut prevented_redundant_path_selection = false;
1546 let prev_hop_iter = core::iter::once(&our_node_id)
1547 .chain(payment_path.hops.iter().map(|(hop, _)| &hop.node_id));
1548 for (prev_hop, (hop, _)) in prev_hop_iter.zip(payment_path.hops.iter()) {
1549 let spent_on_hop_msat = value_contribution_msat + hop.next_hops_fee_msat;
1550 let used_liquidity_msat = used_channel_liquidities
1551 .entry((hop.candidate.short_channel_id(), *prev_hop < hop.node_id))
1552 .and_modify(|used_liquidity_msat| *used_liquidity_msat += spent_on_hop_msat)
1553 .or_insert(spent_on_hop_msat);
1554 let hop_capacity = hop.candidate.effective_capacity();
1555 let hop_max_msat = max_htlc_from_capacity(hop_capacity, channel_saturation_pow_half);
1556 if *used_liquidity_msat == hop_max_msat {
1557 // If this path used all of this channel's available liquidity, we know
1558 // this path will not be selected again in the next loop iteration.
1559 prevented_redundant_path_selection = true;
1561 debug_assert!(*used_liquidity_msat <= hop_max_msat);
1563 if !prevented_redundant_path_selection {
1564 // If we weren't capped by hitting a liquidity limit on a channel in the path,
1565 // we'll probably end up picking the same path again on the next iteration.
1566 // Decrease the available liquidity of a hop in the middle of the path.
1567 let victim_scid = payment_path.hops[(payment_path.hops.len()) / 2].0.candidate.short_channel_id();
1568 let exhausted = u64::max_value();
1569 log_trace!(logger, "Disabling channel {} for future path building iterations to avoid duplicates.", victim_scid);
1570 *used_channel_liquidities.entry((victim_scid, false)).or_default() = exhausted;
1571 *used_channel_liquidities.entry((victim_scid, true)).or_default() = exhausted;
1574 // Track the total amount all our collected paths allow to send so that we know
1575 // when to stop looking for more paths
1576 already_collected_value_msat += value_contribution_msat;
1578 payment_paths.push(payment_path);
1579 found_new_path = true;
1580 break 'path_construction;
1583 // If we found a path back to the payee, we shouldn't try to process it again. This is
1584 // the equivalent of the `elem.was_processed` check in
1585 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
1586 if node_id == payee_node_id { continue 'path_construction; }
1588 // Otherwise, since the current target node is not us,
1589 // keep "unrolling" the payment graph from payee to payer by
1590 // finding a way to reach the current target from the payer side.
1591 match network_nodes.get(&node_id) {
1594 add_entries_to_cheapest_to_target_node!(node, node_id, lowest_fee_to_node,
1595 value_contribution_msat, path_htlc_minimum_msat, path_penalty_msat,
1596 total_cltv_delta, path_length_to_node);
1602 if !found_new_path && channel_saturation_pow_half != 0 {
1603 channel_saturation_pow_half = 0;
1604 continue 'paths_collection;
1606 // If we don't support MPP, no use trying to gather more value ever.
1607 break 'paths_collection;
1611 // Stop either when the recommended value is reached or if no new path was found in this
1613 // In the latter case, making another path finding attempt won't help,
1614 // because we deterministically terminated the search due to low liquidity.
1615 if !found_new_path && channel_saturation_pow_half != 0 {
1616 channel_saturation_pow_half = 0;
1617 } else if already_collected_value_msat >= recommended_value_msat || !found_new_path {
1618 log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
1619 already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
1620 break 'paths_collection;
1621 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
1622 // Further, if this was our first walk of the graph, and we weren't limited by an
1623 // htlc_minimum_msat, return immediately because this path should suffice. If we were
1624 // limited by an htlc_minimum_msat value, find another path with a higher value,
1625 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
1626 // still keeping a lower total fee than this path.
1627 if !hit_minimum_limit {
1628 log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
1629 break 'paths_collection;
1631 log_trace!(logger, "Collected our payment amount on the first pass, but running again to collect extra paths with a potentially higher limit.");
1632 path_value_msat = recommended_value_msat;
1637 if payment_paths.len() == 0 {
1638 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1641 if already_collected_value_msat < final_value_msat {
1642 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1645 // Sort by total fees and take the best paths.
1646 payment_paths.sort_unstable_by_key(|path| path.get_total_fee_paid_msat());
1647 if payment_paths.len() > 50 {
1648 payment_paths.truncate(50);
1651 // Draw multiple sufficient routes by randomly combining the selected paths.
1652 let mut drawn_routes = Vec::new();
1653 let mut prng = ChaCha20::new(random_seed_bytes, &[0u8; 12]);
1654 let mut random_index_bytes = [0u8; ::core::mem::size_of::<usize>()];
1656 let num_permutations = payment_paths.len();
1657 for _ in 0..num_permutations {
1658 let mut cur_route = Vec::<PaymentPath>::new();
1659 let mut aggregate_route_value_msat = 0;
1662 // Do a Fisher-Yates shuffle to create a random permutation of the payment paths
1663 for cur_index in (1..payment_paths.len()).rev() {
1664 prng.process_in_place(&mut random_index_bytes);
1665 let random_index = usize::from_be_bytes(random_index_bytes).wrapping_rem(cur_index+1);
1666 payment_paths.swap(cur_index, random_index);
1670 for payment_path in &payment_paths {
1671 cur_route.push(payment_path.clone());
1672 aggregate_route_value_msat += payment_path.get_value_msat();
1673 if aggregate_route_value_msat > final_value_msat {
1674 // Last path likely overpaid. Substract it from the most expensive
1675 // (in terms of proportional fee) path in this route and recompute fees.
1676 // This might be not the most economically efficient way, but fewer paths
1677 // also makes routing more reliable.
1678 let mut overpaid_value_msat = aggregate_route_value_msat - final_value_msat;
1680 // First, we drop some expensive low-value paths entirely if possible, since fewer
1681 // paths is better: the payment is less likely to fail. In order to do so, we sort
1682 // by value and fall back to total fees paid, i.e., in case of equal values we
1683 // prefer lower cost paths.
1684 cur_route.sort_unstable_by(|a, b| {
1685 a.get_value_msat().cmp(&b.get_value_msat())
1686 // Reverse ordering for cost, so we drop higher-cost paths first
1687 .then_with(|| b.get_cost_msat().cmp(&a.get_cost_msat()))
1690 // We should make sure that at least 1 path left.
1691 let mut paths_left = cur_route.len();
1692 cur_route.retain(|path| {
1693 if paths_left == 1 {
1696 let mut keep = true;
1697 let path_value_msat = path.get_value_msat();
1698 if path_value_msat <= overpaid_value_msat {
1700 overpaid_value_msat -= path_value_msat;
1706 if overpaid_value_msat == 0 {
1710 assert!(cur_route.len() > 0);
1713 // Now, subtract the overpaid value from the most-expensive path.
1714 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1715 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1716 cur_route.sort_unstable_by_key(|path| { path.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>() });
1717 let expensive_payment_path = cur_route.first_mut().unwrap();
1719 // We already dropped all the small value paths above, meaning all the
1720 // remaining paths are larger than remaining overpaid_value_msat.
1721 // Thus, this can't be negative.
1722 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
1723 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
1727 drawn_routes.push(cur_route);
1731 // Select the best route by lowest total cost.
1732 drawn_routes.sort_unstable_by_key(|paths| paths.iter().map(|path| path.get_cost_msat()).sum::<u64>());
1733 let selected_route = drawn_routes.first_mut().unwrap();
1735 // Sort by the path itself and combine redundant paths.
1736 // Note that we sort by SCIDs alone as its simpler but when combining we have to ensure we
1737 // compare both SCIDs and NodeIds as individual nodes may use random aliases causing collisions
1739 selected_route.sort_unstable_by_key(|path| {
1740 let mut key = [0u64; MAX_PATH_LENGTH_ESTIMATE as usize];
1741 debug_assert!(path.hops.len() <= key.len());
1742 for (scid, key) in path.hops.iter().map(|h| h.0.candidate.short_channel_id()).zip(key.iter_mut()) {
1747 for idx in 0..(selected_route.len() - 1) {
1748 if idx + 1 >= selected_route.len() { break; }
1749 if iter_equal(selected_route[idx ].hops.iter().map(|h| (h.0.candidate.short_channel_id(), h.0.node_id)),
1750 selected_route[idx + 1].hops.iter().map(|h| (h.0.candidate.short_channel_id(), h.0.node_id))) {
1751 let new_value = selected_route[idx].get_value_msat() + selected_route[idx + 1].get_value_msat();
1752 selected_route[idx].update_value_and_recompute_fees(new_value);
1753 selected_route.remove(idx + 1);
1757 let mut selected_paths = Vec::<Vec<Result<RouteHop, LightningError>>>::new();
1758 for payment_path in selected_route {
1759 let mut path = payment_path.hops.iter().map(|(payment_hop, node_features)| {
1761 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)})?,
1762 node_features: node_features.clone(),
1763 short_channel_id: payment_hop.candidate.short_channel_id(),
1764 channel_features: payment_hop.candidate.features(),
1765 fee_msat: payment_hop.fee_msat,
1766 cltv_expiry_delta: payment_hop.candidate.cltv_expiry_delta(),
1768 }).collect::<Vec<_>>();
1769 // Propagate the cltv_expiry_delta one hop backwards since the delta from the current hop is
1770 // applicable for the previous hop.
1771 path.iter_mut().rev().fold(final_cltv_expiry_delta, |prev_cltv_expiry_delta, hop| {
1772 core::mem::replace(&mut hop.as_mut().unwrap().cltv_expiry_delta, prev_cltv_expiry_delta)
1774 selected_paths.push(path);
1776 // Make sure we would never create a route with more paths than we allow.
1777 debug_assert!(selected_paths.len() <= payment_params.max_path_count.into());
1779 if let Some(features) = &payment_params.features {
1780 for path in selected_paths.iter_mut() {
1781 if let Ok(route_hop) = path.last_mut().unwrap() {
1782 route_hop.node_features = features.to_context();
1788 paths: selected_paths.into_iter().map(|path| path.into_iter().collect()).collect::<Result<Vec<_>, _>>()?,
1789 payment_params: Some(payment_params.clone()),
1791 log_info!(logger, "Got route to {}: {}", payment_params.payee_pubkey, log_route!(route));
1795 // When an adversarial intermediary node observes a payment, it may be able to infer its
1796 // destination, if the remaining CLTV expiry delta exactly matches a feasible path in the network
1797 // graph. In order to improve privacy, this method obfuscates the CLTV expiry deltas along the
1798 // payment path by adding a randomized 'shadow route' offset to the final hop.
1799 fn add_random_cltv_offset(route: &mut Route, payment_params: &PaymentParameters,
1800 network_graph: &ReadOnlyNetworkGraph, random_seed_bytes: &[u8; 32]
1802 let network_channels = network_graph.channels();
1803 let network_nodes = network_graph.nodes();
1805 for path in route.paths.iter_mut() {
1806 let mut shadow_ctlv_expiry_delta_offset: u32 = 0;
1808 // Remember the last three nodes of the random walk and avoid looping back on them.
1809 // Init with the last three nodes from the actual path, if possible.
1810 let mut nodes_to_avoid: [NodeId; 3] = [NodeId::from_pubkey(&path.last().unwrap().pubkey),
1811 NodeId::from_pubkey(&path.get(path.len().saturating_sub(2)).unwrap().pubkey),
1812 NodeId::from_pubkey(&path.get(path.len().saturating_sub(3)).unwrap().pubkey)];
1814 // Choose the last publicly known node as the starting point for the random walk.
1815 let mut cur_hop: Option<NodeId> = None;
1816 let mut path_nonce = [0u8; 12];
1817 if let Some(starting_hop) = path.iter().rev()
1818 .find(|h| network_nodes.contains_key(&NodeId::from_pubkey(&h.pubkey))) {
1819 cur_hop = Some(NodeId::from_pubkey(&starting_hop.pubkey));
1820 path_nonce.copy_from_slice(&cur_hop.unwrap().as_slice()[..12]);
1823 // Init PRNG with the path-dependant nonce, which is static for private paths.
1824 let mut prng = ChaCha20::new(random_seed_bytes, &path_nonce);
1825 let mut random_path_bytes = [0u8; ::core::mem::size_of::<usize>()];
1827 // Pick a random path length in [1 .. 3]
1828 prng.process_in_place(&mut random_path_bytes);
1829 let random_walk_length = usize::from_be_bytes(random_path_bytes).wrapping_rem(3).wrapping_add(1);
1831 for random_hop in 0..random_walk_length {
1832 // If we don't find a suitable offset in the public network graph, we default to
1833 // MEDIAN_HOP_CLTV_EXPIRY_DELTA.
1834 let mut random_hop_offset = MEDIAN_HOP_CLTV_EXPIRY_DELTA;
1836 if let Some(cur_node_id) = cur_hop {
1837 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
1838 // Randomly choose the next unvisited hop.
1839 prng.process_in_place(&mut random_path_bytes);
1840 if let Some(random_channel) = usize::from_be_bytes(random_path_bytes)
1841 .checked_rem(cur_node.channels.len())
1842 .and_then(|index| cur_node.channels.get(index))
1843 .and_then(|id| network_channels.get(id)) {
1844 random_channel.as_directed_from(&cur_node_id).map(|(dir_info, next_id)| {
1845 if !nodes_to_avoid.iter().any(|x| x == next_id) {
1846 nodes_to_avoid[random_hop] = *next_id;
1847 dir_info.direction().map(|channel_update_info| {
1848 random_hop_offset = channel_update_info.cltv_expiry_delta.into();
1849 cur_hop = Some(*next_id);
1857 shadow_ctlv_expiry_delta_offset = shadow_ctlv_expiry_delta_offset
1858 .checked_add(random_hop_offset)
1859 .unwrap_or(shadow_ctlv_expiry_delta_offset);
1862 // Limit the total offset to reduce the worst-case locked liquidity timevalue
1863 const MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET: u32 = 3*144;
1864 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET);
1866 // Limit the offset so we never exceed the max_total_cltv_expiry_delta. To improve plausibility,
1867 // we choose the limit to be the largest possible multiple of MEDIAN_HOP_CLTV_EXPIRY_DELTA.
1868 let path_total_cltv_expiry_delta: u32 = path.iter().map(|h| h.cltv_expiry_delta).sum();
1869 let mut max_path_offset = payment_params.max_total_cltv_expiry_delta - path_total_cltv_expiry_delta;
1870 max_path_offset = cmp::max(
1871 max_path_offset - (max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA),
1872 max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA);
1873 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, max_path_offset);
1875 // Add 'shadow' CLTV offset to the final hop
1876 if let Some(last_hop) = path.last_mut() {
1877 last_hop.cltv_expiry_delta = last_hop.cltv_expiry_delta
1878 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(last_hop.cltv_expiry_delta);
1883 /// Construct a route from us (payer) to the target node (payee) via the given hops (which should
1884 /// exclude the payer, but include the payee). This may be useful, e.g., for probing the chosen path.
1886 /// Re-uses logic from `find_route`, so the restrictions described there also apply here.
1887 pub fn build_route_from_hops<L: Deref, GL: Deref>(
1888 our_node_pubkey: &PublicKey, hops: &[PublicKey], route_params: &RouteParameters,
1889 network_graph: &NetworkGraph<GL>, logger: L, random_seed_bytes: &[u8; 32]
1890 ) -> Result<Route, LightningError>
1891 where L::Target: Logger, GL::Target: Logger {
1892 let graph_lock = network_graph.read_only();
1893 let mut route = build_route_from_hops_internal(
1894 our_node_pubkey, hops, &route_params.payment_params, &graph_lock,
1895 route_params.final_value_msat, route_params.final_cltv_expiry_delta, logger, random_seed_bytes)?;
1896 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
1900 fn build_route_from_hops_internal<L: Deref>(
1901 our_node_pubkey: &PublicKey, hops: &[PublicKey], payment_params: &PaymentParameters,
1902 network_graph: &ReadOnlyNetworkGraph, final_value_msat: u64, final_cltv_expiry_delta: u32,
1903 logger: L, random_seed_bytes: &[u8; 32]
1904 ) -> Result<Route, LightningError> where L::Target: Logger {
1907 our_node_id: NodeId,
1908 hop_ids: [Option<NodeId>; MAX_PATH_LENGTH_ESTIMATE as usize],
1911 impl Score for HopScorer {
1912 fn channel_penalty_msat(&self, _short_channel_id: u64, source: &NodeId, target: &NodeId,
1913 _usage: ChannelUsage) -> u64
1915 let mut cur_id = self.our_node_id;
1916 for i in 0..self.hop_ids.len() {
1917 if let Some(next_id) = self.hop_ids[i] {
1918 if cur_id == *source && next_id == *target {
1929 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
1931 fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
1933 fn probe_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
1935 fn probe_successful(&mut self, _path: &[&RouteHop]) {}
1938 impl<'a> Writeable for HopScorer {
1940 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), io::Error> {
1945 if hops.len() > MAX_PATH_LENGTH_ESTIMATE.into() {
1946 return Err(LightningError{err: "Cannot build a route exceeding the maximum path length.".to_owned(), action: ErrorAction::IgnoreError});
1949 let our_node_id = NodeId::from_pubkey(our_node_pubkey);
1950 let mut hop_ids = [None; MAX_PATH_LENGTH_ESTIMATE as usize];
1951 for i in 0..hops.len() {
1952 hop_ids[i] = Some(NodeId::from_pubkey(&hops[i]));
1955 let scorer = HopScorer { our_node_id, hop_ids };
1957 get_route(our_node_pubkey, payment_params, network_graph, None, final_value_msat,
1958 final_cltv_expiry_delta, logger, &scorer, random_seed_bytes)
1963 use routing::gossip::{NetworkGraph, P2PGossipSync, NodeId};
1964 use routing::router::{get_route, build_route_from_hops_internal, add_random_cltv_offset, default_node_features,
1965 PaymentParameters, Route, RouteHint, RouteHintHop, RouteHop, RoutingFees,
1966 DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA, MAX_PATH_LENGTH_ESTIMATE};
1967 use routing::scoring::{ChannelUsage, Score, ProbabilisticScorer, ProbabilisticScoringParameters};
1968 use chain::transaction::OutPoint;
1969 use chain::keysinterface::KeysInterface;
1970 use ln::features::{ChannelFeatures, InitFeatures, InvoiceFeatures, NodeFeatures};
1971 use ln::msgs::{ErrorAction, LightningError, OptionalField, UnsignedChannelAnnouncement, ChannelAnnouncement, RoutingMessageHandler,
1972 NodeAnnouncement, UnsignedNodeAnnouncement, ChannelUpdate, UnsignedChannelUpdate};
1973 use ln::channelmanager;
1974 use util::test_utils;
1975 use util::chacha20::ChaCha20;
1976 use util::ser::Writeable;
1978 use util::ser::Writer;
1980 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
1981 use bitcoin::hashes::Hash;
1982 use bitcoin::network::constants::Network;
1983 use bitcoin::blockdata::constants::genesis_block;
1984 use bitcoin::blockdata::script::Builder;
1985 use bitcoin::blockdata::opcodes;
1986 use bitcoin::blockdata::transaction::TxOut;
1990 use bitcoin::secp256k1::{PublicKey,SecretKey};
1991 use bitcoin::secp256k1::{Secp256k1, All};
1994 use sync::{self, Arc};
1996 fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
1997 features: InitFeatures, outbound_capacity_msat: u64) -> channelmanager::ChannelDetails {
1998 channelmanager::ChannelDetails {
1999 channel_id: [0; 32],
2000 counterparty: channelmanager::ChannelCounterparty {
2003 unspendable_punishment_reserve: 0,
2004 forwarding_info: None,
2005 outbound_htlc_minimum_msat: None,
2006 outbound_htlc_maximum_msat: None,
2008 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
2011 outbound_scid_alias: None,
2012 inbound_scid_alias: None,
2013 channel_value_satoshis: 0,
2016 outbound_capacity_msat,
2017 next_outbound_htlc_limit_msat: outbound_capacity_msat,
2018 inbound_capacity_msat: 42,
2019 unspendable_punishment_reserve: None,
2020 confirmations_required: None,
2021 force_close_spend_delay: None,
2022 is_outbound: true, is_channel_ready: true,
2023 is_usable: true, is_public: true,
2024 inbound_htlc_minimum_msat: None,
2025 inbound_htlc_maximum_msat: None,
2030 // Using the same keys for LN and BTC ids
2032 gossip_sync: &P2PGossipSync<Arc<NetworkGraph<Arc<test_utils::TestLogger>>>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
2033 secp_ctx: &Secp256k1<All>, node_1_privkey: &SecretKey, node_2_privkey: &SecretKey, features: ChannelFeatures, short_channel_id: u64
2035 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
2036 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
2038 let unsigned_announcement = UnsignedChannelAnnouncement {
2040 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2044 bitcoin_key_1: node_id_1,
2045 bitcoin_key_2: node_id_2,
2046 excess_data: Vec::new(),
2049 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
2050 let valid_announcement = ChannelAnnouncement {
2051 node_signature_1: secp_ctx.sign_ecdsa(&msghash, node_1_privkey),
2052 node_signature_2: secp_ctx.sign_ecdsa(&msghash, node_2_privkey),
2053 bitcoin_signature_1: secp_ctx.sign_ecdsa(&msghash, node_1_privkey),
2054 bitcoin_signature_2: secp_ctx.sign_ecdsa(&msghash, node_2_privkey),
2055 contents: unsigned_announcement.clone(),
2057 match gossip_sync.handle_channel_announcement(&valid_announcement) {
2058 Ok(res) => assert!(res),
2064 gossip_sync: &P2PGossipSync<Arc<NetworkGraph<Arc<test_utils::TestLogger>>>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
2065 secp_ctx: &Secp256k1<All>, node_privkey: &SecretKey, update: UnsignedChannelUpdate
2067 let msghash = hash_to_message!(&Sha256dHash::hash(&update.encode()[..])[..]);
2068 let valid_channel_update = ChannelUpdate {
2069 signature: secp_ctx.sign_ecdsa(&msghash, node_privkey),
2070 contents: update.clone()
2073 match gossip_sync.handle_channel_update(&valid_channel_update) {
2074 Ok(res) => assert!(res),
2079 fn add_or_update_node(
2080 gossip_sync: &P2PGossipSync<Arc<NetworkGraph<Arc<test_utils::TestLogger>>>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
2081 secp_ctx: &Secp256k1<All>, node_privkey: &SecretKey, features: NodeFeatures, timestamp: u32
2083 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
2084 let unsigned_announcement = UnsignedNodeAnnouncement {
2090 addresses: Vec::new(),
2091 excess_address_data: Vec::new(),
2092 excess_data: Vec::new(),
2094 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
2095 let valid_announcement = NodeAnnouncement {
2096 signature: secp_ctx.sign_ecdsa(&msghash, node_privkey),
2097 contents: unsigned_announcement.clone()
2100 match gossip_sync.handle_node_announcement(&valid_announcement) {
2106 fn get_nodes(secp_ctx: &Secp256k1<All>) -> (SecretKey, PublicKey, Vec<SecretKey>, Vec<PublicKey>) {
2107 let privkeys: Vec<SecretKey> = (2..22).map(|i| {
2108 SecretKey::from_slice(&hex::decode(format!("{:02x}", i).repeat(32)).unwrap()[..]).unwrap()
2111 let pubkeys = privkeys.iter().map(|secret| PublicKey::from_secret_key(&secp_ctx, secret)).collect();
2113 let our_privkey = SecretKey::from_slice(&hex::decode("01".repeat(32)).unwrap()[..]).unwrap();
2114 let our_id = PublicKey::from_secret_key(&secp_ctx, &our_privkey);
2116 (our_privkey, our_id, privkeys, pubkeys)
2119 fn id_to_feature_flags(id: u8) -> Vec<u8> {
2120 // Set the feature flags to the id'th odd (ie non-required) feature bit so that we can
2121 // test for it later.
2122 let idx = (id - 1) * 2 + 1;
2124 vec![1 << (idx - 8*3), 0, 0, 0]
2125 } else if idx > 8*2 {
2126 vec![1 << (idx - 8*2), 0, 0]
2127 } else if idx > 8*1 {
2128 vec![1 << (idx - 8*1), 0]
2134 fn build_line_graph() -> (
2135 Secp256k1<All>, sync::Arc<NetworkGraph<Arc<test_utils::TestLogger>>>,
2136 P2PGossipSync<sync::Arc<NetworkGraph<Arc<test_utils::TestLogger>>>, sync::Arc<test_utils::TestChainSource>, sync::Arc<test_utils::TestLogger>>,
2137 sync::Arc<test_utils::TestChainSource>, sync::Arc<test_utils::TestLogger>,
2139 let secp_ctx = Secp256k1::new();
2140 let logger = Arc::new(test_utils::TestLogger::new());
2141 let chain_monitor = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
2142 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
2143 let network_graph = Arc::new(NetworkGraph::new(genesis_hash, Arc::clone(&logger)));
2144 let gossip_sync = P2PGossipSync::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
2146 // Build network from our_id to node 19:
2147 // our_id -1(1)2- node0 -1(2)2- node1 - ... - node19
2148 let (our_privkey, _, privkeys, _) = get_nodes(&secp_ctx);
2150 for (idx, (cur_privkey, next_privkey)) in core::iter::once(&our_privkey)
2151 .chain(privkeys.iter()).zip(privkeys.iter()).enumerate() {
2152 let cur_short_channel_id = (idx as u64) + 1;
2153 add_channel(&gossip_sync, &secp_ctx, &cur_privkey, &next_privkey,
2154 ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), cur_short_channel_id);
2155 update_channel(&gossip_sync, &secp_ctx, &cur_privkey, UnsignedChannelUpdate {
2156 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2157 short_channel_id: cur_short_channel_id,
2158 timestamp: idx as u32,
2160 cltv_expiry_delta: 0,
2161 htlc_minimum_msat: 0,
2162 htlc_maximum_msat: OptionalField::Absent,
2164 fee_proportional_millionths: 0,
2165 excess_data: Vec::new()
2167 update_channel(&gossip_sync, &secp_ctx, &next_privkey, UnsignedChannelUpdate {
2168 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2169 short_channel_id: cur_short_channel_id,
2170 timestamp: (idx as u32)+1,
2172 cltv_expiry_delta: 0,
2173 htlc_minimum_msat: 0,
2174 htlc_maximum_msat: OptionalField::Absent,
2176 fee_proportional_millionths: 0,
2177 excess_data: Vec::new()
2179 add_or_update_node(&gossip_sync, &secp_ctx, next_privkey,
2180 NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
2183 (secp_ctx, network_graph, gossip_sync, chain_monitor, logger)
2186 fn build_graph() -> (
2188 sync::Arc<NetworkGraph<Arc<test_utils::TestLogger>>>,
2189 P2PGossipSync<sync::Arc<NetworkGraph<Arc<test_utils::TestLogger>>>, sync::Arc<test_utils::TestChainSource>, sync::Arc<test_utils::TestLogger>>,
2190 sync::Arc<test_utils::TestChainSource>,
2191 sync::Arc<test_utils::TestLogger>,
2193 let secp_ctx = Secp256k1::new();
2194 let logger = Arc::new(test_utils::TestLogger::new());
2195 let chain_monitor = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
2196 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
2197 let network_graph = Arc::new(NetworkGraph::new(genesis_hash, Arc::clone(&logger)));
2198 let gossip_sync = P2PGossipSync::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
2199 // Build network from our_id to node6:
2201 // -1(1)2- node0 -1(3)2-
2203 // our_id -1(12)2- node7 -1(13)2--- node2
2205 // -1(2)2- node1 -1(4)2-
2208 // chan1 1-to-2: disabled
2209 // chan1 2-to-1: enabled, 0 fee
2211 // chan2 1-to-2: enabled, ignored fee
2212 // chan2 2-to-1: enabled, 0 fee
2214 // chan3 1-to-2: enabled, 0 fee
2215 // chan3 2-to-1: enabled, 100 msat fee
2217 // chan4 1-to-2: enabled, 100% fee
2218 // chan4 2-to-1: enabled, 0 fee
2220 // chan12 1-to-2: enabled, ignored fee
2221 // chan12 2-to-1: enabled, 0 fee
2223 // chan13 1-to-2: enabled, 200% fee
2224 // chan13 2-to-1: enabled, 0 fee
2227 // -1(5)2- node3 -1(8)2--
2231 // node2--1(6)2- node4 -1(9)2--- node6 (not in global route map)
2233 // -1(7)2- node5 -1(10)2-
2235 // Channels 5, 8, 9 and 10 are private channels.
2237 // chan5 1-to-2: enabled, 100 msat fee
2238 // chan5 2-to-1: enabled, 0 fee
2240 // chan6 1-to-2: enabled, 0 fee
2241 // chan6 2-to-1: enabled, 0 fee
2243 // chan7 1-to-2: enabled, 100% fee
2244 // chan7 2-to-1: enabled, 0 fee
2246 // chan8 1-to-2: enabled, variable fee (0 then 1000 msat)
2247 // chan8 2-to-1: enabled, 0 fee
2249 // chan9 1-to-2: enabled, 1001 msat fee
2250 // chan9 2-to-1: enabled, 0 fee
2252 // chan10 1-to-2: enabled, 0 fee
2253 // chan10 2-to-1: enabled, 0 fee
2255 // chan11 1-to-2: enabled, 0 fee
2256 // chan11 2-to-1: enabled, 0 fee
2258 let (our_privkey, _, privkeys, _) = get_nodes(&secp_ctx);
2260 add_channel(&gossip_sync, &secp_ctx, &our_privkey, &privkeys[0], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
2261 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2262 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2263 short_channel_id: 1,
2266 cltv_expiry_delta: 0,
2267 htlc_minimum_msat: 0,
2268 htlc_maximum_msat: OptionalField::Absent,
2270 fee_proportional_millionths: 0,
2271 excess_data: Vec::new()
2274 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[0], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
2276 add_channel(&gossip_sync, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
2277 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2278 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2279 short_channel_id: 2,
2282 cltv_expiry_delta: (5 << 4) | 3,
2283 htlc_minimum_msat: 0,
2284 htlc_maximum_msat: OptionalField::Absent,
2285 fee_base_msat: u32::max_value(),
2286 fee_proportional_millionths: u32::max_value(),
2287 excess_data: Vec::new()
2289 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2290 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2291 short_channel_id: 2,
2294 cltv_expiry_delta: 0,
2295 htlc_minimum_msat: 0,
2296 htlc_maximum_msat: OptionalField::Absent,
2298 fee_proportional_millionths: 0,
2299 excess_data: Vec::new()
2302 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
2304 add_channel(&gossip_sync, &secp_ctx, &our_privkey, &privkeys[7], ChannelFeatures::from_le_bytes(id_to_feature_flags(12)), 12);
2305 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2306 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2307 short_channel_id: 12,
2310 cltv_expiry_delta: (5 << 4) | 3,
2311 htlc_minimum_msat: 0,
2312 htlc_maximum_msat: OptionalField::Absent,
2313 fee_base_msat: u32::max_value(),
2314 fee_proportional_millionths: u32::max_value(),
2315 excess_data: Vec::new()
2317 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2318 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2319 short_channel_id: 12,
2322 cltv_expiry_delta: 0,
2323 htlc_minimum_msat: 0,
2324 htlc_maximum_msat: OptionalField::Absent,
2326 fee_proportional_millionths: 0,
2327 excess_data: Vec::new()
2330 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[7], NodeFeatures::from_le_bytes(id_to_feature_flags(8)), 0);
2332 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
2333 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2334 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2335 short_channel_id: 3,
2338 cltv_expiry_delta: (3 << 4) | 1,
2339 htlc_minimum_msat: 0,
2340 htlc_maximum_msat: OptionalField::Absent,
2342 fee_proportional_millionths: 0,
2343 excess_data: Vec::new()
2345 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2346 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2347 short_channel_id: 3,
2350 cltv_expiry_delta: (3 << 4) | 2,
2351 htlc_minimum_msat: 0,
2352 htlc_maximum_msat: OptionalField::Absent,
2354 fee_proportional_millionths: 0,
2355 excess_data: Vec::new()
2358 add_channel(&gossip_sync, &secp_ctx, &privkeys[1], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
2359 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2360 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2361 short_channel_id: 4,
2364 cltv_expiry_delta: (4 << 4) | 1,
2365 htlc_minimum_msat: 0,
2366 htlc_maximum_msat: OptionalField::Absent,
2368 fee_proportional_millionths: 1000000,
2369 excess_data: Vec::new()
2371 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2372 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2373 short_channel_id: 4,
2376 cltv_expiry_delta: (4 << 4) | 2,
2377 htlc_minimum_msat: 0,
2378 htlc_maximum_msat: OptionalField::Absent,
2380 fee_proportional_millionths: 0,
2381 excess_data: Vec::new()
2384 add_channel(&gossip_sync, &secp_ctx, &privkeys[7], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(13)), 13);
2385 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2386 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2387 short_channel_id: 13,
2390 cltv_expiry_delta: (13 << 4) | 1,
2391 htlc_minimum_msat: 0,
2392 htlc_maximum_msat: OptionalField::Absent,
2394 fee_proportional_millionths: 2000000,
2395 excess_data: Vec::new()
2397 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2398 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2399 short_channel_id: 13,
2402 cltv_expiry_delta: (13 << 4) | 2,
2403 htlc_minimum_msat: 0,
2404 htlc_maximum_msat: OptionalField::Absent,
2406 fee_proportional_millionths: 0,
2407 excess_data: Vec::new()
2410 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
2412 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
2413 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2414 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2415 short_channel_id: 6,
2418 cltv_expiry_delta: (6 << 4) | 1,
2419 htlc_minimum_msat: 0,
2420 htlc_maximum_msat: OptionalField::Absent,
2422 fee_proportional_millionths: 0,
2423 excess_data: Vec::new()
2425 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
2426 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2427 short_channel_id: 6,
2430 cltv_expiry_delta: (6 << 4) | 2,
2431 htlc_minimum_msat: 0,
2432 htlc_maximum_msat: OptionalField::Absent,
2434 fee_proportional_millionths: 0,
2435 excess_data: Vec::new(),
2438 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(11)), 11);
2439 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
2440 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2441 short_channel_id: 11,
2444 cltv_expiry_delta: (11 << 4) | 1,
2445 htlc_minimum_msat: 0,
2446 htlc_maximum_msat: OptionalField::Absent,
2448 fee_proportional_millionths: 0,
2449 excess_data: Vec::new()
2451 update_channel(&gossip_sync, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
2452 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2453 short_channel_id: 11,
2456 cltv_expiry_delta: (11 << 4) | 2,
2457 htlc_minimum_msat: 0,
2458 htlc_maximum_msat: OptionalField::Absent,
2460 fee_proportional_millionths: 0,
2461 excess_data: Vec::new()
2464 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(5)), 0);
2466 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
2468 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[5], ChannelFeatures::from_le_bytes(id_to_feature_flags(7)), 7);
2469 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2470 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2471 short_channel_id: 7,
2474 cltv_expiry_delta: (7 << 4) | 1,
2475 htlc_minimum_msat: 0,
2476 htlc_maximum_msat: OptionalField::Absent,
2478 fee_proportional_millionths: 1000000,
2479 excess_data: Vec::new()
2481 update_channel(&gossip_sync, &secp_ctx, &privkeys[5], UnsignedChannelUpdate {
2482 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2483 short_channel_id: 7,
2486 cltv_expiry_delta: (7 << 4) | 2,
2487 htlc_minimum_msat: 0,
2488 htlc_maximum_msat: OptionalField::Absent,
2490 fee_proportional_millionths: 0,
2491 excess_data: Vec::new()
2494 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[5], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
2496 (secp_ctx, network_graph, gossip_sync, chain_monitor, logger)
2500 fn simple_route_test() {
2501 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2502 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2503 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2504 let scorer = test_utils::TestScorer::with_penalty(0);
2505 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2506 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2508 // Simple route to 2 via 1
2510 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) {
2511 assert_eq!(err, "Cannot send a payment of 0 msat");
2512 } else { panic!(); }
2514 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2515 assert_eq!(route.paths[0].len(), 2);
2517 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2518 assert_eq!(route.paths[0][0].short_channel_id, 2);
2519 assert_eq!(route.paths[0][0].fee_msat, 100);
2520 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2521 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2522 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2524 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2525 assert_eq!(route.paths[0][1].short_channel_id, 4);
2526 assert_eq!(route.paths[0][1].fee_msat, 100);
2527 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2528 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2529 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2533 fn invalid_first_hop_test() {
2534 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2535 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2536 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2537 let scorer = test_utils::TestScorer::with_penalty(0);
2538 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2539 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2541 // Simple route to 2 via 1
2543 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
2545 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) =
2546 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) {
2547 assert_eq!(err, "First hop cannot have our_node_pubkey as a destination.");
2548 } else { panic!(); }
2550 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2551 assert_eq!(route.paths[0].len(), 2);
2555 fn htlc_minimum_test() {
2556 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2557 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2558 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2559 let scorer = test_utils::TestScorer::with_penalty(0);
2560 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2561 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2563 // Simple route to 2 via 1
2565 // Disable other paths
2566 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2567 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2568 short_channel_id: 12,
2570 flags: 2, // to disable
2571 cltv_expiry_delta: 0,
2572 htlc_minimum_msat: 0,
2573 htlc_maximum_msat: OptionalField::Absent,
2575 fee_proportional_millionths: 0,
2576 excess_data: Vec::new()
2578 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2579 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2580 short_channel_id: 3,
2582 flags: 2, // to disable
2583 cltv_expiry_delta: 0,
2584 htlc_minimum_msat: 0,
2585 htlc_maximum_msat: OptionalField::Absent,
2587 fee_proportional_millionths: 0,
2588 excess_data: Vec::new()
2590 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2591 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2592 short_channel_id: 13,
2594 flags: 2, // to disable
2595 cltv_expiry_delta: 0,
2596 htlc_minimum_msat: 0,
2597 htlc_maximum_msat: OptionalField::Absent,
2599 fee_proportional_millionths: 0,
2600 excess_data: Vec::new()
2602 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2603 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2604 short_channel_id: 6,
2606 flags: 2, // to disable
2607 cltv_expiry_delta: 0,
2608 htlc_minimum_msat: 0,
2609 htlc_maximum_msat: OptionalField::Absent,
2611 fee_proportional_millionths: 0,
2612 excess_data: Vec::new()
2614 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2615 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2616 short_channel_id: 7,
2618 flags: 2, // to disable
2619 cltv_expiry_delta: 0,
2620 htlc_minimum_msat: 0,
2621 htlc_maximum_msat: OptionalField::Absent,
2623 fee_proportional_millionths: 0,
2624 excess_data: Vec::new()
2627 // Check against amount_to_transfer_over_msat.
2628 // Set minimal HTLC of 200_000_000 msat.
2629 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2630 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2631 short_channel_id: 2,
2634 cltv_expiry_delta: 0,
2635 htlc_minimum_msat: 200_000_000,
2636 htlc_maximum_msat: OptionalField::Absent,
2638 fee_proportional_millionths: 0,
2639 excess_data: Vec::new()
2642 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
2644 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2645 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2646 short_channel_id: 4,
2649 cltv_expiry_delta: 0,
2650 htlc_minimum_msat: 0,
2651 htlc_maximum_msat: OptionalField::Present(199_999_999),
2653 fee_proportional_millionths: 0,
2654 excess_data: Vec::new()
2657 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
2658 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) {
2659 assert_eq!(err, "Failed to find a path to the given destination");
2660 } else { panic!(); }
2662 // Lift the restriction on the first hop.
2663 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2664 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2665 short_channel_id: 2,
2668 cltv_expiry_delta: 0,
2669 htlc_minimum_msat: 0,
2670 htlc_maximum_msat: OptionalField::Absent,
2672 fee_proportional_millionths: 0,
2673 excess_data: Vec::new()
2676 // A payment above the minimum should pass
2677 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();
2678 assert_eq!(route.paths[0].len(), 2);
2682 fn htlc_minimum_overpay_test() {
2683 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2684 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2685 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
2686 let scorer = test_utils::TestScorer::with_penalty(0);
2687 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2688 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2690 // A route to node#2 via two paths.
2691 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
2692 // Thus, they can't send 60 without overpaying.
2693 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2694 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2695 short_channel_id: 2,
2698 cltv_expiry_delta: 0,
2699 htlc_minimum_msat: 35_000,
2700 htlc_maximum_msat: OptionalField::Present(40_000),
2702 fee_proportional_millionths: 0,
2703 excess_data: Vec::new()
2705 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2706 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2707 short_channel_id: 12,
2710 cltv_expiry_delta: 0,
2711 htlc_minimum_msat: 35_000,
2712 htlc_maximum_msat: OptionalField::Present(40_000),
2714 fee_proportional_millionths: 0,
2715 excess_data: Vec::new()
2719 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2720 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2721 short_channel_id: 13,
2724 cltv_expiry_delta: 0,
2725 htlc_minimum_msat: 0,
2726 htlc_maximum_msat: OptionalField::Absent,
2728 fee_proportional_millionths: 0,
2729 excess_data: Vec::new()
2731 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2732 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2733 short_channel_id: 4,
2736 cltv_expiry_delta: 0,
2737 htlc_minimum_msat: 0,
2738 htlc_maximum_msat: OptionalField::Absent,
2740 fee_proportional_millionths: 0,
2741 excess_data: Vec::new()
2744 // Disable other paths
2745 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2746 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2747 short_channel_id: 1,
2749 flags: 2, // to disable
2750 cltv_expiry_delta: 0,
2751 htlc_minimum_msat: 0,
2752 htlc_maximum_msat: OptionalField::Absent,
2754 fee_proportional_millionths: 0,
2755 excess_data: Vec::new()
2758 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 60_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2759 // Overpay fees to hit htlc_minimum_msat.
2760 let overpaid_fees = route.paths[0][0].fee_msat + route.paths[1][0].fee_msat;
2761 // TODO: this could be better balanced to overpay 10k and not 15k.
2762 assert_eq!(overpaid_fees, 15_000);
2764 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
2765 // while taking even more fee to match htlc_minimum_msat.
2766 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2767 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2768 short_channel_id: 12,
2771 cltv_expiry_delta: 0,
2772 htlc_minimum_msat: 65_000,
2773 htlc_maximum_msat: OptionalField::Present(80_000),
2775 fee_proportional_millionths: 0,
2776 excess_data: Vec::new()
2778 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2779 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2780 short_channel_id: 2,
2783 cltv_expiry_delta: 0,
2784 htlc_minimum_msat: 0,
2785 htlc_maximum_msat: OptionalField::Absent,
2787 fee_proportional_millionths: 0,
2788 excess_data: Vec::new()
2790 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2791 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2792 short_channel_id: 4,
2795 cltv_expiry_delta: 0,
2796 htlc_minimum_msat: 0,
2797 htlc_maximum_msat: OptionalField::Absent,
2799 fee_proportional_millionths: 100_000,
2800 excess_data: Vec::new()
2803 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 60_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2804 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
2805 assert_eq!(route.paths.len(), 1);
2806 assert_eq!(route.paths[0][0].short_channel_id, 12);
2807 let fees = route.paths[0][0].fee_msat;
2808 assert_eq!(fees, 5_000);
2810 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2811 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
2812 // the other channel.
2813 assert_eq!(route.paths.len(), 1);
2814 assert_eq!(route.paths[0][0].short_channel_id, 2);
2815 let fees = route.paths[0][0].fee_msat;
2816 assert_eq!(fees, 5_000);
2820 fn disable_channels_test() {
2821 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2822 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2823 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2824 let scorer = test_utils::TestScorer::with_penalty(0);
2825 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2826 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2828 // // Disable channels 4 and 12 by flags=2
2829 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2830 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2831 short_channel_id: 4,
2833 flags: 2, // to disable
2834 cltv_expiry_delta: 0,
2835 htlc_minimum_msat: 0,
2836 htlc_maximum_msat: OptionalField::Absent,
2838 fee_proportional_millionths: 0,
2839 excess_data: Vec::new()
2841 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2842 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2843 short_channel_id: 12,
2845 flags: 2, // to disable
2846 cltv_expiry_delta: 0,
2847 htlc_minimum_msat: 0,
2848 htlc_maximum_msat: OptionalField::Absent,
2850 fee_proportional_millionths: 0,
2851 excess_data: Vec::new()
2854 // If all the channels require some features we don't understand, route should fail
2855 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) {
2856 assert_eq!(err, "Failed to find a path to the given destination");
2857 } else { panic!(); }
2859 // If we specify a channel to node7, that overrides our local channel view and that gets used
2860 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2861 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();
2862 assert_eq!(route.paths[0].len(), 2);
2864 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2865 assert_eq!(route.paths[0][0].short_channel_id, 42);
2866 assert_eq!(route.paths[0][0].fee_msat, 200);
2867 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2868 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2869 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2871 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2872 assert_eq!(route.paths[0][1].short_channel_id, 13);
2873 assert_eq!(route.paths[0][1].fee_msat, 100);
2874 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2875 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2876 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2880 fn disable_node_test() {
2881 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2882 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2883 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2884 let scorer = test_utils::TestScorer::with_penalty(0);
2885 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2886 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2888 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
2889 let mut unknown_features = NodeFeatures::known();
2890 unknown_features.set_unknown_feature_required();
2891 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
2892 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
2893 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
2895 // If all nodes require some features we don't understand, route should fail
2896 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) {
2897 assert_eq!(err, "Failed to find a path to the given destination");
2898 } else { panic!(); }
2900 // If we specify a channel to node7, that overrides our local channel view and that gets used
2901 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2902 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();
2903 assert_eq!(route.paths[0].len(), 2);
2905 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2906 assert_eq!(route.paths[0][0].short_channel_id, 42);
2907 assert_eq!(route.paths[0][0].fee_msat, 200);
2908 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2909 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2910 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2912 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2913 assert_eq!(route.paths[0][1].short_channel_id, 13);
2914 assert_eq!(route.paths[0][1].fee_msat, 100);
2915 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2916 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2917 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2919 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
2920 // naively) assume that the user checked the feature bits on the invoice, which override
2921 // the node_announcement.
2925 fn our_chans_test() {
2926 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2927 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2928 let scorer = test_utils::TestScorer::with_penalty(0);
2929 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2930 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2932 // Route to 1 via 2 and 3 because our channel to 1 is disabled
2933 let payment_params = PaymentParameters::from_node_id(nodes[0]);
2934 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2935 assert_eq!(route.paths[0].len(), 3);
2937 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2938 assert_eq!(route.paths[0][0].short_channel_id, 2);
2939 assert_eq!(route.paths[0][0].fee_msat, 200);
2940 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2941 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2942 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2944 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2945 assert_eq!(route.paths[0][1].short_channel_id, 4);
2946 assert_eq!(route.paths[0][1].fee_msat, 100);
2947 assert_eq!(route.paths[0][1].cltv_expiry_delta, (3 << 4) | 2);
2948 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2949 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2951 assert_eq!(route.paths[0][2].pubkey, nodes[0]);
2952 assert_eq!(route.paths[0][2].short_channel_id, 3);
2953 assert_eq!(route.paths[0][2].fee_msat, 100);
2954 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
2955 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(1));
2956 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(3));
2958 // If we specify a channel to node7, that overrides our local channel view and that gets used
2959 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2960 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2961 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();
2962 assert_eq!(route.paths[0].len(), 2);
2964 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2965 assert_eq!(route.paths[0][0].short_channel_id, 42);
2966 assert_eq!(route.paths[0][0].fee_msat, 200);
2967 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2968 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2969 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2971 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2972 assert_eq!(route.paths[0][1].short_channel_id, 13);
2973 assert_eq!(route.paths[0][1].fee_msat, 100);
2974 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2975 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2976 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2979 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2980 let zero_fees = RoutingFees {
2982 proportional_millionths: 0,
2984 vec![RouteHint(vec![RouteHintHop {
2985 src_node_id: nodes[3],
2986 short_channel_id: 8,
2988 cltv_expiry_delta: (8 << 4) | 1,
2989 htlc_minimum_msat: None,
2990 htlc_maximum_msat: None,
2992 ]), RouteHint(vec![RouteHintHop {
2993 src_node_id: nodes[4],
2994 short_channel_id: 9,
2997 proportional_millionths: 0,
2999 cltv_expiry_delta: (9 << 4) | 1,
3000 htlc_minimum_msat: None,
3001 htlc_maximum_msat: None,
3002 }]), RouteHint(vec![RouteHintHop {
3003 src_node_id: nodes[5],
3004 short_channel_id: 10,
3006 cltv_expiry_delta: (10 << 4) | 1,
3007 htlc_minimum_msat: None,
3008 htlc_maximum_msat: None,
3012 fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3013 let zero_fees = RoutingFees {
3015 proportional_millionths: 0,
3017 vec![RouteHint(vec![RouteHintHop {
3018 src_node_id: nodes[2],
3019 short_channel_id: 5,
3022 proportional_millionths: 0,
3024 cltv_expiry_delta: (5 << 4) | 1,
3025 htlc_minimum_msat: None,
3026 htlc_maximum_msat: None,
3028 src_node_id: nodes[3],
3029 short_channel_id: 8,
3031 cltv_expiry_delta: (8 << 4) | 1,
3032 htlc_minimum_msat: None,
3033 htlc_maximum_msat: None,
3035 ]), RouteHint(vec![RouteHintHop {
3036 src_node_id: nodes[4],
3037 short_channel_id: 9,
3040 proportional_millionths: 0,
3042 cltv_expiry_delta: (9 << 4) | 1,
3043 htlc_minimum_msat: None,
3044 htlc_maximum_msat: None,
3045 }]), RouteHint(vec![RouteHintHop {
3046 src_node_id: nodes[5],
3047 short_channel_id: 10,
3049 cltv_expiry_delta: (10 << 4) | 1,
3050 htlc_minimum_msat: None,
3051 htlc_maximum_msat: None,
3056 fn partial_route_hint_test() {
3057 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3058 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3059 let scorer = test_utils::TestScorer::with_penalty(0);
3060 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3061 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3063 // Simple test across 2, 3, 5, and 4 via a last_hop channel
3064 // Tests the behaviour when the RouteHint contains a suboptimal hop.
3065 // RouteHint may be partially used by the algo to build the best path.
3067 // First check that last hop can't have its source as the payee.
3068 let invalid_last_hop = RouteHint(vec![RouteHintHop {
3069 src_node_id: nodes[6],
3070 short_channel_id: 8,
3073 proportional_millionths: 0,
3075 cltv_expiry_delta: (8 << 4) | 1,
3076 htlc_minimum_msat: None,
3077 htlc_maximum_msat: None,
3080 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
3081 invalid_last_hops.push(invalid_last_hop);
3083 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(invalid_last_hops);
3084 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) {
3085 assert_eq!(err, "Route hint cannot have the payee as the source.");
3086 } else { panic!(); }
3089 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops_multi_private_channels(&nodes));
3090 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3091 assert_eq!(route.paths[0].len(), 5);
3093 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3094 assert_eq!(route.paths[0][0].short_channel_id, 2);
3095 assert_eq!(route.paths[0][0].fee_msat, 100);
3096 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
3097 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3098 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3100 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3101 assert_eq!(route.paths[0][1].short_channel_id, 4);
3102 assert_eq!(route.paths[0][1].fee_msat, 0);
3103 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
3104 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3105 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3107 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
3108 assert_eq!(route.paths[0][2].short_channel_id, 6);
3109 assert_eq!(route.paths[0][2].fee_msat, 0);
3110 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
3111 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
3112 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
3114 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
3115 assert_eq!(route.paths[0][3].short_channel_id, 11);
3116 assert_eq!(route.paths[0][3].fee_msat, 0);
3117 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
3118 // If we have a peer in the node map, we'll use their features here since we don't have
3119 // a way of figuring out their features from the invoice:
3120 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
3121 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
3123 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
3124 assert_eq!(route.paths[0][4].short_channel_id, 8);
3125 assert_eq!(route.paths[0][4].fee_msat, 100);
3126 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
3127 assert_eq!(route.paths[0][4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3128 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3131 fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3132 let zero_fees = RoutingFees {
3134 proportional_millionths: 0,
3136 vec![RouteHint(vec![RouteHintHop {
3137 src_node_id: nodes[3],
3138 short_channel_id: 8,
3140 cltv_expiry_delta: (8 << 4) | 1,
3141 htlc_minimum_msat: None,
3142 htlc_maximum_msat: None,
3143 }]), RouteHint(vec![
3145 ]), RouteHint(vec![RouteHintHop {
3146 src_node_id: nodes[5],
3147 short_channel_id: 10,
3149 cltv_expiry_delta: (10 << 4) | 1,
3150 htlc_minimum_msat: None,
3151 htlc_maximum_msat: None,
3156 fn ignores_empty_last_hops_test() {
3157 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3158 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3159 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(empty_last_hop(&nodes));
3160 let scorer = test_utils::TestScorer::with_penalty(0);
3161 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3162 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3164 // Test handling of an empty RouteHint passed in Invoice.
3166 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3167 assert_eq!(route.paths[0].len(), 5);
3169 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3170 assert_eq!(route.paths[0][0].short_channel_id, 2);
3171 assert_eq!(route.paths[0][0].fee_msat, 100);
3172 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
3173 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3174 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3176 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3177 assert_eq!(route.paths[0][1].short_channel_id, 4);
3178 assert_eq!(route.paths[0][1].fee_msat, 0);
3179 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
3180 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3181 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3183 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
3184 assert_eq!(route.paths[0][2].short_channel_id, 6);
3185 assert_eq!(route.paths[0][2].fee_msat, 0);
3186 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
3187 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
3188 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
3190 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
3191 assert_eq!(route.paths[0][3].short_channel_id, 11);
3192 assert_eq!(route.paths[0][3].fee_msat, 0);
3193 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
3194 // If we have a peer in the node map, we'll use their features here since we don't have
3195 // a way of figuring out their features from the invoice:
3196 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
3197 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
3199 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
3200 assert_eq!(route.paths[0][4].short_channel_id, 8);
3201 assert_eq!(route.paths[0][4].fee_msat, 100);
3202 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
3203 assert_eq!(route.paths[0][4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3204 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3207 /// Builds a trivial last-hop hint that passes through the two nodes given, with channel 0xff00
3209 fn multi_hop_last_hops_hint(hint_hops: [PublicKey; 2]) -> Vec<RouteHint> {
3210 let zero_fees = RoutingFees {
3212 proportional_millionths: 0,
3214 vec![RouteHint(vec![RouteHintHop {
3215 src_node_id: hint_hops[0],
3216 short_channel_id: 0xff00,
3219 proportional_millionths: 0,
3221 cltv_expiry_delta: (5 << 4) | 1,
3222 htlc_minimum_msat: None,
3223 htlc_maximum_msat: None,
3225 src_node_id: hint_hops[1],
3226 short_channel_id: 0xff01,
3228 cltv_expiry_delta: (8 << 4) | 1,
3229 htlc_minimum_msat: None,
3230 htlc_maximum_msat: None,
3235 fn multi_hint_last_hops_test() {
3236 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3237 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3238 let last_hops = multi_hop_last_hops_hint([nodes[2], nodes[3]]);
3239 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops.clone());
3240 let scorer = test_utils::TestScorer::with_penalty(0);
3241 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3242 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3243 // Test through channels 2, 3, 0xff00, 0xff01.
3244 // Test shows that multiple hop hints are considered.
3246 // Disabling channels 6 & 7 by flags=2
3247 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3248 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3249 short_channel_id: 6,
3251 flags: 2, // to disable
3252 cltv_expiry_delta: 0,
3253 htlc_minimum_msat: 0,
3254 htlc_maximum_msat: OptionalField::Absent,
3256 fee_proportional_millionths: 0,
3257 excess_data: Vec::new()
3259 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3260 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3261 short_channel_id: 7,
3263 flags: 2, // to disable
3264 cltv_expiry_delta: 0,
3265 htlc_minimum_msat: 0,
3266 htlc_maximum_msat: OptionalField::Absent,
3268 fee_proportional_millionths: 0,
3269 excess_data: Vec::new()
3272 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3273 assert_eq!(route.paths[0].len(), 4);
3275 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3276 assert_eq!(route.paths[0][0].short_channel_id, 2);
3277 assert_eq!(route.paths[0][0].fee_msat, 200);
3278 assert_eq!(route.paths[0][0].cltv_expiry_delta, 65);
3279 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3280 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3282 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3283 assert_eq!(route.paths[0][1].short_channel_id, 4);
3284 assert_eq!(route.paths[0][1].fee_msat, 100);
3285 assert_eq!(route.paths[0][1].cltv_expiry_delta, 81);
3286 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3287 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3289 assert_eq!(route.paths[0][2].pubkey, nodes[3]);
3290 assert_eq!(route.paths[0][2].short_channel_id, last_hops[0].0[0].short_channel_id);
3291 assert_eq!(route.paths[0][2].fee_msat, 0);
3292 assert_eq!(route.paths[0][2].cltv_expiry_delta, 129);
3293 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(4));
3294 assert_eq!(route.paths[0][2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3296 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
3297 assert_eq!(route.paths[0][3].short_channel_id, last_hops[0].0[1].short_channel_id);
3298 assert_eq!(route.paths[0][3].fee_msat, 100);
3299 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
3300 assert_eq!(route.paths[0][3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3301 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3305 fn private_multi_hint_last_hops_test() {
3306 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3307 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3309 let non_announced_privkey = SecretKey::from_slice(&hex::decode(format!("{:02x}", 0xf0).repeat(32)).unwrap()[..]).unwrap();
3310 let non_announced_pubkey = PublicKey::from_secret_key(&secp_ctx, &non_announced_privkey);
3312 let last_hops = multi_hop_last_hops_hint([nodes[2], non_announced_pubkey]);
3313 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops.clone());
3314 let scorer = test_utils::TestScorer::with_penalty(0);
3315 // Test through channels 2, 3, 0xff00, 0xff01.
3316 // Test shows that multiple hop hints are considered.
3318 // Disabling channels 6 & 7 by flags=2
3319 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3320 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3321 short_channel_id: 6,
3323 flags: 2, // to disable
3324 cltv_expiry_delta: 0,
3325 htlc_minimum_msat: 0,
3326 htlc_maximum_msat: OptionalField::Absent,
3328 fee_proportional_millionths: 0,
3329 excess_data: Vec::new()
3331 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3332 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3333 short_channel_id: 7,
3335 flags: 2, // to disable
3336 cltv_expiry_delta: 0,
3337 htlc_minimum_msat: 0,
3338 htlc_maximum_msat: OptionalField::Absent,
3340 fee_proportional_millionths: 0,
3341 excess_data: Vec::new()
3344 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &[42u8; 32]).unwrap();
3345 assert_eq!(route.paths[0].len(), 4);
3347 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3348 assert_eq!(route.paths[0][0].short_channel_id, 2);
3349 assert_eq!(route.paths[0][0].fee_msat, 200);
3350 assert_eq!(route.paths[0][0].cltv_expiry_delta, 65);
3351 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3352 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3354 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3355 assert_eq!(route.paths[0][1].short_channel_id, 4);
3356 assert_eq!(route.paths[0][1].fee_msat, 100);
3357 assert_eq!(route.paths[0][1].cltv_expiry_delta, 81);
3358 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3359 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3361 assert_eq!(route.paths[0][2].pubkey, non_announced_pubkey);
3362 assert_eq!(route.paths[0][2].short_channel_id, last_hops[0].0[0].short_channel_id);
3363 assert_eq!(route.paths[0][2].fee_msat, 0);
3364 assert_eq!(route.paths[0][2].cltv_expiry_delta, 129);
3365 assert_eq!(route.paths[0][2].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3366 assert_eq!(route.paths[0][2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3368 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
3369 assert_eq!(route.paths[0][3].short_channel_id, last_hops[0].0[1].short_channel_id);
3370 assert_eq!(route.paths[0][3].fee_msat, 100);
3371 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
3372 assert_eq!(route.paths[0][3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3373 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3376 fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3377 let zero_fees = RoutingFees {
3379 proportional_millionths: 0,
3381 vec![RouteHint(vec![RouteHintHop {
3382 src_node_id: nodes[4],
3383 short_channel_id: 11,
3385 cltv_expiry_delta: (11 << 4) | 1,
3386 htlc_minimum_msat: None,
3387 htlc_maximum_msat: None,
3389 src_node_id: nodes[3],
3390 short_channel_id: 8,
3392 cltv_expiry_delta: (8 << 4) | 1,
3393 htlc_minimum_msat: None,
3394 htlc_maximum_msat: None,
3395 }]), RouteHint(vec![RouteHintHop {
3396 src_node_id: nodes[4],
3397 short_channel_id: 9,
3400 proportional_millionths: 0,
3402 cltv_expiry_delta: (9 << 4) | 1,
3403 htlc_minimum_msat: None,
3404 htlc_maximum_msat: None,
3405 }]), RouteHint(vec![RouteHintHop {
3406 src_node_id: nodes[5],
3407 short_channel_id: 10,
3409 cltv_expiry_delta: (10 << 4) | 1,
3410 htlc_minimum_msat: None,
3411 htlc_maximum_msat: None,
3416 fn last_hops_with_public_channel_test() {
3417 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3418 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3419 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops_with_public_channel(&nodes));
3420 let scorer = test_utils::TestScorer::with_penalty(0);
3421 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3422 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3423 // This test shows that public routes can be present in the invoice
3424 // which would be handled in the same manner.
3426 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3427 assert_eq!(route.paths[0].len(), 5);
3429 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3430 assert_eq!(route.paths[0][0].short_channel_id, 2);
3431 assert_eq!(route.paths[0][0].fee_msat, 100);
3432 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
3433 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3434 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3436 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3437 assert_eq!(route.paths[0][1].short_channel_id, 4);
3438 assert_eq!(route.paths[0][1].fee_msat, 0);
3439 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
3440 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3441 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3443 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
3444 assert_eq!(route.paths[0][2].short_channel_id, 6);
3445 assert_eq!(route.paths[0][2].fee_msat, 0);
3446 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
3447 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
3448 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
3450 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
3451 assert_eq!(route.paths[0][3].short_channel_id, 11);
3452 assert_eq!(route.paths[0][3].fee_msat, 0);
3453 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
3454 // If we have a peer in the node map, we'll use their features here since we don't have
3455 // a way of figuring out their features from the invoice:
3456 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
3457 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
3459 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
3460 assert_eq!(route.paths[0][4].short_channel_id, 8);
3461 assert_eq!(route.paths[0][4].fee_msat, 100);
3462 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
3463 assert_eq!(route.paths[0][4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3464 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3468 fn our_chans_last_hop_connect_test() {
3469 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3470 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3471 let scorer = test_utils::TestScorer::with_penalty(0);
3472 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3473 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3475 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
3476 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3477 let mut last_hops = last_hops(&nodes);
3478 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops.clone());
3479 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();
3480 assert_eq!(route.paths[0].len(), 2);
3482 assert_eq!(route.paths[0][0].pubkey, nodes[3]);
3483 assert_eq!(route.paths[0][0].short_channel_id, 42);
3484 assert_eq!(route.paths[0][0].fee_msat, 0);
3485 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 4) | 1);
3486 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
3487 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3489 assert_eq!(route.paths[0][1].pubkey, nodes[6]);
3490 assert_eq!(route.paths[0][1].short_channel_id, 8);
3491 assert_eq!(route.paths[0][1].fee_msat, 100);
3492 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
3493 assert_eq!(route.paths[0][1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3494 assert_eq!(route.paths[0][1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3496 last_hops[0].0[0].fees.base_msat = 1000;
3498 // Revert to via 6 as the fee on 8 goes up
3499 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops);
3500 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3501 assert_eq!(route.paths[0].len(), 4);
3503 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3504 assert_eq!(route.paths[0][0].short_channel_id, 2);
3505 assert_eq!(route.paths[0][0].fee_msat, 200); // fee increased as its % of value transferred across node
3506 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
3507 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3508 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3510 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3511 assert_eq!(route.paths[0][1].short_channel_id, 4);
3512 assert_eq!(route.paths[0][1].fee_msat, 100);
3513 assert_eq!(route.paths[0][1].cltv_expiry_delta, (7 << 4) | 1);
3514 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3515 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3517 assert_eq!(route.paths[0][2].pubkey, nodes[5]);
3518 assert_eq!(route.paths[0][2].short_channel_id, 7);
3519 assert_eq!(route.paths[0][2].fee_msat, 0);
3520 assert_eq!(route.paths[0][2].cltv_expiry_delta, (10 << 4) | 1);
3521 // If we have a peer in the node map, we'll use their features here since we don't have
3522 // a way of figuring out their features from the invoice:
3523 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
3524 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(7));
3526 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
3527 assert_eq!(route.paths[0][3].short_channel_id, 10);
3528 assert_eq!(route.paths[0][3].fee_msat, 100);
3529 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
3530 assert_eq!(route.paths[0][3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3531 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3533 // ...but still use 8 for larger payments as 6 has a variable feerate
3534 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 2000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3535 assert_eq!(route.paths[0].len(), 5);
3537 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3538 assert_eq!(route.paths[0][0].short_channel_id, 2);
3539 assert_eq!(route.paths[0][0].fee_msat, 3000);
3540 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
3541 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3542 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3544 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3545 assert_eq!(route.paths[0][1].short_channel_id, 4);
3546 assert_eq!(route.paths[0][1].fee_msat, 0);
3547 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
3548 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3549 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3551 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
3552 assert_eq!(route.paths[0][2].short_channel_id, 6);
3553 assert_eq!(route.paths[0][2].fee_msat, 0);
3554 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
3555 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
3556 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
3558 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
3559 assert_eq!(route.paths[0][3].short_channel_id, 11);
3560 assert_eq!(route.paths[0][3].fee_msat, 1000);
3561 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
3562 // If we have a peer in the node map, we'll use their features here since we don't have
3563 // a way of figuring out their features from the invoice:
3564 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
3565 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
3567 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
3568 assert_eq!(route.paths[0][4].short_channel_id, 8);
3569 assert_eq!(route.paths[0][4].fee_msat, 2000);
3570 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
3571 assert_eq!(route.paths[0][4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3572 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3575 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> {
3576 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
3577 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3578 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3580 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
3581 let last_hops = RouteHint(vec![RouteHintHop {
3582 src_node_id: middle_node_id,
3583 short_channel_id: 8,
3586 proportional_millionths: last_hop_fee_prop,
3588 cltv_expiry_delta: (8 << 4) | 1,
3589 htlc_minimum_msat: None,
3590 htlc_maximum_msat: last_hop_htlc_max,
3592 let payment_params = PaymentParameters::from_node_id(target_node_id).with_route_hints(vec![last_hops]);
3593 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
3594 let scorer = test_utils::TestScorer::with_penalty(0);
3595 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3596 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3597 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
3598 let logger = test_utils::TestLogger::new();
3599 let network_graph = NetworkGraph::new(genesis_hash, &logger);
3600 let route = get_route(&source_node_id, &payment_params, &network_graph.read_only(),
3601 Some(&our_chans.iter().collect::<Vec<_>>()), route_val, 42, &logger, &scorer, &random_seed_bytes);
3606 fn unannounced_path_test() {
3607 // We should be able to send a payment to a destination without any help of a routing graph
3608 // if we have a channel with a common counterparty that appears in the first and last hop
3610 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
3612 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3613 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3614 assert_eq!(route.paths[0].len(), 2);
3616 assert_eq!(route.paths[0][0].pubkey, middle_node_id);
3617 assert_eq!(route.paths[0][0].short_channel_id, 42);
3618 assert_eq!(route.paths[0][0].fee_msat, 1001);
3619 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 4) | 1);
3620 assert_eq!(route.paths[0][0].node_features.le_flags(), &[0b11]);
3621 assert_eq!(route.paths[0][0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3623 assert_eq!(route.paths[0][1].pubkey, target_node_id);
3624 assert_eq!(route.paths[0][1].short_channel_id, 8);
3625 assert_eq!(route.paths[0][1].fee_msat, 1000000);
3626 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
3627 assert_eq!(route.paths[0][1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3628 assert_eq!(route.paths[0][1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3632 fn overflow_unannounced_path_test_liquidity_underflow() {
3633 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
3634 // the last-hop had a fee which overflowed a u64, we'd panic.
3635 // This was due to us adding the first-hop from us unconditionally, causing us to think
3636 // we'd built a path (as our node is in the "best candidate" set), when we had not.
3637 // In this test, we previously hit a subtraction underflow due to having less available
3638 // liquidity at the last hop than 0.
3639 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());
3643 fn overflow_unannounced_path_test_feerate_overflow() {
3644 // This tests for the same case as above, except instead of hitting a subtraction
3645 // underflow, we hit a case where the fee charged at a hop overflowed.
3646 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());
3650 fn available_amount_while_routing_test() {
3651 // Tests whether we choose the correct available channel amount while routing.
3653 let (secp_ctx, network_graph, mut gossip_sync, chain_monitor, logger) = build_graph();
3654 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3655 let scorer = test_utils::TestScorer::with_penalty(0);
3656 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3657 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3658 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
3660 // We will use a simple single-path route from
3661 // our node to node2 via node0: channels {1, 3}.
3663 // First disable all other paths.
3664 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3665 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3666 short_channel_id: 2,
3669 cltv_expiry_delta: 0,
3670 htlc_minimum_msat: 0,
3671 htlc_maximum_msat: OptionalField::Present(100_000),
3673 fee_proportional_millionths: 0,
3674 excess_data: Vec::new()
3676 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3677 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3678 short_channel_id: 12,
3681 cltv_expiry_delta: 0,
3682 htlc_minimum_msat: 0,
3683 htlc_maximum_msat: OptionalField::Present(100_000),
3685 fee_proportional_millionths: 0,
3686 excess_data: Vec::new()
3689 // Make the first channel (#1) very permissive,
3690 // and we will be testing all limits on the second channel.
3691 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3692 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3693 short_channel_id: 1,
3696 cltv_expiry_delta: 0,
3697 htlc_minimum_msat: 0,
3698 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3700 fee_proportional_millionths: 0,
3701 excess_data: Vec::new()
3704 // First, let's see if routing works if we have absolutely no idea about the available amount.
3705 // In this case, it should be set to 250_000 sats.
3706 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3707 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3708 short_channel_id: 3,
3711 cltv_expiry_delta: 0,
3712 htlc_minimum_msat: 0,
3713 htlc_maximum_msat: OptionalField::Absent,
3715 fee_proportional_millionths: 0,
3716 excess_data: Vec::new()
3720 // Attempt to route more than available results in a failure.
3721 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3722 &our_id, &payment_params, &network_graph.read_only(), None, 250_000_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3723 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3724 } else { panic!(); }
3728 // Now, attempt to route an exact amount we have should be fine.
3729 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();
3730 assert_eq!(route.paths.len(), 1);
3731 let path = route.paths.last().unwrap();
3732 assert_eq!(path.len(), 2);
3733 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3734 assert_eq!(path.last().unwrap().fee_msat, 250_000_000);
3737 // Check that setting next_outbound_htlc_limit_msat in first_hops limits the channels.
3738 // Disable channel #1 and use another first hop.
3739 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3740 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3741 short_channel_id: 1,
3744 cltv_expiry_delta: 0,
3745 htlc_minimum_msat: 0,
3746 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3748 fee_proportional_millionths: 0,
3749 excess_data: Vec::new()
3752 // Now, limit the first_hop by the next_outbound_htlc_limit_msat of 200_000 sats.
3753 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
3756 // Attempt to route more than available results in a failure.
3757 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3758 &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) {
3759 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3760 } else { panic!(); }
3764 // Now, attempt to route an exact amount we have should be fine.
3765 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();
3766 assert_eq!(route.paths.len(), 1);
3767 let path = route.paths.last().unwrap();
3768 assert_eq!(path.len(), 2);
3769 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3770 assert_eq!(path.last().unwrap().fee_msat, 200_000_000);
3773 // Enable channel #1 back.
3774 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3775 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3776 short_channel_id: 1,
3779 cltv_expiry_delta: 0,
3780 htlc_minimum_msat: 0,
3781 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3783 fee_proportional_millionths: 0,
3784 excess_data: Vec::new()
3788 // Now let's see if routing works if we know only htlc_maximum_msat.
3789 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3790 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3791 short_channel_id: 3,
3794 cltv_expiry_delta: 0,
3795 htlc_minimum_msat: 0,
3796 htlc_maximum_msat: OptionalField::Present(15_000),
3798 fee_proportional_millionths: 0,
3799 excess_data: Vec::new()
3803 // Attempt to route more than available results in a failure.
3804 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3805 &our_id, &payment_params, &network_graph.read_only(), None, 15_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3806 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3807 } else { panic!(); }
3811 // Now, attempt to route an exact amount we have should be fine.
3812 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 15_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3813 assert_eq!(route.paths.len(), 1);
3814 let path = route.paths.last().unwrap();
3815 assert_eq!(path.len(), 2);
3816 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3817 assert_eq!(path.last().unwrap().fee_msat, 15_000);
3820 // Now let's see if routing works if we know only capacity from the UTXO.
3822 // We can't change UTXO capacity on the fly, so we'll disable
3823 // the existing channel and add another one with the capacity we need.
3824 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3825 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3826 short_channel_id: 3,
3829 cltv_expiry_delta: 0,
3830 htlc_minimum_msat: 0,
3831 htlc_maximum_msat: OptionalField::Absent,
3833 fee_proportional_millionths: 0,
3834 excess_data: Vec::new()
3837 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
3838 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
3839 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
3840 .push_opcode(opcodes::all::OP_PUSHNUM_2)
3841 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
3843 *chain_monitor.utxo_ret.lock().unwrap() = Ok(TxOut { value: 15, script_pubkey: good_script.clone() });
3844 gossip_sync.add_chain_access(Some(chain_monitor));
3846 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
3847 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3848 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3849 short_channel_id: 333,
3852 cltv_expiry_delta: (3 << 4) | 1,
3853 htlc_minimum_msat: 0,
3854 htlc_maximum_msat: OptionalField::Absent,
3856 fee_proportional_millionths: 0,
3857 excess_data: Vec::new()
3859 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3860 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3861 short_channel_id: 333,
3864 cltv_expiry_delta: (3 << 4) | 2,
3865 htlc_minimum_msat: 0,
3866 htlc_maximum_msat: OptionalField::Absent,
3868 fee_proportional_millionths: 0,
3869 excess_data: Vec::new()
3873 // Attempt to route more than available results in a failure.
3874 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3875 &our_id, &payment_params, &network_graph.read_only(), None, 15_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3876 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3877 } else { panic!(); }
3881 // Now, attempt to route an exact amount we have should be fine.
3882 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 15_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3883 assert_eq!(route.paths.len(), 1);
3884 let path = route.paths.last().unwrap();
3885 assert_eq!(path.len(), 2);
3886 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3887 assert_eq!(path.last().unwrap().fee_msat, 15_000);
3890 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
3891 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3892 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3893 short_channel_id: 333,
3896 cltv_expiry_delta: 0,
3897 htlc_minimum_msat: 0,
3898 htlc_maximum_msat: OptionalField::Present(10_000),
3900 fee_proportional_millionths: 0,
3901 excess_data: Vec::new()
3905 // Attempt to route more than available results in a failure.
3906 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3907 &our_id, &payment_params, &network_graph.read_only(), None, 10_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3908 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3909 } else { panic!(); }
3913 // Now, attempt to route an exact amount we have should be fine.
3914 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 10_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3915 assert_eq!(route.paths.len(), 1);
3916 let path = route.paths.last().unwrap();
3917 assert_eq!(path.len(), 2);
3918 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3919 assert_eq!(path.last().unwrap().fee_msat, 10_000);
3924 fn available_liquidity_last_hop_test() {
3925 // Check that available liquidity properly limits the path even when only
3926 // one of the latter hops is limited.
3927 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3928 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3929 let scorer = test_utils::TestScorer::with_penalty(0);
3930 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3931 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3932 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
3934 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3935 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
3936 // Total capacity: 50 sats.
3938 // Disable other potential paths.
3939 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3940 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3941 short_channel_id: 2,
3944 cltv_expiry_delta: 0,
3945 htlc_minimum_msat: 0,
3946 htlc_maximum_msat: OptionalField::Present(100_000),
3948 fee_proportional_millionths: 0,
3949 excess_data: Vec::new()
3951 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3952 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3953 short_channel_id: 7,
3956 cltv_expiry_delta: 0,
3957 htlc_minimum_msat: 0,
3958 htlc_maximum_msat: OptionalField::Present(100_000),
3960 fee_proportional_millionths: 0,
3961 excess_data: Vec::new()
3966 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3967 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3968 short_channel_id: 12,
3971 cltv_expiry_delta: 0,
3972 htlc_minimum_msat: 0,
3973 htlc_maximum_msat: OptionalField::Present(100_000),
3975 fee_proportional_millionths: 0,
3976 excess_data: Vec::new()
3978 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3979 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3980 short_channel_id: 13,
3983 cltv_expiry_delta: 0,
3984 htlc_minimum_msat: 0,
3985 htlc_maximum_msat: OptionalField::Present(100_000),
3987 fee_proportional_millionths: 0,
3988 excess_data: Vec::new()
3991 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3992 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3993 short_channel_id: 6,
3996 cltv_expiry_delta: 0,
3997 htlc_minimum_msat: 0,
3998 htlc_maximum_msat: OptionalField::Present(50_000),
4000 fee_proportional_millionths: 0,
4001 excess_data: Vec::new()
4003 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4004 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4005 short_channel_id: 11,
4008 cltv_expiry_delta: 0,
4009 htlc_minimum_msat: 0,
4010 htlc_maximum_msat: OptionalField::Present(100_000),
4012 fee_proportional_millionths: 0,
4013 excess_data: Vec::new()
4016 // Attempt to route more than available results in a failure.
4017 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4018 &our_id, &payment_params, &network_graph.read_only(), None, 60_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
4019 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4020 } else { panic!(); }
4024 // Now, attempt to route 49 sats (just a bit below the capacity).
4025 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 49_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4026 assert_eq!(route.paths.len(), 1);
4027 let mut total_amount_paid_msat = 0;
4028 for path in &route.paths {
4029 assert_eq!(path.len(), 4);
4030 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
4031 total_amount_paid_msat += path.last().unwrap().fee_msat;
4033 assert_eq!(total_amount_paid_msat, 49_000);
4037 // Attempt to route an exact amount is also fine
4038 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4039 assert_eq!(route.paths.len(), 1);
4040 let mut total_amount_paid_msat = 0;
4041 for path in &route.paths {
4042 assert_eq!(path.len(), 4);
4043 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
4044 total_amount_paid_msat += path.last().unwrap().fee_msat;
4046 assert_eq!(total_amount_paid_msat, 50_000);
4051 fn ignore_fee_first_hop_test() {
4052 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4053 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4054 let scorer = test_utils::TestScorer::with_penalty(0);
4055 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4056 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4057 let payment_params = PaymentParameters::from_node_id(nodes[2]);
4059 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
4060 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4061 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4062 short_channel_id: 1,
4065 cltv_expiry_delta: 0,
4066 htlc_minimum_msat: 0,
4067 htlc_maximum_msat: OptionalField::Present(100_000),
4068 fee_base_msat: 1_000_000,
4069 fee_proportional_millionths: 0,
4070 excess_data: Vec::new()
4072 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4073 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4074 short_channel_id: 3,
4077 cltv_expiry_delta: 0,
4078 htlc_minimum_msat: 0,
4079 htlc_maximum_msat: OptionalField::Present(50_000),
4081 fee_proportional_millionths: 0,
4082 excess_data: Vec::new()
4086 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4087 assert_eq!(route.paths.len(), 1);
4088 let mut total_amount_paid_msat = 0;
4089 for path in &route.paths {
4090 assert_eq!(path.len(), 2);
4091 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4092 total_amount_paid_msat += path.last().unwrap().fee_msat;
4094 assert_eq!(total_amount_paid_msat, 50_000);
4099 fn simple_mpp_route_test() {
4100 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4101 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4102 let scorer = test_utils::TestScorer::with_penalty(0);
4103 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4104 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4105 let payment_params = PaymentParameters::from_node_id(nodes[2])
4106 .with_features(InvoiceFeatures::known());
4108 // We need a route consisting of 3 paths:
4109 // From our node to node2 via node0, node7, node1 (three paths one hop each).
4110 // To achieve this, the amount being transferred should be around
4111 // the total capacity of these 3 paths.
4113 // First, we set limits on these (previously unlimited) channels.
4114 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
4116 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
4117 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4118 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4119 short_channel_id: 1,
4122 cltv_expiry_delta: 0,
4123 htlc_minimum_msat: 0,
4124 htlc_maximum_msat: OptionalField::Present(100_000),
4126 fee_proportional_millionths: 0,
4127 excess_data: Vec::new()
4129 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4130 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4131 short_channel_id: 3,
4134 cltv_expiry_delta: 0,
4135 htlc_minimum_msat: 0,
4136 htlc_maximum_msat: OptionalField::Present(50_000),
4138 fee_proportional_millionths: 0,
4139 excess_data: Vec::new()
4142 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
4143 // (total limit 60).
4144 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4145 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4146 short_channel_id: 12,
4149 cltv_expiry_delta: 0,
4150 htlc_minimum_msat: 0,
4151 htlc_maximum_msat: OptionalField::Present(60_000),
4153 fee_proportional_millionths: 0,
4154 excess_data: Vec::new()
4156 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4157 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4158 short_channel_id: 13,
4161 cltv_expiry_delta: 0,
4162 htlc_minimum_msat: 0,
4163 htlc_maximum_msat: OptionalField::Present(60_000),
4165 fee_proportional_millionths: 0,
4166 excess_data: Vec::new()
4169 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
4170 // (total capacity 180 sats).
4171 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4172 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4173 short_channel_id: 2,
4176 cltv_expiry_delta: 0,
4177 htlc_minimum_msat: 0,
4178 htlc_maximum_msat: OptionalField::Present(200_000),
4180 fee_proportional_millionths: 0,
4181 excess_data: Vec::new()
4183 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4184 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4185 short_channel_id: 4,
4188 cltv_expiry_delta: 0,
4189 htlc_minimum_msat: 0,
4190 htlc_maximum_msat: OptionalField::Present(180_000),
4192 fee_proportional_millionths: 0,
4193 excess_data: Vec::new()
4197 // Attempt to route more than available results in a failure.
4198 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4199 &our_id, &payment_params, &network_graph.read_only(), None, 300_000, 42,
4200 Arc::clone(&logger), &scorer, &random_seed_bytes) {
4201 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4202 } else { panic!(); }
4206 // Attempt to route while setting max_path_count to 0 results in a failure.
4207 let zero_payment_params = payment_params.clone().with_max_path_count(0);
4208 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4209 &our_id, &zero_payment_params, &network_graph.read_only(), None, 100, 42,
4210 Arc::clone(&logger), &scorer, &random_seed_bytes) {
4211 assert_eq!(err, "Can't find a route with no paths allowed.");
4212 } else { panic!(); }
4216 // Attempt to route while setting max_path_count to 3 results in a failure.
4217 // This is the case because the minimal_value_contribution_msat would require each path
4218 // to account for 1/3 of the total value, which is violated by 2 out of 3 paths.
4219 let fail_payment_params = payment_params.clone().with_max_path_count(3);
4220 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4221 &our_id, &fail_payment_params, &network_graph.read_only(), None, 250_000, 42,
4222 Arc::clone(&logger), &scorer, &random_seed_bytes) {
4223 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4224 } else { panic!(); }
4228 // Now, attempt to route 250 sats (just a bit below the capacity).
4229 // Our algorithm should provide us with these 3 paths.
4230 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None,
4231 250_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4232 assert_eq!(route.paths.len(), 3);
4233 let mut total_amount_paid_msat = 0;
4234 for path in &route.paths {
4235 assert_eq!(path.len(), 2);
4236 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4237 total_amount_paid_msat += path.last().unwrap().fee_msat;
4239 assert_eq!(total_amount_paid_msat, 250_000);
4243 // Attempt to route an exact amount is also fine
4244 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None,
4245 290_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4246 assert_eq!(route.paths.len(), 3);
4247 let mut total_amount_paid_msat = 0;
4248 for path in &route.paths {
4249 assert_eq!(path.len(), 2);
4250 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4251 total_amount_paid_msat += path.last().unwrap().fee_msat;
4253 assert_eq!(total_amount_paid_msat, 290_000);
4258 fn long_mpp_route_test() {
4259 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4260 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4261 let scorer = test_utils::TestScorer::with_penalty(0);
4262 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4263 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4264 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
4266 // We need a route consisting of 3 paths:
4267 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
4268 // Note that these paths overlap (channels 5, 12, 13).
4269 // We will route 300 sats.
4270 // Each path will have 100 sats capacity, those channels which
4271 // are used twice will have 200 sats capacity.
4273 // Disable other potential paths.
4274 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4275 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4276 short_channel_id: 2,
4279 cltv_expiry_delta: 0,
4280 htlc_minimum_msat: 0,
4281 htlc_maximum_msat: OptionalField::Present(100_000),
4283 fee_proportional_millionths: 0,
4284 excess_data: Vec::new()
4286 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4287 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4288 short_channel_id: 7,
4291 cltv_expiry_delta: 0,
4292 htlc_minimum_msat: 0,
4293 htlc_maximum_msat: OptionalField::Present(100_000),
4295 fee_proportional_millionths: 0,
4296 excess_data: Vec::new()
4299 // Path via {node0, node2} is channels {1, 3, 5}.
4300 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4301 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4302 short_channel_id: 1,
4305 cltv_expiry_delta: 0,
4306 htlc_minimum_msat: 0,
4307 htlc_maximum_msat: OptionalField::Present(100_000),
4309 fee_proportional_millionths: 0,
4310 excess_data: Vec::new()
4312 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4313 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4314 short_channel_id: 3,
4317 cltv_expiry_delta: 0,
4318 htlc_minimum_msat: 0,
4319 htlc_maximum_msat: OptionalField::Present(100_000),
4321 fee_proportional_millionths: 0,
4322 excess_data: Vec::new()
4325 // Capacity of 200 sats because this channel will be used by 3rd path as well.
4326 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4327 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4328 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4329 short_channel_id: 5,
4332 cltv_expiry_delta: 0,
4333 htlc_minimum_msat: 0,
4334 htlc_maximum_msat: OptionalField::Present(200_000),
4336 fee_proportional_millionths: 0,
4337 excess_data: Vec::new()
4340 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4341 // Add 100 sats to the capacities of {12, 13}, because these channels
4342 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
4343 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4344 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4345 short_channel_id: 12,
4348 cltv_expiry_delta: 0,
4349 htlc_minimum_msat: 0,
4350 htlc_maximum_msat: OptionalField::Present(200_000),
4352 fee_proportional_millionths: 0,
4353 excess_data: Vec::new()
4355 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4356 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4357 short_channel_id: 13,
4360 cltv_expiry_delta: 0,
4361 htlc_minimum_msat: 0,
4362 htlc_maximum_msat: OptionalField::Present(200_000),
4364 fee_proportional_millionths: 0,
4365 excess_data: Vec::new()
4368 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4369 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4370 short_channel_id: 6,
4373 cltv_expiry_delta: 0,
4374 htlc_minimum_msat: 0,
4375 htlc_maximum_msat: OptionalField::Present(100_000),
4377 fee_proportional_millionths: 0,
4378 excess_data: Vec::new()
4380 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4381 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4382 short_channel_id: 11,
4385 cltv_expiry_delta: 0,
4386 htlc_minimum_msat: 0,
4387 htlc_maximum_msat: OptionalField::Present(100_000),
4389 fee_proportional_millionths: 0,
4390 excess_data: Vec::new()
4393 // Path via {node7, node2} is channels {12, 13, 5}.
4394 // We already limited them to 200 sats (they are used twice for 100 sats).
4395 // Nothing to do here.
4398 // Attempt to route more than available results in a failure.
4399 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4400 &our_id, &payment_params, &network_graph.read_only(), None, 350_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
4401 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4402 } else { panic!(); }
4406 // Now, attempt to route 300 sats (exact amount we can route).
4407 // Our algorithm should provide us with these 3 paths, 100 sats each.
4408 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 300_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4409 assert_eq!(route.paths.len(), 3);
4411 let mut total_amount_paid_msat = 0;
4412 for path in &route.paths {
4413 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
4414 total_amount_paid_msat += path.last().unwrap().fee_msat;
4416 assert_eq!(total_amount_paid_msat, 300_000);
4422 fn mpp_cheaper_route_test() {
4423 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4424 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4425 let scorer = test_utils::TestScorer::with_penalty(0);
4426 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4427 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4428 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
4430 // This test checks that if we have two cheaper paths and one more expensive path,
4431 // so that liquidity-wise any 2 of 3 combination is sufficient,
4432 // two cheaper paths will be taken.
4433 // These paths have equal available liquidity.
4435 // We need a combination of 3 paths:
4436 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
4437 // Note that these paths overlap (channels 5, 12, 13).
4438 // Each path will have 100 sats capacity, those channels which
4439 // are used twice will have 200 sats capacity.
4441 // Disable other potential paths.
4442 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4443 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4444 short_channel_id: 2,
4447 cltv_expiry_delta: 0,
4448 htlc_minimum_msat: 0,
4449 htlc_maximum_msat: OptionalField::Present(100_000),
4451 fee_proportional_millionths: 0,
4452 excess_data: Vec::new()
4454 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4455 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4456 short_channel_id: 7,
4459 cltv_expiry_delta: 0,
4460 htlc_minimum_msat: 0,
4461 htlc_maximum_msat: OptionalField::Present(100_000),
4463 fee_proportional_millionths: 0,
4464 excess_data: Vec::new()
4467 // Path via {node0, node2} is channels {1, 3, 5}.
4468 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4469 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4470 short_channel_id: 1,
4473 cltv_expiry_delta: 0,
4474 htlc_minimum_msat: 0,
4475 htlc_maximum_msat: OptionalField::Present(100_000),
4477 fee_proportional_millionths: 0,
4478 excess_data: Vec::new()
4480 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4481 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4482 short_channel_id: 3,
4485 cltv_expiry_delta: 0,
4486 htlc_minimum_msat: 0,
4487 htlc_maximum_msat: OptionalField::Present(100_000),
4489 fee_proportional_millionths: 0,
4490 excess_data: Vec::new()
4493 // Capacity of 200 sats because this channel will be used by 3rd path as well.
4494 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4495 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4496 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4497 short_channel_id: 5,
4500 cltv_expiry_delta: 0,
4501 htlc_minimum_msat: 0,
4502 htlc_maximum_msat: OptionalField::Present(200_000),
4504 fee_proportional_millionths: 0,
4505 excess_data: Vec::new()
4508 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4509 // Add 100 sats to the capacities of {12, 13}, because these channels
4510 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
4511 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4512 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4513 short_channel_id: 12,
4516 cltv_expiry_delta: 0,
4517 htlc_minimum_msat: 0,
4518 htlc_maximum_msat: OptionalField::Present(200_000),
4520 fee_proportional_millionths: 0,
4521 excess_data: Vec::new()
4523 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4524 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4525 short_channel_id: 13,
4528 cltv_expiry_delta: 0,
4529 htlc_minimum_msat: 0,
4530 htlc_maximum_msat: OptionalField::Present(200_000),
4532 fee_proportional_millionths: 0,
4533 excess_data: Vec::new()
4536 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4537 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4538 short_channel_id: 6,
4541 cltv_expiry_delta: 0,
4542 htlc_minimum_msat: 0,
4543 htlc_maximum_msat: OptionalField::Present(100_000),
4544 fee_base_msat: 1_000,
4545 fee_proportional_millionths: 0,
4546 excess_data: Vec::new()
4548 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4549 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4550 short_channel_id: 11,
4553 cltv_expiry_delta: 0,
4554 htlc_minimum_msat: 0,
4555 htlc_maximum_msat: OptionalField::Present(100_000),
4557 fee_proportional_millionths: 0,
4558 excess_data: Vec::new()
4561 // Path via {node7, node2} is channels {12, 13, 5}.
4562 // We already limited them to 200 sats (they are used twice for 100 sats).
4563 // Nothing to do here.
4566 // Now, attempt to route 180 sats.
4567 // Our algorithm should provide us with these 2 paths.
4568 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 180_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4569 assert_eq!(route.paths.len(), 2);
4571 let mut total_value_transferred_msat = 0;
4572 let mut total_paid_msat = 0;
4573 for path in &route.paths {
4574 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
4575 total_value_transferred_msat += path.last().unwrap().fee_msat;
4577 total_paid_msat += hop.fee_msat;
4580 // If we paid fee, this would be higher.
4581 assert_eq!(total_value_transferred_msat, 180_000);
4582 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
4583 assert_eq!(total_fees_paid, 0);
4588 fn fees_on_mpp_route_test() {
4589 // This test makes sure that MPP algorithm properly takes into account
4590 // fees charged on the channels, by making the fees impactful:
4591 // if the fee is not properly accounted for, the behavior is different.
4592 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4593 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4594 let scorer = test_utils::TestScorer::with_penalty(0);
4595 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4596 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4597 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
4599 // We need a route consisting of 2 paths:
4600 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
4601 // We will route 200 sats, Each path will have 100 sats capacity.
4603 // This test is not particularly stable: e.g.,
4604 // there's a way to route via {node0, node2, node4}.
4605 // It works while pathfinding is deterministic, but can be broken otherwise.
4606 // It's fine to ignore this concern for now.
4608 // Disable other potential paths.
4609 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4610 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4611 short_channel_id: 2,
4614 cltv_expiry_delta: 0,
4615 htlc_minimum_msat: 0,
4616 htlc_maximum_msat: OptionalField::Present(100_000),
4618 fee_proportional_millionths: 0,
4619 excess_data: Vec::new()
4622 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4623 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4624 short_channel_id: 7,
4627 cltv_expiry_delta: 0,
4628 htlc_minimum_msat: 0,
4629 htlc_maximum_msat: OptionalField::Present(100_000),
4631 fee_proportional_millionths: 0,
4632 excess_data: Vec::new()
4635 // Path via {node0, node2} is channels {1, 3, 5}.
4636 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4637 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4638 short_channel_id: 1,
4641 cltv_expiry_delta: 0,
4642 htlc_minimum_msat: 0,
4643 htlc_maximum_msat: OptionalField::Present(100_000),
4645 fee_proportional_millionths: 0,
4646 excess_data: Vec::new()
4648 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4649 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4650 short_channel_id: 3,
4653 cltv_expiry_delta: 0,
4654 htlc_minimum_msat: 0,
4655 htlc_maximum_msat: OptionalField::Present(100_000),
4657 fee_proportional_millionths: 0,
4658 excess_data: Vec::new()
4661 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4662 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4663 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4664 short_channel_id: 5,
4667 cltv_expiry_delta: 0,
4668 htlc_minimum_msat: 0,
4669 htlc_maximum_msat: OptionalField::Present(100_000),
4671 fee_proportional_millionths: 0,
4672 excess_data: Vec::new()
4675 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4676 // All channels should be 100 sats capacity. But for the fee experiment,
4677 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
4678 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
4679 // 100 sats (and pay 150 sats in fees for the use of channel 6),
4680 // so no matter how large are other channels,
4681 // the whole path will be limited by 100 sats with just these 2 conditions:
4682 // - channel 12 capacity is 250 sats
4683 // - fee for channel 6 is 150 sats
4684 // Let's test this by enforcing these 2 conditions and removing other limits.
4685 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4686 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4687 short_channel_id: 12,
4690 cltv_expiry_delta: 0,
4691 htlc_minimum_msat: 0,
4692 htlc_maximum_msat: OptionalField::Present(250_000),
4694 fee_proportional_millionths: 0,
4695 excess_data: Vec::new()
4697 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4698 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4699 short_channel_id: 13,
4702 cltv_expiry_delta: 0,
4703 htlc_minimum_msat: 0,
4704 htlc_maximum_msat: OptionalField::Absent,
4706 fee_proportional_millionths: 0,
4707 excess_data: Vec::new()
4710 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4711 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4712 short_channel_id: 6,
4715 cltv_expiry_delta: 0,
4716 htlc_minimum_msat: 0,
4717 htlc_maximum_msat: OptionalField::Absent,
4718 fee_base_msat: 150_000,
4719 fee_proportional_millionths: 0,
4720 excess_data: Vec::new()
4722 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4723 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4724 short_channel_id: 11,
4727 cltv_expiry_delta: 0,
4728 htlc_minimum_msat: 0,
4729 htlc_maximum_msat: OptionalField::Absent,
4731 fee_proportional_millionths: 0,
4732 excess_data: Vec::new()
4736 // Attempt to route more than available results in a failure.
4737 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4738 &our_id, &payment_params, &network_graph.read_only(), None, 210_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
4739 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4740 } else { panic!(); }
4744 // Now, attempt to route 200 sats (exact amount we can route).
4745 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 200_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4746 assert_eq!(route.paths.len(), 2);
4748 let mut total_amount_paid_msat = 0;
4749 for path in &route.paths {
4750 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
4751 total_amount_paid_msat += path.last().unwrap().fee_msat;
4753 assert_eq!(total_amount_paid_msat, 200_000);
4754 assert_eq!(route.get_total_fees(), 150_000);
4759 fn mpp_with_last_hops() {
4760 // Previously, if we tried to send an MPP payment to a destination which was only reachable
4761 // via a single last-hop route hint, we'd fail to route if we first collected routes
4762 // totaling close but not quite enough to fund the full payment.
4764 // This was because we considered last-hop hints to have exactly the sought payment amount
4765 // instead of the amount we were trying to collect, needlessly limiting our path searching
4766 // at the very first hop.
4768 // Specifically, this interacted with our "all paths must fund at least 5% of total target"
4769 // criterion to cause us to refuse all routes at the last hop hint which would be considered
4770 // to only have the remaining to-collect amount in available liquidity.
4772 // This bug appeared in production in some specific channel configurations.
4773 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4774 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4775 let scorer = test_utils::TestScorer::with_penalty(0);
4776 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4777 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4778 let payment_params = PaymentParameters::from_node_id(PublicKey::from_slice(&[02; 33]).unwrap()).with_features(InvoiceFeatures::known())
4779 .with_route_hints(vec![RouteHint(vec![RouteHintHop {
4780 src_node_id: nodes[2],
4781 short_channel_id: 42,
4782 fees: RoutingFees { base_msat: 0, proportional_millionths: 0 },
4783 cltv_expiry_delta: 42,
4784 htlc_minimum_msat: None,
4785 htlc_maximum_msat: None,
4788 // Keep only two paths from us to nodes[2], both with a 99sat HTLC maximum, with one with
4789 // no fee and one with a 1msat fee. Previously, trying to route 100 sats to nodes[2] here
4790 // would first use the no-fee route and then fail to find a path along the second route as
4791 // we think we can only send up to 1 additional sat over the last-hop but refuse to as its
4792 // under 5% of our payment amount.
4793 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4794 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4795 short_channel_id: 1,
4798 cltv_expiry_delta: (5 << 4) | 5,
4799 htlc_minimum_msat: 0,
4800 htlc_maximum_msat: OptionalField::Present(99_000),
4801 fee_base_msat: u32::max_value(),
4802 fee_proportional_millionths: u32::max_value(),
4803 excess_data: Vec::new()
4805 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4806 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4807 short_channel_id: 2,
4810 cltv_expiry_delta: (5 << 4) | 3,
4811 htlc_minimum_msat: 0,
4812 htlc_maximum_msat: OptionalField::Present(99_000),
4813 fee_base_msat: u32::max_value(),
4814 fee_proportional_millionths: u32::max_value(),
4815 excess_data: Vec::new()
4817 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4818 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4819 short_channel_id: 4,
4822 cltv_expiry_delta: (4 << 4) | 1,
4823 htlc_minimum_msat: 0,
4824 htlc_maximum_msat: OptionalField::Absent,
4826 fee_proportional_millionths: 0,
4827 excess_data: Vec::new()
4829 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4830 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4831 short_channel_id: 13,
4833 flags: 0|2, // Channel disabled
4834 cltv_expiry_delta: (13 << 4) | 1,
4835 htlc_minimum_msat: 0,
4836 htlc_maximum_msat: OptionalField::Absent,
4838 fee_proportional_millionths: 2000000,
4839 excess_data: Vec::new()
4842 // Get a route for 100 sats and check that we found the MPP route no problem and didn't
4844 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();
4845 assert_eq!(route.paths.len(), 2);
4846 route.paths.sort_by_key(|path| path[0].short_channel_id);
4847 // Paths are manually ordered ordered by SCID, so:
4848 // * the first is channel 1 (0 fee, but 99 sat maximum) -> channel 3 -> channel 42
4849 // * the second is channel 2 (1 msat fee) -> channel 4 -> channel 42
4850 assert_eq!(route.paths[0][0].short_channel_id, 1);
4851 assert_eq!(route.paths[0][0].fee_msat, 0);
4852 assert_eq!(route.paths[0][2].fee_msat, 99_000);
4853 assert_eq!(route.paths[1][0].short_channel_id, 2);
4854 assert_eq!(route.paths[1][0].fee_msat, 1);
4855 assert_eq!(route.paths[1][2].fee_msat, 1_000);
4856 assert_eq!(route.get_total_fees(), 1);
4857 assert_eq!(route.get_total_amount(), 100_000);
4861 fn drop_lowest_channel_mpp_route_test() {
4862 // This test checks that low-capacity channel is dropped when after
4863 // path finding we realize that we found more capacity than we need.
4864 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4865 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4866 let scorer = test_utils::TestScorer::with_penalty(0);
4867 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4868 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4869 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known())
4870 .with_max_channel_saturation_power_of_half(0);
4872 // We need a route consisting of 3 paths:
4873 // From our node to node2 via node0, node7, node1 (three paths one hop each).
4875 // The first and the second paths should be sufficient, but the third should be
4876 // cheaper, so that we select it but drop later.
4878 // First, we set limits on these (previously unlimited) channels.
4879 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
4881 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
4882 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4883 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4884 short_channel_id: 1,
4887 cltv_expiry_delta: 0,
4888 htlc_minimum_msat: 0,
4889 htlc_maximum_msat: OptionalField::Present(100_000),
4891 fee_proportional_millionths: 0,
4892 excess_data: Vec::new()
4894 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4895 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4896 short_channel_id: 3,
4899 cltv_expiry_delta: 0,
4900 htlc_minimum_msat: 0,
4901 htlc_maximum_msat: OptionalField::Present(50_000),
4903 fee_proportional_millionths: 0,
4904 excess_data: Vec::new()
4907 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
4908 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4909 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4910 short_channel_id: 12,
4913 cltv_expiry_delta: 0,
4914 htlc_minimum_msat: 0,
4915 htlc_maximum_msat: OptionalField::Present(60_000),
4917 fee_proportional_millionths: 0,
4918 excess_data: Vec::new()
4920 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4921 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4922 short_channel_id: 13,
4925 cltv_expiry_delta: 0,
4926 htlc_minimum_msat: 0,
4927 htlc_maximum_msat: OptionalField::Present(60_000),
4929 fee_proportional_millionths: 0,
4930 excess_data: Vec::new()
4933 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
4934 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4935 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4936 short_channel_id: 2,
4939 cltv_expiry_delta: 0,
4940 htlc_minimum_msat: 0,
4941 htlc_maximum_msat: OptionalField::Present(20_000),
4943 fee_proportional_millionths: 0,
4944 excess_data: Vec::new()
4946 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4947 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4948 short_channel_id: 4,
4951 cltv_expiry_delta: 0,
4952 htlc_minimum_msat: 0,
4953 htlc_maximum_msat: OptionalField::Present(20_000),
4955 fee_proportional_millionths: 0,
4956 excess_data: Vec::new()
4960 // Attempt to route more than available results in a failure.
4961 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4962 &our_id, &payment_params, &network_graph.read_only(), None, 150_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
4963 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4964 } else { panic!(); }
4968 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
4969 // Our algorithm should provide us with these 3 paths.
4970 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 125_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4971 assert_eq!(route.paths.len(), 3);
4972 let mut total_amount_paid_msat = 0;
4973 for path in &route.paths {
4974 assert_eq!(path.len(), 2);
4975 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4976 total_amount_paid_msat += path.last().unwrap().fee_msat;
4978 assert_eq!(total_amount_paid_msat, 125_000);
4982 // Attempt to route without the last small cheap channel
4983 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4984 assert_eq!(route.paths.len(), 2);
4985 let mut total_amount_paid_msat = 0;
4986 for path in &route.paths {
4987 assert_eq!(path.len(), 2);
4988 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4989 total_amount_paid_msat += path.last().unwrap().fee_msat;
4991 assert_eq!(total_amount_paid_msat, 90_000);
4996 fn min_criteria_consistency() {
4997 // Test that we don't use an inconsistent metric between updating and walking nodes during
4998 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
4999 // was updated with a different criterion from the heap sorting, resulting in loops in
5000 // calculated paths. We test for that specific case here.
5002 // We construct a network that looks like this:
5004 // node2 -1(3)2- node3
5008 // node1 -1(5)2- node4 -1(1)2- node6
5014 // We create a loop on the side of our real path - our destination is node 6, with a
5015 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
5016 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
5017 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
5018 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
5019 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
5020 // "previous hop" being set to node 3, creating a loop in the path.
5021 let secp_ctx = Secp256k1::new();
5022 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
5023 let logger = Arc::new(test_utils::TestLogger::new());
5024 let network = Arc::new(NetworkGraph::new(genesis_hash, Arc::clone(&logger)));
5025 let gossip_sync = P2PGossipSync::new(Arc::clone(&network), None, Arc::clone(&logger));
5026 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5027 let scorer = test_utils::TestScorer::with_penalty(0);
5028 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5029 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5030 let payment_params = PaymentParameters::from_node_id(nodes[6]);
5032 add_channel(&gossip_sync, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
5033 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5034 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5035 short_channel_id: 6,
5038 cltv_expiry_delta: (6 << 4) | 0,
5039 htlc_minimum_msat: 0,
5040 htlc_maximum_msat: OptionalField::Absent,
5042 fee_proportional_millionths: 0,
5043 excess_data: Vec::new()
5045 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
5047 add_channel(&gossip_sync, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5048 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5049 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5050 short_channel_id: 5,
5053 cltv_expiry_delta: (5 << 4) | 0,
5054 htlc_minimum_msat: 0,
5055 htlc_maximum_msat: OptionalField::Absent,
5057 fee_proportional_millionths: 0,
5058 excess_data: Vec::new()
5060 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
5062 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
5063 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5064 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5065 short_channel_id: 4,
5068 cltv_expiry_delta: (4 << 4) | 0,
5069 htlc_minimum_msat: 0,
5070 htlc_maximum_msat: OptionalField::Absent,
5072 fee_proportional_millionths: 0,
5073 excess_data: Vec::new()
5075 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
5077 add_channel(&gossip_sync, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
5078 update_channel(&gossip_sync, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
5079 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5080 short_channel_id: 3,
5083 cltv_expiry_delta: (3 << 4) | 0,
5084 htlc_minimum_msat: 0,
5085 htlc_maximum_msat: OptionalField::Absent,
5087 fee_proportional_millionths: 0,
5088 excess_data: Vec::new()
5090 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
5092 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
5093 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5094 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5095 short_channel_id: 2,
5098 cltv_expiry_delta: (2 << 4) | 0,
5099 htlc_minimum_msat: 0,
5100 htlc_maximum_msat: OptionalField::Absent,
5102 fee_proportional_millionths: 0,
5103 excess_data: Vec::new()
5106 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
5107 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5108 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5109 short_channel_id: 1,
5112 cltv_expiry_delta: (1 << 4) | 0,
5113 htlc_minimum_msat: 100,
5114 htlc_maximum_msat: OptionalField::Absent,
5116 fee_proportional_millionths: 0,
5117 excess_data: Vec::new()
5119 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
5122 // Now ensure the route flows simply over nodes 1 and 4 to 6.
5123 let route = get_route(&our_id, &payment_params, &network.read_only(), None, 10_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5124 assert_eq!(route.paths.len(), 1);
5125 assert_eq!(route.paths[0].len(), 3);
5127 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
5128 assert_eq!(route.paths[0][0].short_channel_id, 6);
5129 assert_eq!(route.paths[0][0].fee_msat, 100);
5130 assert_eq!(route.paths[0][0].cltv_expiry_delta, (5 << 4) | 0);
5131 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(1));
5132 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(6));
5134 assert_eq!(route.paths[0][1].pubkey, nodes[4]);
5135 assert_eq!(route.paths[0][1].short_channel_id, 5);
5136 assert_eq!(route.paths[0][1].fee_msat, 0);
5137 assert_eq!(route.paths[0][1].cltv_expiry_delta, (1 << 4) | 0);
5138 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(4));
5139 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(5));
5141 assert_eq!(route.paths[0][2].pubkey, nodes[6]);
5142 assert_eq!(route.paths[0][2].short_channel_id, 1);
5143 assert_eq!(route.paths[0][2].fee_msat, 10_000);
5144 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
5145 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
5146 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(1));
5152 fn exact_fee_liquidity_limit() {
5153 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
5154 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
5155 // we calculated fees on a higher value, resulting in us ignoring such paths.
5156 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5157 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
5158 let scorer = test_utils::TestScorer::with_penalty(0);
5159 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5160 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5161 let payment_params = PaymentParameters::from_node_id(nodes[2]);
5163 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
5165 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5166 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5167 short_channel_id: 2,
5170 cltv_expiry_delta: 0,
5171 htlc_minimum_msat: 0,
5172 htlc_maximum_msat: OptionalField::Present(85_000),
5174 fee_proportional_millionths: 0,
5175 excess_data: Vec::new()
5178 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5179 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5180 short_channel_id: 12,
5183 cltv_expiry_delta: (4 << 4) | 1,
5184 htlc_minimum_msat: 0,
5185 htlc_maximum_msat: OptionalField::Present(270_000),
5187 fee_proportional_millionths: 1000000,
5188 excess_data: Vec::new()
5192 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
5193 // 200% fee charged channel 13 in the 1-to-2 direction.
5194 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5195 assert_eq!(route.paths.len(), 1);
5196 assert_eq!(route.paths[0].len(), 2);
5198 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
5199 assert_eq!(route.paths[0][0].short_channel_id, 12);
5200 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
5201 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
5202 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
5203 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
5205 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
5206 assert_eq!(route.paths[0][1].short_channel_id, 13);
5207 assert_eq!(route.paths[0][1].fee_msat, 90_000);
5208 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
5209 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
5210 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
5215 fn htlc_max_reduction_below_min() {
5216 // Test that if, while walking the graph, we reduce the value being sent to meet an
5217 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
5218 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
5219 // resulting in us thinking there is no possible path, even if other paths exist.
5220 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5221 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5222 let scorer = test_utils::TestScorer::with_penalty(0);
5223 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5224 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5225 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
5227 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
5228 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
5229 // then try to send 90_000.
5230 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5231 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5232 short_channel_id: 2,
5235 cltv_expiry_delta: 0,
5236 htlc_minimum_msat: 0,
5237 htlc_maximum_msat: OptionalField::Present(80_000),
5239 fee_proportional_millionths: 0,
5240 excess_data: Vec::new()
5242 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5243 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5244 short_channel_id: 4,
5247 cltv_expiry_delta: (4 << 4) | 1,
5248 htlc_minimum_msat: 90_000,
5249 htlc_maximum_msat: OptionalField::Absent,
5251 fee_proportional_millionths: 0,
5252 excess_data: Vec::new()
5256 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
5257 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
5258 // expensive) channels 12-13 path.
5259 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5260 assert_eq!(route.paths.len(), 1);
5261 assert_eq!(route.paths[0].len(), 2);
5263 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
5264 assert_eq!(route.paths[0][0].short_channel_id, 12);
5265 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
5266 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
5267 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
5268 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
5270 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
5271 assert_eq!(route.paths[0][1].short_channel_id, 13);
5272 assert_eq!(route.paths[0][1].fee_msat, 90_000);
5273 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
5274 assert_eq!(route.paths[0][1].node_features.le_flags(), InvoiceFeatures::known().le_flags());
5275 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
5280 fn multiple_direct_first_hops() {
5281 // Previously we'd only ever considered one first hop path per counterparty.
5282 // However, as we don't restrict users to one channel per peer, we really need to support
5283 // looking at all first hop paths.
5284 // Here we test that we do not ignore all-but-the-last first hop paths per counterparty (as
5285 // we used to do by overwriting the `first_hop_targets` hashmap entry) and that we can MPP
5286 // route over multiple channels with the same first hop.
5287 let secp_ctx = Secp256k1::new();
5288 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5289 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
5290 let logger = Arc::new(test_utils::TestLogger::new());
5291 let network_graph = NetworkGraph::new(genesis_hash, Arc::clone(&logger));
5292 let scorer = test_utils::TestScorer::with_penalty(0);
5293 let payment_params = PaymentParameters::from_node_id(nodes[0]).with_features(InvoiceFeatures::known());
5294 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5295 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5298 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
5299 &get_channel_details(Some(3), nodes[0], InitFeatures::known(), 200_000),
5300 &get_channel_details(Some(2), nodes[0], InitFeatures::known(), 10_000),
5301 ]), 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5302 assert_eq!(route.paths.len(), 1);
5303 assert_eq!(route.paths[0].len(), 1);
5305 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
5306 assert_eq!(route.paths[0][0].short_channel_id, 3);
5307 assert_eq!(route.paths[0][0].fee_msat, 100_000);
5310 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
5311 &get_channel_details(Some(3), nodes[0], InitFeatures::known(), 50_000),
5312 &get_channel_details(Some(2), nodes[0], InitFeatures::known(), 50_000),
5313 ]), 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5314 assert_eq!(route.paths.len(), 2);
5315 assert_eq!(route.paths[0].len(), 1);
5316 assert_eq!(route.paths[1].len(), 1);
5318 assert!((route.paths[0][0].short_channel_id == 3 && route.paths[1][0].short_channel_id == 2) ||
5319 (route.paths[0][0].short_channel_id == 2 && route.paths[1][0].short_channel_id == 3));
5321 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
5322 assert_eq!(route.paths[0][0].fee_msat, 50_000);
5324 assert_eq!(route.paths[1][0].pubkey, nodes[0]);
5325 assert_eq!(route.paths[1][0].fee_msat, 50_000);
5329 // If we have a bunch of outbound channels to the same node, where most are not
5330 // sufficient to pay the full payment, but one is, we should default to just using the
5331 // one single channel that has sufficient balance, avoiding MPP.
5333 // If we have several options above the 3xpayment value threshold, we should pick the
5334 // smallest of them, avoiding further fragmenting our available outbound balance to
5336 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
5337 &get_channel_details(Some(2), nodes[0], InitFeatures::known(), 50_000),
5338 &get_channel_details(Some(3), nodes[0], InitFeatures::known(), 50_000),
5339 &get_channel_details(Some(5), nodes[0], InitFeatures::known(), 50_000),
5340 &get_channel_details(Some(6), nodes[0], InitFeatures::known(), 300_000),
5341 &get_channel_details(Some(7), nodes[0], InitFeatures::known(), 50_000),
5342 &get_channel_details(Some(8), nodes[0], InitFeatures::known(), 50_000),
5343 &get_channel_details(Some(9), nodes[0], InitFeatures::known(), 50_000),
5344 &get_channel_details(Some(4), nodes[0], InitFeatures::known(), 1_000_000),
5345 ]), 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5346 assert_eq!(route.paths.len(), 1);
5347 assert_eq!(route.paths[0].len(), 1);
5349 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
5350 assert_eq!(route.paths[0][0].short_channel_id, 6);
5351 assert_eq!(route.paths[0][0].fee_msat, 100_000);
5356 fn prefers_shorter_route_with_higher_fees() {
5357 let (secp_ctx, network_graph, _, _, logger) = build_graph();
5358 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5359 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
5361 // Without penalizing each hop 100 msats, a longer path with lower fees is chosen.
5362 let scorer = test_utils::TestScorer::with_penalty(0);
5363 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5364 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5365 let route = get_route(
5366 &our_id, &payment_params, &network_graph.read_only(), None, 100, 42,
5367 Arc::clone(&logger), &scorer, &random_seed_bytes
5369 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5371 assert_eq!(route.get_total_fees(), 100);
5372 assert_eq!(route.get_total_amount(), 100);
5373 assert_eq!(path, vec![2, 4, 6, 11, 8]);
5375 // Applying a 100 msat penalty to each hop results in taking channels 7 and 10 to nodes[6]
5376 // from nodes[2] rather than channel 6, 11, and 8, even though the longer path is cheaper.
5377 let scorer = test_utils::TestScorer::with_penalty(100);
5378 let route = get_route(
5379 &our_id, &payment_params, &network_graph.read_only(), None, 100, 42,
5380 Arc::clone(&logger), &scorer, &random_seed_bytes
5382 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5384 assert_eq!(route.get_total_fees(), 300);
5385 assert_eq!(route.get_total_amount(), 100);
5386 assert_eq!(path, vec![2, 4, 7, 10]);
5389 struct BadChannelScorer {
5390 short_channel_id: u64,
5394 impl Writeable for BadChannelScorer {
5395 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), ::io::Error> { unimplemented!() }
5397 impl Score for BadChannelScorer {
5398 fn channel_penalty_msat(&self, short_channel_id: u64, _: &NodeId, _: &NodeId, _: ChannelUsage) -> u64 {
5399 if short_channel_id == self.short_channel_id { u64::max_value() } else { 0 }
5402 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
5403 fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
5404 fn probe_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
5405 fn probe_successful(&mut self, _path: &[&RouteHop]) {}
5408 struct BadNodeScorer {
5413 impl Writeable for BadNodeScorer {
5414 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), ::io::Error> { unimplemented!() }
5417 impl Score for BadNodeScorer {
5418 fn channel_penalty_msat(&self, _: u64, _: &NodeId, target: &NodeId, _: ChannelUsage) -> u64 {
5419 if *target == self.node_id { u64::max_value() } else { 0 }
5422 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
5423 fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
5424 fn probe_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
5425 fn probe_successful(&mut self, _path: &[&RouteHop]) {}
5429 fn avoids_routing_through_bad_channels_and_nodes() {
5430 let (secp_ctx, network, _, _, logger) = build_graph();
5431 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5432 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
5433 let network_graph = network.read_only();
5435 // A path to nodes[6] exists when no penalties are applied to any channel.
5436 let scorer = test_utils::TestScorer::with_penalty(0);
5437 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5438 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5439 let route = get_route(
5440 &our_id, &payment_params, &network_graph, None, 100, 42,
5441 Arc::clone(&logger), &scorer, &random_seed_bytes
5443 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5445 assert_eq!(route.get_total_fees(), 100);
5446 assert_eq!(route.get_total_amount(), 100);
5447 assert_eq!(path, vec![2, 4, 6, 11, 8]);
5449 // A different path to nodes[6] exists if channel 6 cannot be routed over.
5450 let scorer = BadChannelScorer { short_channel_id: 6 };
5451 let route = get_route(
5452 &our_id, &payment_params, &network_graph, None, 100, 42,
5453 Arc::clone(&logger), &scorer, &random_seed_bytes
5455 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5457 assert_eq!(route.get_total_fees(), 300);
5458 assert_eq!(route.get_total_amount(), 100);
5459 assert_eq!(path, vec![2, 4, 7, 10]);
5461 // A path to nodes[6] does not exist if nodes[2] cannot be routed through.
5462 let scorer = BadNodeScorer { node_id: NodeId::from_pubkey(&nodes[2]) };
5464 &our_id, &payment_params, &network_graph, None, 100, 42,
5465 Arc::clone(&logger), &scorer, &random_seed_bytes
5467 Err(LightningError { err, .. } ) => {
5468 assert_eq!(err, "Failed to find a path to the given destination");
5470 Ok(_) => panic!("Expected error"),
5475 fn total_fees_single_path() {
5479 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5480 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5481 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5484 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5485 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5486 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5489 pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
5490 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5491 short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0
5494 payment_params: None,
5497 assert_eq!(route.get_total_fees(), 250);
5498 assert_eq!(route.get_total_amount(), 225);
5502 fn total_fees_multi_path() {
5506 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5507 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5508 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5511 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5512 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5513 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5517 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5518 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5519 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5522 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5523 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5524 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5527 payment_params: None,
5530 assert_eq!(route.get_total_fees(), 200);
5531 assert_eq!(route.get_total_amount(), 300);
5535 fn total_empty_route_no_panic() {
5536 // In an earlier version of `Route::get_total_fees` and `Route::get_total_amount`, they
5537 // would both panic if the route was completely empty. We test to ensure they return 0
5538 // here, even though its somewhat nonsensical as a route.
5539 let route = Route { paths: Vec::new(), payment_params: None };
5541 assert_eq!(route.get_total_fees(), 0);
5542 assert_eq!(route.get_total_amount(), 0);
5546 fn limits_total_cltv_delta() {
5547 let (secp_ctx, network, _, _, logger) = build_graph();
5548 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5549 let network_graph = network.read_only();
5551 let scorer = test_utils::TestScorer::with_penalty(0);
5553 // Make sure that generally there is at least one route available
5554 let feasible_max_total_cltv_delta = 1008;
5555 let feasible_payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes))
5556 .with_max_total_cltv_expiry_delta(feasible_max_total_cltv_delta);
5557 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5558 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5559 let route = get_route(&our_id, &feasible_payment_params, &network_graph, None, 100, 0, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5560 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5561 assert_ne!(path.len(), 0);
5563 // But not if we exclude all paths on the basis of their accumulated CLTV delta
5564 let fail_max_total_cltv_delta = 23;
5565 let fail_payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes))
5566 .with_max_total_cltv_expiry_delta(fail_max_total_cltv_delta);
5567 match get_route(&our_id, &fail_payment_params, &network_graph, None, 100, 0, Arc::clone(&logger), &scorer, &random_seed_bytes)
5569 Err(LightningError { err, .. } ) => {
5570 assert_eq!(err, "Failed to find a path to the given destination");
5572 Ok(_) => panic!("Expected error"),
5577 fn limits_path_length() {
5578 let (secp_ctx, network, _, _, logger) = build_line_graph();
5579 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5580 let network_graph = network.read_only();
5582 let scorer = test_utils::TestScorer::with_penalty(0);
5583 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5584 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5586 // First check we can actually create a long route on this graph.
5587 let feasible_payment_params = PaymentParameters::from_node_id(nodes[18]);
5588 let route = get_route(&our_id, &feasible_payment_params, &network_graph, None, 100, 0,
5589 Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5590 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5591 assert!(path.len() == MAX_PATH_LENGTH_ESTIMATE.into());
5593 // But we can't create a path surpassing the MAX_PATH_LENGTH_ESTIMATE limit.
5594 let fail_payment_params = PaymentParameters::from_node_id(nodes[19]);
5595 match get_route(&our_id, &fail_payment_params, &network_graph, None, 100, 0,
5596 Arc::clone(&logger), &scorer, &random_seed_bytes)
5598 Err(LightningError { err, .. } ) => {
5599 assert_eq!(err, "Failed to find a path to the given destination");
5601 Ok(_) => panic!("Expected error"),
5606 fn adds_and_limits_cltv_offset() {
5607 let (secp_ctx, network_graph, _, _, logger) = build_graph();
5608 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5610 let scorer = test_utils::TestScorer::with_penalty(0);
5612 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
5613 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5614 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5615 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5616 assert_eq!(route.paths.len(), 1);
5618 let cltv_expiry_deltas_before = route.paths[0].iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5620 // Check whether the offset added to the last hop by default is in [1 .. DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA]
5621 let mut route_default = route.clone();
5622 add_random_cltv_offset(&mut route_default, &payment_params, &network_graph.read_only(), &random_seed_bytes);
5623 let cltv_expiry_deltas_default = route_default.paths[0].iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5624 assert_eq!(cltv_expiry_deltas_before.split_last().unwrap().1, cltv_expiry_deltas_default.split_last().unwrap().1);
5625 assert!(cltv_expiry_deltas_default.last() > cltv_expiry_deltas_before.last());
5626 assert!(cltv_expiry_deltas_default.last().unwrap() <= &DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA);
5628 // Check that no offset is added when we restrict the max_total_cltv_expiry_delta
5629 let mut route_limited = route.clone();
5630 let limited_max_total_cltv_expiry_delta = cltv_expiry_deltas_before.iter().sum();
5631 let limited_payment_params = payment_params.with_max_total_cltv_expiry_delta(limited_max_total_cltv_expiry_delta);
5632 add_random_cltv_offset(&mut route_limited, &limited_payment_params, &network_graph.read_only(), &random_seed_bytes);
5633 let cltv_expiry_deltas_limited = route_limited.paths[0].iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5634 assert_eq!(cltv_expiry_deltas_before, cltv_expiry_deltas_limited);
5638 fn adds_plausible_cltv_offset() {
5639 let (secp_ctx, network, _, _, logger) = build_graph();
5640 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5641 let network_graph = network.read_only();
5642 let network_nodes = network_graph.nodes();
5643 let network_channels = network_graph.channels();
5644 let scorer = test_utils::TestScorer::with_penalty(0);
5645 let payment_params = PaymentParameters::from_node_id(nodes[3]);
5646 let keys_manager = test_utils::TestKeysInterface::new(&[4u8; 32], Network::Testnet);
5647 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5649 let mut route = get_route(&our_id, &payment_params, &network_graph, None, 100, 0,
5650 Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5651 add_random_cltv_offset(&mut route, &payment_params, &network_graph, &random_seed_bytes);
5653 let mut path_plausibility = vec![];
5655 for p in route.paths {
5656 // 1. Select random observation point
5657 let mut prng = ChaCha20::new(&random_seed_bytes, &[0u8; 12]);
5658 let mut random_bytes = [0u8; ::core::mem::size_of::<usize>()];
5660 prng.process_in_place(&mut random_bytes);
5661 let random_path_index = usize::from_be_bytes(random_bytes).wrapping_rem(p.len());
5662 let observation_point = NodeId::from_pubkey(&p.get(random_path_index).unwrap().pubkey);
5664 // 2. Calculate what CLTV expiry delta we would observe there
5665 let observed_cltv_expiry_delta: u32 = p[random_path_index..].iter().map(|h| h.cltv_expiry_delta).sum();
5667 // 3. Starting from the observation point, find candidate paths
5668 let mut candidates: VecDeque<(NodeId, Vec<u32>)> = VecDeque::new();
5669 candidates.push_back((observation_point, vec![]));
5671 let mut found_plausible_candidate = false;
5673 'candidate_loop: while let Some((cur_node_id, cur_path_cltv_deltas)) = candidates.pop_front() {
5674 if let Some(remaining) = observed_cltv_expiry_delta.checked_sub(cur_path_cltv_deltas.iter().sum::<u32>()) {
5675 if remaining == 0 || remaining.wrapping_rem(40) == 0 || remaining.wrapping_rem(144) == 0 {
5676 found_plausible_candidate = true;
5677 break 'candidate_loop;
5681 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
5682 for channel_id in &cur_node.channels {
5683 if let Some(channel_info) = network_channels.get(&channel_id) {
5684 if let Some((dir_info, next_id)) = channel_info.as_directed_from(&cur_node_id) {
5685 if let Some(channel_update_info) = dir_info.direction() {
5686 let next_cltv_expiry_delta = channel_update_info.cltv_expiry_delta as u32;
5687 if cur_path_cltv_deltas.iter().sum::<u32>()
5688 .saturating_add(next_cltv_expiry_delta) <= observed_cltv_expiry_delta {
5689 let mut new_path_cltv_deltas = cur_path_cltv_deltas.clone();
5690 new_path_cltv_deltas.push(next_cltv_expiry_delta);
5691 candidates.push_back((*next_id, new_path_cltv_deltas));
5700 path_plausibility.push(found_plausible_candidate);
5702 assert!(path_plausibility.iter().all(|x| *x));
5706 fn builds_correct_path_from_hops() {
5707 let (secp_ctx, network, _, _, logger) = build_graph();
5708 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5709 let network_graph = network.read_only();
5711 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5712 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5714 let payment_params = PaymentParameters::from_node_id(nodes[3]);
5715 let hops = [nodes[1], nodes[2], nodes[4], nodes[3]];
5716 let route = build_route_from_hops_internal(&our_id, &hops, &payment_params,
5717 &network_graph, 100, 0, Arc::clone(&logger), &random_seed_bytes).unwrap();
5718 let route_hop_pubkeys = route.paths[0].iter().map(|hop| hop.pubkey).collect::<Vec<_>>();
5719 assert_eq!(hops.len(), route.paths[0].len());
5720 for (idx, hop_pubkey) in hops.iter().enumerate() {
5721 assert!(*hop_pubkey == route_hop_pubkeys[idx]);
5726 fn avoids_saturating_channels() {
5727 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5728 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5730 let scorer = ProbabilisticScorer::new(Default::default(), &*network_graph, Arc::clone(&logger));
5732 // Set the fee on channel 13 to 100% to match channel 4 giving us two equivalent paths (us
5733 // -> node 7 -> node2 and us -> node 1 -> node 2) which we should balance over.
5734 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5735 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5736 short_channel_id: 4,
5739 cltv_expiry_delta: (4 << 4) | 1,
5740 htlc_minimum_msat: 0,
5741 htlc_maximum_msat: OptionalField::Present(200_000_000),
5743 fee_proportional_millionths: 0,
5744 excess_data: Vec::new()
5746 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5747 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5748 short_channel_id: 13,
5751 cltv_expiry_delta: (13 << 4) | 1,
5752 htlc_minimum_msat: 0,
5753 htlc_maximum_msat: OptionalField::Present(200_000_000),
5755 fee_proportional_millionths: 0,
5756 excess_data: Vec::new()
5759 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
5760 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5761 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5762 // 150,000 sat is less than the available liquidity on each channel, set above.
5763 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 150_000_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5764 assert_eq!(route.paths.len(), 2);
5765 assert!((route.paths[0][1].short_channel_id == 4 && route.paths[1][1].short_channel_id == 13) ||
5766 (route.paths[1][1].short_channel_id == 4 && route.paths[0][1].short_channel_id == 13));
5769 #[cfg(not(feature = "no-std"))]
5770 pub(super) fn random_init_seed() -> u64 {
5771 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
5772 use core::hash::{BuildHasher, Hasher};
5773 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
5774 println!("Using seed of {}", seed);
5777 #[cfg(not(feature = "no-std"))]
5778 use util::ser::ReadableArgs;
5781 #[cfg(not(feature = "no-std"))]
5782 fn generate_routes() {
5783 use routing::scoring::{ProbabilisticScorer, ProbabilisticScoringParameters};
5785 let mut d = match super::test_utils::get_route_file() {
5792 let logger = test_utils::TestLogger::new();
5793 let graph = NetworkGraph::read(&mut d, &logger).unwrap();
5794 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5795 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5797 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
5798 let mut seed = random_init_seed() as usize;
5799 let nodes = graph.read_only().nodes().clone();
5800 'load_endpoints: for _ in 0..10 {
5802 seed = seed.overflowing_mul(0xdeadbeef).0;
5803 let src = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5804 seed = seed.overflowing_mul(0xdeadbeef).0;
5805 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5806 let payment_params = PaymentParameters::from_node_id(dst);
5807 let amt = seed as u64 % 200_000_000;
5808 let params = ProbabilisticScoringParameters::default();
5809 let scorer = ProbabilisticScorer::new(params, &graph, &logger);
5810 if get_route(src, &payment_params, &graph.read_only(), None, amt, 42, &logger, &scorer, &random_seed_bytes).is_ok() {
5811 continue 'load_endpoints;
5818 #[cfg(not(feature = "no-std"))]
5819 fn generate_routes_mpp() {
5820 use routing::scoring::{ProbabilisticScorer, ProbabilisticScoringParameters};
5822 let mut d = match super::test_utils::get_route_file() {
5829 let logger = test_utils::TestLogger::new();
5830 let graph = NetworkGraph::read(&mut d, &logger).unwrap();
5831 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5832 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5834 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
5835 let mut seed = random_init_seed() as usize;
5836 let nodes = graph.read_only().nodes().clone();
5837 'load_endpoints: for _ in 0..10 {
5839 seed = seed.overflowing_mul(0xdeadbeef).0;
5840 let src = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5841 seed = seed.overflowing_mul(0xdeadbeef).0;
5842 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5843 let payment_params = PaymentParameters::from_node_id(dst).with_features(InvoiceFeatures::known());
5844 let amt = seed as u64 % 200_000_000;
5845 let params = ProbabilisticScoringParameters::default();
5846 let scorer = ProbabilisticScorer::new(params, &graph, &logger);
5847 if get_route(src, &payment_params, &graph.read_only(), None, amt, 42, &logger, &scorer, &random_seed_bytes).is_ok() {
5848 continue 'load_endpoints;
5855 fn avoids_banned_nodes() {
5856 let (secp_ctx, network_graph, _, _, logger) = build_line_graph();
5857 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5859 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5860 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5862 let scorer_params = ProbabilisticScoringParameters::default();
5863 let mut scorer = ProbabilisticScorer::new(scorer_params, Arc::clone(&network_graph), Arc::clone(&logger));
5865 // First check we can get a route.
5866 let payment_params = PaymentParameters::from_node_id(nodes[10]);
5867 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes);
5868 assert!(route.is_ok());
5870 // Then check that we can't get a route if we ban an intermediate node.
5871 scorer.add_banned(&NodeId::from_pubkey(&nodes[3]));
5872 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes);
5873 assert!(route.is_err());
5875 // Finally make sure we can route again, when we remove the ban.
5876 scorer.remove_banned(&NodeId::from_pubkey(&nodes[3]));
5877 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes);
5878 assert!(route.is_ok());
5882 #[cfg(all(test, not(feature = "no-std")))]
5883 pub(crate) mod test_utils {
5885 /// Tries to open a network graph file, or panics with a URL to fetch it.
5886 pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
5887 let res = File::open("net_graph-2021-05-31.bin") // By default we're run in RL/lightning
5888 .or_else(|_| File::open("lightning/net_graph-2021-05-31.bin")) // We may be run manually in RL/
5889 .or_else(|_| { // Fall back to guessing based on the binary location
5890 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
5891 let mut path = std::env::current_exe().unwrap();
5892 path.pop(); // lightning-...
5894 path.pop(); // debug
5895 path.pop(); // target
5896 path.push("lightning");
5897 path.push("net_graph-2021-05-31.bin");
5898 eprintln!("{}", path.to_str().unwrap());
5901 .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");
5902 #[cfg(require_route_graph_test)]
5903 return Ok(res.unwrap());
5904 #[cfg(not(require_route_graph_test))]
5909 #[cfg(all(test, feature = "_bench_unstable", not(feature = "no-std")))]
5912 use bitcoin::hashes::Hash;
5913 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
5914 use chain::transaction::OutPoint;
5915 use chain::keysinterface::{KeysManager,KeysInterface};
5916 use ln::channelmanager::{ChannelCounterparty, ChannelDetails};
5917 use ln::features::{InitFeatures, InvoiceFeatures};
5918 use routing::gossip::NetworkGraph;
5919 use routing::scoring::{FixedPenaltyScorer, ProbabilisticScorer, ProbabilisticScoringParameters};
5920 use util::logger::{Logger, Record};
5921 use util::ser::ReadableArgs;
5925 struct DummyLogger {}
5926 impl Logger for DummyLogger {
5927 fn log(&self, _record: &Record) {}
5930 fn read_network_graph(logger: &DummyLogger) -> NetworkGraph<&DummyLogger> {
5931 let mut d = test_utils::get_route_file().unwrap();
5932 NetworkGraph::read(&mut d, logger).unwrap()
5935 fn payer_pubkey() -> PublicKey {
5936 let secp_ctx = Secp256k1::new();
5937 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
5941 fn first_hop(node_id: PublicKey) -> ChannelDetails {
5943 channel_id: [0; 32],
5944 counterparty: ChannelCounterparty {
5945 features: InitFeatures::known(),
5947 unspendable_punishment_reserve: 0,
5948 forwarding_info: None,
5949 outbound_htlc_minimum_msat: None,
5950 outbound_htlc_maximum_msat: None,
5952 funding_txo: Some(OutPoint {
5953 txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0
5956 short_channel_id: Some(1),
5957 inbound_scid_alias: None,
5958 outbound_scid_alias: None,
5959 channel_value_satoshis: 10_000_000,
5961 balance_msat: 10_000_000,
5962 outbound_capacity_msat: 10_000_000,
5963 next_outbound_htlc_limit_msat: 10_000_000,
5964 inbound_capacity_msat: 0,
5965 unspendable_punishment_reserve: None,
5966 confirmations_required: None,
5967 force_close_spend_delay: None,
5969 is_channel_ready: true,
5972 inbound_htlc_minimum_msat: None,
5973 inbound_htlc_maximum_msat: None,
5979 fn generate_routes_with_zero_penalty_scorer(bench: &mut Bencher) {
5980 let logger = DummyLogger {};
5981 let network_graph = read_network_graph(&logger);
5982 let scorer = FixedPenaltyScorer::with_penalty(0);
5983 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::empty());
5987 fn generate_mpp_routes_with_zero_penalty_scorer(bench: &mut Bencher) {
5988 let logger = DummyLogger {};
5989 let network_graph = read_network_graph(&logger);
5990 let scorer = FixedPenaltyScorer::with_penalty(0);
5991 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::known());
5995 fn generate_routes_with_probabilistic_scorer(bench: &mut Bencher) {
5996 let logger = DummyLogger {};
5997 let network_graph = read_network_graph(&logger);
5998 let params = ProbabilisticScoringParameters::default();
5999 let scorer = ProbabilisticScorer::new(params, &network_graph, &logger);
6000 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::empty());
6004 fn generate_mpp_routes_with_probabilistic_scorer(bench: &mut Bencher) {
6005 let logger = DummyLogger {};
6006 let network_graph = read_network_graph(&logger);
6007 let params = ProbabilisticScoringParameters::default();
6008 let scorer = ProbabilisticScorer::new(params, &network_graph, &logger);
6009 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::known());
6012 fn generate_routes<S: Score>(
6013 bench: &mut Bencher, graph: &NetworkGraph<&DummyLogger>, mut scorer: S,
6014 features: InvoiceFeatures
6016 let nodes = graph.read_only().nodes().clone();
6017 let payer = payer_pubkey();
6018 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
6019 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6021 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
6022 let mut routes = Vec::new();
6023 let mut route_endpoints = Vec::new();
6024 let mut seed: usize = 0xdeadbeef;
6025 'load_endpoints: for _ in 0..150 {
6028 let src = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
6030 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
6031 let params = PaymentParameters::from_node_id(dst).with_features(features.clone());
6032 let first_hop = first_hop(src);
6033 let amt = seed as u64 % 1_000_000;
6034 if let Ok(route) = get_route(&payer, ¶ms, &graph.read_only(), Some(&[&first_hop]), amt, 42, &DummyLogger{}, &scorer, &random_seed_bytes) {
6036 route_endpoints.push((first_hop, params, amt));
6037 continue 'load_endpoints;
6042 // ...and seed the scorer with success and failure data...
6043 for route in routes {
6044 let amount = route.get_total_amount();
6045 if amount < 250_000 {
6046 for path in route.paths {
6047 scorer.payment_path_successful(&path.iter().collect::<Vec<_>>());
6049 } else if amount > 750_000 {
6050 for path in route.paths {
6051 let short_channel_id = path[path.len() / 2].short_channel_id;
6052 scorer.payment_path_failed(&path.iter().collect::<Vec<_>>(), short_channel_id);
6057 // Because we've changed channel scores, its possible we'll take different routes to the
6058 // selected destinations, possibly causing us to fail because, eg, the newly-selected path
6059 // requires a too-high CLTV delta.
6060 route_endpoints.retain(|(first_hop, params, amt)| {
6061 get_route(&payer, params, &graph.read_only(), Some(&[first_hop]), *amt, 42, &DummyLogger{}, &scorer, &random_seed_bytes).is_ok()
6063 route_endpoints.truncate(100);
6064 assert_eq!(route_endpoints.len(), 100);
6066 // ...then benchmark finding paths between the nodes we learned.
6069 let (first_hop, params, amt) = &route_endpoints[idx % route_endpoints.len()];
6070 assert!(get_route(&payer, params, &graph.read_only(), Some(&[first_hop]), *amt, 42, &DummyLogger{}, &scorer, &random_seed_bytes).is_ok());