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 NetGraphMsgHandler and use that as your RoutingMessageHandler and then
13 //! interrogate it to get routes for your own payments.
15 use bitcoin::secp256k1::key::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::scoring::Score;
21 use routing::network_graph::{DirectedChannelInfoWithUpdate, EffectiveCapacity, NetworkGraph, ReadOnlyNetworkGraph, NodeId, RoutingFees};
22 use util::ser::{Writeable, Readable};
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.
69 /// Each entry represents a list of hops, NOT INCLUDING our own, where the last hop is the
70 /// destination. Thus, this must always be at least length one. While the maximum length of any
71 /// given path is variable, keeping the length of any path to less than 20 should currently
72 /// ensure it is viable.
73 pub paths: Vec<Vec<RouteHop>>,
74 /// The `payment_params` parameter passed to [`find_route`].
75 /// This is used by `ChannelManager` to track information which may be required for retries,
76 /// provided back to you via [`Event::PaymentPathFailed`].
78 /// [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed
79 pub payment_params: Option<PaymentParameters>,
82 pub(crate) trait RoutePath {
83 /// Gets the fees for a given path, excluding any excess paid to the recipient.
84 fn get_path_fees(&self) -> u64;
86 impl RoutePath for Vec<RouteHop> {
87 fn get_path_fees(&self) -> u64 {
88 // Do not count last hop of each path since that's the full value of the payment
89 self.split_last().map(|(_, path_prefix)| path_prefix).unwrap_or(&[])
90 .iter().map(|hop| &hop.fee_msat)
96 /// Returns the total amount of fees paid on this [`Route`].
98 /// This doesn't include any extra payment made to the recipient, which can happen in excess of
99 /// the amount passed to [`find_route`]'s `params.final_value_msat`.
100 pub fn get_total_fees(&self) -> u64 {
101 self.paths.iter().map(|path| path.get_path_fees()).sum()
104 /// Returns the total amount paid on this [`Route`], excluding the fees.
105 pub fn get_total_amount(&self) -> u64 {
106 return self.paths.iter()
107 .map(|path| path.split_last().map(|(hop, _)| hop.fee_msat).unwrap_or(0))
112 const SERIALIZATION_VERSION: u8 = 1;
113 const MIN_SERIALIZATION_VERSION: u8 = 1;
115 impl Writeable for Route {
116 fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
117 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
118 (self.paths.len() as u64).write(writer)?;
119 for hops in self.paths.iter() {
120 (hops.len() as u8).write(writer)?;
121 for hop in hops.iter() {
125 write_tlv_fields!(writer, {
126 (1, self.payment_params, option),
132 impl Readable for Route {
133 fn read<R: io::Read>(reader: &mut R) -> Result<Route, DecodeError> {
134 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
135 let path_count: u64 = Readable::read(reader)?;
136 let mut paths = Vec::with_capacity(cmp::min(path_count, 128) as usize);
137 for _ in 0..path_count {
138 let hop_count: u8 = Readable::read(reader)?;
139 let mut hops = Vec::with_capacity(hop_count as usize);
140 for _ in 0..hop_count {
141 hops.push(Readable::read(reader)?);
145 let mut payment_params = None;
146 read_tlv_fields!(reader, {
147 (1, payment_params, option),
149 Ok(Route { paths, payment_params })
153 /// Parameters needed to find a [`Route`].
155 /// Passed to [`find_route`] and also provided in [`Event::PaymentPathFailed`] for retrying a failed
158 /// [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed
159 #[derive(Clone, Debug)]
160 pub struct RouteParameters {
161 /// The parameters of the failed payment path.
162 pub payment_params: PaymentParameters,
164 /// The amount in msats sent on the failed payment path.
165 pub final_value_msat: u64,
167 /// The CLTV on the final hop of the failed payment path.
168 pub final_cltv_expiry_delta: u32,
171 impl_writeable_tlv_based!(RouteParameters, {
172 (0, payment_params, required),
173 (2, final_value_msat, required),
174 (4, final_cltv_expiry_delta, required),
177 /// Maximum total CTLV difference we allow for a full payment path.
178 pub const DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA: u32 = 1008;
180 /// The median hop CLTV expiry delta currently seen in the network.
181 const MEDIAN_HOP_CLTV_EXPIRY_DELTA: u32 = 40;
183 /// The recipient of a payment.
184 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
185 pub struct PaymentParameters {
186 /// The node id of the payee.
187 pub payee_pubkey: PublicKey,
189 /// Features supported by the payee.
191 /// May be set from the payee's invoice or via [`for_keysend`]. May be `None` if the invoice
192 /// does not contain any features.
194 /// [`for_keysend`]: Self::for_keysend
195 pub features: Option<InvoiceFeatures>,
197 /// Hints for routing to the payee, containing channels connecting the payee to public nodes.
198 pub route_hints: Vec<RouteHint>,
200 /// Expiration of a payment to the payee, in seconds relative to the UNIX epoch.
201 pub expiry_time: Option<u64>,
203 /// The maximum total CLTV delta we accept for the route.
204 pub max_total_cltv_expiry_delta: u32,
207 impl_writeable_tlv_based!(PaymentParameters, {
208 (0, payee_pubkey, required),
209 (1, max_total_cltv_expiry_delta, (default_value, DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA)),
210 (2, features, option),
211 (4, route_hints, vec_type),
212 (6, expiry_time, option),
215 impl PaymentParameters {
216 /// Creates a payee with the node id of the given `pubkey`.
217 pub fn from_node_id(payee_pubkey: PublicKey) -> Self {
223 max_total_cltv_expiry_delta: DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA,
227 /// Creates a payee with the node id of the given `pubkey` to use for keysend payments.
228 pub fn for_keysend(payee_pubkey: PublicKey) -> Self {
229 Self::from_node_id(payee_pubkey).with_features(InvoiceFeatures::for_keysend())
232 /// Includes the payee's features.
234 /// (C-not exported) since bindings don't support move semantics
235 pub fn with_features(self, features: InvoiceFeatures) -> Self {
236 Self { features: Some(features), ..self }
239 /// Includes hints for routing to the payee.
241 /// (C-not exported) since bindings don't support move semantics
242 pub fn with_route_hints(self, route_hints: Vec<RouteHint>) -> Self {
243 Self { route_hints, ..self }
246 /// Includes a payment expiration in seconds relative to the UNIX epoch.
248 /// (C-not exported) since bindings don't support move semantics
249 pub fn with_expiry_time(self, expiry_time: u64) -> Self {
250 Self { expiry_time: Some(expiry_time), ..self }
253 /// Includes a limit for the total CLTV expiry delta which is considered during routing
255 /// (C-not exported) since bindings don't support move semantics
256 pub fn with_max_total_cltv_expiry_delta(self, max_total_cltv_expiry_delta: u32) -> Self {
257 Self { max_total_cltv_expiry_delta, ..self }
261 /// A list of hops along a payment path terminating with a channel to the recipient.
262 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
263 pub struct RouteHint(pub Vec<RouteHintHop>);
265 impl Writeable for RouteHint {
266 fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
267 (self.0.len() as u64).write(writer)?;
268 for hop in self.0.iter() {
275 impl Readable for RouteHint {
276 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
277 let hop_count: u64 = Readable::read(reader)?;
278 let mut hops = Vec::with_capacity(cmp::min(hop_count, 16) as usize);
279 for _ in 0..hop_count {
280 hops.push(Readable::read(reader)?);
286 /// A channel descriptor for a hop along a payment path.
287 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
288 pub struct RouteHintHop {
289 /// The node_id of the non-target end of the route
290 pub src_node_id: PublicKey,
291 /// The short_channel_id of this channel
292 pub short_channel_id: u64,
293 /// The fees which must be paid to use this channel
294 pub fees: RoutingFees,
295 /// The difference in CLTV values between this node and the next node.
296 pub cltv_expiry_delta: u16,
297 /// The minimum value, in msat, which must be relayed to the next hop.
298 pub htlc_minimum_msat: Option<u64>,
299 /// The maximum value in msat available for routing with a single HTLC.
300 pub htlc_maximum_msat: Option<u64>,
303 impl_writeable_tlv_based!(RouteHintHop, {
304 (0, src_node_id, required),
305 (1, htlc_minimum_msat, option),
306 (2, short_channel_id, required),
307 (3, htlc_maximum_msat, option),
309 (6, cltv_expiry_delta, required),
312 #[derive(Eq, PartialEq)]
313 struct RouteGraphNode {
315 lowest_fee_to_peer_through_node: u64,
316 lowest_fee_to_node: u64,
317 total_cltv_delta: u32,
318 // The maximum value a yet-to-be-constructed payment path might flow through this node.
319 // This value is upper-bounded by us by:
320 // - how much is needed for a path being constructed
321 // - how much value can channels following this node (up to the destination) can contribute,
322 // considering their capacity and fees
323 value_contribution_msat: u64,
324 /// The effective htlc_minimum_msat at this hop. If a later hop on the path had a higher HTLC
325 /// minimum, we use it, plus the fees required at each earlier hop to meet it.
326 path_htlc_minimum_msat: u64,
327 /// All penalties incurred from this hop on the way to the destination, as calculated using
329 path_penalty_msat: u64,
332 impl cmp::Ord for RouteGraphNode {
333 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
334 let other_score = cmp::max(other.lowest_fee_to_peer_through_node, other.path_htlc_minimum_msat)
335 .checked_add(other.path_penalty_msat)
336 .unwrap_or_else(|| u64::max_value());
337 let self_score = cmp::max(self.lowest_fee_to_peer_through_node, self.path_htlc_minimum_msat)
338 .checked_add(self.path_penalty_msat)
339 .unwrap_or_else(|| u64::max_value());
340 other_score.cmp(&self_score).then_with(|| other.node_id.cmp(&self.node_id))
344 impl cmp::PartialOrd for RouteGraphNode {
345 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
346 Some(self.cmp(other))
350 /// A wrapper around the various hop representations.
352 /// Used to construct a [`PathBuildingHop`] and to estimate [`EffectiveCapacity`].
353 #[derive(Clone, Debug)]
354 enum CandidateRouteHop<'a> {
355 /// A hop from the payer, where the outbound liquidity is known.
357 details: &'a ChannelDetails,
359 /// A hop found in the [`NetworkGraph`], where the channel capacity may or may not be known.
361 info: DirectedChannelInfoWithUpdate<'a>,
362 short_channel_id: u64,
364 /// A hop to the payee found in the payment invoice, though not necessarily a direct channel.
366 hint: &'a RouteHintHop,
370 impl<'a> CandidateRouteHop<'a> {
371 fn short_channel_id(&self) -> u64 {
373 CandidateRouteHop::FirstHop { details } => details.short_channel_id.unwrap(),
374 CandidateRouteHop::PublicHop { short_channel_id, .. } => *short_channel_id,
375 CandidateRouteHop::PrivateHop { hint } => hint.short_channel_id,
379 // NOTE: This may alloc memory so avoid calling it in a hot code path.
380 fn features(&self) -> ChannelFeatures {
382 CandidateRouteHop::FirstHop { details } => details.counterparty.features.to_context(),
383 CandidateRouteHop::PublicHop { info, .. } => info.channel().features.clone(),
384 CandidateRouteHop::PrivateHop { .. } => ChannelFeatures::empty(),
388 fn cltv_expiry_delta(&self) -> u32 {
390 CandidateRouteHop::FirstHop { .. } => 0,
391 CandidateRouteHop::PublicHop { info, .. } => info.direction().cltv_expiry_delta as u32,
392 CandidateRouteHop::PrivateHop { hint } => hint.cltv_expiry_delta as u32,
396 fn htlc_minimum_msat(&self) -> u64 {
398 CandidateRouteHop::FirstHop { .. } => 0,
399 CandidateRouteHop::PublicHop { info, .. } => info.direction().htlc_minimum_msat,
400 CandidateRouteHop::PrivateHop { hint } => hint.htlc_minimum_msat.unwrap_or(0),
404 fn fees(&self) -> RoutingFees {
406 CandidateRouteHop::FirstHop { .. } => RoutingFees {
407 base_msat: 0, proportional_millionths: 0,
409 CandidateRouteHop::PublicHop { info, .. } => info.direction().fees,
410 CandidateRouteHop::PrivateHop { hint } => hint.fees,
414 fn effective_capacity(&self) -> EffectiveCapacity {
416 CandidateRouteHop::FirstHop { details } => EffectiveCapacity::ExactLiquidity {
417 liquidity_msat: details.outbound_capacity_msat,
419 CandidateRouteHop::PublicHop { info, .. } => info.effective_capacity(),
420 CandidateRouteHop::PrivateHop { .. } => EffectiveCapacity::Infinite,
425 /// It's useful to keep track of the hops associated with the fees required to use them,
426 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
427 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
428 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
430 struct PathBuildingHop<'a> {
431 // Note that this should be dropped in favor of loading it from CandidateRouteHop, but doing so
432 // is a larger refactor and will require careful performance analysis.
434 candidate: CandidateRouteHop<'a>,
437 /// Minimal fees required to route to the source node of the current hop via any of its inbound channels.
438 src_lowest_inbound_fees: RoutingFees,
439 /// All the fees paid *after* this channel on the way to the destination
440 next_hops_fee_msat: u64,
441 /// Fee paid for the use of the current channel (see candidate.fees()).
442 /// The value will be actually deducted from the counterparty balance on the previous link.
443 hop_use_fee_msat: u64,
444 /// Used to compare channels when choosing the for routing.
445 /// Includes paying for the use of a hop and the following hops, as well as
446 /// an estimated cost of reaching this hop.
447 /// Might get stale when fees are recomputed. Primarily for internal use.
449 /// A mirror of the same field in RouteGraphNode. Note that this is only used during the graph
450 /// walk and may be invalid thereafter.
451 path_htlc_minimum_msat: u64,
452 /// All penalties incurred from this channel on the way to the destination, as calculated using
454 path_penalty_msat: u64,
455 /// If we've already processed a node as the best node, we shouldn't process it again. Normally
456 /// we'd just ignore it if we did as all channels would have a higher new fee, but because we
457 /// may decrease the amounts in use as we walk the graph, the actual calculated fee may
458 /// decrease as well. Thus, we have to explicitly track which nodes have been processed and
459 /// avoid processing them again.
461 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
462 // In tests, we apply further sanity checks on cases where we skip nodes we already processed
463 // to ensure it is specifically in cases where the fee has gone down because of a decrease in
464 // value_contribution_msat, which requires tracking it here. See comments below where it is
465 // used for more info.
466 value_contribution_msat: u64,
469 impl<'a> core::fmt::Debug for PathBuildingHop<'a> {
470 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
471 f.debug_struct("PathBuildingHop")
472 .field("node_id", &self.node_id)
473 .field("short_channel_id", &self.candidate.short_channel_id())
474 .field("total_fee_msat", &self.total_fee_msat)
475 .field("next_hops_fee_msat", &self.next_hops_fee_msat)
476 .field("hop_use_fee_msat", &self.hop_use_fee_msat)
477 .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)))
478 .field("path_penalty_msat", &self.path_penalty_msat)
479 .field("path_htlc_minimum_msat", &self.path_htlc_minimum_msat)
480 .field("cltv_expiry_delta", &self.candidate.cltv_expiry_delta())
485 // Instantiated with a list of hops with correct data in them collected during path finding,
486 // an instance of this struct should be further modified only via given methods.
488 struct PaymentPath<'a> {
489 hops: Vec<(PathBuildingHop<'a>, NodeFeatures)>,
492 impl<'a> PaymentPath<'a> {
493 // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
494 fn get_value_msat(&self) -> u64 {
495 self.hops.last().unwrap().0.fee_msat
498 fn get_total_fee_paid_msat(&self) -> u64 {
499 if self.hops.len() < 1 {
503 // Can't use next_hops_fee_msat because it gets outdated.
504 for (i, (hop, _)) in self.hops.iter().enumerate() {
505 if i != self.hops.len() - 1 {
506 result += hop.fee_msat;
512 // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
513 // to change fees may result in an inconsistency.
515 // Sometimes we call this function right after constructing a path which is inconsistent in
516 // that it the value being transferred has decreased while we were doing path finding, leading
517 // to the fees being paid not lining up with the actual limits.
519 // Note that this function is not aware of the available_liquidity limit, and thus does not
520 // support increasing the value being transferred.
521 fn update_value_and_recompute_fees(&mut self, value_msat: u64) {
522 assert!(value_msat <= self.hops.last().unwrap().0.fee_msat);
524 let mut total_fee_paid_msat = 0 as u64;
525 for i in (0..self.hops.len()).rev() {
526 let last_hop = i == self.hops.len() - 1;
528 // For non-last-hop, this value will represent the fees paid on the current hop. It
529 // will consist of the fees for the use of the next hop, and extra fees to match
530 // htlc_minimum_msat of the current channel. Last hop is handled separately.
531 let mut cur_hop_fees_msat = 0;
533 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().0.hop_use_fee_msat;
536 let mut cur_hop = &mut self.hops.get_mut(i).unwrap().0;
537 cur_hop.next_hops_fee_msat = total_fee_paid_msat;
538 // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
539 // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
540 // set it too high just to maliciously take more fees by exploiting this
541 // match htlc_minimum_msat logic.
542 let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
543 if let Some(extra_fees_msat) = cur_hop.candidate.htlc_minimum_msat().checked_sub(cur_hop_transferred_amount_msat) {
544 // Note that there is a risk that *previous hops* (those closer to us, as we go
545 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
547 // This might make us end up with a broken route, although this should be super-rare
548 // in practice, both because of how healthy channels look like, and how we pick
549 // channels in add_entry.
550 // Also, this can't be exploited more heavily than *announce a free path and fail
552 cur_hop_transferred_amount_msat += extra_fees_msat;
553 total_fee_paid_msat += extra_fees_msat;
554 cur_hop_fees_msat += extra_fees_msat;
558 // Final hop is a special case: it usually has just value_msat (by design), but also
559 // it still could overpay for the htlc_minimum_msat.
560 cur_hop.fee_msat = cur_hop_transferred_amount_msat;
562 // Propagate updated fees for the use of the channels to one hop back, where they
563 // will be actually paid (fee_msat). The last hop is handled above separately.
564 cur_hop.fee_msat = cur_hop_fees_msat;
567 // Fee for the use of the current hop which will be deducted on the previous hop.
568 // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
569 // this channel is free for us.
571 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.candidate.fees()) {
572 cur_hop.hop_use_fee_msat = new_fee;
573 total_fee_paid_msat += new_fee;
575 // It should not be possible because this function is called only to reduce the
576 // value. In that case, compute_fee was already called with the same fees for
577 // larger amount and there was no overflow.
585 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
586 let proportional_fee_millions =
587 amount_msat.checked_mul(channel_fees.proportional_millionths as u64);
588 if let Some(new_fee) = proportional_fee_millions.and_then(|part| {
589 (channel_fees.base_msat as u64).checked_add(part / 1_000_000) }) {
593 // This function may be (indirectly) called without any verification,
594 // with channel_fees provided by a caller. We should handle it gracefully.
599 /// Finds a route from us (payer) to the given target node (payee).
601 /// If the payee provided features in their invoice, they should be provided via `params.payee`.
602 /// Without this, MPP will only be used if the payee's features are available in the network graph.
604 /// Private routing paths between a public node and the target may be included in `params.payee`.
606 /// If some channels aren't announced, it may be useful to fill in `first_hops` with the results
607 /// from [`ChannelManager::list_usable_channels`]. If it is filled in, the view of our local
608 /// channels from [`NetworkGraph`] will be ignored, and only those in `first_hops` will be used.
610 /// The fees on channels from us to the next hop are ignored as they are assumed to all be equal.
611 /// However, the enabled/disabled bit on such channels as well as the `htlc_minimum_msat` /
612 /// `htlc_maximum_msat` *are* checked as they may change based on the receiving node.
616 /// May be used to re-compute a [`Route`] when handling a [`Event::PaymentPathFailed`]. Any
617 /// adjustments to the [`NetworkGraph`] and channel scores should be made prior to calling this
622 /// Panics if first_hops contains channels without short_channel_ids;
623 /// [`ChannelManager::list_usable_channels`] will never include such channels.
625 /// [`ChannelManager::list_usable_channels`]: crate::ln::channelmanager::ChannelManager::list_usable_channels
626 /// [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed
627 pub fn find_route<L: Deref, S: Score>(
628 our_node_pubkey: &PublicKey, route_params: &RouteParameters, network: &NetworkGraph,
629 first_hops: Option<&[&ChannelDetails]>, logger: L, scorer: &S, random_seed_bytes: &[u8; 32]
630 ) -> Result<Route, LightningError>
631 where L::Target: Logger {
632 let network_graph = network.read_only();
634 our_node_pubkey, &route_params.payment_params, &network_graph, first_hops, route_params.final_value_msat,
635 route_params.final_cltv_expiry_delta, logger, scorer, random_seed_bytes
638 add_random_cltv_offset(&mut route, &route_params.payment_params, &network_graph, random_seed_bytes);
641 Err(err) => Err(err),
645 pub(crate) fn get_route<L: Deref, S: Score>(
646 our_node_pubkey: &PublicKey, payment_params: &PaymentParameters, network_graph: &ReadOnlyNetworkGraph,
647 first_hops: Option<&[&ChannelDetails]>, final_value_msat: u64, final_cltv_expiry_delta: u32,
648 logger: L, scorer: &S, _random_seed_bytes: &[u8; 32]
649 ) -> Result<Route, LightningError>
650 where L::Target: Logger {
651 let payee_node_id = NodeId::from_pubkey(&payment_params.payee_pubkey);
652 let our_node_id = NodeId::from_pubkey(&our_node_pubkey);
654 if payee_node_id == our_node_id {
655 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
658 if final_value_msat > MAX_VALUE_MSAT {
659 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
662 if final_value_msat == 0 {
663 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
666 for route in payment_params.route_hints.iter() {
667 for hop in &route.0 {
668 if hop.src_node_id == payment_params.payee_pubkey {
669 return Err(LightningError{err: "Route hint cannot have the payee as the source.".to_owned(), action: ErrorAction::IgnoreError});
673 if payment_params.max_total_cltv_expiry_delta <= final_cltv_expiry_delta {
674 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});
677 // The general routing idea is the following:
678 // 1. Fill first/last hops communicated by the caller.
679 // 2. Attempt to construct a path from payer to payee for transferring
680 // any ~sufficient (described later) value.
681 // If succeed, remember which channels were used and how much liquidity they have available,
682 // so that future paths don't rely on the same liquidity.
683 // 3. Proceed to the next step if:
684 // - we hit the recommended target value;
685 // - OR if we could not construct a new path. Any next attempt will fail too.
686 // Otherwise, repeat step 2.
687 // 4. See if we managed to collect paths which aggregately are able to transfer target value
688 // (not recommended value).
689 // 5. If yes, proceed. If not, fail routing.
690 // 6. Randomly combine paths into routes having enough to fulfill the payment. (TODO: knapsack)
691 // 7. Of all the found paths, select only those with the lowest total fee.
692 // 8. The last path in every selected route is likely to be more than we need.
693 // Reduce its value-to-transfer and recompute fees.
694 // 9. Choose the best route by the lowest total fee.
696 // As for the actual search algorithm,
697 // we do a payee-to-payer pseudo-Dijkstra's sorting by each node's distance from the payee
698 // plus the minimum per-HTLC fee to get from it to another node (aka "shitty pseudo-A*").
700 // We are not a faithful Dijkstra's implementation because we can change values which impact
701 // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
702 // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) than
703 // the value we are currently attempting to send over a path, we simply reduce the value being
704 // sent along the path for any hops after that channel. This may imply that later fees (which
705 // we've already tabulated) are lower because a smaller value is passing through the channels
706 // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
707 // channels which were selected earlier (and which may still be used for other paths without a
708 // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
711 // One potentially problematic case for this algorithm would be if there are many
712 // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
713 // graph walking), we may never find a path which is not liquidity-limited and has lower
714 // proportional fee (and only lower absolute fee when considering the ultimate value sent).
715 // Because we only consider paths with at least 5% of the total value being sent, the damage
716 // from such a case should be limited, however this could be further reduced in the future by
717 // calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
718 // limits for the purposes of fee calculation.
720 // Alternatively, we could store more detailed path information in the heap (targets, below)
721 // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
722 // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
723 // and practically (as we would need to store dynamically-allocated path information in heap
724 // objects, increasing malloc traffic and indirect memory access significantly). Further, the
725 // results of such an algorithm would likely be biased towards lower-value paths.
727 // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
728 // outside of our current search value, running a path search more times to gather candidate
729 // paths at different values. While this may be acceptable, further path searches may increase
730 // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
731 // graph for candidate paths, calculating the maximum value which can realistically be sent at
732 // the same time, remaining generic across different payment values.
734 // TODO: There are a few tweaks we could do, including possibly pre-calculating more stuff
735 // to use as the A* heuristic beyond just the cost to get one node further than the current
738 let network_channels = network_graph.channels();
739 let network_nodes = network_graph.nodes();
741 // Allow MPP only if we have a features set from somewhere that indicates the payee supports
742 // it. If the payee supports it they're supposed to include it in the invoice, so that should
744 let allow_mpp = if let Some(features) = &payment_params.features {
745 features.supports_basic_mpp()
746 } else if let Some(node) = network_nodes.get(&payee_node_id) {
747 if let Some(node_info) = node.announcement_info.as_ref() {
748 node_info.features.supports_basic_mpp()
751 log_trace!(logger, "Searching for a route from payer {} to payee {} {} MPP and {} first hops {}overriding the network graph", our_node_pubkey,
752 payment_params.payee_pubkey, if allow_mpp { "with" } else { "without" },
753 first_hops.map(|hops| hops.len()).unwrap_or(0), if first_hops.is_some() { "" } else { "not " });
756 // Prepare the data we'll use for payee-to-payer search by
757 // inserting first hops suggested by the caller as targets.
758 // Our search will then attempt to reach them while traversing from the payee node.
759 let mut first_hop_targets: HashMap<_, Vec<&ChannelDetails>> =
760 HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
761 if let Some(hops) = first_hops {
763 if chan.short_channel_id.is_none() {
764 panic!("first_hops should be filled in with usable channels, not pending ones");
766 if chan.counterparty.node_id == *our_node_pubkey {
767 return Err(LightningError{err: "First hop cannot have our_node_pubkey as a destination.".to_owned(), action: ErrorAction::IgnoreError});
770 .entry(NodeId::from_pubkey(&chan.counterparty.node_id))
771 .or_insert(Vec::new())
774 if first_hop_targets.is_empty() {
775 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
779 // The main heap containing all candidate next-hops sorted by their score (max(A* fee,
780 // htlc_minimum)). Ideally this would be a heap which allowed cheap score reduction instead of
781 // adding duplicate entries when we find a better path to a given node.
782 let mut targets = BinaryHeap::new();
784 // Map from node_id to information about the best current path to that node, including feerate
786 let mut dist = HashMap::with_capacity(network_nodes.len());
788 // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
789 // indicating that we may wish to try again with a higher value, potentially paying to meet an
790 // htlc_minimum with extra fees while still finding a cheaper path.
791 let mut hit_minimum_limit;
793 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
794 // We start with a path_value of the exact amount we want, and if that generates a route we may
795 // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
796 // amount we want in total across paths, selecting the best subset at the end.
797 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
798 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
799 let mut path_value_msat = final_value_msat;
801 // We don't want multiple paths (as per MPP) share liquidity of the same channels.
802 // This map allows paths to be aware of the channel use by other paths in the same call.
803 // This would help to make a better path finding decisions and not "overbook" channels.
804 // It is unaware of the directions (except for `outbound_capacity_msat` in `first_hops`).
805 let mut bookkept_channels_liquidity_available_msat = HashMap::with_capacity(network_nodes.len());
807 // Keeping track of how much value we already collected across other paths. Helps to decide:
808 // - how much a new path should be transferring (upper bound);
809 // - whether a channel should be disregarded because
810 // it's available liquidity is too small comparing to how much more we need to collect;
811 // - when we want to stop looking for new paths.
812 let mut already_collected_value_msat = 0;
814 for (_, channels) in first_hop_targets.iter_mut() {
815 // Sort the first_hops channels to the same node(s) in priority order of which channel we'd
818 // First, if channels are below `recommended_value_msat`, sort them in descending order,
819 // preferring larger channels to avoid splitting the payment into more MPP parts than is
822 // Second, because simply always sorting in descending order would always use our largest
823 // available outbound capacity, needlessly fragmenting our available channel capacities,
824 // sort channels above `recommended_value_msat` in ascending order, preferring channels
825 // which have enough, but not too much, capacity for the payment.
826 channels.sort_unstable_by(|chan_a, chan_b| {
827 if chan_b.outbound_capacity_msat < recommended_value_msat || chan_a.outbound_capacity_msat < recommended_value_msat {
828 // Sort in descending order
829 chan_b.outbound_capacity_msat.cmp(&chan_a.outbound_capacity_msat)
831 // Sort in ascending order
832 chan_a.outbound_capacity_msat.cmp(&chan_b.outbound_capacity_msat)
837 log_trace!(logger, "Building path from {} (payee) to {} (us/payer) for value {} msat.", payment_params.payee_pubkey, our_node_pubkey, final_value_msat);
839 macro_rules! add_entry {
840 // Adds entry which goes from $src_node_id to $dest_node_id over the $candidate hop.
841 // $next_hops_fee_msat represents the fees paid for using all the channels *after* this one,
842 // since that value has to be transferred over this channel.
843 // Returns whether this channel caused an update to `targets`.
844 ( $candidate: expr, $src_node_id: expr, $dest_node_id: expr, $next_hops_fee_msat: expr,
845 $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr,
846 $next_hops_path_penalty_msat: expr, $next_hops_cltv_delta: expr ) => { {
847 // We "return" whether we updated the path at the end, via this:
848 let mut did_add_update_path_to_src_node = false;
849 // Channels to self should not be used. This is more of belt-and-suspenders, because in
850 // practice these cases should be caught earlier:
851 // - for regular channels at channel announcement (TODO)
852 // - for first and last hops early in get_route
853 if $src_node_id != $dest_node_id {
854 let short_channel_id = $candidate.short_channel_id();
855 let available_liquidity_msat = bookkept_channels_liquidity_available_msat
856 .entry(short_channel_id)
857 .or_insert_with(|| $candidate.effective_capacity());
859 // It is tricky to substract $next_hops_fee_msat from available liquidity here.
860 // It may be misleading because we might later choose to reduce the value transferred
861 // over these channels, and the channel which was insufficient might become sufficient.
862 // Worst case: we drop a good channel here because it can't cover the high following
863 // fees caused by one expensive channel, but then this channel could have been used
864 // if the amount being transferred over this path is lower.
865 // We do this for now, but this is a subject for removal.
866 if let Some(available_value_contribution) = available_liquidity_msat.checked_sub($next_hops_fee_msat) {
868 // Routing Fragmentation Mitigation heuristic:
870 // Routing fragmentation across many payment paths increases the overall routing
871 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
872 // Taking too many smaller paths also increases the chance of payment failure.
873 // Thus to avoid this effect, we require from our collected links to provide
874 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
876 // This requirement is currently 5% of the remaining-to-be-collected value.
877 // This means as we successfully advance in our collection,
878 // the absolute liquidity contribution is lowered,
879 // thus increasing the number of potential channels to be selected.
881 // Derive the minimal liquidity contribution with a ratio of 20 (5%, rounded up)
882 // or 100% if we're not allowed to do multipath payments.
883 let minimal_value_contribution_msat: u64 = if allow_mpp {
884 (recommended_value_msat - already_collected_value_msat + 19) / 20
888 // Verify the liquidity offered by this channel complies to the minimal contribution.
889 let available_value_contribution_msat = available_value_contribution.as_msat_without_bounds();
890 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
892 // Do not consider candidates that exceed the maximum total cltv expiry limit.
893 // In order to already account for some of the privacy enhancing random CLTV
894 // expiry delta offset we add on top later, we subtract a rough estimate
895 // (2*MEDIAN_HOP_CLTV_EXPIRY_DELTA) here.
896 let max_total_cltv_expiry_delta = (payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta)
897 .checked_sub(2*MEDIAN_HOP_CLTV_EXPIRY_DELTA)
898 .unwrap_or(payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta);
899 let hop_total_cltv_delta = ($next_hops_cltv_delta as u32)
900 .checked_add($candidate.cltv_expiry_delta())
901 .unwrap_or(u32::max_value());
902 let doesnt_exceed_cltv_delta_limit = hop_total_cltv_delta <= max_total_cltv_expiry_delta;
904 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
905 // Includes paying fees for the use of the following channels.
906 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
907 Some(result) => result,
908 // Can't overflow due to how the values were computed right above.
909 None => unreachable!(),
911 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
912 let over_path_minimum_msat = amount_to_transfer_over_msat >= $candidate.htlc_minimum_msat() &&
913 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
915 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
916 // bother considering this channel.
917 // Since we're choosing amount_to_transfer_over_msat as maximum possible, it can
918 // be only reduced later (not increased), so this channel should just be skipped
919 // as not sufficient.
920 if !over_path_minimum_msat && doesnt_exceed_cltv_delta_limit {
921 hit_minimum_limit = true;
922 } else if contributes_sufficient_value && doesnt_exceed_cltv_delta_limit {
923 // Note that low contribution here (limited by available_liquidity_msat)
924 // might violate htlc_minimum_msat on the hops which are next along the
925 // payment path (upstream to the payee). To avoid that, we recompute
926 // path fees knowing the final path contribution after constructing it.
927 let path_htlc_minimum_msat = compute_fees($next_hops_path_htlc_minimum_msat, $candidate.fees())
928 .and_then(|fee_msat| fee_msat.checked_add($next_hops_path_htlc_minimum_msat))
929 .map(|fee_msat| cmp::max(fee_msat, $candidate.htlc_minimum_msat()))
930 .unwrap_or_else(|| u64::max_value());
931 let hm_entry = dist.entry($src_node_id);
932 let old_entry = hm_entry.or_insert_with(|| {
933 // If there was previously no known way to access the source node
934 // (recall it goes payee-to-payer) of short_channel_id, first add a
935 // semi-dummy record just to compute the fees to reach the source node.
936 // This will affect our decision on selecting short_channel_id
937 // as a way to reach the $dest_node_id.
938 let mut fee_base_msat = 0;
939 let mut fee_proportional_millionths = 0;
940 if let Some(Some(fees)) = network_nodes.get(&$src_node_id).map(|node| node.lowest_inbound_channel_fees) {
941 fee_base_msat = fees.base_msat;
942 fee_proportional_millionths = fees.proportional_millionths;
945 node_id: $dest_node_id.clone(),
946 candidate: $candidate.clone(),
948 src_lowest_inbound_fees: RoutingFees {
949 base_msat: fee_base_msat,
950 proportional_millionths: fee_proportional_millionths,
952 next_hops_fee_msat: u64::max_value(),
953 hop_use_fee_msat: u64::max_value(),
954 total_fee_msat: u64::max_value(),
955 path_htlc_minimum_msat,
956 path_penalty_msat: u64::max_value(),
957 was_processed: false,
958 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
959 value_contribution_msat,
963 #[allow(unused_mut)] // We only use the mut in cfg(test)
964 let mut should_process = !old_entry.was_processed;
965 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
967 // In test/fuzzing builds, we do extra checks to make sure the skipping
968 // of already-seen nodes only happens in cases we expect (see below).
969 if !should_process { should_process = true; }
973 let mut hop_use_fee_msat = 0;
974 let mut total_fee_msat = $next_hops_fee_msat;
976 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
977 // will have the same effective-fee
978 if $src_node_id != our_node_id {
979 match compute_fees(amount_to_transfer_over_msat, $candidate.fees()) {
980 // max_value means we'll always fail
981 // the old_entry.total_fee_msat > total_fee_msat check
982 None => total_fee_msat = u64::max_value(),
984 hop_use_fee_msat = fee_msat;
985 total_fee_msat += hop_use_fee_msat;
986 // When calculating the lowest inbound fees to a node, we
987 // calculate fees here not based on the actual value we think
988 // will flow over this channel, but on the minimum value that
989 // we'll accept flowing over it. The minimum accepted value
990 // is a constant through each path collection run, ensuring
991 // consistent basis. Otherwise we may later find a
992 // different path to the source node that is more expensive,
993 // but which we consider to be cheaper because we are capacity
994 // constrained and the relative fee becomes lower.
995 match compute_fees(minimal_value_contribution_msat, old_entry.src_lowest_inbound_fees)
996 .map(|a| a.checked_add(total_fee_msat)) {
1001 total_fee_msat = u64::max_value();
1008 let path_penalty_msat = $next_hops_path_penalty_msat.checked_add(
1009 scorer.channel_penalty_msat(short_channel_id, amount_to_transfer_over_msat, *available_liquidity_msat,
1010 &$src_node_id, &$dest_node_id)).unwrap_or_else(|| u64::max_value());
1011 let new_graph_node = RouteGraphNode {
1012 node_id: $src_node_id,
1013 lowest_fee_to_peer_through_node: total_fee_msat,
1014 lowest_fee_to_node: $next_hops_fee_msat as u64 + hop_use_fee_msat,
1015 total_cltv_delta: hop_total_cltv_delta,
1016 value_contribution_msat: value_contribution_msat,
1017 path_htlc_minimum_msat,
1021 // Update the way of reaching $src_node_id with the given short_channel_id (from $dest_node_id),
1022 // if this way is cheaper than the already known
1023 // (considering the cost to "reach" this channel from the route destination,
1024 // the cost of using this channel,
1025 // and the cost of routing to the source node of this channel).
1026 // Also, consider that htlc_minimum_msat_difference, because we might end up
1027 // paying it. Consider the following exploit:
1028 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
1029 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
1030 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
1031 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
1033 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
1034 // but it may require additional tracking - we don't want to double-count
1035 // the fees included in $next_hops_path_htlc_minimum_msat, but also
1036 // can't use something that may decrease on future hops.
1037 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat)
1038 .checked_add(old_entry.path_penalty_msat)
1039 .unwrap_or_else(|| u64::max_value());
1040 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat)
1041 .checked_add(path_penalty_msat)
1042 .unwrap_or_else(|| u64::max_value());
1044 if !old_entry.was_processed && new_cost < old_cost {
1045 targets.push(new_graph_node);
1046 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
1047 old_entry.hop_use_fee_msat = hop_use_fee_msat;
1048 old_entry.total_fee_msat = total_fee_msat;
1049 old_entry.node_id = $dest_node_id.clone();
1050 old_entry.candidate = $candidate.clone();
1051 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
1052 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
1053 old_entry.path_penalty_msat = path_penalty_msat;
1054 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
1056 old_entry.value_contribution_msat = value_contribution_msat;
1058 did_add_update_path_to_src_node = true;
1059 } else if old_entry.was_processed && new_cost < old_cost {
1060 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
1062 // If we're skipping processing a node which was previously
1063 // processed even though we found another path to it with a
1064 // cheaper fee, check that it was because the second path we
1065 // found (which we are processing now) has a lower value
1066 // contribution due to an HTLC minimum limit.
1068 // e.g. take a graph with two paths from node 1 to node 2, one
1069 // through channel A, and one through channel B. Channel A and
1070 // B are both in the to-process heap, with their scores set by
1071 // a higher htlc_minimum than fee.
1072 // Channel A is processed first, and the channels onwards from
1073 // node 1 are added to the to-process heap. Thereafter, we pop
1074 // Channel B off of the heap, note that it has a much more
1075 // restrictive htlc_maximum_msat, and recalculate the fees for
1076 // all of node 1's channels using the new, reduced, amount.
1078 // This would be bogus - we'd be selecting a higher-fee path
1079 // with a lower htlc_maximum_msat instead of the one we'd
1080 // already decided to use.
1081 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
1083 value_contribution_msat + path_penalty_msat <
1084 old_entry.value_contribution_msat + old_entry.path_penalty_msat
1092 did_add_update_path_to_src_node
1096 let empty_node_features = NodeFeatures::empty();
1097 // Find ways (channels with destination) to reach a given node and store them
1098 // in the corresponding data structures (routing graph etc).
1099 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
1100 // meaning how much will be paid in fees after this node (to the best of our knowledge).
1101 // This data can later be helpful to optimize routing (pay lower fees).
1102 macro_rules! add_entries_to_cheapest_to_target_node {
1103 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr, $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr, $next_hops_path_penalty_msat: expr, $next_hops_cltv_delta: expr ) => {
1104 let skip_node = if let Some(elem) = dist.get_mut(&$node_id) {
1105 let was_processed = elem.was_processed;
1106 elem.was_processed = true;
1109 // Entries are added to dist in add_entry!() when there is a channel from a node.
1110 // Because there are no channels from payee, it will not have a dist entry at this point.
1111 // If we're processing any other node, it is always be the result of a channel from it.
1112 assert_eq!($node_id, payee_node_id);
1117 if let Some(first_channels) = first_hop_targets.get(&$node_id) {
1118 for details in first_channels {
1119 let candidate = CandidateRouteHop::FirstHop { details };
1120 add_entry!(candidate, our_node_id, $node_id, $fee_to_target_msat, $next_hops_value_contribution, $next_hops_path_htlc_minimum_msat, $next_hops_path_penalty_msat, $next_hops_cltv_delta);
1124 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
1127 &empty_node_features
1130 if !features.requires_unknown_bits() {
1131 for chan_id in $node.channels.iter() {
1132 let chan = network_channels.get(chan_id).unwrap();
1133 if !chan.features.requires_unknown_bits() {
1134 let (directed_channel, source) =
1135 chan.as_directed_to(&$node_id).expect("inconsistent NetworkGraph");
1136 if first_hops.is_none() || *source != our_node_id {
1137 if let Some(direction) = directed_channel.direction() {
1138 if direction.enabled {
1139 let candidate = CandidateRouteHop::PublicHop {
1140 info: directed_channel.with_update().unwrap(),
1141 short_channel_id: *chan_id,
1143 add_entry!(candidate, *source, $node_id, $fee_to_target_msat, $next_hops_value_contribution, $next_hops_path_htlc_minimum_msat, $next_hops_path_penalty_msat, $next_hops_cltv_delta);
1154 let mut payment_paths = Vec::<PaymentPath>::new();
1156 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
1157 'paths_collection: loop {
1158 // For every new path, start from scratch, except
1159 // bookkept_channels_liquidity_available_msat, which will improve
1160 // the further iterations of path finding. Also don't erase first_hop_targets.
1163 hit_minimum_limit = false;
1165 // If first hop is a private channel and the only way to reach the payee, this is the only
1166 // place where it could be added.
1167 if let Some(first_channels) = first_hop_targets.get(&payee_node_id) {
1168 for details in first_channels {
1169 let candidate = CandidateRouteHop::FirstHop { details };
1170 let added = add_entry!(candidate, our_node_id, payee_node_id, 0, path_value_msat, 0, 0u64, 0);
1171 log_trace!(logger, "{} direct route to payee via SCID {}", if added { "Added" } else { "Skipped" }, candidate.short_channel_id());
1175 // Add the payee as a target, so that the payee-to-payer
1176 // search algorithm knows what to start with.
1177 match network_nodes.get(&payee_node_id) {
1178 // The payee is not in our network graph, so nothing to add here.
1179 // There is still a chance of reaching them via last_hops though,
1180 // so don't yet fail the payment here.
1181 // If not, targets.pop() will not even let us enter the loop in step 2.
1184 add_entries_to_cheapest_to_target_node!(node, payee_node_id, 0, path_value_msat, 0, 0u64, 0);
1189 // If a caller provided us with last hops, add them to routing targets. Since this happens
1190 // earlier than general path finding, they will be somewhat prioritized, although currently
1191 // it matters only if the fees are exactly the same.
1192 for route in payment_params.route_hints.iter().filter(|route| !route.0.is_empty()) {
1193 let first_hop_in_route = &(route.0)[0];
1194 let have_hop_src_in_graph =
1195 // Only add the hops in this route to our candidate set if either
1196 // we have a direct channel to the first hop or the first hop is
1197 // in the regular network graph.
1198 first_hop_targets.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some() ||
1199 network_nodes.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some();
1200 if have_hop_src_in_graph {
1201 // We start building the path from reverse, i.e., from payee
1202 // to the first RouteHintHop in the path.
1203 let hop_iter = route.0.iter().rev();
1204 let prev_hop_iter = core::iter::once(&payment_params.payee_pubkey).chain(
1205 route.0.iter().skip(1).rev().map(|hop| &hop.src_node_id));
1206 let mut hop_used = true;
1207 let mut aggregate_next_hops_fee_msat: u64 = 0;
1208 let mut aggregate_next_hops_path_htlc_minimum_msat: u64 = 0;
1209 let mut aggregate_next_hops_path_penalty_msat: u64 = 0;
1210 let mut aggregate_next_hops_cltv_delta: u32 = 0;
1212 for (idx, (hop, prev_hop_id)) in hop_iter.zip(prev_hop_iter).enumerate() {
1213 let source = NodeId::from_pubkey(&hop.src_node_id);
1214 let target = NodeId::from_pubkey(&prev_hop_id);
1215 let candidate = network_channels
1216 .get(&hop.short_channel_id)
1217 .and_then(|channel| channel.as_directed_to(&target))
1218 .and_then(|(channel, _)| channel.with_update())
1219 .map(|info| CandidateRouteHop::PublicHop {
1221 short_channel_id: hop.short_channel_id,
1223 .unwrap_or_else(|| CandidateRouteHop::PrivateHop { hint: hop });
1224 aggregate_next_hops_path_penalty_msat = aggregate_next_hops_path_penalty_msat
1225 .checked_add(scorer.channel_penalty_msat(hop.short_channel_id, path_value_msat, candidate.effective_capacity(), &source, &target))
1226 .unwrap_or_else(|| u64::max_value());
1228 aggregate_next_hops_cltv_delta = aggregate_next_hops_cltv_delta
1229 .checked_add(hop.cltv_expiry_delta as u32)
1230 .unwrap_or_else(|| u32::max_value());
1232 if !add_entry!(candidate, source, target, aggregate_next_hops_fee_msat, path_value_msat, aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat, aggregate_next_hops_cltv_delta) {
1233 // If this hop was not used then there is no use checking the preceding hops
1234 // in the RouteHint. We can break by just searching for a direct channel between
1235 // last checked hop and first_hop_targets
1239 // Searching for a direct channel between last checked hop and first_hop_targets
1240 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&prev_hop_id)) {
1241 for details in first_channels {
1242 let candidate = CandidateRouteHop::FirstHop { details };
1243 add_entry!(candidate, our_node_id, NodeId::from_pubkey(&prev_hop_id), aggregate_next_hops_fee_msat, path_value_msat, aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat, aggregate_next_hops_cltv_delta);
1251 // In the next values of the iterator, the aggregate fees already reflects
1252 // the sum of value sent from payer (final_value_msat) and routing fees
1253 // for the last node in the RouteHint. We need to just add the fees to
1254 // route through the current node so that the preceeding node (next iteration)
1256 let hops_fee = compute_fees(aggregate_next_hops_fee_msat + final_value_msat, hop.fees)
1257 .map_or(None, |inc| inc.checked_add(aggregate_next_hops_fee_msat));
1258 aggregate_next_hops_fee_msat = if let Some(val) = hops_fee { val } else { break; };
1260 let hop_htlc_minimum_msat = candidate.htlc_minimum_msat();
1261 let hop_htlc_minimum_msat_inc = if let Some(val) = compute_fees(aggregate_next_hops_path_htlc_minimum_msat, hop.fees) { val } else { break; };
1262 let hops_path_htlc_minimum = aggregate_next_hops_path_htlc_minimum_msat
1263 .checked_add(hop_htlc_minimum_msat_inc);
1264 aggregate_next_hops_path_htlc_minimum_msat = if let Some(val) = hops_path_htlc_minimum { cmp::max(hop_htlc_minimum_msat, val) } else { break; };
1266 if idx == route.0.len() - 1 {
1267 // The last hop in this iterator is the first hop in
1268 // overall RouteHint.
1269 // If this hop connects to a node with which we have a direct channel,
1270 // ignore the network graph and, if the last hop was added, add our
1271 // direct channel to the candidate set.
1273 // Note that we *must* check if the last hop was added as `add_entry`
1274 // always assumes that the third argument is a node to which we have a
1276 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&hop.src_node_id)) {
1277 for details in first_channels {
1278 let candidate = CandidateRouteHop::FirstHop { details };
1279 add_entry!(candidate, our_node_id, NodeId::from_pubkey(&hop.src_node_id), aggregate_next_hops_fee_msat, path_value_msat, aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat, aggregate_next_hops_cltv_delta);
1287 log_trace!(logger, "Starting main path collection loop with {} nodes pre-filled from first/last hops.", targets.len());
1289 // At this point, targets are filled with the data from first and
1290 // last hops communicated by the caller, and the payment receiver.
1291 let mut found_new_path = false;
1294 // If this loop terminates due the exhaustion of targets, two situations are possible:
1295 // - not enough outgoing liquidity:
1296 // 0 < already_collected_value_msat < final_value_msat
1297 // - enough outgoing liquidity:
1298 // final_value_msat <= already_collected_value_msat < recommended_value_msat
1299 // Both these cases (and other cases except reaching recommended_value_msat) mean that
1300 // paths_collection will be stopped because found_new_path==false.
1301 // This is not necessarily a routing failure.
1302 '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, .. }) = targets.pop() {
1304 // Since we're going payee-to-payer, hitting our node as a target means we should stop
1305 // traversing the graph and arrange the path out of what we found.
1306 if node_id == our_node_id {
1307 let mut new_entry = dist.remove(&our_node_id).unwrap();
1308 let mut ordered_hops = vec!((new_entry.clone(), NodeFeatures::empty()));
1311 let mut features_set = false;
1312 if let Some(first_channels) = first_hop_targets.get(&ordered_hops.last().unwrap().0.node_id) {
1313 for details in first_channels {
1314 if details.short_channel_id.unwrap() == ordered_hops.last().unwrap().0.candidate.short_channel_id() {
1315 ordered_hops.last_mut().unwrap().1 = details.counterparty.features.to_context();
1316 features_set = true;
1322 if let Some(node) = network_nodes.get(&ordered_hops.last().unwrap().0.node_id) {
1323 if let Some(node_info) = node.announcement_info.as_ref() {
1324 ordered_hops.last_mut().unwrap().1 = node_info.features.clone();
1326 ordered_hops.last_mut().unwrap().1 = NodeFeatures::empty();
1329 // We can fill in features for everything except hops which were
1330 // provided via the invoice we're paying. We could guess based on the
1331 // recipient's features but for now we simply avoid guessing at all.
1335 // Means we succesfully traversed from the payer to the payee, now
1336 // save this path for the payment route. Also, update the liquidity
1337 // remaining on the used hops, so that we take them into account
1338 // while looking for more paths.
1339 if ordered_hops.last().unwrap().0.node_id == payee_node_id {
1343 new_entry = match dist.remove(&ordered_hops.last().unwrap().0.node_id) {
1344 Some(payment_hop) => payment_hop,
1345 // We can't arrive at None because, if we ever add an entry to targets,
1346 // we also fill in the entry in dist (see add_entry!).
1347 None => unreachable!(),
1349 // We "propagate" the fees one hop backward (topologically) here,
1350 // so that fees paid for a HTLC forwarding on the current channel are
1351 // associated with the previous channel (where they will be subtracted).
1352 ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
1353 ordered_hops.push((new_entry.clone(), NodeFeatures::empty()));
1355 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
1356 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
1358 log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: \n {:#?}",
1359 ordered_hops.len(), value_contribution_msat, ordered_hops.iter().map(|h| &(h.0)).collect::<Vec<&PathBuildingHop>>());
1361 let mut payment_path = PaymentPath {hops: ordered_hops};
1363 // We could have possibly constructed a slightly inconsistent path: since we reduce
1364 // value being transferred along the way, we could have violated htlc_minimum_msat
1365 // on some channels we already passed (assuming dest->source direction). Here, we
1366 // recompute the fees again, so that if that's the case, we match the currently
1367 // underpaid htlc_minimum_msat with fees.
1368 payment_path.update_value_and_recompute_fees(cmp::min(value_contribution_msat, final_value_msat));
1370 // Since a path allows to transfer as much value as
1371 // the smallest channel it has ("bottleneck"), we should recompute
1372 // the fees so sender HTLC don't overpay fees when traversing
1373 // larger channels than the bottleneck. This may happen because
1374 // when we were selecting those channels we were not aware how much value
1375 // this path will transfer, and the relative fee for them
1376 // might have been computed considering a larger value.
1377 // Remember that we used these channels so that we don't rely
1378 // on the same liquidity in future paths.
1379 let mut prevented_redundant_path_selection = false;
1380 for (payment_hop, _) in payment_path.hops.iter() {
1381 let channel_liquidity_available_msat = bookkept_channels_liquidity_available_msat.get_mut(&payment_hop.candidate.short_channel_id()).unwrap();
1382 let mut spent_on_hop_msat = value_contribution_msat;
1383 let next_hops_fee_msat = payment_hop.next_hops_fee_msat;
1384 spent_on_hop_msat += next_hops_fee_msat;
1385 if spent_on_hop_msat == channel_liquidity_available_msat.as_msat_without_bounds() {
1386 // If this path used all of this channel's available liquidity, we know
1387 // this path will not be selected again in the next loop iteration.
1388 prevented_redundant_path_selection = true;
1390 *channel_liquidity_available_msat = channel_liquidity_available_msat
1391 .checked_sub(spent_on_hop_msat).unwrap_or(EffectiveCapacity::ExactLiquidity { liquidity_msat: 0 });
1393 if !prevented_redundant_path_selection {
1394 // If we weren't capped by hitting a liquidity limit on a channel in the path,
1395 // we'll probably end up picking the same path again on the next iteration.
1396 // Decrease the available liquidity of a hop in the middle of the path.
1397 let victim_scid = payment_path.hops[(payment_path.hops.len() - 1) / 2].0.candidate.short_channel_id();
1398 log_trace!(logger, "Disabling channel {} for future path building iterations to avoid duplicates.", victim_scid);
1399 let victim_liquidity = bookkept_channels_liquidity_available_msat.get_mut(&victim_scid).unwrap();
1400 *victim_liquidity = EffectiveCapacity::ExactLiquidity { liquidity_msat: 0 };
1403 // Track the total amount all our collected paths allow to send so that we:
1404 // - know when to stop looking for more paths
1405 // - know which of the hops are useless considering how much more sats we need
1406 // (contributes_sufficient_value)
1407 already_collected_value_msat += value_contribution_msat;
1409 payment_paths.push(payment_path);
1410 found_new_path = true;
1411 break 'path_construction;
1414 // If we found a path back to the payee, we shouldn't try to process it again. This is
1415 // the equivalent of the `elem.was_processed` check in
1416 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
1417 if node_id == payee_node_id { continue 'path_construction; }
1419 // Otherwise, since the current target node is not us,
1420 // keep "unrolling" the payment graph from payee to payer by
1421 // finding a way to reach the current target from the payer side.
1422 match network_nodes.get(&node_id) {
1425 add_entries_to_cheapest_to_target_node!(node, node_id, lowest_fee_to_node, value_contribution_msat, path_htlc_minimum_msat, path_penalty_msat, total_cltv_delta);
1431 // If we don't support MPP, no use trying to gather more value ever.
1432 break 'paths_collection;
1436 // Stop either when the recommended value is reached or if no new path was found in this
1438 // In the latter case, making another path finding attempt won't help,
1439 // because we deterministically terminated the search due to low liquidity.
1440 if already_collected_value_msat >= recommended_value_msat || !found_new_path {
1441 log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
1442 already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
1443 break 'paths_collection;
1444 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
1445 // Further, if this was our first walk of the graph, and we weren't limited by an
1446 // htlc_minimum_msat, return immediately because this path should suffice. If we were
1447 // limited by an htlc_minimum_msat value, find another path with a higher value,
1448 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
1449 // still keeping a lower total fee than this path.
1450 if !hit_minimum_limit {
1451 log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
1452 break 'paths_collection;
1454 log_trace!(logger, "Collected our payment amount on the first pass, but running again to collect extra paths with a potentially higher limit.");
1455 path_value_msat = recommended_value_msat;
1460 if payment_paths.len() == 0 {
1461 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1464 if already_collected_value_msat < final_value_msat {
1465 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1468 // Sort by total fees and take the best paths.
1469 payment_paths.sort_by_key(|path| path.get_total_fee_paid_msat());
1470 if payment_paths.len() > 50 {
1471 payment_paths.truncate(50);
1474 // Draw multiple sufficient routes by randomly combining the selected paths.
1475 let mut drawn_routes = Vec::new();
1476 for i in 0..payment_paths.len() {
1477 let mut cur_route = Vec::<PaymentPath>::new();
1478 let mut aggregate_route_value_msat = 0;
1481 // TODO: real random shuffle
1482 // Currently just starts with i_th and goes up to i-1_th in a looped way.
1483 let cur_payment_paths = [&payment_paths[i..], &payment_paths[..i]].concat();
1486 for payment_path in cur_payment_paths {
1487 cur_route.push(payment_path.clone());
1488 aggregate_route_value_msat += payment_path.get_value_msat();
1489 if aggregate_route_value_msat > final_value_msat {
1490 // Last path likely overpaid. Substract it from the most expensive
1491 // (in terms of proportional fee) path in this route and recompute fees.
1492 // This might be not the most economically efficient way, but fewer paths
1493 // also makes routing more reliable.
1494 let mut overpaid_value_msat = aggregate_route_value_msat - final_value_msat;
1496 // First, drop some expensive low-value paths entirely if possible.
1497 // Sort by value so that we drop many really-low values first, since
1498 // fewer paths is better: the payment is less likely to fail.
1499 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1500 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1501 cur_route.sort_by_key(|path| path.get_value_msat());
1502 // We should make sure that at least 1 path left.
1503 let mut paths_left = cur_route.len();
1504 cur_route.retain(|path| {
1505 if paths_left == 1 {
1508 let mut keep = true;
1509 let path_value_msat = path.get_value_msat();
1510 if path_value_msat <= overpaid_value_msat {
1512 overpaid_value_msat -= path_value_msat;
1518 if overpaid_value_msat == 0 {
1522 assert!(cur_route.len() > 0);
1525 // Now, substract the overpaid value from the most-expensive path.
1526 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1527 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1528 cur_route.sort_by_key(|path| { path.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>() });
1529 let expensive_payment_path = cur_route.first_mut().unwrap();
1530 // We already dropped all the small channels above, meaning all the
1531 // remaining channels are larger than remaining overpaid_value_msat.
1532 // Thus, this can't be negative.
1533 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
1534 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
1538 drawn_routes.push(cur_route);
1542 // Select the best route by lowest total fee.
1543 drawn_routes.sort_by_key(|paths| paths.iter().map(|path| path.get_total_fee_paid_msat()).sum::<u64>());
1544 let mut selected_paths = Vec::<Vec<Result<RouteHop, LightningError>>>::new();
1545 for payment_path in drawn_routes.first().unwrap() {
1546 let mut path = payment_path.hops.iter().map(|(payment_hop, node_features)| {
1548 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)})?,
1549 node_features: node_features.clone(),
1550 short_channel_id: payment_hop.candidate.short_channel_id(),
1551 channel_features: payment_hop.candidate.features(),
1552 fee_msat: payment_hop.fee_msat,
1553 cltv_expiry_delta: payment_hop.candidate.cltv_expiry_delta(),
1555 }).collect::<Vec<_>>();
1556 // Propagate the cltv_expiry_delta one hop backwards since the delta from the current hop is
1557 // applicable for the previous hop.
1558 path.iter_mut().rev().fold(final_cltv_expiry_delta, |prev_cltv_expiry_delta, hop| {
1559 core::mem::replace(&mut hop.as_mut().unwrap().cltv_expiry_delta, prev_cltv_expiry_delta)
1561 selected_paths.push(path);
1564 if let Some(features) = &payment_params.features {
1565 for path in selected_paths.iter_mut() {
1566 if let Ok(route_hop) = path.last_mut().unwrap() {
1567 route_hop.node_features = features.to_context();
1573 paths: selected_paths.into_iter().map(|path| path.into_iter().collect()).collect::<Result<Vec<_>, _>>()?,
1574 payment_params: Some(payment_params.clone()),
1576 log_info!(logger, "Got route to {}: {}", payment_params.payee_pubkey, log_route!(route));
1580 // When an adversarial intermediary node observes a payment, it may be able to infer its
1581 // destination, if the remaining CLTV expiry delta exactly matches a feasible path in the network
1582 // graph. In order to improve privacy, this method obfuscates the CLTV expiry deltas along the
1583 // payment path by adding a randomized 'shadow route' offset to the final hop.
1584 fn add_random_cltv_offset(route: &mut Route, payment_params: &PaymentParameters, network_graph: &ReadOnlyNetworkGraph, random_seed_bytes: &[u8; 32]) {
1585 let network_channels = network_graph.channels();
1586 let network_nodes = network_graph.nodes();
1588 for path in route.paths.iter_mut() {
1589 let mut shadow_ctlv_expiry_delta_offset: u32 = 0;
1591 // Remember the last three nodes of the random walk and avoid looping back on them.
1592 // Init with the last three nodes from the actual path, if possible.
1593 let mut nodes_to_avoid: [NodeId; 3] = [NodeId::from_pubkey(&path.last().unwrap().pubkey),
1594 NodeId::from_pubkey(&path.get(path.len().saturating_sub(2)).unwrap().pubkey),
1595 NodeId::from_pubkey(&path.get(path.len().saturating_sub(3)).unwrap().pubkey)];
1597 // Choose the last publicly known node as the starting point for the random walk.
1598 let mut cur_hop: Option<NodeId> = None;
1599 let mut path_nonce = [0u8; 12];
1600 if let Some(starting_hop) = path.iter().rev()
1601 .find(|h| network_nodes.contains_key(&NodeId::from_pubkey(&h.pubkey))) {
1602 cur_hop = Some(NodeId::from_pubkey(&starting_hop.pubkey));
1603 path_nonce.copy_from_slice(&cur_hop.unwrap().as_slice()[..12]);
1606 // Init PRNG with the path-dependant nonce, which is static for private paths.
1607 let mut prng = ChaCha20::new(random_seed_bytes, &path_nonce);
1608 let mut random_path_bytes = [0u8; ::core::mem::size_of::<usize>()];
1610 // Pick a random path length in [1 .. 3]
1611 prng.process_in_place(&mut random_path_bytes);
1612 let random_walk_length = usize::from_be_bytes(random_path_bytes).wrapping_rem(3).wrapping_add(1);
1614 for random_hop in 0..random_walk_length {
1615 // If we don't find a suitable offset in the public network graph, we default to
1616 // MEDIAN_HOP_CLTV_EXPIRY_DELTA.
1617 let mut random_hop_offset = MEDIAN_HOP_CLTV_EXPIRY_DELTA;
1619 if let Some(cur_node_id) = cur_hop {
1620 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
1621 // Randomly choose the next unvisited hop.
1622 prng.process_in_place(&mut random_path_bytes);
1623 if let Some(random_channel) = usize::from_be_bytes(random_path_bytes)
1624 .checked_rem(cur_node.channels.len())
1625 .and_then(|index| cur_node.channels.get(index))
1626 .and_then(|id| network_channels.get(id)) {
1627 random_channel.as_directed_from(&cur_node_id).map(|(dir_info, next_id)| {
1628 if !nodes_to_avoid.iter().any(|x| x == next_id) {
1629 nodes_to_avoid[random_hop] = *next_id;
1630 dir_info.direction().map(|channel_update_info| {
1631 random_hop_offset = channel_update_info.cltv_expiry_delta.into();
1632 cur_hop = Some(*next_id);
1640 shadow_ctlv_expiry_delta_offset = shadow_ctlv_expiry_delta_offset
1641 .checked_add(random_hop_offset)
1642 .unwrap_or(shadow_ctlv_expiry_delta_offset);
1645 // Limit the total offset to reduce the worst-case locked liquidity timevalue
1646 const MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET: u32 = 3*144;
1647 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET);
1649 // Limit the offset so we never exceed the max_total_cltv_expiry_delta. To improve plausibility,
1650 // we choose the limit to be the largest possible multiple of MEDIAN_HOP_CLTV_EXPIRY_DELTA.
1651 let path_total_cltv_expiry_delta: u32 = path.iter().map(|h| h.cltv_expiry_delta).sum();
1652 let mut max_path_offset = payment_params.max_total_cltv_expiry_delta - path_total_cltv_expiry_delta;
1653 max_path_offset = cmp::max(
1654 max_path_offset - (max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA),
1655 max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA);
1656 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, max_path_offset);
1658 // Add 'shadow' CLTV offset to the final hop
1659 if let Some(last_hop) = path.last_mut() {
1660 last_hop.cltv_expiry_delta = last_hop.cltv_expiry_delta
1661 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(last_hop.cltv_expiry_delta);
1668 use routing::network_graph::{EffectiveCapacity, NetworkGraph, NetGraphMsgHandler, NodeId};
1669 use routing::router::{get_route, add_random_cltv_offset, PaymentParameters, Route, RouteHint, RouteHintHop, RouteHop, RoutingFees, DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA};
1670 use routing::scoring::Score;
1671 use chain::transaction::OutPoint;
1672 use chain::keysinterface::KeysInterface;
1673 use ln::features::{ChannelFeatures, InitFeatures, InvoiceFeatures, NodeFeatures};
1674 use ln::msgs::{ErrorAction, LightningError, OptionalField, UnsignedChannelAnnouncement, ChannelAnnouncement, RoutingMessageHandler,
1675 NodeAnnouncement, UnsignedNodeAnnouncement, ChannelUpdate, UnsignedChannelUpdate};
1676 use ln::channelmanager;
1677 use util::test_utils;
1678 use util::chacha20::ChaCha20;
1679 use util::ser::Writeable;
1681 use util::ser::Writer;
1683 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
1684 use bitcoin::hashes::Hash;
1685 use bitcoin::network::constants::Network;
1686 use bitcoin::blockdata::constants::genesis_block;
1687 use bitcoin::blockdata::script::Builder;
1688 use bitcoin::blockdata::opcodes;
1689 use bitcoin::blockdata::transaction::TxOut;
1693 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
1694 use bitcoin::secp256k1::{Secp256k1, All};
1697 use sync::{self, Arc};
1699 fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
1700 features: InitFeatures, outbound_capacity_msat: u64) -> channelmanager::ChannelDetails {
1701 channelmanager::ChannelDetails {
1702 channel_id: [0; 32],
1703 counterparty: channelmanager::ChannelCounterparty {
1706 unspendable_punishment_reserve: 0,
1707 forwarding_info: None,
1709 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
1711 inbound_scid_alias: None,
1712 channel_value_satoshis: 0,
1715 outbound_capacity_msat,
1716 inbound_capacity_msat: 42,
1717 unspendable_punishment_reserve: None,
1718 confirmations_required: None,
1719 force_close_spend_delay: None,
1720 is_outbound: true, is_funding_locked: true,
1721 is_usable: true, is_public: true,
1725 // Using the same keys for LN and BTC ids
1727 net_graph_msg_handler: &NetGraphMsgHandler<Arc<NetworkGraph>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1728 secp_ctx: &Secp256k1<All>, node_1_privkey: &SecretKey, node_2_privkey: &SecretKey, features: ChannelFeatures, short_channel_id: u64
1730 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1731 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1733 let unsigned_announcement = UnsignedChannelAnnouncement {
1735 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1739 bitcoin_key_1: node_id_1,
1740 bitcoin_key_2: node_id_2,
1741 excess_data: Vec::new(),
1744 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1745 let valid_announcement = ChannelAnnouncement {
1746 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1747 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1748 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1749 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1750 contents: unsigned_announcement.clone(),
1752 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1753 Ok(res) => assert!(res),
1759 net_graph_msg_handler: &NetGraphMsgHandler<Arc<NetworkGraph>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1760 secp_ctx: &Secp256k1<All>, node_privkey: &SecretKey, update: UnsignedChannelUpdate
1762 let msghash = hash_to_message!(&Sha256dHash::hash(&update.encode()[..])[..]);
1763 let valid_channel_update = ChannelUpdate {
1764 signature: secp_ctx.sign(&msghash, node_privkey),
1765 contents: update.clone()
1768 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1769 Ok(res) => assert!(res),
1774 fn add_or_update_node(
1775 net_graph_msg_handler: &NetGraphMsgHandler<Arc<NetworkGraph>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1776 secp_ctx: &Secp256k1<All>, node_privkey: &SecretKey, features: NodeFeatures, timestamp: u32
1778 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
1779 let unsigned_announcement = UnsignedNodeAnnouncement {
1785 addresses: Vec::new(),
1786 excess_address_data: Vec::new(),
1787 excess_data: Vec::new(),
1789 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1790 let valid_announcement = NodeAnnouncement {
1791 signature: secp_ctx.sign(&msghash, node_privkey),
1792 contents: unsigned_announcement.clone()
1795 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1801 fn get_nodes(secp_ctx: &Secp256k1<All>) -> (SecretKey, PublicKey, Vec<SecretKey>, Vec<PublicKey>) {
1802 let privkeys: Vec<SecretKey> = (2..10).map(|i| {
1803 SecretKey::from_slice(&hex::decode(format!("{:02x}", i).repeat(32)).unwrap()[..]).unwrap()
1806 let pubkeys = privkeys.iter().map(|secret| PublicKey::from_secret_key(&secp_ctx, secret)).collect();
1808 let our_privkey = SecretKey::from_slice(&hex::decode("01".repeat(32)).unwrap()[..]).unwrap();
1809 let our_id = PublicKey::from_secret_key(&secp_ctx, &our_privkey);
1811 (our_privkey, our_id, privkeys, pubkeys)
1814 fn id_to_feature_flags(id: u8) -> Vec<u8> {
1815 // Set the feature flags to the id'th odd (ie non-required) feature bit so that we can
1816 // test for it later.
1817 let idx = (id - 1) * 2 + 1;
1819 vec![1 << (idx - 8*3), 0, 0, 0]
1820 } else if idx > 8*2 {
1821 vec![1 << (idx - 8*2), 0, 0]
1822 } else if idx > 8*1 {
1823 vec![1 << (idx - 8*1), 0]
1829 fn build_graph() -> (
1831 sync::Arc<NetworkGraph>,
1832 NetGraphMsgHandler<sync::Arc<NetworkGraph>, sync::Arc<test_utils::TestChainSource>, sync::Arc<crate::util::test_utils::TestLogger>>,
1833 sync::Arc<test_utils::TestChainSource>,
1834 sync::Arc<test_utils::TestLogger>,
1836 let secp_ctx = Secp256k1::new();
1837 let logger = Arc::new(test_utils::TestLogger::new());
1838 let chain_monitor = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1839 let network_graph = Arc::new(NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash()));
1840 let net_graph_msg_handler = NetGraphMsgHandler::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
1841 // Build network from our_id to node6:
1843 // -1(1)2- node0 -1(3)2-
1845 // our_id -1(12)2- node7 -1(13)2--- node2
1847 // -1(2)2- node1 -1(4)2-
1850 // chan1 1-to-2: disabled
1851 // chan1 2-to-1: enabled, 0 fee
1853 // chan2 1-to-2: enabled, ignored fee
1854 // chan2 2-to-1: enabled, 0 fee
1856 // chan3 1-to-2: enabled, 0 fee
1857 // chan3 2-to-1: enabled, 100 msat fee
1859 // chan4 1-to-2: enabled, 100% fee
1860 // chan4 2-to-1: enabled, 0 fee
1862 // chan12 1-to-2: enabled, ignored fee
1863 // chan12 2-to-1: enabled, 0 fee
1865 // chan13 1-to-2: enabled, 200% fee
1866 // chan13 2-to-1: enabled, 0 fee
1869 // -1(5)2- node3 -1(8)2--
1873 // node2--1(6)2- node4 -1(9)2--- node6 (not in global route map)
1875 // -1(7)2- node5 -1(10)2-
1877 // Channels 5, 8, 9 and 10 are private channels.
1879 // chan5 1-to-2: enabled, 100 msat fee
1880 // chan5 2-to-1: enabled, 0 fee
1882 // chan6 1-to-2: enabled, 0 fee
1883 // chan6 2-to-1: enabled, 0 fee
1885 // chan7 1-to-2: enabled, 100% fee
1886 // chan7 2-to-1: enabled, 0 fee
1888 // chan8 1-to-2: enabled, variable fee (0 then 1000 msat)
1889 // chan8 2-to-1: enabled, 0 fee
1891 // chan9 1-to-2: enabled, 1001 msat fee
1892 // chan9 2-to-1: enabled, 0 fee
1894 // chan10 1-to-2: enabled, 0 fee
1895 // chan10 2-to-1: enabled, 0 fee
1897 // chan11 1-to-2: enabled, 0 fee
1898 // chan11 2-to-1: enabled, 0 fee
1900 let (our_privkey, _, privkeys, _) = get_nodes(&secp_ctx);
1902 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[0], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
1903 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1904 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1905 short_channel_id: 1,
1908 cltv_expiry_delta: 0,
1909 htlc_minimum_msat: 0,
1910 htlc_maximum_msat: OptionalField::Absent,
1912 fee_proportional_millionths: 0,
1913 excess_data: Vec::new()
1916 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
1918 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
1919 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1920 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1921 short_channel_id: 2,
1924 cltv_expiry_delta: (5 << 4) | 3,
1925 htlc_minimum_msat: 0,
1926 htlc_maximum_msat: OptionalField::Absent,
1927 fee_base_msat: u32::max_value(),
1928 fee_proportional_millionths: u32::max_value(),
1929 excess_data: Vec::new()
1931 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1932 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1933 short_channel_id: 2,
1936 cltv_expiry_delta: 0,
1937 htlc_minimum_msat: 0,
1938 htlc_maximum_msat: OptionalField::Absent,
1940 fee_proportional_millionths: 0,
1941 excess_data: Vec::new()
1944 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
1946 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[7], ChannelFeatures::from_le_bytes(id_to_feature_flags(12)), 12);
1947 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1948 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1949 short_channel_id: 12,
1952 cltv_expiry_delta: (5 << 4) | 3,
1953 htlc_minimum_msat: 0,
1954 htlc_maximum_msat: OptionalField::Absent,
1955 fee_base_msat: u32::max_value(),
1956 fee_proportional_millionths: u32::max_value(),
1957 excess_data: Vec::new()
1959 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1960 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1961 short_channel_id: 12,
1964 cltv_expiry_delta: 0,
1965 htlc_minimum_msat: 0,
1966 htlc_maximum_msat: OptionalField::Absent,
1968 fee_proportional_millionths: 0,
1969 excess_data: Vec::new()
1972 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], NodeFeatures::from_le_bytes(id_to_feature_flags(8)), 0);
1974 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
1975 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1976 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1977 short_channel_id: 3,
1980 cltv_expiry_delta: (3 << 4) | 1,
1981 htlc_minimum_msat: 0,
1982 htlc_maximum_msat: OptionalField::Absent,
1984 fee_proportional_millionths: 0,
1985 excess_data: Vec::new()
1987 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1988 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1989 short_channel_id: 3,
1992 cltv_expiry_delta: (3 << 4) | 2,
1993 htlc_minimum_msat: 0,
1994 htlc_maximum_msat: OptionalField::Absent,
1996 fee_proportional_millionths: 0,
1997 excess_data: Vec::new()
2000 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
2001 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2002 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2003 short_channel_id: 4,
2006 cltv_expiry_delta: (4 << 4) | 1,
2007 htlc_minimum_msat: 0,
2008 htlc_maximum_msat: OptionalField::Absent,
2010 fee_proportional_millionths: 1000000,
2011 excess_data: Vec::new()
2013 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2014 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2015 short_channel_id: 4,
2018 cltv_expiry_delta: (4 << 4) | 2,
2019 htlc_minimum_msat: 0,
2020 htlc_maximum_msat: OptionalField::Absent,
2022 fee_proportional_millionths: 0,
2023 excess_data: Vec::new()
2026 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(13)), 13);
2027 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2028 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2029 short_channel_id: 13,
2032 cltv_expiry_delta: (13 << 4) | 1,
2033 htlc_minimum_msat: 0,
2034 htlc_maximum_msat: OptionalField::Absent,
2036 fee_proportional_millionths: 2000000,
2037 excess_data: Vec::new()
2039 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2040 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2041 short_channel_id: 13,
2044 cltv_expiry_delta: (13 << 4) | 2,
2045 htlc_minimum_msat: 0,
2046 htlc_maximum_msat: OptionalField::Absent,
2048 fee_proportional_millionths: 0,
2049 excess_data: Vec::new()
2052 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
2054 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
2055 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2056 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2057 short_channel_id: 6,
2060 cltv_expiry_delta: (6 << 4) | 1,
2061 htlc_minimum_msat: 0,
2062 htlc_maximum_msat: OptionalField::Absent,
2064 fee_proportional_millionths: 0,
2065 excess_data: Vec::new()
2067 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
2068 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2069 short_channel_id: 6,
2072 cltv_expiry_delta: (6 << 4) | 2,
2073 htlc_minimum_msat: 0,
2074 htlc_maximum_msat: OptionalField::Absent,
2076 fee_proportional_millionths: 0,
2077 excess_data: Vec::new(),
2080 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(11)), 11);
2081 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
2082 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2083 short_channel_id: 11,
2086 cltv_expiry_delta: (11 << 4) | 1,
2087 htlc_minimum_msat: 0,
2088 htlc_maximum_msat: OptionalField::Absent,
2090 fee_proportional_millionths: 0,
2091 excess_data: Vec::new()
2093 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
2094 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2095 short_channel_id: 11,
2098 cltv_expiry_delta: (11 << 4) | 2,
2099 htlc_minimum_msat: 0,
2100 htlc_maximum_msat: OptionalField::Absent,
2102 fee_proportional_millionths: 0,
2103 excess_data: Vec::new()
2106 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(5)), 0);
2108 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
2110 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[5], ChannelFeatures::from_le_bytes(id_to_feature_flags(7)), 7);
2111 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2112 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2113 short_channel_id: 7,
2116 cltv_expiry_delta: (7 << 4) | 1,
2117 htlc_minimum_msat: 0,
2118 htlc_maximum_msat: OptionalField::Absent,
2120 fee_proportional_millionths: 1000000,
2121 excess_data: Vec::new()
2123 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[5], UnsignedChannelUpdate {
2124 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2125 short_channel_id: 7,
2128 cltv_expiry_delta: (7 << 4) | 2,
2129 htlc_minimum_msat: 0,
2130 htlc_maximum_msat: OptionalField::Absent,
2132 fee_proportional_millionths: 0,
2133 excess_data: Vec::new()
2136 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[5], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
2138 (secp_ctx, network_graph, net_graph_msg_handler, chain_monitor, logger)
2142 fn simple_route_test() {
2143 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2144 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2145 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2146 let scorer = test_utils::TestScorer::with_penalty(0);
2147 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2148 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2150 // Simple route to 2 via 1
2152 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) {
2153 assert_eq!(err, "Cannot send a payment of 0 msat");
2154 } else { panic!(); }
2156 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2157 assert_eq!(route.paths[0].len(), 2);
2159 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2160 assert_eq!(route.paths[0][0].short_channel_id, 2);
2161 assert_eq!(route.paths[0][0].fee_msat, 100);
2162 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2163 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2164 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2166 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2167 assert_eq!(route.paths[0][1].short_channel_id, 4);
2168 assert_eq!(route.paths[0][1].fee_msat, 100);
2169 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2170 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2171 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2175 fn invalid_first_hop_test() {
2176 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2177 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2178 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2179 let scorer = test_utils::TestScorer::with_penalty(0);
2180 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2181 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2183 // Simple route to 2 via 1
2185 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
2187 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) =
2188 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) {
2189 assert_eq!(err, "First hop cannot have our_node_pubkey as a destination.");
2190 } else { panic!(); }
2192 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2193 assert_eq!(route.paths[0].len(), 2);
2197 fn htlc_minimum_test() {
2198 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2199 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2200 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2201 let scorer = test_utils::TestScorer::with_penalty(0);
2202 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2203 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2205 // Simple route to 2 via 1
2207 // Disable other paths
2208 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2209 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2210 short_channel_id: 12,
2212 flags: 2, // to disable
2213 cltv_expiry_delta: 0,
2214 htlc_minimum_msat: 0,
2215 htlc_maximum_msat: OptionalField::Absent,
2217 fee_proportional_millionths: 0,
2218 excess_data: Vec::new()
2220 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2221 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2222 short_channel_id: 3,
2224 flags: 2, // to disable
2225 cltv_expiry_delta: 0,
2226 htlc_minimum_msat: 0,
2227 htlc_maximum_msat: OptionalField::Absent,
2229 fee_proportional_millionths: 0,
2230 excess_data: Vec::new()
2232 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2233 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2234 short_channel_id: 13,
2236 flags: 2, // to disable
2237 cltv_expiry_delta: 0,
2238 htlc_minimum_msat: 0,
2239 htlc_maximum_msat: OptionalField::Absent,
2241 fee_proportional_millionths: 0,
2242 excess_data: Vec::new()
2244 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2245 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2246 short_channel_id: 6,
2248 flags: 2, // to disable
2249 cltv_expiry_delta: 0,
2250 htlc_minimum_msat: 0,
2251 htlc_maximum_msat: OptionalField::Absent,
2253 fee_proportional_millionths: 0,
2254 excess_data: Vec::new()
2256 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2257 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2258 short_channel_id: 7,
2260 flags: 2, // to disable
2261 cltv_expiry_delta: 0,
2262 htlc_minimum_msat: 0,
2263 htlc_maximum_msat: OptionalField::Absent,
2265 fee_proportional_millionths: 0,
2266 excess_data: Vec::new()
2269 // Check against amount_to_transfer_over_msat.
2270 // Set minimal HTLC of 200_000_000 msat.
2271 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2272 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2273 short_channel_id: 2,
2276 cltv_expiry_delta: 0,
2277 htlc_minimum_msat: 200_000_000,
2278 htlc_maximum_msat: OptionalField::Absent,
2280 fee_proportional_millionths: 0,
2281 excess_data: Vec::new()
2284 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
2286 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2287 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2288 short_channel_id: 4,
2291 cltv_expiry_delta: 0,
2292 htlc_minimum_msat: 0,
2293 htlc_maximum_msat: OptionalField::Present(199_999_999),
2295 fee_proportional_millionths: 0,
2296 excess_data: Vec::new()
2299 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
2300 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) {
2301 assert_eq!(err, "Failed to find a path to the given destination");
2302 } else { panic!(); }
2304 // Lift the restriction on the first hop.
2305 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2306 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2307 short_channel_id: 2,
2310 cltv_expiry_delta: 0,
2311 htlc_minimum_msat: 0,
2312 htlc_maximum_msat: OptionalField::Absent,
2314 fee_proportional_millionths: 0,
2315 excess_data: Vec::new()
2318 // A payment above the minimum should pass
2319 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();
2320 assert_eq!(route.paths[0].len(), 2);
2324 fn htlc_minimum_overpay_test() {
2325 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2326 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2327 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
2328 let scorer = test_utils::TestScorer::with_penalty(0);
2329 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2330 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2332 // A route to node#2 via two paths.
2333 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
2334 // Thus, they can't send 60 without overpaying.
2335 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2336 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2337 short_channel_id: 2,
2340 cltv_expiry_delta: 0,
2341 htlc_minimum_msat: 35_000,
2342 htlc_maximum_msat: OptionalField::Present(40_000),
2344 fee_proportional_millionths: 0,
2345 excess_data: Vec::new()
2347 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2348 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2349 short_channel_id: 12,
2352 cltv_expiry_delta: 0,
2353 htlc_minimum_msat: 35_000,
2354 htlc_maximum_msat: OptionalField::Present(40_000),
2356 fee_proportional_millionths: 0,
2357 excess_data: Vec::new()
2361 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2362 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2363 short_channel_id: 13,
2366 cltv_expiry_delta: 0,
2367 htlc_minimum_msat: 0,
2368 htlc_maximum_msat: OptionalField::Absent,
2370 fee_proportional_millionths: 0,
2371 excess_data: Vec::new()
2373 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2374 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2375 short_channel_id: 4,
2378 cltv_expiry_delta: 0,
2379 htlc_minimum_msat: 0,
2380 htlc_maximum_msat: OptionalField::Absent,
2382 fee_proportional_millionths: 0,
2383 excess_data: Vec::new()
2386 // Disable other paths
2387 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2388 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2389 short_channel_id: 1,
2391 flags: 2, // to disable
2392 cltv_expiry_delta: 0,
2393 htlc_minimum_msat: 0,
2394 htlc_maximum_msat: OptionalField::Absent,
2396 fee_proportional_millionths: 0,
2397 excess_data: Vec::new()
2400 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 60_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2401 // Overpay fees to hit htlc_minimum_msat.
2402 let overpaid_fees = route.paths[0][0].fee_msat + route.paths[1][0].fee_msat;
2403 // TODO: this could be better balanced to overpay 10k and not 15k.
2404 assert_eq!(overpaid_fees, 15_000);
2406 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
2407 // while taking even more fee to match htlc_minimum_msat.
2408 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2409 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2410 short_channel_id: 12,
2413 cltv_expiry_delta: 0,
2414 htlc_minimum_msat: 65_000,
2415 htlc_maximum_msat: OptionalField::Present(80_000),
2417 fee_proportional_millionths: 0,
2418 excess_data: Vec::new()
2420 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2421 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2422 short_channel_id: 2,
2425 cltv_expiry_delta: 0,
2426 htlc_minimum_msat: 0,
2427 htlc_maximum_msat: OptionalField::Absent,
2429 fee_proportional_millionths: 0,
2430 excess_data: Vec::new()
2432 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2433 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2434 short_channel_id: 4,
2437 cltv_expiry_delta: 0,
2438 htlc_minimum_msat: 0,
2439 htlc_maximum_msat: OptionalField::Absent,
2441 fee_proportional_millionths: 100_000,
2442 excess_data: Vec::new()
2445 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 60_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2446 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
2447 assert_eq!(route.paths.len(), 1);
2448 assert_eq!(route.paths[0][0].short_channel_id, 12);
2449 let fees = route.paths[0][0].fee_msat;
2450 assert_eq!(fees, 5_000);
2452 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2453 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
2454 // the other channel.
2455 assert_eq!(route.paths.len(), 1);
2456 assert_eq!(route.paths[0][0].short_channel_id, 2);
2457 let fees = route.paths[0][0].fee_msat;
2458 assert_eq!(fees, 5_000);
2462 fn disable_channels_test() {
2463 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2464 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2465 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2466 let scorer = test_utils::TestScorer::with_penalty(0);
2467 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2468 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2470 // // Disable channels 4 and 12 by flags=2
2471 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2472 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2473 short_channel_id: 4,
2475 flags: 2, // to disable
2476 cltv_expiry_delta: 0,
2477 htlc_minimum_msat: 0,
2478 htlc_maximum_msat: OptionalField::Absent,
2480 fee_proportional_millionths: 0,
2481 excess_data: Vec::new()
2483 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2484 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2485 short_channel_id: 12,
2487 flags: 2, // to disable
2488 cltv_expiry_delta: 0,
2489 htlc_minimum_msat: 0,
2490 htlc_maximum_msat: OptionalField::Absent,
2492 fee_proportional_millionths: 0,
2493 excess_data: Vec::new()
2496 // If all the channels require some features we don't understand, route should fail
2497 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) {
2498 assert_eq!(err, "Failed to find a path to the given destination");
2499 } else { panic!(); }
2501 // If we specify a channel to node7, that overrides our local channel view and that gets used
2502 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2503 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();
2504 assert_eq!(route.paths[0].len(), 2);
2506 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2507 assert_eq!(route.paths[0][0].short_channel_id, 42);
2508 assert_eq!(route.paths[0][0].fee_msat, 200);
2509 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2510 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2511 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2513 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2514 assert_eq!(route.paths[0][1].short_channel_id, 13);
2515 assert_eq!(route.paths[0][1].fee_msat, 100);
2516 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2517 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2518 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2522 fn disable_node_test() {
2523 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2524 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2525 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2526 let scorer = test_utils::TestScorer::with_penalty(0);
2527 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2528 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2530 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
2531 let mut unknown_features = NodeFeatures::known();
2532 unknown_features.set_unknown_feature_required();
2533 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
2534 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
2535 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
2537 // If all nodes require some features we don't understand, route should fail
2538 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) {
2539 assert_eq!(err, "Failed to find a path to the given destination");
2540 } else { panic!(); }
2542 // If we specify a channel to node7, that overrides our local channel view and that gets used
2543 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2544 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();
2545 assert_eq!(route.paths[0].len(), 2);
2547 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2548 assert_eq!(route.paths[0][0].short_channel_id, 42);
2549 assert_eq!(route.paths[0][0].fee_msat, 200);
2550 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2551 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2552 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2554 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2555 assert_eq!(route.paths[0][1].short_channel_id, 13);
2556 assert_eq!(route.paths[0][1].fee_msat, 100);
2557 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2558 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2559 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2561 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
2562 // naively) assume that the user checked the feature bits on the invoice, which override
2563 // the node_announcement.
2567 fn our_chans_test() {
2568 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2569 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2570 let scorer = test_utils::TestScorer::with_penalty(0);
2571 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2572 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2574 // Route to 1 via 2 and 3 because our channel to 1 is disabled
2575 let payment_params = PaymentParameters::from_node_id(nodes[0]);
2576 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2577 assert_eq!(route.paths[0].len(), 3);
2579 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2580 assert_eq!(route.paths[0][0].short_channel_id, 2);
2581 assert_eq!(route.paths[0][0].fee_msat, 200);
2582 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2583 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2584 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2586 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2587 assert_eq!(route.paths[0][1].short_channel_id, 4);
2588 assert_eq!(route.paths[0][1].fee_msat, 100);
2589 assert_eq!(route.paths[0][1].cltv_expiry_delta, (3 << 4) | 2);
2590 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2591 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2593 assert_eq!(route.paths[0][2].pubkey, nodes[0]);
2594 assert_eq!(route.paths[0][2].short_channel_id, 3);
2595 assert_eq!(route.paths[0][2].fee_msat, 100);
2596 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
2597 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(1));
2598 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(3));
2600 // If we specify a channel to node7, that overrides our local channel view and that gets used
2601 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2602 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2603 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();
2604 assert_eq!(route.paths[0].len(), 2);
2606 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2607 assert_eq!(route.paths[0][0].short_channel_id, 42);
2608 assert_eq!(route.paths[0][0].fee_msat, 200);
2609 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2610 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2611 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2613 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2614 assert_eq!(route.paths[0][1].short_channel_id, 13);
2615 assert_eq!(route.paths[0][1].fee_msat, 100);
2616 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2617 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2618 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2621 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2622 let zero_fees = RoutingFees {
2624 proportional_millionths: 0,
2626 vec![RouteHint(vec![RouteHintHop {
2627 src_node_id: nodes[3],
2628 short_channel_id: 8,
2630 cltv_expiry_delta: (8 << 4) | 1,
2631 htlc_minimum_msat: None,
2632 htlc_maximum_msat: None,
2634 ]), RouteHint(vec![RouteHintHop {
2635 src_node_id: nodes[4],
2636 short_channel_id: 9,
2639 proportional_millionths: 0,
2641 cltv_expiry_delta: (9 << 4) | 1,
2642 htlc_minimum_msat: None,
2643 htlc_maximum_msat: None,
2644 }]), RouteHint(vec![RouteHintHop {
2645 src_node_id: nodes[5],
2646 short_channel_id: 10,
2648 cltv_expiry_delta: (10 << 4) | 1,
2649 htlc_minimum_msat: None,
2650 htlc_maximum_msat: None,
2654 fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2655 let zero_fees = RoutingFees {
2657 proportional_millionths: 0,
2659 vec![RouteHint(vec![RouteHintHop {
2660 src_node_id: nodes[2],
2661 short_channel_id: 5,
2664 proportional_millionths: 0,
2666 cltv_expiry_delta: (5 << 4) | 1,
2667 htlc_minimum_msat: None,
2668 htlc_maximum_msat: None,
2670 src_node_id: nodes[3],
2671 short_channel_id: 8,
2673 cltv_expiry_delta: (8 << 4) | 1,
2674 htlc_minimum_msat: None,
2675 htlc_maximum_msat: None,
2677 ]), RouteHint(vec![RouteHintHop {
2678 src_node_id: nodes[4],
2679 short_channel_id: 9,
2682 proportional_millionths: 0,
2684 cltv_expiry_delta: (9 << 4) | 1,
2685 htlc_minimum_msat: None,
2686 htlc_maximum_msat: None,
2687 }]), RouteHint(vec![RouteHintHop {
2688 src_node_id: nodes[5],
2689 short_channel_id: 10,
2691 cltv_expiry_delta: (10 << 4) | 1,
2692 htlc_minimum_msat: None,
2693 htlc_maximum_msat: None,
2698 fn partial_route_hint_test() {
2699 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2700 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2701 let scorer = test_utils::TestScorer::with_penalty(0);
2702 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2703 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2705 // Simple test across 2, 3, 5, and 4 via a last_hop channel
2706 // Tests the behaviour when the RouteHint contains a suboptimal hop.
2707 // RouteHint may be partially used by the algo to build the best path.
2709 // First check that last hop can't have its source as the payee.
2710 let invalid_last_hop = RouteHint(vec![RouteHintHop {
2711 src_node_id: nodes[6],
2712 short_channel_id: 8,
2715 proportional_millionths: 0,
2717 cltv_expiry_delta: (8 << 4) | 1,
2718 htlc_minimum_msat: None,
2719 htlc_maximum_msat: None,
2722 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
2723 invalid_last_hops.push(invalid_last_hop);
2725 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(invalid_last_hops);
2726 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) {
2727 assert_eq!(err, "Route hint cannot have the payee as the source.");
2728 } else { panic!(); }
2731 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops_multi_private_channels(&nodes));
2732 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2733 assert_eq!(route.paths[0].len(), 5);
2735 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2736 assert_eq!(route.paths[0][0].short_channel_id, 2);
2737 assert_eq!(route.paths[0][0].fee_msat, 100);
2738 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2739 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2740 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2742 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2743 assert_eq!(route.paths[0][1].short_channel_id, 4);
2744 assert_eq!(route.paths[0][1].fee_msat, 0);
2745 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
2746 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2747 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2749 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2750 assert_eq!(route.paths[0][2].short_channel_id, 6);
2751 assert_eq!(route.paths[0][2].fee_msat, 0);
2752 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
2753 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2754 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2756 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2757 assert_eq!(route.paths[0][3].short_channel_id, 11);
2758 assert_eq!(route.paths[0][3].fee_msat, 0);
2759 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
2760 // If we have a peer in the node map, we'll use their features here since we don't have
2761 // a way of figuring out their features from the invoice:
2762 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2763 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2765 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2766 assert_eq!(route.paths[0][4].short_channel_id, 8);
2767 assert_eq!(route.paths[0][4].fee_msat, 100);
2768 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2769 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2770 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2773 fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2774 let zero_fees = RoutingFees {
2776 proportional_millionths: 0,
2778 vec![RouteHint(vec![RouteHintHop {
2779 src_node_id: nodes[3],
2780 short_channel_id: 8,
2782 cltv_expiry_delta: (8 << 4) | 1,
2783 htlc_minimum_msat: None,
2784 htlc_maximum_msat: None,
2785 }]), RouteHint(vec![
2787 ]), RouteHint(vec![RouteHintHop {
2788 src_node_id: nodes[5],
2789 short_channel_id: 10,
2791 cltv_expiry_delta: (10 << 4) | 1,
2792 htlc_minimum_msat: None,
2793 htlc_maximum_msat: None,
2798 fn ignores_empty_last_hops_test() {
2799 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2800 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2801 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(empty_last_hop(&nodes));
2802 let scorer = test_utils::TestScorer::with_penalty(0);
2803 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2804 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2806 // Test handling of an empty RouteHint passed in Invoice.
2808 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2809 assert_eq!(route.paths[0].len(), 5);
2811 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2812 assert_eq!(route.paths[0][0].short_channel_id, 2);
2813 assert_eq!(route.paths[0][0].fee_msat, 100);
2814 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2815 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2816 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2818 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2819 assert_eq!(route.paths[0][1].short_channel_id, 4);
2820 assert_eq!(route.paths[0][1].fee_msat, 0);
2821 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
2822 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2823 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2825 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2826 assert_eq!(route.paths[0][2].short_channel_id, 6);
2827 assert_eq!(route.paths[0][2].fee_msat, 0);
2828 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
2829 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2830 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2832 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2833 assert_eq!(route.paths[0][3].short_channel_id, 11);
2834 assert_eq!(route.paths[0][3].fee_msat, 0);
2835 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
2836 // If we have a peer in the node map, we'll use their features here since we don't have
2837 // a way of figuring out their features from the invoice:
2838 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2839 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2841 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2842 assert_eq!(route.paths[0][4].short_channel_id, 8);
2843 assert_eq!(route.paths[0][4].fee_msat, 100);
2844 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2845 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2846 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2849 /// Builds a trivial last-hop hint that passes through the two nodes given, with channel 0xff00
2851 fn multi_hop_last_hops_hint(hint_hops: [PublicKey; 2]) -> Vec<RouteHint> {
2852 let zero_fees = RoutingFees {
2854 proportional_millionths: 0,
2856 vec![RouteHint(vec![RouteHintHop {
2857 src_node_id: hint_hops[0],
2858 short_channel_id: 0xff00,
2861 proportional_millionths: 0,
2863 cltv_expiry_delta: (5 << 4) | 1,
2864 htlc_minimum_msat: None,
2865 htlc_maximum_msat: None,
2867 src_node_id: hint_hops[1],
2868 short_channel_id: 0xff01,
2870 cltv_expiry_delta: (8 << 4) | 1,
2871 htlc_minimum_msat: None,
2872 htlc_maximum_msat: None,
2877 fn multi_hint_last_hops_test() {
2878 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2879 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2880 let last_hops = multi_hop_last_hops_hint([nodes[2], nodes[3]]);
2881 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops.clone());
2882 let scorer = test_utils::TestScorer::with_penalty(0);
2883 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2884 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2885 // Test through channels 2, 3, 0xff00, 0xff01.
2886 // Test shows that multiple hop hints are considered.
2888 // Disabling channels 6 & 7 by flags=2
2889 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2890 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2891 short_channel_id: 6,
2893 flags: 2, // to disable
2894 cltv_expiry_delta: 0,
2895 htlc_minimum_msat: 0,
2896 htlc_maximum_msat: OptionalField::Absent,
2898 fee_proportional_millionths: 0,
2899 excess_data: Vec::new()
2901 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2902 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2903 short_channel_id: 7,
2905 flags: 2, // to disable
2906 cltv_expiry_delta: 0,
2907 htlc_minimum_msat: 0,
2908 htlc_maximum_msat: OptionalField::Absent,
2910 fee_proportional_millionths: 0,
2911 excess_data: Vec::new()
2914 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2915 assert_eq!(route.paths[0].len(), 4);
2917 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2918 assert_eq!(route.paths[0][0].short_channel_id, 2);
2919 assert_eq!(route.paths[0][0].fee_msat, 200);
2920 assert_eq!(route.paths[0][0].cltv_expiry_delta, 65);
2921 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2922 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2924 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2925 assert_eq!(route.paths[0][1].short_channel_id, 4);
2926 assert_eq!(route.paths[0][1].fee_msat, 100);
2927 assert_eq!(route.paths[0][1].cltv_expiry_delta, 81);
2928 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2929 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2931 assert_eq!(route.paths[0][2].pubkey, nodes[3]);
2932 assert_eq!(route.paths[0][2].short_channel_id, last_hops[0].0[0].short_channel_id);
2933 assert_eq!(route.paths[0][2].fee_msat, 0);
2934 assert_eq!(route.paths[0][2].cltv_expiry_delta, 129);
2935 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(4));
2936 assert_eq!(route.paths[0][2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2938 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2939 assert_eq!(route.paths[0][3].short_channel_id, last_hops[0].0[1].short_channel_id);
2940 assert_eq!(route.paths[0][3].fee_msat, 100);
2941 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2942 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2943 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2947 fn private_multi_hint_last_hops_test() {
2948 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2949 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2951 let non_announced_privkey = SecretKey::from_slice(&hex::decode(format!("{:02x}", 0xf0).repeat(32)).unwrap()[..]).unwrap();
2952 let non_announced_pubkey = PublicKey::from_secret_key(&secp_ctx, &non_announced_privkey);
2954 let last_hops = multi_hop_last_hops_hint([nodes[2], non_announced_pubkey]);
2955 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops.clone());
2956 let scorer = test_utils::TestScorer::with_penalty(0);
2957 // Test through channels 2, 3, 0xff00, 0xff01.
2958 // Test shows that multiple hop hints are considered.
2960 // Disabling channels 6 & 7 by flags=2
2961 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2962 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2963 short_channel_id: 6,
2965 flags: 2, // to disable
2966 cltv_expiry_delta: 0,
2967 htlc_minimum_msat: 0,
2968 htlc_maximum_msat: OptionalField::Absent,
2970 fee_proportional_millionths: 0,
2971 excess_data: Vec::new()
2973 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2974 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2975 short_channel_id: 7,
2977 flags: 2, // to disable
2978 cltv_expiry_delta: 0,
2979 htlc_minimum_msat: 0,
2980 htlc_maximum_msat: OptionalField::Absent,
2982 fee_proportional_millionths: 0,
2983 excess_data: Vec::new()
2986 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &[42u8; 32]).unwrap();
2987 assert_eq!(route.paths[0].len(), 4);
2989 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2990 assert_eq!(route.paths[0][0].short_channel_id, 2);
2991 assert_eq!(route.paths[0][0].fee_msat, 200);
2992 assert_eq!(route.paths[0][0].cltv_expiry_delta, 65);
2993 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2994 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2996 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2997 assert_eq!(route.paths[0][1].short_channel_id, 4);
2998 assert_eq!(route.paths[0][1].fee_msat, 100);
2999 assert_eq!(route.paths[0][1].cltv_expiry_delta, 81);
3000 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3001 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3003 assert_eq!(route.paths[0][2].pubkey, non_announced_pubkey);
3004 assert_eq!(route.paths[0][2].short_channel_id, last_hops[0].0[0].short_channel_id);
3005 assert_eq!(route.paths[0][2].fee_msat, 0);
3006 assert_eq!(route.paths[0][2].cltv_expiry_delta, 129);
3007 assert_eq!(route.paths[0][2].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
3008 assert_eq!(route.paths[0][2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3010 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
3011 assert_eq!(route.paths[0][3].short_channel_id, last_hops[0].0[1].short_channel_id);
3012 assert_eq!(route.paths[0][3].fee_msat, 100);
3013 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
3014 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
3015 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3018 fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3019 let zero_fees = RoutingFees {
3021 proportional_millionths: 0,
3023 vec![RouteHint(vec![RouteHintHop {
3024 src_node_id: nodes[4],
3025 short_channel_id: 11,
3027 cltv_expiry_delta: (11 << 4) | 1,
3028 htlc_minimum_msat: None,
3029 htlc_maximum_msat: None,
3031 src_node_id: nodes[3],
3032 short_channel_id: 8,
3034 cltv_expiry_delta: (8 << 4) | 1,
3035 htlc_minimum_msat: None,
3036 htlc_maximum_msat: None,
3037 }]), RouteHint(vec![RouteHintHop {
3038 src_node_id: nodes[4],
3039 short_channel_id: 9,
3042 proportional_millionths: 0,
3044 cltv_expiry_delta: (9 << 4) | 1,
3045 htlc_minimum_msat: None,
3046 htlc_maximum_msat: None,
3047 }]), RouteHint(vec![RouteHintHop {
3048 src_node_id: nodes[5],
3049 short_channel_id: 10,
3051 cltv_expiry_delta: (10 << 4) | 1,
3052 htlc_minimum_msat: None,
3053 htlc_maximum_msat: None,
3058 fn last_hops_with_public_channel_test() {
3059 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3060 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3061 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops_with_public_channel(&nodes));
3062 let scorer = test_utils::TestScorer::with_penalty(0);
3063 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3064 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3065 // This test shows that public routes can be present in the invoice
3066 // which would be handled in the same manner.
3068 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3069 assert_eq!(route.paths[0].len(), 5);
3071 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3072 assert_eq!(route.paths[0][0].short_channel_id, 2);
3073 assert_eq!(route.paths[0][0].fee_msat, 100);
3074 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
3075 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3076 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3078 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3079 assert_eq!(route.paths[0][1].short_channel_id, 4);
3080 assert_eq!(route.paths[0][1].fee_msat, 0);
3081 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
3082 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3083 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3085 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
3086 assert_eq!(route.paths[0][2].short_channel_id, 6);
3087 assert_eq!(route.paths[0][2].fee_msat, 0);
3088 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
3089 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
3090 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
3092 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
3093 assert_eq!(route.paths[0][3].short_channel_id, 11);
3094 assert_eq!(route.paths[0][3].fee_msat, 0);
3095 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
3096 // If we have a peer in the node map, we'll use their features here since we don't have
3097 // a way of figuring out their features from the invoice:
3098 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
3099 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
3101 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
3102 assert_eq!(route.paths[0][4].short_channel_id, 8);
3103 assert_eq!(route.paths[0][4].fee_msat, 100);
3104 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
3105 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
3106 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3110 fn our_chans_last_hop_connect_test() {
3111 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3112 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3113 let scorer = test_utils::TestScorer::with_penalty(0);
3114 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3115 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3117 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
3118 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3119 let mut last_hops = last_hops(&nodes);
3120 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops.clone());
3121 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();
3122 assert_eq!(route.paths[0].len(), 2);
3124 assert_eq!(route.paths[0][0].pubkey, nodes[3]);
3125 assert_eq!(route.paths[0][0].short_channel_id, 42);
3126 assert_eq!(route.paths[0][0].fee_msat, 0);
3127 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 4) | 1);
3128 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
3129 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3131 assert_eq!(route.paths[0][1].pubkey, nodes[6]);
3132 assert_eq!(route.paths[0][1].short_channel_id, 8);
3133 assert_eq!(route.paths[0][1].fee_msat, 100);
3134 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
3135 assert_eq!(route.paths[0][1].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
3136 assert_eq!(route.paths[0][1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3138 last_hops[0].0[0].fees.base_msat = 1000;
3140 // Revert to via 6 as the fee on 8 goes up
3141 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops);
3142 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3143 assert_eq!(route.paths[0].len(), 4);
3145 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3146 assert_eq!(route.paths[0][0].short_channel_id, 2);
3147 assert_eq!(route.paths[0][0].fee_msat, 200); // fee increased as its % of value transferred across node
3148 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
3149 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3150 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3152 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3153 assert_eq!(route.paths[0][1].short_channel_id, 4);
3154 assert_eq!(route.paths[0][1].fee_msat, 100);
3155 assert_eq!(route.paths[0][1].cltv_expiry_delta, (7 << 4) | 1);
3156 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3157 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3159 assert_eq!(route.paths[0][2].pubkey, nodes[5]);
3160 assert_eq!(route.paths[0][2].short_channel_id, 7);
3161 assert_eq!(route.paths[0][2].fee_msat, 0);
3162 assert_eq!(route.paths[0][2].cltv_expiry_delta, (10 << 4) | 1);
3163 // If we have a peer in the node map, we'll use their features here since we don't have
3164 // a way of figuring out their features from the invoice:
3165 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
3166 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(7));
3168 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
3169 assert_eq!(route.paths[0][3].short_channel_id, 10);
3170 assert_eq!(route.paths[0][3].fee_msat, 100);
3171 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
3172 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
3173 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3175 // ...but still use 8 for larger payments as 6 has a variable feerate
3176 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 2000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3177 assert_eq!(route.paths[0].len(), 5);
3179 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3180 assert_eq!(route.paths[0][0].short_channel_id, 2);
3181 assert_eq!(route.paths[0][0].fee_msat, 3000);
3182 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
3183 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3184 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3186 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3187 assert_eq!(route.paths[0][1].short_channel_id, 4);
3188 assert_eq!(route.paths[0][1].fee_msat, 0);
3189 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
3190 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3191 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3193 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
3194 assert_eq!(route.paths[0][2].short_channel_id, 6);
3195 assert_eq!(route.paths[0][2].fee_msat, 0);
3196 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
3197 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
3198 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
3200 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
3201 assert_eq!(route.paths[0][3].short_channel_id, 11);
3202 assert_eq!(route.paths[0][3].fee_msat, 1000);
3203 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
3204 // If we have a peer in the node map, we'll use their features here since we don't have
3205 // a way of figuring out their features from the invoice:
3206 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
3207 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
3209 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
3210 assert_eq!(route.paths[0][4].short_channel_id, 8);
3211 assert_eq!(route.paths[0][4].fee_msat, 2000);
3212 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
3213 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
3214 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3217 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> {
3218 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
3219 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3220 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3222 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
3223 let last_hops = RouteHint(vec![RouteHintHop {
3224 src_node_id: middle_node_id,
3225 short_channel_id: 8,
3228 proportional_millionths: last_hop_fee_prop,
3230 cltv_expiry_delta: (8 << 4) | 1,
3231 htlc_minimum_msat: None,
3232 htlc_maximum_msat: last_hop_htlc_max,
3234 let payment_params = PaymentParameters::from_node_id(target_node_id).with_route_hints(vec![last_hops]);
3235 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
3236 let scorer = test_utils::TestScorer::with_penalty(0);
3237 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3238 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3239 get_route(&source_node_id, &payment_params, &NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash()).read_only(),
3240 Some(&our_chans.iter().collect::<Vec<_>>()), route_val, 42, &test_utils::TestLogger::new(), &scorer, &random_seed_bytes)
3244 fn unannounced_path_test() {
3245 // We should be able to send a payment to a destination without any help of a routing graph
3246 // if we have a channel with a common counterparty that appears in the first and last hop
3248 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
3250 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3251 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3252 assert_eq!(route.paths[0].len(), 2);
3254 assert_eq!(route.paths[0][0].pubkey, middle_node_id);
3255 assert_eq!(route.paths[0][0].short_channel_id, 42);
3256 assert_eq!(route.paths[0][0].fee_msat, 1001);
3257 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 4) | 1);
3258 assert_eq!(route.paths[0][0].node_features.le_flags(), &[0b11]);
3259 assert_eq!(route.paths[0][0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3261 assert_eq!(route.paths[0][1].pubkey, target_node_id);
3262 assert_eq!(route.paths[0][1].short_channel_id, 8);
3263 assert_eq!(route.paths[0][1].fee_msat, 1000000);
3264 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
3265 assert_eq!(route.paths[0][1].node_features.le_flags(), &[0; 0]); // We dont pass flags in from invoices yet
3266 assert_eq!(route.paths[0][1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3270 fn overflow_unannounced_path_test_liquidity_underflow() {
3271 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
3272 // the last-hop had a fee which overflowed a u64, we'd panic.
3273 // This was due to us adding the first-hop from us unconditionally, causing us to think
3274 // we'd built a path (as our node is in the "best candidate" set), when we had not.
3275 // In this test, we previously hit a subtraction underflow due to having less available
3276 // liquidity at the last hop than 0.
3277 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());
3281 fn overflow_unannounced_path_test_feerate_overflow() {
3282 // This tests for the same case as above, except instead of hitting a subtraction
3283 // underflow, we hit a case where the fee charged at a hop overflowed.
3284 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());
3288 fn available_amount_while_routing_test() {
3289 // Tests whether we choose the correct available channel amount while routing.
3291 let (secp_ctx, network_graph, mut net_graph_msg_handler, chain_monitor, logger) = build_graph();
3292 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3293 let scorer = test_utils::TestScorer::with_penalty(0);
3294 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3295 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3296 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
3298 // We will use a simple single-path route from
3299 // our node to node2 via node0: channels {1, 3}.
3301 // First disable all other paths.
3302 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3303 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3304 short_channel_id: 2,
3307 cltv_expiry_delta: 0,
3308 htlc_minimum_msat: 0,
3309 htlc_maximum_msat: OptionalField::Present(100_000),
3311 fee_proportional_millionths: 0,
3312 excess_data: Vec::new()
3314 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3315 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3316 short_channel_id: 12,
3319 cltv_expiry_delta: 0,
3320 htlc_minimum_msat: 0,
3321 htlc_maximum_msat: OptionalField::Present(100_000),
3323 fee_proportional_millionths: 0,
3324 excess_data: Vec::new()
3327 // Make the first channel (#1) very permissive,
3328 // and we will be testing all limits on the second channel.
3329 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3330 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3331 short_channel_id: 1,
3334 cltv_expiry_delta: 0,
3335 htlc_minimum_msat: 0,
3336 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3338 fee_proportional_millionths: 0,
3339 excess_data: Vec::new()
3342 // First, let's see if routing works if we have absolutely no idea about the available amount.
3343 // In this case, it should be set to 250_000 sats.
3344 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3345 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3346 short_channel_id: 3,
3349 cltv_expiry_delta: 0,
3350 htlc_minimum_msat: 0,
3351 htlc_maximum_msat: OptionalField::Absent,
3353 fee_proportional_millionths: 0,
3354 excess_data: Vec::new()
3358 // Attempt to route more than available results in a failure.
3359 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3360 &our_id, &payment_params, &network_graph.read_only(), None, 250_000_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3361 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3362 } else { panic!(); }
3366 // Now, attempt to route an exact amount we have should be fine.
3367 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();
3368 assert_eq!(route.paths.len(), 1);
3369 let path = route.paths.last().unwrap();
3370 assert_eq!(path.len(), 2);
3371 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3372 assert_eq!(path.last().unwrap().fee_msat, 250_000_000);
3375 // Check that setting outbound_capacity_msat in first_hops limits the channels.
3376 // Disable channel #1 and use another first hop.
3377 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3378 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3379 short_channel_id: 1,
3382 cltv_expiry_delta: 0,
3383 htlc_minimum_msat: 0,
3384 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3386 fee_proportional_millionths: 0,
3387 excess_data: Vec::new()
3390 // Now, limit the first_hop by the outbound_capacity_msat of 200_000 sats.
3391 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
3394 // Attempt to route more than available results in a failure.
3395 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3396 &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) {
3397 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3398 } else { panic!(); }
3402 // Now, attempt to route an exact amount we have should be fine.
3403 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();
3404 assert_eq!(route.paths.len(), 1);
3405 let path = route.paths.last().unwrap();
3406 assert_eq!(path.len(), 2);
3407 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3408 assert_eq!(path.last().unwrap().fee_msat, 200_000_000);
3411 // Enable channel #1 back.
3412 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3413 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3414 short_channel_id: 1,
3417 cltv_expiry_delta: 0,
3418 htlc_minimum_msat: 0,
3419 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3421 fee_proportional_millionths: 0,
3422 excess_data: Vec::new()
3426 // Now let's see if routing works if we know only htlc_maximum_msat.
3427 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3428 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3429 short_channel_id: 3,
3432 cltv_expiry_delta: 0,
3433 htlc_minimum_msat: 0,
3434 htlc_maximum_msat: OptionalField::Present(15_000),
3436 fee_proportional_millionths: 0,
3437 excess_data: Vec::new()
3441 // Attempt to route more than available results in a failure.
3442 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3443 &our_id, &payment_params, &network_graph.read_only(), None, 15_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3444 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3445 } else { panic!(); }
3449 // Now, attempt to route an exact amount we have should be fine.
3450 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 15_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3451 assert_eq!(route.paths.len(), 1);
3452 let path = route.paths.last().unwrap();
3453 assert_eq!(path.len(), 2);
3454 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3455 assert_eq!(path.last().unwrap().fee_msat, 15_000);
3458 // Now let's see if routing works if we know only capacity from the UTXO.
3460 // We can't change UTXO capacity on the fly, so we'll disable
3461 // the existing channel and add another one with the capacity we need.
3462 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3463 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3464 short_channel_id: 3,
3467 cltv_expiry_delta: 0,
3468 htlc_minimum_msat: 0,
3469 htlc_maximum_msat: OptionalField::Absent,
3471 fee_proportional_millionths: 0,
3472 excess_data: Vec::new()
3475 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
3476 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
3477 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
3478 .push_opcode(opcodes::all::OP_PUSHNUM_2)
3479 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
3481 *chain_monitor.utxo_ret.lock().unwrap() = Ok(TxOut { value: 15, script_pubkey: good_script.clone() });
3482 net_graph_msg_handler.add_chain_access(Some(chain_monitor));
3484 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
3485 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3486 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3487 short_channel_id: 333,
3490 cltv_expiry_delta: (3 << 4) | 1,
3491 htlc_minimum_msat: 0,
3492 htlc_maximum_msat: OptionalField::Absent,
3494 fee_proportional_millionths: 0,
3495 excess_data: Vec::new()
3497 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3498 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3499 short_channel_id: 333,
3502 cltv_expiry_delta: (3 << 4) | 2,
3503 htlc_minimum_msat: 0,
3504 htlc_maximum_msat: OptionalField::Absent,
3506 fee_proportional_millionths: 0,
3507 excess_data: Vec::new()
3511 // Attempt to route more than available results in a failure.
3512 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3513 &our_id, &payment_params, &network_graph.read_only(), None, 15_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3514 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3515 } else { panic!(); }
3519 // Now, attempt to route an exact amount we have should be fine.
3520 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 15_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3521 assert_eq!(route.paths.len(), 1);
3522 let path = route.paths.last().unwrap();
3523 assert_eq!(path.len(), 2);
3524 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3525 assert_eq!(path.last().unwrap().fee_msat, 15_000);
3528 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
3529 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3530 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3531 short_channel_id: 333,
3534 cltv_expiry_delta: 0,
3535 htlc_minimum_msat: 0,
3536 htlc_maximum_msat: OptionalField::Present(10_000),
3538 fee_proportional_millionths: 0,
3539 excess_data: Vec::new()
3543 // Attempt to route more than available results in a failure.
3544 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3545 &our_id, &payment_params, &network_graph.read_only(), None, 10_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3546 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3547 } else { panic!(); }
3551 // Now, attempt to route an exact amount we have should be fine.
3552 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 10_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3553 assert_eq!(route.paths.len(), 1);
3554 let path = route.paths.last().unwrap();
3555 assert_eq!(path.len(), 2);
3556 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3557 assert_eq!(path.last().unwrap().fee_msat, 10_000);
3562 fn available_liquidity_last_hop_test() {
3563 // Check that available liquidity properly limits the path even when only
3564 // one of the latter hops is limited.
3565 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3566 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3567 let scorer = test_utils::TestScorer::with_penalty(0);
3568 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3569 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3570 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
3572 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3573 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
3574 // Total capacity: 50 sats.
3576 // Disable other potential paths.
3577 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3578 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3579 short_channel_id: 2,
3582 cltv_expiry_delta: 0,
3583 htlc_minimum_msat: 0,
3584 htlc_maximum_msat: OptionalField::Present(100_000),
3586 fee_proportional_millionths: 0,
3587 excess_data: Vec::new()
3589 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3590 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3591 short_channel_id: 7,
3594 cltv_expiry_delta: 0,
3595 htlc_minimum_msat: 0,
3596 htlc_maximum_msat: OptionalField::Present(100_000),
3598 fee_proportional_millionths: 0,
3599 excess_data: Vec::new()
3604 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3605 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3606 short_channel_id: 12,
3609 cltv_expiry_delta: 0,
3610 htlc_minimum_msat: 0,
3611 htlc_maximum_msat: OptionalField::Present(100_000),
3613 fee_proportional_millionths: 0,
3614 excess_data: Vec::new()
3616 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3617 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3618 short_channel_id: 13,
3621 cltv_expiry_delta: 0,
3622 htlc_minimum_msat: 0,
3623 htlc_maximum_msat: OptionalField::Present(100_000),
3625 fee_proportional_millionths: 0,
3626 excess_data: Vec::new()
3629 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3630 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3631 short_channel_id: 6,
3634 cltv_expiry_delta: 0,
3635 htlc_minimum_msat: 0,
3636 htlc_maximum_msat: OptionalField::Present(50_000),
3638 fee_proportional_millionths: 0,
3639 excess_data: Vec::new()
3641 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3642 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3643 short_channel_id: 11,
3646 cltv_expiry_delta: 0,
3647 htlc_minimum_msat: 0,
3648 htlc_maximum_msat: OptionalField::Present(100_000),
3650 fee_proportional_millionths: 0,
3651 excess_data: Vec::new()
3654 // Attempt to route more than available results in a failure.
3655 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3656 &our_id, &payment_params, &network_graph.read_only(), None, 60_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3657 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3658 } else { panic!(); }
3662 // Now, attempt to route 49 sats (just a bit below the capacity).
3663 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 49_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3664 assert_eq!(route.paths.len(), 1);
3665 let mut total_amount_paid_msat = 0;
3666 for path in &route.paths {
3667 assert_eq!(path.len(), 4);
3668 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3669 total_amount_paid_msat += path.last().unwrap().fee_msat;
3671 assert_eq!(total_amount_paid_msat, 49_000);
3675 // Attempt to route an exact amount is also fine
3676 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3677 assert_eq!(route.paths.len(), 1);
3678 let mut total_amount_paid_msat = 0;
3679 for path in &route.paths {
3680 assert_eq!(path.len(), 4);
3681 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3682 total_amount_paid_msat += path.last().unwrap().fee_msat;
3684 assert_eq!(total_amount_paid_msat, 50_000);
3689 fn ignore_fee_first_hop_test() {
3690 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3691 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3692 let scorer = test_utils::TestScorer::with_penalty(0);
3693 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3694 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3695 let payment_params = PaymentParameters::from_node_id(nodes[2]);
3697 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3698 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3699 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3700 short_channel_id: 1,
3703 cltv_expiry_delta: 0,
3704 htlc_minimum_msat: 0,
3705 htlc_maximum_msat: OptionalField::Present(100_000),
3706 fee_base_msat: 1_000_000,
3707 fee_proportional_millionths: 0,
3708 excess_data: Vec::new()
3710 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3711 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3712 short_channel_id: 3,
3715 cltv_expiry_delta: 0,
3716 htlc_minimum_msat: 0,
3717 htlc_maximum_msat: OptionalField::Present(50_000),
3719 fee_proportional_millionths: 0,
3720 excess_data: Vec::new()
3724 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3725 assert_eq!(route.paths.len(), 1);
3726 let mut total_amount_paid_msat = 0;
3727 for path in &route.paths {
3728 assert_eq!(path.len(), 2);
3729 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3730 total_amount_paid_msat += path.last().unwrap().fee_msat;
3732 assert_eq!(total_amount_paid_msat, 50_000);
3737 fn simple_mpp_route_test() {
3738 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3739 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3740 let scorer = test_utils::TestScorer::with_penalty(0);
3741 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3742 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3743 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
3745 // We need a route consisting of 3 paths:
3746 // From our node to node2 via node0, node7, node1 (three paths one hop each).
3747 // To achieve this, the amount being transferred should be around
3748 // the total capacity of these 3 paths.
3750 // First, we set limits on these (previously unlimited) channels.
3751 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
3753 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3754 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3755 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3756 short_channel_id: 1,
3759 cltv_expiry_delta: 0,
3760 htlc_minimum_msat: 0,
3761 htlc_maximum_msat: OptionalField::Present(100_000),
3763 fee_proportional_millionths: 0,
3764 excess_data: Vec::new()
3766 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3767 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3768 short_channel_id: 3,
3771 cltv_expiry_delta: 0,
3772 htlc_minimum_msat: 0,
3773 htlc_maximum_msat: OptionalField::Present(50_000),
3775 fee_proportional_millionths: 0,
3776 excess_data: Vec::new()
3779 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
3780 // (total limit 60).
3781 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3782 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3783 short_channel_id: 12,
3786 cltv_expiry_delta: 0,
3787 htlc_minimum_msat: 0,
3788 htlc_maximum_msat: OptionalField::Present(60_000),
3790 fee_proportional_millionths: 0,
3791 excess_data: Vec::new()
3793 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3794 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3795 short_channel_id: 13,
3798 cltv_expiry_delta: 0,
3799 htlc_minimum_msat: 0,
3800 htlc_maximum_msat: OptionalField::Present(60_000),
3802 fee_proportional_millionths: 0,
3803 excess_data: Vec::new()
3806 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
3807 // (total capacity 180 sats).
3808 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3809 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3810 short_channel_id: 2,
3813 cltv_expiry_delta: 0,
3814 htlc_minimum_msat: 0,
3815 htlc_maximum_msat: OptionalField::Present(200_000),
3817 fee_proportional_millionths: 0,
3818 excess_data: Vec::new()
3820 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3821 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3822 short_channel_id: 4,
3825 cltv_expiry_delta: 0,
3826 htlc_minimum_msat: 0,
3827 htlc_maximum_msat: OptionalField::Present(180_000),
3829 fee_proportional_millionths: 0,
3830 excess_data: Vec::new()
3834 // Attempt to route more than available results in a failure.
3835 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3836 &our_id, &payment_params, &network_graph.read_only(), None, 300_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3837 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3838 } else { panic!(); }
3842 // Now, attempt to route 250 sats (just a bit below the capacity).
3843 // Our algorithm should provide us with these 3 paths.
3844 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 250_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3845 assert_eq!(route.paths.len(), 3);
3846 let mut total_amount_paid_msat = 0;
3847 for path in &route.paths {
3848 assert_eq!(path.len(), 2);
3849 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3850 total_amount_paid_msat += path.last().unwrap().fee_msat;
3852 assert_eq!(total_amount_paid_msat, 250_000);
3856 // Attempt to route an exact amount is also fine
3857 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 290_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3858 assert_eq!(route.paths.len(), 3);
3859 let mut total_amount_paid_msat = 0;
3860 for path in &route.paths {
3861 assert_eq!(path.len(), 2);
3862 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3863 total_amount_paid_msat += path.last().unwrap().fee_msat;
3865 assert_eq!(total_amount_paid_msat, 290_000);
3870 fn long_mpp_route_test() {
3871 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3872 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3873 let scorer = test_utils::TestScorer::with_penalty(0);
3874 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3875 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3876 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
3878 // We need a route consisting of 3 paths:
3879 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3880 // Note that these paths overlap (channels 5, 12, 13).
3881 // We will route 300 sats.
3882 // Each path will have 100 sats capacity, those channels which
3883 // are used twice will have 200 sats capacity.
3885 // Disable other potential paths.
3886 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3887 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3888 short_channel_id: 2,
3891 cltv_expiry_delta: 0,
3892 htlc_minimum_msat: 0,
3893 htlc_maximum_msat: OptionalField::Present(100_000),
3895 fee_proportional_millionths: 0,
3896 excess_data: Vec::new()
3898 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3899 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3900 short_channel_id: 7,
3903 cltv_expiry_delta: 0,
3904 htlc_minimum_msat: 0,
3905 htlc_maximum_msat: OptionalField::Present(100_000),
3907 fee_proportional_millionths: 0,
3908 excess_data: Vec::new()
3911 // Path via {node0, node2} is channels {1, 3, 5}.
3912 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3913 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3914 short_channel_id: 1,
3917 cltv_expiry_delta: 0,
3918 htlc_minimum_msat: 0,
3919 htlc_maximum_msat: OptionalField::Present(100_000),
3921 fee_proportional_millionths: 0,
3922 excess_data: Vec::new()
3924 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3925 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3926 short_channel_id: 3,
3929 cltv_expiry_delta: 0,
3930 htlc_minimum_msat: 0,
3931 htlc_maximum_msat: OptionalField::Present(100_000),
3933 fee_proportional_millionths: 0,
3934 excess_data: Vec::new()
3937 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3938 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3939 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3940 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3941 short_channel_id: 5,
3944 cltv_expiry_delta: 0,
3945 htlc_minimum_msat: 0,
3946 htlc_maximum_msat: OptionalField::Present(200_000),
3948 fee_proportional_millionths: 0,
3949 excess_data: Vec::new()
3952 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3953 // Add 100 sats to the capacities of {12, 13}, because these channels
3954 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3955 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3956 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3957 short_channel_id: 12,
3960 cltv_expiry_delta: 0,
3961 htlc_minimum_msat: 0,
3962 htlc_maximum_msat: OptionalField::Present(200_000),
3964 fee_proportional_millionths: 0,
3965 excess_data: Vec::new()
3967 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3968 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3969 short_channel_id: 13,
3972 cltv_expiry_delta: 0,
3973 htlc_minimum_msat: 0,
3974 htlc_maximum_msat: OptionalField::Present(200_000),
3976 fee_proportional_millionths: 0,
3977 excess_data: Vec::new()
3980 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3981 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3982 short_channel_id: 6,
3985 cltv_expiry_delta: 0,
3986 htlc_minimum_msat: 0,
3987 htlc_maximum_msat: OptionalField::Present(100_000),
3989 fee_proportional_millionths: 0,
3990 excess_data: Vec::new()
3992 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3993 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3994 short_channel_id: 11,
3997 cltv_expiry_delta: 0,
3998 htlc_minimum_msat: 0,
3999 htlc_maximum_msat: OptionalField::Present(100_000),
4001 fee_proportional_millionths: 0,
4002 excess_data: Vec::new()
4005 // Path via {node7, node2} is channels {12, 13, 5}.
4006 // We already limited them to 200 sats (they are used twice for 100 sats).
4007 // Nothing to do here.
4010 // Attempt to route more than available results in a failure.
4011 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4012 &our_id, &payment_params, &network_graph.read_only(), None, 350_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
4013 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4014 } else { panic!(); }
4018 // Now, attempt to route 300 sats (exact amount we can route).
4019 // Our algorithm should provide us with these 3 paths, 100 sats each.
4020 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 300_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4021 assert_eq!(route.paths.len(), 3);
4023 let mut total_amount_paid_msat = 0;
4024 for path in &route.paths {
4025 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
4026 total_amount_paid_msat += path.last().unwrap().fee_msat;
4028 assert_eq!(total_amount_paid_msat, 300_000);
4034 fn mpp_cheaper_route_test() {
4035 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4036 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4037 let scorer = test_utils::TestScorer::with_penalty(0);
4038 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4039 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4040 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
4042 // This test checks that if we have two cheaper paths and one more expensive path,
4043 // so that liquidity-wise any 2 of 3 combination is sufficient,
4044 // two cheaper paths will be taken.
4045 // These paths have equal available liquidity.
4047 // We need a combination of 3 paths:
4048 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
4049 // Note that these paths overlap (channels 5, 12, 13).
4050 // Each path will have 100 sats capacity, those channels which
4051 // are used twice will have 200 sats capacity.
4053 // Disable other potential paths.
4054 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4055 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4056 short_channel_id: 2,
4059 cltv_expiry_delta: 0,
4060 htlc_minimum_msat: 0,
4061 htlc_maximum_msat: OptionalField::Present(100_000),
4063 fee_proportional_millionths: 0,
4064 excess_data: Vec::new()
4066 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4067 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4068 short_channel_id: 7,
4071 cltv_expiry_delta: 0,
4072 htlc_minimum_msat: 0,
4073 htlc_maximum_msat: OptionalField::Present(100_000),
4075 fee_proportional_millionths: 0,
4076 excess_data: Vec::new()
4079 // Path via {node0, node2} is channels {1, 3, 5}.
4080 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4081 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4082 short_channel_id: 1,
4085 cltv_expiry_delta: 0,
4086 htlc_minimum_msat: 0,
4087 htlc_maximum_msat: OptionalField::Present(100_000),
4089 fee_proportional_millionths: 0,
4090 excess_data: Vec::new()
4092 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4093 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4094 short_channel_id: 3,
4097 cltv_expiry_delta: 0,
4098 htlc_minimum_msat: 0,
4099 htlc_maximum_msat: OptionalField::Present(100_000),
4101 fee_proportional_millionths: 0,
4102 excess_data: Vec::new()
4105 // Capacity of 200 sats because this channel will be used by 3rd path as well.
4106 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4107 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4108 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4109 short_channel_id: 5,
4112 cltv_expiry_delta: 0,
4113 htlc_minimum_msat: 0,
4114 htlc_maximum_msat: OptionalField::Present(200_000),
4116 fee_proportional_millionths: 0,
4117 excess_data: Vec::new()
4120 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4121 // Add 100 sats to the capacities of {12, 13}, because these channels
4122 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
4123 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4124 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4125 short_channel_id: 12,
4128 cltv_expiry_delta: 0,
4129 htlc_minimum_msat: 0,
4130 htlc_maximum_msat: OptionalField::Present(200_000),
4132 fee_proportional_millionths: 0,
4133 excess_data: Vec::new()
4135 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4136 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4137 short_channel_id: 13,
4140 cltv_expiry_delta: 0,
4141 htlc_minimum_msat: 0,
4142 htlc_maximum_msat: OptionalField::Present(200_000),
4144 fee_proportional_millionths: 0,
4145 excess_data: Vec::new()
4148 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4149 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4150 short_channel_id: 6,
4153 cltv_expiry_delta: 0,
4154 htlc_minimum_msat: 0,
4155 htlc_maximum_msat: OptionalField::Present(100_000),
4156 fee_base_msat: 1_000,
4157 fee_proportional_millionths: 0,
4158 excess_data: Vec::new()
4160 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4161 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4162 short_channel_id: 11,
4165 cltv_expiry_delta: 0,
4166 htlc_minimum_msat: 0,
4167 htlc_maximum_msat: OptionalField::Present(100_000),
4169 fee_proportional_millionths: 0,
4170 excess_data: Vec::new()
4173 // Path via {node7, node2} is channels {12, 13, 5}.
4174 // We already limited them to 200 sats (they are used twice for 100 sats).
4175 // Nothing to do here.
4178 // Now, attempt to route 180 sats.
4179 // Our algorithm should provide us with these 2 paths.
4180 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 180_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4181 assert_eq!(route.paths.len(), 2);
4183 let mut total_value_transferred_msat = 0;
4184 let mut total_paid_msat = 0;
4185 for path in &route.paths {
4186 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
4187 total_value_transferred_msat += path.last().unwrap().fee_msat;
4189 total_paid_msat += hop.fee_msat;
4192 // If we paid fee, this would be higher.
4193 assert_eq!(total_value_transferred_msat, 180_000);
4194 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
4195 assert_eq!(total_fees_paid, 0);
4200 fn fees_on_mpp_route_test() {
4201 // This test makes sure that MPP algorithm properly takes into account
4202 // fees charged on the channels, by making the fees impactful:
4203 // if the fee is not properly accounted for, the behavior is different.
4204 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4205 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4206 let scorer = test_utils::TestScorer::with_penalty(0);
4207 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4208 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4209 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
4211 // We need a route consisting of 2 paths:
4212 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
4213 // We will route 200 sats, Each path will have 100 sats capacity.
4215 // This test is not particularly stable: e.g.,
4216 // there's a way to route via {node0, node2, node4}.
4217 // It works while pathfinding is deterministic, but can be broken otherwise.
4218 // It's fine to ignore this concern for now.
4220 // Disable other potential paths.
4221 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4222 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4223 short_channel_id: 2,
4226 cltv_expiry_delta: 0,
4227 htlc_minimum_msat: 0,
4228 htlc_maximum_msat: OptionalField::Present(100_000),
4230 fee_proportional_millionths: 0,
4231 excess_data: Vec::new()
4234 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4235 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4236 short_channel_id: 7,
4239 cltv_expiry_delta: 0,
4240 htlc_minimum_msat: 0,
4241 htlc_maximum_msat: OptionalField::Present(100_000),
4243 fee_proportional_millionths: 0,
4244 excess_data: Vec::new()
4247 // Path via {node0, node2} is channels {1, 3, 5}.
4248 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4249 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4250 short_channel_id: 1,
4253 cltv_expiry_delta: 0,
4254 htlc_minimum_msat: 0,
4255 htlc_maximum_msat: OptionalField::Present(100_000),
4257 fee_proportional_millionths: 0,
4258 excess_data: Vec::new()
4260 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4261 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4262 short_channel_id: 3,
4265 cltv_expiry_delta: 0,
4266 htlc_minimum_msat: 0,
4267 htlc_maximum_msat: OptionalField::Present(100_000),
4269 fee_proportional_millionths: 0,
4270 excess_data: Vec::new()
4273 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4274 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4275 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4276 short_channel_id: 5,
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()
4287 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4288 // All channels should be 100 sats capacity. But for the fee experiment,
4289 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
4290 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
4291 // 100 sats (and pay 150 sats in fees for the use of channel 6),
4292 // so no matter how large are other channels,
4293 // the whole path will be limited by 100 sats with just these 2 conditions:
4294 // - channel 12 capacity is 250 sats
4295 // - fee for channel 6 is 150 sats
4296 // Let's test this by enforcing these 2 conditions and removing other limits.
4297 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4298 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4299 short_channel_id: 12,
4302 cltv_expiry_delta: 0,
4303 htlc_minimum_msat: 0,
4304 htlc_maximum_msat: OptionalField::Present(250_000),
4306 fee_proportional_millionths: 0,
4307 excess_data: Vec::new()
4309 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4310 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4311 short_channel_id: 13,
4314 cltv_expiry_delta: 0,
4315 htlc_minimum_msat: 0,
4316 htlc_maximum_msat: OptionalField::Absent,
4318 fee_proportional_millionths: 0,
4319 excess_data: Vec::new()
4322 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4323 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4324 short_channel_id: 6,
4327 cltv_expiry_delta: 0,
4328 htlc_minimum_msat: 0,
4329 htlc_maximum_msat: OptionalField::Absent,
4330 fee_base_msat: 150_000,
4331 fee_proportional_millionths: 0,
4332 excess_data: Vec::new()
4334 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4335 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4336 short_channel_id: 11,
4339 cltv_expiry_delta: 0,
4340 htlc_minimum_msat: 0,
4341 htlc_maximum_msat: OptionalField::Absent,
4343 fee_proportional_millionths: 0,
4344 excess_data: Vec::new()
4348 // Attempt to route more than available results in a failure.
4349 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4350 &our_id, &payment_params, &network_graph.read_only(), None, 210_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
4351 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4352 } else { panic!(); }
4356 // Now, attempt to route 200 sats (exact amount we can route).
4357 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 200_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4358 assert_eq!(route.paths.len(), 2);
4360 let mut total_amount_paid_msat = 0;
4361 for path in &route.paths {
4362 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
4363 total_amount_paid_msat += path.last().unwrap().fee_msat;
4365 assert_eq!(total_amount_paid_msat, 200_000);
4366 assert_eq!(route.get_total_fees(), 150_000);
4371 fn mpp_with_last_hops() {
4372 // Previously, if we tried to send an MPP payment to a destination which was only reachable
4373 // via a single last-hop route hint, we'd fail to route if we first collected routes
4374 // totaling close but not quite enough to fund the full payment.
4376 // This was because we considered last-hop hints to have exactly the sought payment amount
4377 // instead of the amount we were trying to collect, needlessly limiting our path searching
4378 // at the very first hop.
4380 // Specifically, this interacted with our "all paths must fund at least 5% of total target"
4381 // criterion to cause us to refuse all routes at the last hop hint which would be considered
4382 // to only have the remaining to-collect amount in available liquidity.
4384 // This bug appeared in production in some specific channel configurations.
4385 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4386 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4387 let scorer = test_utils::TestScorer::with_penalty(0);
4388 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4389 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4390 let payment_params = PaymentParameters::from_node_id(PublicKey::from_slice(&[02; 33]).unwrap()).with_features(InvoiceFeatures::known())
4391 .with_route_hints(vec![RouteHint(vec![RouteHintHop {
4392 src_node_id: nodes[2],
4393 short_channel_id: 42,
4394 fees: RoutingFees { base_msat: 0, proportional_millionths: 0 },
4395 cltv_expiry_delta: 42,
4396 htlc_minimum_msat: None,
4397 htlc_maximum_msat: None,
4400 // Keep only two paths from us to nodes[2], both with a 99sat HTLC maximum, with one with
4401 // no fee and one with a 1msat fee. Previously, trying to route 100 sats to nodes[2] here
4402 // would first use the no-fee route and then fail to find a path along the second route as
4403 // we think we can only send up to 1 additional sat over the last-hop but refuse to as its
4404 // under 5% of our payment amount.
4405 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4406 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4407 short_channel_id: 1,
4410 cltv_expiry_delta: (5 << 4) | 5,
4411 htlc_minimum_msat: 0,
4412 htlc_maximum_msat: OptionalField::Present(99_000),
4413 fee_base_msat: u32::max_value(),
4414 fee_proportional_millionths: u32::max_value(),
4415 excess_data: Vec::new()
4417 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4418 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4419 short_channel_id: 2,
4422 cltv_expiry_delta: (5 << 4) | 3,
4423 htlc_minimum_msat: 0,
4424 htlc_maximum_msat: OptionalField::Present(99_000),
4425 fee_base_msat: u32::max_value(),
4426 fee_proportional_millionths: u32::max_value(),
4427 excess_data: Vec::new()
4429 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4430 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4431 short_channel_id: 4,
4434 cltv_expiry_delta: (4 << 4) | 1,
4435 htlc_minimum_msat: 0,
4436 htlc_maximum_msat: OptionalField::Absent,
4438 fee_proportional_millionths: 0,
4439 excess_data: Vec::new()
4441 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4442 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4443 short_channel_id: 13,
4445 flags: 0|2, // Channel disabled
4446 cltv_expiry_delta: (13 << 4) | 1,
4447 htlc_minimum_msat: 0,
4448 htlc_maximum_msat: OptionalField::Absent,
4450 fee_proportional_millionths: 2000000,
4451 excess_data: Vec::new()
4454 // Get a route for 100 sats and check that we found the MPP route no problem and didn't
4456 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4457 assert_eq!(route.paths.len(), 2);
4458 // Paths are somewhat randomly ordered, but:
4459 // * the first is channel 2 (1 msat fee) -> channel 4 -> channel 42
4460 // * the second is channel 1 (0 fee, but 99 sat maximum) -> channel 3 -> channel 42
4461 assert_eq!(route.paths[0][0].short_channel_id, 2);
4462 assert_eq!(route.paths[0][0].fee_msat, 1);
4463 assert_eq!(route.paths[0][2].fee_msat, 1_000);
4464 assert_eq!(route.paths[1][0].short_channel_id, 1);
4465 assert_eq!(route.paths[1][0].fee_msat, 0);
4466 assert_eq!(route.paths[1][2].fee_msat, 99_000);
4467 assert_eq!(route.get_total_fees(), 1);
4468 assert_eq!(route.get_total_amount(), 100_000);
4472 fn drop_lowest_channel_mpp_route_test() {
4473 // This test checks that low-capacity channel is dropped when after
4474 // path finding we realize that we found more capacity than we need.
4475 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4476 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4477 let scorer = test_utils::TestScorer::with_penalty(0);
4478 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4479 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4480 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
4482 // We need a route consisting of 3 paths:
4483 // From our node to node2 via node0, node7, node1 (three paths one hop each).
4485 // The first and the second paths should be sufficient, but the third should be
4486 // cheaper, so that we select it but drop later.
4488 // First, we set limits on these (previously unlimited) channels.
4489 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
4491 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
4492 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4493 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4494 short_channel_id: 1,
4497 cltv_expiry_delta: 0,
4498 htlc_minimum_msat: 0,
4499 htlc_maximum_msat: OptionalField::Present(100_000),
4501 fee_proportional_millionths: 0,
4502 excess_data: Vec::new()
4504 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4505 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4506 short_channel_id: 3,
4509 cltv_expiry_delta: 0,
4510 htlc_minimum_msat: 0,
4511 htlc_maximum_msat: OptionalField::Present(50_000),
4513 fee_proportional_millionths: 0,
4514 excess_data: Vec::new()
4517 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
4518 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4519 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4520 short_channel_id: 12,
4523 cltv_expiry_delta: 0,
4524 htlc_minimum_msat: 0,
4525 htlc_maximum_msat: OptionalField::Present(60_000),
4527 fee_proportional_millionths: 0,
4528 excess_data: Vec::new()
4530 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4531 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4532 short_channel_id: 13,
4535 cltv_expiry_delta: 0,
4536 htlc_minimum_msat: 0,
4537 htlc_maximum_msat: OptionalField::Present(60_000),
4539 fee_proportional_millionths: 0,
4540 excess_data: Vec::new()
4543 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
4544 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4545 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4546 short_channel_id: 2,
4549 cltv_expiry_delta: 0,
4550 htlc_minimum_msat: 0,
4551 htlc_maximum_msat: OptionalField::Present(20_000),
4553 fee_proportional_millionths: 0,
4554 excess_data: Vec::new()
4556 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4557 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4558 short_channel_id: 4,
4561 cltv_expiry_delta: 0,
4562 htlc_minimum_msat: 0,
4563 htlc_maximum_msat: OptionalField::Present(20_000),
4565 fee_proportional_millionths: 0,
4566 excess_data: Vec::new()
4570 // Attempt to route more than available results in a failure.
4571 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4572 &our_id, &payment_params, &network_graph.read_only(), None, 150_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
4573 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4574 } else { panic!(); }
4578 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
4579 // Our algorithm should provide us with these 3 paths.
4580 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 125_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4581 assert_eq!(route.paths.len(), 3);
4582 let mut total_amount_paid_msat = 0;
4583 for path in &route.paths {
4584 assert_eq!(path.len(), 2);
4585 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4586 total_amount_paid_msat += path.last().unwrap().fee_msat;
4588 assert_eq!(total_amount_paid_msat, 125_000);
4592 // Attempt to route without the last small cheap channel
4593 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4594 assert_eq!(route.paths.len(), 2);
4595 let mut total_amount_paid_msat = 0;
4596 for path in &route.paths {
4597 assert_eq!(path.len(), 2);
4598 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4599 total_amount_paid_msat += path.last().unwrap().fee_msat;
4601 assert_eq!(total_amount_paid_msat, 90_000);
4606 fn min_criteria_consistency() {
4607 // Test that we don't use an inconsistent metric between updating and walking nodes during
4608 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
4609 // was updated with a different criterion from the heap sorting, resulting in loops in
4610 // calculated paths. We test for that specific case here.
4612 // We construct a network that looks like this:
4614 // node2 -1(3)2- node3
4618 // node1 -1(5)2- node4 -1(1)2- node6
4624 // We create a loop on the side of our real path - our destination is node 6, with a
4625 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
4626 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
4627 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
4628 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
4629 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
4630 // "previous hop" being set to node 3, creating a loop in the path.
4631 let secp_ctx = Secp256k1::new();
4632 let logger = Arc::new(test_utils::TestLogger::new());
4633 let network = Arc::new(NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash()));
4634 let net_graph_msg_handler = NetGraphMsgHandler::new(Arc::clone(&network), None, Arc::clone(&logger));
4635 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4636 let scorer = test_utils::TestScorer::with_penalty(0);
4637 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4638 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4639 let payment_params = PaymentParameters::from_node_id(nodes[6]);
4641 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
4642 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4643 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4644 short_channel_id: 6,
4647 cltv_expiry_delta: (6 << 4) | 0,
4648 htlc_minimum_msat: 0,
4649 htlc_maximum_msat: OptionalField::Absent,
4651 fee_proportional_millionths: 0,
4652 excess_data: Vec::new()
4654 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
4656 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4657 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4658 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4659 short_channel_id: 5,
4662 cltv_expiry_delta: (5 << 4) | 0,
4663 htlc_minimum_msat: 0,
4664 htlc_maximum_msat: OptionalField::Absent,
4666 fee_proportional_millionths: 0,
4667 excess_data: Vec::new()
4669 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
4671 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
4672 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4673 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4674 short_channel_id: 4,
4677 cltv_expiry_delta: (4 << 4) | 0,
4678 htlc_minimum_msat: 0,
4679 htlc_maximum_msat: OptionalField::Absent,
4681 fee_proportional_millionths: 0,
4682 excess_data: Vec::new()
4684 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
4686 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
4687 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
4688 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4689 short_channel_id: 3,
4692 cltv_expiry_delta: (3 << 4) | 0,
4693 htlc_minimum_msat: 0,
4694 htlc_maximum_msat: OptionalField::Absent,
4696 fee_proportional_millionths: 0,
4697 excess_data: Vec::new()
4699 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
4701 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
4702 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4703 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4704 short_channel_id: 2,
4707 cltv_expiry_delta: (2 << 4) | 0,
4708 htlc_minimum_msat: 0,
4709 htlc_maximum_msat: OptionalField::Absent,
4711 fee_proportional_millionths: 0,
4712 excess_data: Vec::new()
4715 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
4716 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4717 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4718 short_channel_id: 1,
4721 cltv_expiry_delta: (1 << 4) | 0,
4722 htlc_minimum_msat: 100,
4723 htlc_maximum_msat: OptionalField::Absent,
4725 fee_proportional_millionths: 0,
4726 excess_data: Vec::new()
4728 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
4731 // Now ensure the route flows simply over nodes 1 and 4 to 6.
4732 let route = get_route(&our_id, &payment_params, &network.read_only(), None, 10_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4733 assert_eq!(route.paths.len(), 1);
4734 assert_eq!(route.paths[0].len(), 3);
4736 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
4737 assert_eq!(route.paths[0][0].short_channel_id, 6);
4738 assert_eq!(route.paths[0][0].fee_msat, 100);
4739 assert_eq!(route.paths[0][0].cltv_expiry_delta, (5 << 4) | 0);
4740 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(1));
4741 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(6));
4743 assert_eq!(route.paths[0][1].pubkey, nodes[4]);
4744 assert_eq!(route.paths[0][1].short_channel_id, 5);
4745 assert_eq!(route.paths[0][1].fee_msat, 0);
4746 assert_eq!(route.paths[0][1].cltv_expiry_delta, (1 << 4) | 0);
4747 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(4));
4748 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(5));
4750 assert_eq!(route.paths[0][2].pubkey, nodes[6]);
4751 assert_eq!(route.paths[0][2].short_channel_id, 1);
4752 assert_eq!(route.paths[0][2].fee_msat, 10_000);
4753 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
4754 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
4755 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(1));
4761 fn exact_fee_liquidity_limit() {
4762 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
4763 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
4764 // we calculated fees on a higher value, resulting in us ignoring such paths.
4765 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4766 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
4767 let scorer = test_utils::TestScorer::with_penalty(0);
4768 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4769 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4770 let payment_params = PaymentParameters::from_node_id(nodes[2]);
4772 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
4774 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4775 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4776 short_channel_id: 2,
4779 cltv_expiry_delta: 0,
4780 htlc_minimum_msat: 0,
4781 htlc_maximum_msat: OptionalField::Present(85_000),
4783 fee_proportional_millionths: 0,
4784 excess_data: Vec::new()
4787 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4788 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4789 short_channel_id: 12,
4792 cltv_expiry_delta: (4 << 4) | 1,
4793 htlc_minimum_msat: 0,
4794 htlc_maximum_msat: OptionalField::Present(270_000),
4796 fee_proportional_millionths: 1000000,
4797 excess_data: Vec::new()
4801 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
4802 // 200% fee charged channel 13 in the 1-to-2 direction.
4803 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4804 assert_eq!(route.paths.len(), 1);
4805 assert_eq!(route.paths[0].len(), 2);
4807 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
4808 assert_eq!(route.paths[0][0].short_channel_id, 12);
4809 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
4810 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
4811 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
4812 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
4814 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
4815 assert_eq!(route.paths[0][1].short_channel_id, 13);
4816 assert_eq!(route.paths[0][1].fee_msat, 90_000);
4817 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
4818 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
4819 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
4824 fn htlc_max_reduction_below_min() {
4825 // Test that if, while walking the graph, we reduce the value being sent to meet an
4826 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
4827 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
4828 // resulting in us thinking there is no possible path, even if other paths exist.
4829 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4830 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4831 let scorer = test_utils::TestScorer::with_penalty(0);
4832 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4833 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4834 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
4836 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
4837 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
4838 // then try to send 90_000.
4839 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4840 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4841 short_channel_id: 2,
4844 cltv_expiry_delta: 0,
4845 htlc_minimum_msat: 0,
4846 htlc_maximum_msat: OptionalField::Present(80_000),
4848 fee_proportional_millionths: 0,
4849 excess_data: Vec::new()
4851 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4852 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4853 short_channel_id: 4,
4856 cltv_expiry_delta: (4 << 4) | 1,
4857 htlc_minimum_msat: 90_000,
4858 htlc_maximum_msat: OptionalField::Absent,
4860 fee_proportional_millionths: 0,
4861 excess_data: Vec::new()
4865 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
4866 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
4867 // expensive) channels 12-13 path.
4868 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4869 assert_eq!(route.paths.len(), 1);
4870 assert_eq!(route.paths[0].len(), 2);
4872 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
4873 assert_eq!(route.paths[0][0].short_channel_id, 12);
4874 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
4875 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
4876 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
4877 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
4879 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
4880 assert_eq!(route.paths[0][1].short_channel_id, 13);
4881 assert_eq!(route.paths[0][1].fee_msat, 90_000);
4882 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
4883 assert_eq!(route.paths[0][1].node_features.le_flags(), InvoiceFeatures::known().le_flags());
4884 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
4889 fn multiple_direct_first_hops() {
4890 // Previously we'd only ever considered one first hop path per counterparty.
4891 // However, as we don't restrict users to one channel per peer, we really need to support
4892 // looking at all first hop paths.
4893 // Here we test that we do not ignore all-but-the-last first hop paths per counterparty (as
4894 // we used to do by overwriting the `first_hop_targets` hashmap entry) and that we can MPP
4895 // route over multiple channels with the same first hop.
4896 let secp_ctx = Secp256k1::new();
4897 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4898 let logger = Arc::new(test_utils::TestLogger::new());
4899 let network_graph = NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash());
4900 let scorer = test_utils::TestScorer::with_penalty(0);
4901 let payment_params = PaymentParameters::from_node_id(nodes[0]).with_features(InvoiceFeatures::known());
4902 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4903 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4906 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
4907 &get_channel_details(Some(3), nodes[0], InitFeatures::known(), 200_000),
4908 &get_channel_details(Some(2), nodes[0], InitFeatures::known(), 10_000),
4909 ]), 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4910 assert_eq!(route.paths.len(), 1);
4911 assert_eq!(route.paths[0].len(), 1);
4913 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
4914 assert_eq!(route.paths[0][0].short_channel_id, 3);
4915 assert_eq!(route.paths[0][0].fee_msat, 100_000);
4918 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
4919 &get_channel_details(Some(3), nodes[0], InitFeatures::known(), 50_000),
4920 &get_channel_details(Some(2), nodes[0], InitFeatures::known(), 50_000),
4921 ]), 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4922 assert_eq!(route.paths.len(), 2);
4923 assert_eq!(route.paths[0].len(), 1);
4924 assert_eq!(route.paths[1].len(), 1);
4926 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
4927 assert_eq!(route.paths[0][0].short_channel_id, 3);
4928 assert_eq!(route.paths[0][0].fee_msat, 50_000);
4930 assert_eq!(route.paths[1][0].pubkey, nodes[0]);
4931 assert_eq!(route.paths[1][0].short_channel_id, 2);
4932 assert_eq!(route.paths[1][0].fee_msat, 50_000);
4936 // If we have a bunch of outbound channels to the same node, where most are not
4937 // sufficient to pay the full payment, but one is, we should default to just using the
4938 // one single channel that has sufficient balance, avoiding MPP.
4940 // If we have several options above the 3xpayment value threshold, we should pick the
4941 // smallest of them, avoiding further fragmenting our available outbound balance to
4943 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
4944 &get_channel_details(Some(2), nodes[0], InitFeatures::known(), 50_000),
4945 &get_channel_details(Some(3), nodes[0], InitFeatures::known(), 50_000),
4946 &get_channel_details(Some(5), nodes[0], InitFeatures::known(), 50_000),
4947 &get_channel_details(Some(6), nodes[0], InitFeatures::known(), 300_000),
4948 &get_channel_details(Some(7), nodes[0], InitFeatures::known(), 50_000),
4949 &get_channel_details(Some(8), nodes[0], InitFeatures::known(), 50_000),
4950 &get_channel_details(Some(9), nodes[0], InitFeatures::known(), 50_000),
4951 &get_channel_details(Some(4), nodes[0], InitFeatures::known(), 1_000_000),
4952 ]), 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4953 assert_eq!(route.paths.len(), 1);
4954 assert_eq!(route.paths[0].len(), 1);
4956 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
4957 assert_eq!(route.paths[0][0].short_channel_id, 6);
4958 assert_eq!(route.paths[0][0].fee_msat, 100_000);
4963 fn prefers_shorter_route_with_higher_fees() {
4964 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4965 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4966 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
4968 // Without penalizing each hop 100 msats, a longer path with lower fees is chosen.
4969 let scorer = test_utils::TestScorer::with_penalty(0);
4970 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4971 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4972 let route = get_route(
4973 &our_id, &payment_params, &network_graph.read_only(), None, 100, 42,
4974 Arc::clone(&logger), &scorer, &random_seed_bytes
4976 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4978 assert_eq!(route.get_total_fees(), 100);
4979 assert_eq!(route.get_total_amount(), 100);
4980 assert_eq!(path, vec![2, 4, 6, 11, 8]);
4982 // Applying a 100 msat penalty to each hop results in taking channels 7 and 10 to nodes[6]
4983 // from nodes[2] rather than channel 6, 11, and 8, even though the longer path is cheaper.
4984 let scorer = test_utils::TestScorer::with_penalty(100);
4985 let route = get_route(
4986 &our_id, &payment_params, &network_graph.read_only(), None, 100, 42,
4987 Arc::clone(&logger), &scorer, &random_seed_bytes
4989 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4991 assert_eq!(route.get_total_fees(), 300);
4992 assert_eq!(route.get_total_amount(), 100);
4993 assert_eq!(path, vec![2, 4, 7, 10]);
4996 struct BadChannelScorer {
4997 short_channel_id: u64,
5001 impl Writeable for BadChannelScorer {
5002 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), ::io::Error> { unimplemented!() }
5004 impl Score for BadChannelScorer {
5005 fn channel_penalty_msat(&self, short_channel_id: u64, _send_amt: u64, _capacity: EffectiveCapacity, _source: &NodeId, _target: &NodeId) -> u64 {
5006 if short_channel_id == self.short_channel_id { u64::max_value() } else { 0 }
5009 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
5010 fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
5013 struct BadNodeScorer {
5018 impl Writeable for BadNodeScorer {
5019 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), ::io::Error> { unimplemented!() }
5022 impl Score for BadNodeScorer {
5023 fn channel_penalty_msat(&self, _short_channel_id: u64, _send_amt: u64, _capacity: EffectiveCapacity, _source: &NodeId, target: &NodeId) -> u64 {
5024 if *target == self.node_id { u64::max_value() } else { 0 }
5027 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
5028 fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
5032 fn avoids_routing_through_bad_channels_and_nodes() {
5033 let (secp_ctx, network, _, _, logger) = build_graph();
5034 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5035 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
5036 let network_graph = network.read_only();
5038 // A path to nodes[6] exists when no penalties are applied to any channel.
5039 let scorer = test_utils::TestScorer::with_penalty(0);
5040 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5041 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5042 let route = get_route(
5043 &our_id, &payment_params, &network_graph, None, 100, 42,
5044 Arc::clone(&logger), &scorer, &random_seed_bytes
5046 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5048 assert_eq!(route.get_total_fees(), 100);
5049 assert_eq!(route.get_total_amount(), 100);
5050 assert_eq!(path, vec![2, 4, 6, 11, 8]);
5052 // A different path to nodes[6] exists if channel 6 cannot be routed over.
5053 let scorer = BadChannelScorer { short_channel_id: 6 };
5054 let route = get_route(
5055 &our_id, &payment_params, &network_graph, None, 100, 42,
5056 Arc::clone(&logger), &scorer, &random_seed_bytes
5058 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5060 assert_eq!(route.get_total_fees(), 300);
5061 assert_eq!(route.get_total_amount(), 100);
5062 assert_eq!(path, vec![2, 4, 7, 10]);
5064 // A path to nodes[6] does not exist if nodes[2] cannot be routed through.
5065 let scorer = BadNodeScorer { node_id: NodeId::from_pubkey(&nodes[2]) };
5067 &our_id, &payment_params, &network_graph, None, 100, 42,
5068 Arc::clone(&logger), &scorer, &random_seed_bytes
5070 Err(LightningError { err, .. } ) => {
5071 assert_eq!(err, "Failed to find a path to the given destination");
5073 Ok(_) => panic!("Expected error"),
5078 fn total_fees_single_path() {
5082 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5083 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5084 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5087 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5088 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5089 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5092 pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
5093 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5094 short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0
5097 payment_params: None,
5100 assert_eq!(route.get_total_fees(), 250);
5101 assert_eq!(route.get_total_amount(), 225);
5105 fn total_fees_multi_path() {
5109 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5110 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5111 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5114 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5115 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5116 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5120 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5121 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5122 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5125 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5126 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5127 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5130 payment_params: None,
5133 assert_eq!(route.get_total_fees(), 200);
5134 assert_eq!(route.get_total_amount(), 300);
5138 fn total_empty_route_no_panic() {
5139 // In an earlier version of `Route::get_total_fees` and `Route::get_total_amount`, they
5140 // would both panic if the route was completely empty. We test to ensure they return 0
5141 // here, even though its somewhat nonsensical as a route.
5142 let route = Route { paths: Vec::new(), payment_params: None };
5144 assert_eq!(route.get_total_fees(), 0);
5145 assert_eq!(route.get_total_amount(), 0);
5149 fn limits_total_cltv_delta() {
5150 let (secp_ctx, network, _, _, logger) = build_graph();
5151 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5152 let network_graph = network.read_only();
5154 let scorer = test_utils::TestScorer::with_penalty(0);
5156 // Make sure that generally there is at least one route available
5157 let feasible_max_total_cltv_delta = 1008;
5158 let feasible_payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes))
5159 .with_max_total_cltv_expiry_delta(feasible_max_total_cltv_delta);
5160 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5161 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5162 let route = get_route(&our_id, &feasible_payment_params, &network_graph, None, 100, 0, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5163 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5164 assert_ne!(path.len(), 0);
5166 // But not if we exclude all paths on the basis of their accumulated CLTV delta
5167 let fail_max_total_cltv_delta = 23;
5168 let fail_payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes))
5169 .with_max_total_cltv_expiry_delta(fail_max_total_cltv_delta);
5170 match get_route(&our_id, &fail_payment_params, &network_graph, None, 100, 0, Arc::clone(&logger), &scorer, &random_seed_bytes)
5172 Err(LightningError { err, .. } ) => {
5173 assert_eq!(err, "Failed to find a path to the given destination");
5175 Ok(_) => panic!("Expected error"),
5180 fn adds_and_limits_cltv_offset() {
5181 let (secp_ctx, network_graph, _, _, logger) = build_graph();
5182 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5184 let scorer = test_utils::TestScorer::with_penalty(0);
5186 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
5187 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5188 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5189 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5190 assert_eq!(route.paths.len(), 1);
5192 let cltv_expiry_deltas_before = route.paths[0].iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5194 // Check whether the offset added to the last hop by default is in [1 .. DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA]
5195 let mut route_default = route.clone();
5196 add_random_cltv_offset(&mut route_default, &payment_params, &network_graph.read_only(), &random_seed_bytes);
5197 let cltv_expiry_deltas_default = route_default.paths[0].iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5198 assert_eq!(cltv_expiry_deltas_before.split_last().unwrap().1, cltv_expiry_deltas_default.split_last().unwrap().1);
5199 assert!(cltv_expiry_deltas_default.last() > cltv_expiry_deltas_before.last());
5200 assert!(cltv_expiry_deltas_default.last().unwrap() <= &DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA);
5202 // Check that no offset is added when we restrict the max_total_cltv_expiry_delta
5203 let mut route_limited = route.clone();
5204 let limited_max_total_cltv_expiry_delta = cltv_expiry_deltas_before.iter().sum();
5205 let limited_payment_params = payment_params.with_max_total_cltv_expiry_delta(limited_max_total_cltv_expiry_delta);
5206 add_random_cltv_offset(&mut route_limited, &limited_payment_params, &network_graph.read_only(), &random_seed_bytes);
5207 let cltv_expiry_deltas_limited = route_limited.paths[0].iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5208 assert_eq!(cltv_expiry_deltas_before, cltv_expiry_deltas_limited);
5212 fn adds_plausible_cltv_offset() {
5213 let (secp_ctx, network, _, _, logger) = build_graph();
5214 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5215 let network_graph = network.read_only();
5216 let network_nodes = network_graph.nodes();
5217 let network_channels = network_graph.channels();
5218 let scorer = test_utils::TestScorer::with_penalty(0);
5219 let payment_params = PaymentParameters::from_node_id(nodes[3]);
5220 let keys_manager = test_utils::TestKeysInterface::new(&[4u8; 32], Network::Testnet);
5221 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5223 let mut route = get_route(&our_id, &payment_params, &network_graph, None, 100, 0,
5224 Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5225 add_random_cltv_offset(&mut route, &payment_params, &network_graph, &random_seed_bytes);
5227 let mut path_plausibility = vec![];
5229 for p in route.paths {
5230 // 1. Select random observation point
5231 let mut prng = ChaCha20::new(&random_seed_bytes, &[0u8; 12]);
5232 let mut random_bytes = [0u8; ::core::mem::size_of::<usize>()];
5234 prng.process_in_place(&mut random_bytes);
5235 let random_path_index = usize::from_be_bytes(random_bytes).wrapping_rem(p.len());
5236 let observation_point = NodeId::from_pubkey(&p.get(random_path_index).unwrap().pubkey);
5238 // 2. Calculate what CLTV expiry delta we would observe there
5239 let observed_cltv_expiry_delta: u32 = p[random_path_index..].iter().map(|h| h.cltv_expiry_delta).sum();
5241 // 3. Starting from the observation point, find candidate paths
5242 let mut candidates: VecDeque<(NodeId, Vec<u32>)> = VecDeque::new();
5243 candidates.push_back((observation_point, vec![]));
5245 let mut found_plausible_candidate = false;
5247 'candidate_loop: while let Some((cur_node_id, cur_path_cltv_deltas)) = candidates.pop_front() {
5248 if let Some(remaining) = observed_cltv_expiry_delta.checked_sub(cur_path_cltv_deltas.iter().sum::<u32>()) {
5249 if remaining == 0 || remaining.wrapping_rem(40) == 0 || remaining.wrapping_rem(144) == 0 {
5250 found_plausible_candidate = true;
5251 break 'candidate_loop;
5255 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
5256 for channel_id in &cur_node.channels {
5257 if let Some(channel_info) = network_channels.get(&channel_id) {
5258 if let Some((dir_info, next_id)) = channel_info.as_directed_from(&cur_node_id) {
5259 if let Some(channel_update_info) = dir_info.direction() {
5260 let next_cltv_expiry_delta = channel_update_info.cltv_expiry_delta as u32;
5261 if cur_path_cltv_deltas.iter().sum::<u32>()
5262 .saturating_add(next_cltv_expiry_delta) <= observed_cltv_expiry_delta {
5263 let mut new_path_cltv_deltas = cur_path_cltv_deltas.clone();
5264 new_path_cltv_deltas.push(next_cltv_expiry_delta);
5265 candidates.push_back((*next_id, new_path_cltv_deltas));
5274 path_plausibility.push(found_plausible_candidate);
5276 assert!(path_plausibility.iter().all(|x| *x));
5279 #[cfg(not(feature = "no-std"))]
5280 pub(super) fn random_init_seed() -> u64 {
5281 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
5282 use core::hash::{BuildHasher, Hasher};
5283 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
5284 println!("Using seed of {}", seed);
5287 #[cfg(not(feature = "no-std"))]
5288 use util::ser::Readable;
5291 #[cfg(not(feature = "no-std"))]
5292 fn generate_routes() {
5293 use routing::scoring::{ProbabilisticScorer, ProbabilisticScoringParameters};
5295 let mut d = match super::test_utils::get_route_file() {
5302 let graph = NetworkGraph::read(&mut d).unwrap();
5303 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5304 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5306 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
5307 let mut seed = random_init_seed() as usize;
5308 let nodes = graph.read_only().nodes().clone();
5309 'load_endpoints: for _ in 0..10 {
5311 seed = seed.overflowing_mul(0xdeadbeef).0;
5312 let src = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5313 seed = seed.overflowing_mul(0xdeadbeef).0;
5314 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5315 let payment_params = PaymentParameters::from_node_id(dst);
5316 let amt = seed as u64 % 200_000_000;
5317 let params = ProbabilisticScoringParameters::default();
5318 let scorer = ProbabilisticScorer::new(params, &graph);
5319 if get_route(src, &payment_params, &graph.read_only(), None, amt, 42, &test_utils::TestLogger::new(), &scorer, &random_seed_bytes).is_ok() {
5320 continue 'load_endpoints;
5327 #[cfg(not(feature = "no-std"))]
5328 fn generate_routes_mpp() {
5329 use routing::scoring::{ProbabilisticScorer, ProbabilisticScoringParameters};
5331 let mut d = match super::test_utils::get_route_file() {
5338 let graph = NetworkGraph::read(&mut d).unwrap();
5339 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5340 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5342 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
5343 let mut seed = random_init_seed() as usize;
5344 let nodes = graph.read_only().nodes().clone();
5345 'load_endpoints: for _ in 0..10 {
5347 seed = seed.overflowing_mul(0xdeadbeef).0;
5348 let src = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5349 seed = seed.overflowing_mul(0xdeadbeef).0;
5350 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5351 let payment_params = PaymentParameters::from_node_id(dst).with_features(InvoiceFeatures::known());
5352 let amt = seed as u64 % 200_000_000;
5353 let params = ProbabilisticScoringParameters::default();
5354 let scorer = ProbabilisticScorer::new(params, &graph);
5355 if get_route(src, &payment_params, &graph.read_only(), None, amt, 42, &test_utils::TestLogger::new(), &scorer, &random_seed_bytes).is_ok() {
5356 continue 'load_endpoints;
5363 #[cfg(all(test, not(feature = "no-std")))]
5364 pub(crate) mod test_utils {
5366 /// Tries to open a network graph file, or panics with a URL to fetch it.
5367 pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
5368 let res = File::open("net_graph-2021-05-31.bin") // By default we're run in RL/lightning
5369 .or_else(|_| File::open("lightning/net_graph-2021-05-31.bin")) // We may be run manually in RL/
5370 .or_else(|_| { // Fall back to guessing based on the binary location
5371 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
5372 let mut path = std::env::current_exe().unwrap();
5373 path.pop(); // lightning-...
5375 path.pop(); // debug
5376 path.pop(); // target
5377 path.push("lightning");
5378 path.push("net_graph-2021-05-31.bin");
5379 eprintln!("{}", path.to_str().unwrap());
5382 .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");
5383 #[cfg(require_route_graph_test)]
5384 return Ok(res.unwrap());
5385 #[cfg(not(require_route_graph_test))]
5390 #[cfg(all(test, feature = "_bench_unstable", not(feature = "no-std")))]
5393 use bitcoin::hashes::Hash;
5394 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
5395 use chain::transaction::OutPoint;
5396 use chain::keysinterface::{KeysManager,KeysInterface};
5397 use ln::channelmanager::{ChannelCounterparty, ChannelDetails};
5398 use ln::features::{InitFeatures, InvoiceFeatures};
5399 use routing::scoring::{FixedPenaltyScorer, ProbabilisticScorer, ProbabilisticScoringParameters, Scorer};
5400 use util::logger::{Logger, Record};
5404 struct DummyLogger {}
5405 impl Logger for DummyLogger {
5406 fn log(&self, _record: &Record) {}
5409 fn read_network_graph() -> NetworkGraph {
5410 let mut d = test_utils::get_route_file().unwrap();
5411 NetworkGraph::read(&mut d).unwrap()
5414 fn payer_pubkey() -> PublicKey {
5415 let secp_ctx = Secp256k1::new();
5416 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
5420 fn first_hop(node_id: PublicKey) -> ChannelDetails {
5422 channel_id: [0; 32],
5423 counterparty: ChannelCounterparty {
5424 features: InitFeatures::known(),
5426 unspendable_punishment_reserve: 0,
5427 forwarding_info: None,
5429 funding_txo: Some(OutPoint {
5430 txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0
5432 short_channel_id: Some(1),
5433 inbound_scid_alias: None,
5434 channel_value_satoshis: 10_000_000,
5436 balance_msat: 10_000_000,
5437 outbound_capacity_msat: 10_000_000,
5438 inbound_capacity_msat: 0,
5439 unspendable_punishment_reserve: None,
5440 confirmations_required: None,
5441 force_close_spend_delay: None,
5443 is_funding_locked: true,
5450 fn generate_routes_with_zero_penalty_scorer(bench: &mut Bencher) {
5451 let network_graph = read_network_graph();
5452 let scorer = FixedPenaltyScorer::with_penalty(0);
5453 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::empty());
5457 fn generate_mpp_routes_with_zero_penalty_scorer(bench: &mut Bencher) {
5458 let network_graph = read_network_graph();
5459 let scorer = FixedPenaltyScorer::with_penalty(0);
5460 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::known());
5464 fn generate_routes_with_default_scorer(bench: &mut Bencher) {
5465 let network_graph = read_network_graph();
5466 let scorer = Scorer::default();
5467 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::empty());
5471 fn generate_mpp_routes_with_default_scorer(bench: &mut Bencher) {
5472 let network_graph = read_network_graph();
5473 let scorer = Scorer::default();
5474 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::known());
5478 fn generate_routes_with_probabilistic_scorer(bench: &mut Bencher) {
5479 let network_graph = read_network_graph();
5480 let params = ProbabilisticScoringParameters::default();
5481 let scorer = ProbabilisticScorer::new(params, &network_graph);
5482 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::empty());
5486 fn generate_mpp_routes_with_probabilistic_scorer(bench: &mut Bencher) {
5487 let network_graph = read_network_graph();
5488 let params = ProbabilisticScoringParameters::default();
5489 let scorer = ProbabilisticScorer::new(params, &network_graph);
5490 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::known());
5493 fn generate_routes<S: Score>(
5494 bench: &mut Bencher, graph: &NetworkGraph, mut scorer: S, features: InvoiceFeatures
5496 let nodes = graph.read_only().nodes().clone();
5497 let payer = payer_pubkey();
5498 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
5499 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5501 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
5502 let mut routes = Vec::new();
5503 let mut route_endpoints = Vec::new();
5504 let mut seed: usize = 0xdeadbeef;
5505 'load_endpoints: for _ in 0..150 {
5508 let src = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5510 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5511 let params = PaymentParameters::from_node_id(dst).with_features(features.clone());
5512 let first_hop = first_hop(src);
5513 let amt = seed as u64 % 1_000_000;
5514 if let Ok(route) = get_route(&payer, ¶ms, &graph.read_only(), Some(&[&first_hop]), amt, 42, &DummyLogger{}, &scorer, &random_seed_bytes) {
5516 route_endpoints.push((first_hop, params, amt));
5517 continue 'load_endpoints;
5522 // ...and seed the scorer with success and failure data...
5523 for route in routes {
5524 let amount = route.get_total_amount();
5525 if amount < 250_000 {
5526 for path in route.paths {
5527 scorer.payment_path_successful(&path.iter().collect::<Vec<_>>());
5529 } else if amount > 750_000 {
5530 for path in route.paths {
5531 let short_channel_id = path[path.len() / 2].short_channel_id;
5532 scorer.payment_path_failed(&path.iter().collect::<Vec<_>>(), short_channel_id);
5537 // Because we've changed channel scores, its possible we'll take different routes to the
5538 // selected destinations, possibly causing us to fail because, eg, the newly-selected path
5539 // requires a too-high CLTV delta.
5540 route_endpoints.retain(|(first_hop, params, amt)| {
5541 get_route(&payer, params, &graph.read_only(), Some(&[first_hop]), *amt, 42, &DummyLogger{}, &scorer, &random_seed_bytes).is_ok()
5543 route_endpoints.truncate(100);
5544 assert_eq!(route_endpoints.len(), 100);
5546 // ...then benchmark finding paths between the nodes we learned.
5549 let (first_hop, params, amt) = &route_endpoints[idx % route_endpoints.len()];
5550 assert!(get_route(&payer, params, &graph.read_only(), Some(&[first_hop]), *amt, 42, &DummyLogger{}, &scorer, &random_seed_bytes).is_ok());