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 log_trace!(logger, "Building path from {} (payee) to {} (us/payer) for value {} msat.", payment_params.payee_pubkey, our_node_pubkey, final_value_msat);
816 macro_rules! add_entry {
817 // Adds entry which goes from $src_node_id to $dest_node_id over the $candidate hop.
818 // $next_hops_fee_msat represents the fees paid for using all the channels *after* this one,
819 // since that value has to be transferred over this channel.
820 // Returns whether this channel caused an update to `targets`.
821 ( $candidate: expr, $src_node_id: expr, $dest_node_id: expr, $next_hops_fee_msat: expr,
822 $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr,
823 $next_hops_path_penalty_msat: expr, $next_hops_cltv_delta: expr ) => { {
824 // We "return" whether we updated the path at the end, via this:
825 let mut did_add_update_path_to_src_node = false;
826 // Channels to self should not be used. This is more of belt-and-suspenders, because in
827 // practice these cases should be caught earlier:
828 // - for regular channels at channel announcement (TODO)
829 // - for first and last hops early in get_route
830 if $src_node_id != $dest_node_id {
831 let short_channel_id = $candidate.short_channel_id();
832 let available_liquidity_msat = bookkept_channels_liquidity_available_msat
833 .entry(short_channel_id)
834 .or_insert_with(|| $candidate.effective_capacity().as_msat());
836 // It is tricky to substract $next_hops_fee_msat from available liquidity here.
837 // It may be misleading because we might later choose to reduce the value transferred
838 // over these channels, and the channel which was insufficient might become sufficient.
839 // Worst case: we drop a good channel here because it can't cover the high following
840 // fees caused by one expensive channel, but then this channel could have been used
841 // if the amount being transferred over this path is lower.
842 // We do this for now, but this is a subject for removal.
843 if let Some(available_value_contribution_msat) = available_liquidity_msat.checked_sub($next_hops_fee_msat) {
845 // Routing Fragmentation Mitigation heuristic:
847 // Routing fragmentation across many payment paths increases the overall routing
848 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
849 // Taking too many smaller paths also increases the chance of payment failure.
850 // Thus to avoid this effect, we require from our collected links to provide
851 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
853 // This requirement is currently 5% of the remaining-to-be-collected value.
854 // This means as we successfully advance in our collection,
855 // the absolute liquidity contribution is lowered,
856 // thus increasing the number of potential channels to be selected.
858 // Derive the minimal liquidity contribution with a ratio of 20 (5%, rounded up)
859 // or 100% if we're not allowed to do multipath payments.
860 let minimal_value_contribution_msat: u64 = if allow_mpp {
861 (recommended_value_msat - already_collected_value_msat + 19) / 20
865 // Verify the liquidity offered by this channel complies to the minimal contribution.
866 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
868 // Do not consider candidates that exceed the maximum total cltv expiry limit.
869 // In order to already account for some of the privacy enhancing random CLTV
870 // expiry delta offset we add on top later, we subtract a rough estimate
871 // (2*MEDIAN_HOP_CLTV_EXPIRY_DELTA) here.
872 let max_total_cltv_expiry_delta = (payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta)
873 .checked_sub(2*MEDIAN_HOP_CLTV_EXPIRY_DELTA)
874 .unwrap_or(payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta);
875 let hop_total_cltv_delta = ($next_hops_cltv_delta as u32)
876 .checked_add($candidate.cltv_expiry_delta())
877 .unwrap_or(u32::max_value());
878 let doesnt_exceed_cltv_delta_limit = hop_total_cltv_delta <= max_total_cltv_expiry_delta;
880 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
881 // Includes paying fees for the use of the following channels.
882 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
883 Some(result) => result,
884 // Can't overflow due to how the values were computed right above.
885 None => unreachable!(),
887 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
888 let over_path_minimum_msat = amount_to_transfer_over_msat >= $candidate.htlc_minimum_msat() &&
889 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
891 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
892 // bother considering this channel.
893 // Since we're choosing amount_to_transfer_over_msat as maximum possible, it can
894 // be only reduced later (not increased), so this channel should just be skipped
895 // as not sufficient.
896 if !over_path_minimum_msat && doesnt_exceed_cltv_delta_limit {
897 hit_minimum_limit = true;
898 } else if contributes_sufficient_value && doesnt_exceed_cltv_delta_limit {
899 // Note that low contribution here (limited by available_liquidity_msat)
900 // might violate htlc_minimum_msat on the hops which are next along the
901 // payment path (upstream to the payee). To avoid that, we recompute
902 // path fees knowing the final path contribution after constructing it.
903 let path_htlc_minimum_msat = compute_fees($next_hops_path_htlc_minimum_msat, $candidate.fees())
904 .and_then(|fee_msat| fee_msat.checked_add($next_hops_path_htlc_minimum_msat))
905 .map(|fee_msat| cmp::max(fee_msat, $candidate.htlc_minimum_msat()))
906 .unwrap_or_else(|| u64::max_value());
907 let hm_entry = dist.entry($src_node_id);
908 let old_entry = hm_entry.or_insert_with(|| {
909 // If there was previously no known way to access the source node
910 // (recall it goes payee-to-payer) of short_channel_id, first add a
911 // semi-dummy record just to compute the fees to reach the source node.
912 // This will affect our decision on selecting short_channel_id
913 // as a way to reach the $dest_node_id.
914 let mut fee_base_msat = 0;
915 let mut fee_proportional_millionths = 0;
916 if let Some(Some(fees)) = network_nodes.get(&$src_node_id).map(|node| node.lowest_inbound_channel_fees) {
917 fee_base_msat = fees.base_msat;
918 fee_proportional_millionths = fees.proportional_millionths;
921 node_id: $dest_node_id.clone(),
922 candidate: $candidate.clone(),
924 src_lowest_inbound_fees: RoutingFees {
925 base_msat: fee_base_msat,
926 proportional_millionths: fee_proportional_millionths,
928 next_hops_fee_msat: u64::max_value(),
929 hop_use_fee_msat: u64::max_value(),
930 total_fee_msat: u64::max_value(),
931 path_htlc_minimum_msat,
932 path_penalty_msat: u64::max_value(),
933 was_processed: false,
934 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
935 value_contribution_msat,
939 #[allow(unused_mut)] // We only use the mut in cfg(test)
940 let mut should_process = !old_entry.was_processed;
941 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
943 // In test/fuzzing builds, we do extra checks to make sure the skipping
944 // of already-seen nodes only happens in cases we expect (see below).
945 if !should_process { should_process = true; }
949 let mut hop_use_fee_msat = 0;
950 let mut total_fee_msat = $next_hops_fee_msat;
952 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
953 // will have the same effective-fee
954 if $src_node_id != our_node_id {
955 match compute_fees(amount_to_transfer_over_msat, $candidate.fees()) {
956 // max_value means we'll always fail
957 // the old_entry.total_fee_msat > total_fee_msat check
958 None => total_fee_msat = u64::max_value(),
960 hop_use_fee_msat = fee_msat;
961 total_fee_msat += hop_use_fee_msat;
962 // When calculating the lowest inbound fees to a node, we
963 // calculate fees here not based on the actual value we think
964 // will flow over this channel, but on the minimum value that
965 // we'll accept flowing over it. The minimum accepted value
966 // is a constant through each path collection run, ensuring
967 // consistent basis. Otherwise we may later find a
968 // different path to the source node that is more expensive,
969 // but which we consider to be cheaper because we are capacity
970 // constrained and the relative fee becomes lower.
971 match compute_fees(minimal_value_contribution_msat, old_entry.src_lowest_inbound_fees)
972 .map(|a| a.checked_add(total_fee_msat)) {
977 total_fee_msat = u64::max_value();
984 let path_penalty_msat = $next_hops_path_penalty_msat.checked_add(
985 scorer.channel_penalty_msat(short_channel_id, amount_to_transfer_over_msat, *available_liquidity_msat,
986 &$src_node_id, &$dest_node_id)).unwrap_or_else(|| u64::max_value());
987 let new_graph_node = RouteGraphNode {
988 node_id: $src_node_id,
989 lowest_fee_to_peer_through_node: total_fee_msat,
990 lowest_fee_to_node: $next_hops_fee_msat as u64 + hop_use_fee_msat,
991 total_cltv_delta: hop_total_cltv_delta,
992 value_contribution_msat: value_contribution_msat,
993 path_htlc_minimum_msat,
997 // Update the way of reaching $src_node_id with the given short_channel_id (from $dest_node_id),
998 // if this way is cheaper than the already known
999 // (considering the cost to "reach" this channel from the route destination,
1000 // the cost of using this channel,
1001 // and the cost of routing to the source node of this channel).
1002 // Also, consider that htlc_minimum_msat_difference, because we might end up
1003 // paying it. Consider the following exploit:
1004 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
1005 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
1006 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
1007 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
1009 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
1010 // but it may require additional tracking - we don't want to double-count
1011 // the fees included in $next_hops_path_htlc_minimum_msat, but also
1012 // can't use something that may decrease on future hops.
1013 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat)
1014 .checked_add(old_entry.path_penalty_msat)
1015 .unwrap_or_else(|| u64::max_value());
1016 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat)
1017 .checked_add(path_penalty_msat)
1018 .unwrap_or_else(|| u64::max_value());
1020 if !old_entry.was_processed && new_cost < old_cost {
1021 targets.push(new_graph_node);
1022 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
1023 old_entry.hop_use_fee_msat = hop_use_fee_msat;
1024 old_entry.total_fee_msat = total_fee_msat;
1025 old_entry.node_id = $dest_node_id.clone();
1026 old_entry.candidate = $candidate.clone();
1027 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
1028 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
1029 old_entry.path_penalty_msat = path_penalty_msat;
1030 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
1032 old_entry.value_contribution_msat = value_contribution_msat;
1034 did_add_update_path_to_src_node = true;
1035 } else if old_entry.was_processed && new_cost < old_cost {
1036 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
1038 // If we're skipping processing a node which was previously
1039 // processed even though we found another path to it with a
1040 // cheaper fee, check that it was because the second path we
1041 // found (which we are processing now) has a lower value
1042 // contribution due to an HTLC minimum limit.
1044 // e.g. take a graph with two paths from node 1 to node 2, one
1045 // through channel A, and one through channel B. Channel A and
1046 // B are both in the to-process heap, with their scores set by
1047 // a higher htlc_minimum than fee.
1048 // Channel A is processed first, and the channels onwards from
1049 // node 1 are added to the to-process heap. Thereafter, we pop
1050 // Channel B off of the heap, note that it has a much more
1051 // restrictive htlc_maximum_msat, and recalculate the fees for
1052 // all of node 1's channels using the new, reduced, amount.
1054 // This would be bogus - we'd be selecting a higher-fee path
1055 // with a lower htlc_maximum_msat instead of the one we'd
1056 // already decided to use.
1057 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
1059 value_contribution_msat + path_penalty_msat <
1060 old_entry.value_contribution_msat + old_entry.path_penalty_msat
1068 did_add_update_path_to_src_node
1072 let empty_node_features = NodeFeatures::empty();
1073 // Find ways (channels with destination) to reach a given node and store them
1074 // in the corresponding data structures (routing graph etc).
1075 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
1076 // meaning how much will be paid in fees after this node (to the best of our knowledge).
1077 // This data can later be helpful to optimize routing (pay lower fees).
1078 macro_rules! add_entries_to_cheapest_to_target_node {
1079 ( $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 ) => {
1080 let skip_node = if let Some(elem) = dist.get_mut(&$node_id) {
1081 let was_processed = elem.was_processed;
1082 elem.was_processed = true;
1085 // Entries are added to dist in add_entry!() when there is a channel from a node.
1086 // Because there are no channels from payee, it will not have a dist entry at this point.
1087 // If we're processing any other node, it is always be the result of a channel from it.
1088 assert_eq!($node_id, payee_node_id);
1093 if let Some(first_channels) = first_hop_targets.get(&$node_id) {
1094 for details in first_channels {
1095 let candidate = CandidateRouteHop::FirstHop { details };
1096 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);
1100 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
1103 &empty_node_features
1106 if !features.requires_unknown_bits() {
1107 for chan_id in $node.channels.iter() {
1108 let chan = network_channels.get(chan_id).unwrap();
1109 if !chan.features.requires_unknown_bits() {
1110 let (directed_channel, source) =
1111 chan.as_directed_to(&$node_id).expect("inconsistent NetworkGraph");
1112 if first_hops.is_none() || *source != our_node_id {
1113 if let Some(direction) = directed_channel.direction() {
1114 if direction.enabled {
1115 let candidate = CandidateRouteHop::PublicHop {
1116 info: directed_channel.with_update().unwrap(),
1117 short_channel_id: *chan_id,
1119 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);
1130 let mut payment_paths = Vec::<PaymentPath>::new();
1132 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
1133 'paths_collection: loop {
1134 // For every new path, start from scratch, except
1135 // bookkept_channels_liquidity_available_msat, which will improve
1136 // the further iterations of path finding. Also don't erase first_hop_targets.
1139 hit_minimum_limit = false;
1141 // If first hop is a private channel and the only way to reach the payee, this is the only
1142 // place where it could be added.
1143 if let Some(first_channels) = first_hop_targets.get(&payee_node_id) {
1144 for details in first_channels {
1145 let candidate = CandidateRouteHop::FirstHop { details };
1146 let added = add_entry!(candidate, our_node_id, payee_node_id, 0, path_value_msat, 0, 0u64, 0);
1147 log_trace!(logger, "{} direct route to payee via SCID {}", if added { "Added" } else { "Skipped" }, candidate.short_channel_id());
1151 // Add the payee as a target, so that the payee-to-payer
1152 // search algorithm knows what to start with.
1153 match network_nodes.get(&payee_node_id) {
1154 // The payee is not in our network graph, so nothing to add here.
1155 // There is still a chance of reaching them via last_hops though,
1156 // so don't yet fail the payment here.
1157 // If not, targets.pop() will not even let us enter the loop in step 2.
1160 add_entries_to_cheapest_to_target_node!(node, payee_node_id, 0, path_value_msat, 0, 0u64, 0);
1165 // If a caller provided us with last hops, add them to routing targets. Since this happens
1166 // earlier than general path finding, they will be somewhat prioritized, although currently
1167 // it matters only if the fees are exactly the same.
1168 for route in payment_params.route_hints.iter().filter(|route| !route.0.is_empty()) {
1169 let first_hop_in_route = &(route.0)[0];
1170 let have_hop_src_in_graph =
1171 // Only add the hops in this route to our candidate set if either
1172 // we have a direct channel to the first hop or the first hop is
1173 // in the regular network graph.
1174 first_hop_targets.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some() ||
1175 network_nodes.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some();
1176 if have_hop_src_in_graph {
1177 // We start building the path from reverse, i.e., from payee
1178 // to the first RouteHintHop in the path.
1179 let hop_iter = route.0.iter().rev();
1180 let prev_hop_iter = core::iter::once(&payment_params.payee_pubkey).chain(
1181 route.0.iter().skip(1).rev().map(|hop| &hop.src_node_id));
1182 let mut hop_used = true;
1183 let mut aggregate_next_hops_fee_msat: u64 = 0;
1184 let mut aggregate_next_hops_path_htlc_minimum_msat: u64 = 0;
1185 let mut aggregate_next_hops_path_penalty_msat: u64 = 0;
1186 let mut aggregate_next_hops_cltv_delta: u32 = 0;
1188 for (idx, (hop, prev_hop_id)) in hop_iter.zip(prev_hop_iter).enumerate() {
1189 let source = NodeId::from_pubkey(&hop.src_node_id);
1190 let target = NodeId::from_pubkey(&prev_hop_id);
1191 let candidate = network_channels
1192 .get(&hop.short_channel_id)
1193 .and_then(|channel| channel.as_directed_to(&target))
1194 .and_then(|(channel, _)| channel.with_update())
1195 .map(|info| CandidateRouteHop::PublicHop {
1197 short_channel_id: hop.short_channel_id,
1199 .unwrap_or_else(|| CandidateRouteHop::PrivateHop { hint: hop });
1200 let capacity_msat = candidate.effective_capacity().as_msat();
1201 aggregate_next_hops_path_penalty_msat = aggregate_next_hops_path_penalty_msat
1202 .checked_add(scorer.channel_penalty_msat(hop.short_channel_id, final_value_msat, capacity_msat, &source, &target))
1203 .unwrap_or_else(|| u64::max_value());
1205 aggregate_next_hops_cltv_delta = aggregate_next_hops_cltv_delta
1206 .checked_add(hop.cltv_expiry_delta as u32)
1207 .unwrap_or_else(|| u32::max_value());
1209 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) {
1210 // If this hop was not used then there is no use checking the preceding hops
1211 // in the RouteHint. We can break by just searching for a direct channel between
1212 // last checked hop and first_hop_targets
1216 // Searching for a direct channel between last checked hop and first_hop_targets
1217 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&prev_hop_id)) {
1218 for details in first_channels {
1219 let candidate = CandidateRouteHop::FirstHop { details };
1220 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);
1228 // In the next values of the iterator, the aggregate fees already reflects
1229 // the sum of value sent from payer (final_value_msat) and routing fees
1230 // for the last node in the RouteHint. We need to just add the fees to
1231 // route through the current node so that the preceeding node (next iteration)
1233 let hops_fee = compute_fees(aggregate_next_hops_fee_msat + final_value_msat, hop.fees)
1234 .map_or(None, |inc| inc.checked_add(aggregate_next_hops_fee_msat));
1235 aggregate_next_hops_fee_msat = if let Some(val) = hops_fee { val } else { break; };
1237 let hop_htlc_minimum_msat = candidate.htlc_minimum_msat();
1238 let hop_htlc_minimum_msat_inc = if let Some(val) = compute_fees(aggregate_next_hops_path_htlc_minimum_msat, hop.fees) { val } else { break; };
1239 let hops_path_htlc_minimum = aggregate_next_hops_path_htlc_minimum_msat
1240 .checked_add(hop_htlc_minimum_msat_inc);
1241 aggregate_next_hops_path_htlc_minimum_msat = if let Some(val) = hops_path_htlc_minimum { cmp::max(hop_htlc_minimum_msat, val) } else { break; };
1243 if idx == route.0.len() - 1 {
1244 // The last hop in this iterator is the first hop in
1245 // overall RouteHint.
1246 // If this hop connects to a node with which we have a direct channel,
1247 // ignore the network graph and, if the last hop was added, add our
1248 // direct channel to the candidate set.
1250 // Note that we *must* check if the last hop was added as `add_entry`
1251 // always assumes that the third argument is a node to which we have a
1253 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&hop.src_node_id)) {
1254 for details in first_channels {
1255 let candidate = CandidateRouteHop::FirstHop { details };
1256 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);
1264 log_trace!(logger, "Starting main path collection loop with {} nodes pre-filled from first/last hops.", targets.len());
1266 // At this point, targets are filled with the data from first and
1267 // last hops communicated by the caller, and the payment receiver.
1268 let mut found_new_path = false;
1271 // If this loop terminates due the exhaustion of targets, two situations are possible:
1272 // - not enough outgoing liquidity:
1273 // 0 < already_collected_value_msat < final_value_msat
1274 // - enough outgoing liquidity:
1275 // final_value_msat <= already_collected_value_msat < recommended_value_msat
1276 // Both these cases (and other cases except reaching recommended_value_msat) mean that
1277 // paths_collection will be stopped because found_new_path==false.
1278 // This is not necessarily a routing failure.
1279 '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() {
1281 // Since we're going payee-to-payer, hitting our node as a target means we should stop
1282 // traversing the graph and arrange the path out of what we found.
1283 if node_id == our_node_id {
1284 let mut new_entry = dist.remove(&our_node_id).unwrap();
1285 let mut ordered_hops = vec!((new_entry.clone(), NodeFeatures::empty()));
1288 let mut features_set = false;
1289 if let Some(first_channels) = first_hop_targets.get(&ordered_hops.last().unwrap().0.node_id) {
1290 for details in first_channels {
1291 if details.short_channel_id.unwrap() == ordered_hops.last().unwrap().0.candidate.short_channel_id() {
1292 ordered_hops.last_mut().unwrap().1 = details.counterparty.features.to_context();
1293 features_set = true;
1299 if let Some(node) = network_nodes.get(&ordered_hops.last().unwrap().0.node_id) {
1300 if let Some(node_info) = node.announcement_info.as_ref() {
1301 ordered_hops.last_mut().unwrap().1 = node_info.features.clone();
1303 ordered_hops.last_mut().unwrap().1 = NodeFeatures::empty();
1306 // We can fill in features for everything except hops which were
1307 // provided via the invoice we're paying. We could guess based on the
1308 // recipient's features but for now we simply avoid guessing at all.
1312 // Means we succesfully traversed from the payer to the payee, now
1313 // save this path for the payment route. Also, update the liquidity
1314 // remaining on the used hops, so that we take them into account
1315 // while looking for more paths.
1316 if ordered_hops.last().unwrap().0.node_id == payee_node_id {
1320 new_entry = match dist.remove(&ordered_hops.last().unwrap().0.node_id) {
1321 Some(payment_hop) => payment_hop,
1322 // We can't arrive at None because, if we ever add an entry to targets,
1323 // we also fill in the entry in dist (see add_entry!).
1324 None => unreachable!(),
1326 // We "propagate" the fees one hop backward (topologically) here,
1327 // so that fees paid for a HTLC forwarding on the current channel are
1328 // associated with the previous channel (where they will be subtracted).
1329 ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
1330 ordered_hops.push((new_entry.clone(), NodeFeatures::empty()));
1332 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
1333 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
1335 log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: \n {:#?}",
1336 ordered_hops.len(), value_contribution_msat, ordered_hops.iter().map(|h| &(h.0)).collect::<Vec<&PathBuildingHop>>());
1338 let mut payment_path = PaymentPath {hops: ordered_hops};
1340 // We could have possibly constructed a slightly inconsistent path: since we reduce
1341 // value being transferred along the way, we could have violated htlc_minimum_msat
1342 // on some channels we already passed (assuming dest->source direction). Here, we
1343 // recompute the fees again, so that if that's the case, we match the currently
1344 // underpaid htlc_minimum_msat with fees.
1345 payment_path.update_value_and_recompute_fees(cmp::min(value_contribution_msat, final_value_msat));
1347 // Since a path allows to transfer as much value as
1348 // the smallest channel it has ("bottleneck"), we should recompute
1349 // the fees so sender HTLC don't overpay fees when traversing
1350 // larger channels than the bottleneck. This may happen because
1351 // when we were selecting those channels we were not aware how much value
1352 // this path will transfer, and the relative fee for them
1353 // might have been computed considering a larger value.
1354 // Remember that we used these channels so that we don't rely
1355 // on the same liquidity in future paths.
1356 let mut prevented_redundant_path_selection = false;
1357 for (payment_hop, _) in payment_path.hops.iter() {
1358 let channel_liquidity_available_msat = bookkept_channels_liquidity_available_msat.get_mut(&payment_hop.candidate.short_channel_id()).unwrap();
1359 let mut spent_on_hop_msat = value_contribution_msat;
1360 let next_hops_fee_msat = payment_hop.next_hops_fee_msat;
1361 spent_on_hop_msat += next_hops_fee_msat;
1362 if spent_on_hop_msat == *channel_liquidity_available_msat {
1363 // If this path used all of this channel's available liquidity, we know
1364 // this path will not be selected again in the next loop iteration.
1365 prevented_redundant_path_selection = true;
1367 *channel_liquidity_available_msat -= spent_on_hop_msat;
1369 if !prevented_redundant_path_selection {
1370 // If we weren't capped by hitting a liquidity limit on a channel in the path,
1371 // we'll probably end up picking the same path again on the next iteration.
1372 // Decrease the available liquidity of a hop in the middle of the path.
1373 let victim_scid = payment_path.hops[(payment_path.hops.len() - 1) / 2].0.candidate.short_channel_id();
1374 log_trace!(logger, "Disabling channel {} for future path building iterations to avoid duplicates.", victim_scid);
1375 let victim_liquidity = bookkept_channels_liquidity_available_msat.get_mut(&victim_scid).unwrap();
1376 *victim_liquidity = 0;
1379 // Track the total amount all our collected paths allow to send so that we:
1380 // - know when to stop looking for more paths
1381 // - know which of the hops are useless considering how much more sats we need
1382 // (contributes_sufficient_value)
1383 already_collected_value_msat += value_contribution_msat;
1385 payment_paths.push(payment_path);
1386 found_new_path = true;
1387 break 'path_construction;
1390 // If we found a path back to the payee, we shouldn't try to process it again. This is
1391 // the equivalent of the `elem.was_processed` check in
1392 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
1393 if node_id == payee_node_id { continue 'path_construction; }
1395 // Otherwise, since the current target node is not us,
1396 // keep "unrolling" the payment graph from payee to payer by
1397 // finding a way to reach the current target from the payer side.
1398 match network_nodes.get(&node_id) {
1401 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);
1407 // If we don't support MPP, no use trying to gather more value ever.
1408 break 'paths_collection;
1412 // Stop either when the recommended value is reached or if no new path was found in this
1414 // In the latter case, making another path finding attempt won't help,
1415 // because we deterministically terminated the search due to low liquidity.
1416 if already_collected_value_msat >= recommended_value_msat || !found_new_path {
1417 log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
1418 already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
1419 break 'paths_collection;
1420 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
1421 // Further, if this was our first walk of the graph, and we weren't limited by an
1422 // htlc_minimum_msat, return immediately because this path should suffice. If we were
1423 // limited by an htlc_minimum_msat value, find another path with a higher value,
1424 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
1425 // still keeping a lower total fee than this path.
1426 if !hit_minimum_limit {
1427 log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
1428 break 'paths_collection;
1430 log_trace!(logger, "Collected our payment amount on the first pass, but running again to collect extra paths with a potentially higher limit.");
1431 path_value_msat = recommended_value_msat;
1436 if payment_paths.len() == 0 {
1437 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1440 if already_collected_value_msat < final_value_msat {
1441 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1444 // Sort by total fees and take the best paths.
1445 payment_paths.sort_by_key(|path| path.get_total_fee_paid_msat());
1446 if payment_paths.len() > 50 {
1447 payment_paths.truncate(50);
1450 // Draw multiple sufficient routes by randomly combining the selected paths.
1451 let mut drawn_routes = Vec::new();
1452 for i in 0..payment_paths.len() {
1453 let mut cur_route = Vec::<PaymentPath>::new();
1454 let mut aggregate_route_value_msat = 0;
1457 // TODO: real random shuffle
1458 // Currently just starts with i_th and goes up to i-1_th in a looped way.
1459 let cur_payment_paths = [&payment_paths[i..], &payment_paths[..i]].concat();
1462 for payment_path in cur_payment_paths {
1463 cur_route.push(payment_path.clone());
1464 aggregate_route_value_msat += payment_path.get_value_msat();
1465 if aggregate_route_value_msat > final_value_msat {
1466 // Last path likely overpaid. Substract it from the most expensive
1467 // (in terms of proportional fee) path in this route and recompute fees.
1468 // This might be not the most economically efficient way, but fewer paths
1469 // also makes routing more reliable.
1470 let mut overpaid_value_msat = aggregate_route_value_msat - final_value_msat;
1472 // First, drop some expensive low-value paths entirely if possible.
1473 // Sort by value so that we drop many really-low values first, since
1474 // fewer paths is better: the payment is less likely to fail.
1475 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1476 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1477 cur_route.sort_by_key(|path| path.get_value_msat());
1478 // We should make sure that at least 1 path left.
1479 let mut paths_left = cur_route.len();
1480 cur_route.retain(|path| {
1481 if paths_left == 1 {
1484 let mut keep = true;
1485 let path_value_msat = path.get_value_msat();
1486 if path_value_msat <= overpaid_value_msat {
1488 overpaid_value_msat -= path_value_msat;
1494 if overpaid_value_msat == 0 {
1498 assert!(cur_route.len() > 0);
1501 // Now, substract the overpaid value from the most-expensive path.
1502 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1503 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1504 cur_route.sort_by_key(|path| { path.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>() });
1505 let expensive_payment_path = cur_route.first_mut().unwrap();
1506 // We already dropped all the small channels above, meaning all the
1507 // remaining channels are larger than remaining overpaid_value_msat.
1508 // Thus, this can't be negative.
1509 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
1510 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
1514 drawn_routes.push(cur_route);
1518 // Select the best route by lowest total fee.
1519 drawn_routes.sort_by_key(|paths| paths.iter().map(|path| path.get_total_fee_paid_msat()).sum::<u64>());
1520 let mut selected_paths = Vec::<Vec<Result<RouteHop, LightningError>>>::new();
1521 for payment_path in drawn_routes.first().unwrap() {
1522 let mut path = payment_path.hops.iter().map(|(payment_hop, node_features)| {
1524 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)})?,
1525 node_features: node_features.clone(),
1526 short_channel_id: payment_hop.candidate.short_channel_id(),
1527 channel_features: payment_hop.candidate.features(),
1528 fee_msat: payment_hop.fee_msat,
1529 cltv_expiry_delta: payment_hop.candidate.cltv_expiry_delta(),
1531 }).collect::<Vec<_>>();
1532 // Propagate the cltv_expiry_delta one hop backwards since the delta from the current hop is
1533 // applicable for the previous hop.
1534 path.iter_mut().rev().fold(final_cltv_expiry_delta, |prev_cltv_expiry_delta, hop| {
1535 core::mem::replace(&mut hop.as_mut().unwrap().cltv_expiry_delta, prev_cltv_expiry_delta)
1537 selected_paths.push(path);
1540 if let Some(features) = &payment_params.features {
1541 for path in selected_paths.iter_mut() {
1542 if let Ok(route_hop) = path.last_mut().unwrap() {
1543 route_hop.node_features = features.to_context();
1549 paths: selected_paths.into_iter().map(|path| path.into_iter().collect()).collect::<Result<Vec<_>, _>>()?,
1550 payment_params: Some(payment_params.clone()),
1552 log_info!(logger, "Got route to {}: {}", payment_params.payee_pubkey, log_route!(route));
1556 // When an adversarial intermediary node observes a payment, it may be able to infer its
1557 // destination, if the remaining CLTV expiry delta exactly matches a feasible path in the network
1558 // graph. In order to improve privacy, this method obfuscates the CLTV expiry deltas along the
1559 // payment path by adding a randomized 'shadow route' offset to the final hop.
1560 fn add_random_cltv_offset(route: &mut Route, payment_params: &PaymentParameters, network_graph: &ReadOnlyNetworkGraph, random_seed_bytes: &[u8; 32]) {
1561 let network_channels = network_graph.channels();
1562 let network_nodes = network_graph.nodes();
1564 for path in route.paths.iter_mut() {
1565 let mut shadow_ctlv_expiry_delta_offset: u32 = 0;
1567 // Remember the last three nodes of the random walk and avoid looping back on them.
1568 // Init with the last three nodes from the actual path, if possible.
1569 let mut nodes_to_avoid: [NodeId; 3] = [NodeId::from_pubkey(&path.last().unwrap().pubkey),
1570 NodeId::from_pubkey(&path.get(path.len().saturating_sub(2)).unwrap().pubkey),
1571 NodeId::from_pubkey(&path.get(path.len().saturating_sub(3)).unwrap().pubkey)];
1573 // Choose the last publicly known node as the starting point for the random walk.
1574 let mut cur_hop: Option<NodeId> = None;
1575 let mut path_nonce = [0u8; 12];
1576 if let Some(starting_hop) = path.iter().rev()
1577 .find(|h| network_nodes.contains_key(&NodeId::from_pubkey(&h.pubkey))) {
1578 cur_hop = Some(NodeId::from_pubkey(&starting_hop.pubkey));
1579 path_nonce.copy_from_slice(&cur_hop.unwrap().as_slice()[..12]);
1582 // Init PRNG with the path-dependant nonce, which is static for private paths.
1583 let mut prng = ChaCha20::new(random_seed_bytes, &path_nonce);
1584 let mut random_path_bytes = [0u8; ::core::mem::size_of::<usize>()];
1586 // Pick a random path length in [1 .. 3]
1587 prng.process_in_place(&mut random_path_bytes);
1588 let random_walk_length = usize::from_be_bytes(random_path_bytes).wrapping_rem(3).wrapping_add(1);
1590 for random_hop in 0..random_walk_length {
1591 // If we don't find a suitable offset in the public network graph, we default to
1592 // MEDIAN_HOP_CLTV_EXPIRY_DELTA.
1593 let mut random_hop_offset = MEDIAN_HOP_CLTV_EXPIRY_DELTA;
1595 if let Some(cur_node_id) = cur_hop {
1596 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
1597 // Randomly choose the next unvisited hop.
1598 prng.process_in_place(&mut random_path_bytes);
1599 if let Some(random_channel) = usize::from_be_bytes(random_path_bytes)
1600 .checked_rem(cur_node.channels.len())
1601 .and_then(|index| cur_node.channels.get(index))
1602 .and_then(|id| network_channels.get(id)) {
1603 random_channel.as_directed_from(&cur_node_id).map(|(dir_info, next_id)| {
1604 if !nodes_to_avoid.iter().any(|x| x == next_id) {
1605 nodes_to_avoid[random_hop] = *next_id;
1606 dir_info.direction().map(|channel_update_info| {
1607 random_hop_offset = channel_update_info.cltv_expiry_delta.into();
1608 cur_hop = Some(*next_id);
1616 shadow_ctlv_expiry_delta_offset = shadow_ctlv_expiry_delta_offset
1617 .checked_add(random_hop_offset)
1618 .unwrap_or(shadow_ctlv_expiry_delta_offset);
1621 // Limit the total offset to reduce the worst-case locked liquidity timevalue
1622 const MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET: u32 = 3*144;
1623 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET);
1625 // Limit the offset so we never exceed the max_total_cltv_expiry_delta. To improve plausibility,
1626 // we choose the limit to be the largest possible multiple of MEDIAN_HOP_CLTV_EXPIRY_DELTA.
1627 let path_total_cltv_expiry_delta: u32 = path.iter().map(|h| h.cltv_expiry_delta).sum();
1628 let mut max_path_offset = payment_params.max_total_cltv_expiry_delta - path_total_cltv_expiry_delta;
1629 max_path_offset = cmp::max(
1630 max_path_offset - (max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA),
1631 max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA);
1632 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, max_path_offset);
1634 // Add 'shadow' CLTV offset to the final hop
1635 if let Some(last_hop) = path.last_mut() {
1636 last_hop.cltv_expiry_delta = last_hop.cltv_expiry_delta
1637 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(last_hop.cltv_expiry_delta);
1644 use routing::network_graph::{NetworkGraph, NetGraphMsgHandler, NodeId};
1645 use routing::router::{get_route, add_random_cltv_offset, PaymentParameters, Route, RouteHint, RouteHintHop, RouteHop, RoutingFees, DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA};
1646 use routing::scoring::Score;
1647 use chain::transaction::OutPoint;
1648 use chain::keysinterface::KeysInterface;
1649 use ln::features::{ChannelFeatures, InitFeatures, InvoiceFeatures, NodeFeatures};
1650 use ln::msgs::{ErrorAction, LightningError, OptionalField, UnsignedChannelAnnouncement, ChannelAnnouncement, RoutingMessageHandler,
1651 NodeAnnouncement, UnsignedNodeAnnouncement, ChannelUpdate, UnsignedChannelUpdate};
1652 use ln::channelmanager;
1653 use util::test_utils;
1654 use util::chacha20::ChaCha20;
1655 use util::ser::Writeable;
1657 use util::ser::Writer;
1659 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
1660 use bitcoin::hashes::Hash;
1661 use bitcoin::network::constants::Network;
1662 use bitcoin::blockdata::constants::genesis_block;
1663 use bitcoin::blockdata::script::Builder;
1664 use bitcoin::blockdata::opcodes;
1665 use bitcoin::blockdata::transaction::TxOut;
1669 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
1670 use bitcoin::secp256k1::{Secp256k1, All};
1673 use sync::{self, Arc};
1675 fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
1676 features: InitFeatures, outbound_capacity_msat: u64) -> channelmanager::ChannelDetails {
1677 channelmanager::ChannelDetails {
1678 channel_id: [0; 32],
1679 counterparty: channelmanager::ChannelCounterparty {
1682 unspendable_punishment_reserve: 0,
1683 forwarding_info: None,
1685 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
1687 inbound_scid_alias: None,
1688 channel_value_satoshis: 0,
1691 outbound_capacity_msat,
1692 inbound_capacity_msat: 42,
1693 unspendable_punishment_reserve: None,
1694 confirmations_required: None,
1695 force_close_spend_delay: None,
1696 is_outbound: true, is_funding_locked: true,
1697 is_usable: true, is_public: true,
1701 // Using the same keys for LN and BTC ids
1703 net_graph_msg_handler: &NetGraphMsgHandler<Arc<NetworkGraph>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1704 secp_ctx: &Secp256k1<All>, node_1_privkey: &SecretKey, node_2_privkey: &SecretKey, features: ChannelFeatures, short_channel_id: u64
1706 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1707 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1709 let unsigned_announcement = UnsignedChannelAnnouncement {
1711 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1715 bitcoin_key_1: node_id_1,
1716 bitcoin_key_2: node_id_2,
1717 excess_data: Vec::new(),
1720 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1721 let valid_announcement = ChannelAnnouncement {
1722 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1723 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1724 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1725 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1726 contents: unsigned_announcement.clone(),
1728 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1729 Ok(res) => assert!(res),
1735 net_graph_msg_handler: &NetGraphMsgHandler<Arc<NetworkGraph>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1736 secp_ctx: &Secp256k1<All>, node_privkey: &SecretKey, update: UnsignedChannelUpdate
1738 let msghash = hash_to_message!(&Sha256dHash::hash(&update.encode()[..])[..]);
1739 let valid_channel_update = ChannelUpdate {
1740 signature: secp_ctx.sign(&msghash, node_privkey),
1741 contents: update.clone()
1744 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1745 Ok(res) => assert!(res),
1750 fn add_or_update_node(
1751 net_graph_msg_handler: &NetGraphMsgHandler<Arc<NetworkGraph>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1752 secp_ctx: &Secp256k1<All>, node_privkey: &SecretKey, features: NodeFeatures, timestamp: u32
1754 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
1755 let unsigned_announcement = UnsignedNodeAnnouncement {
1761 addresses: Vec::new(),
1762 excess_address_data: Vec::new(),
1763 excess_data: Vec::new(),
1765 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1766 let valid_announcement = NodeAnnouncement {
1767 signature: secp_ctx.sign(&msghash, node_privkey),
1768 contents: unsigned_announcement.clone()
1771 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1777 fn get_nodes(secp_ctx: &Secp256k1<All>) -> (SecretKey, PublicKey, Vec<SecretKey>, Vec<PublicKey>) {
1778 let privkeys: Vec<SecretKey> = (2..10).map(|i| {
1779 SecretKey::from_slice(&hex::decode(format!("{:02x}", i).repeat(32)).unwrap()[..]).unwrap()
1782 let pubkeys = privkeys.iter().map(|secret| PublicKey::from_secret_key(&secp_ctx, secret)).collect();
1784 let our_privkey = SecretKey::from_slice(&hex::decode("01".repeat(32)).unwrap()[..]).unwrap();
1785 let our_id = PublicKey::from_secret_key(&secp_ctx, &our_privkey);
1787 (our_privkey, our_id, privkeys, pubkeys)
1790 fn id_to_feature_flags(id: u8) -> Vec<u8> {
1791 // Set the feature flags to the id'th odd (ie non-required) feature bit so that we can
1792 // test for it later.
1793 let idx = (id - 1) * 2 + 1;
1795 vec![1 << (idx - 8*3), 0, 0, 0]
1796 } else if idx > 8*2 {
1797 vec![1 << (idx - 8*2), 0, 0]
1798 } else if idx > 8*1 {
1799 vec![1 << (idx - 8*1), 0]
1805 fn build_graph() -> (
1807 sync::Arc<NetworkGraph>,
1808 NetGraphMsgHandler<sync::Arc<NetworkGraph>, sync::Arc<test_utils::TestChainSource>, sync::Arc<crate::util::test_utils::TestLogger>>,
1809 sync::Arc<test_utils::TestChainSource>,
1810 sync::Arc<test_utils::TestLogger>,
1812 let secp_ctx = Secp256k1::new();
1813 let logger = Arc::new(test_utils::TestLogger::new());
1814 let chain_monitor = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1815 let network_graph = Arc::new(NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash()));
1816 let net_graph_msg_handler = NetGraphMsgHandler::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
1817 // Build network from our_id to node6:
1819 // -1(1)2- node0 -1(3)2-
1821 // our_id -1(12)2- node7 -1(13)2--- node2
1823 // -1(2)2- node1 -1(4)2-
1826 // chan1 1-to-2: disabled
1827 // chan1 2-to-1: enabled, 0 fee
1829 // chan2 1-to-2: enabled, ignored fee
1830 // chan2 2-to-1: enabled, 0 fee
1832 // chan3 1-to-2: enabled, 0 fee
1833 // chan3 2-to-1: enabled, 100 msat fee
1835 // chan4 1-to-2: enabled, 100% fee
1836 // chan4 2-to-1: enabled, 0 fee
1838 // chan12 1-to-2: enabled, ignored fee
1839 // chan12 2-to-1: enabled, 0 fee
1841 // chan13 1-to-2: enabled, 200% fee
1842 // chan13 2-to-1: enabled, 0 fee
1845 // -1(5)2- node3 -1(8)2--
1849 // node2--1(6)2- node4 -1(9)2--- node6 (not in global route map)
1851 // -1(7)2- node5 -1(10)2-
1853 // Channels 5, 8, 9 and 10 are private channels.
1855 // chan5 1-to-2: enabled, 100 msat fee
1856 // chan5 2-to-1: enabled, 0 fee
1858 // chan6 1-to-2: enabled, 0 fee
1859 // chan6 2-to-1: enabled, 0 fee
1861 // chan7 1-to-2: enabled, 100% fee
1862 // chan7 2-to-1: enabled, 0 fee
1864 // chan8 1-to-2: enabled, variable fee (0 then 1000 msat)
1865 // chan8 2-to-1: enabled, 0 fee
1867 // chan9 1-to-2: enabled, 1001 msat fee
1868 // chan9 2-to-1: enabled, 0 fee
1870 // chan10 1-to-2: enabled, 0 fee
1871 // chan10 2-to-1: enabled, 0 fee
1873 // chan11 1-to-2: enabled, 0 fee
1874 // chan11 2-to-1: enabled, 0 fee
1876 let (our_privkey, _, privkeys, _) = get_nodes(&secp_ctx);
1878 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[0], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
1879 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1880 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1881 short_channel_id: 1,
1884 cltv_expiry_delta: 0,
1885 htlc_minimum_msat: 0,
1886 htlc_maximum_msat: OptionalField::Absent,
1888 fee_proportional_millionths: 0,
1889 excess_data: Vec::new()
1892 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
1894 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
1895 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1896 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1897 short_channel_id: 2,
1900 cltv_expiry_delta: (5 << 4) | 3,
1901 htlc_minimum_msat: 0,
1902 htlc_maximum_msat: OptionalField::Absent,
1903 fee_base_msat: u32::max_value(),
1904 fee_proportional_millionths: u32::max_value(),
1905 excess_data: Vec::new()
1907 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1908 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1909 short_channel_id: 2,
1912 cltv_expiry_delta: 0,
1913 htlc_minimum_msat: 0,
1914 htlc_maximum_msat: OptionalField::Absent,
1916 fee_proportional_millionths: 0,
1917 excess_data: Vec::new()
1920 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
1922 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[7], ChannelFeatures::from_le_bytes(id_to_feature_flags(12)), 12);
1923 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1924 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1925 short_channel_id: 12,
1928 cltv_expiry_delta: (5 << 4) | 3,
1929 htlc_minimum_msat: 0,
1930 htlc_maximum_msat: OptionalField::Absent,
1931 fee_base_msat: u32::max_value(),
1932 fee_proportional_millionths: u32::max_value(),
1933 excess_data: Vec::new()
1935 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1936 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1937 short_channel_id: 12,
1940 cltv_expiry_delta: 0,
1941 htlc_minimum_msat: 0,
1942 htlc_maximum_msat: OptionalField::Absent,
1944 fee_proportional_millionths: 0,
1945 excess_data: Vec::new()
1948 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], NodeFeatures::from_le_bytes(id_to_feature_flags(8)), 0);
1950 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
1951 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1952 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1953 short_channel_id: 3,
1956 cltv_expiry_delta: (3 << 4) | 1,
1957 htlc_minimum_msat: 0,
1958 htlc_maximum_msat: OptionalField::Absent,
1960 fee_proportional_millionths: 0,
1961 excess_data: Vec::new()
1963 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1964 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1965 short_channel_id: 3,
1968 cltv_expiry_delta: (3 << 4) | 2,
1969 htlc_minimum_msat: 0,
1970 htlc_maximum_msat: OptionalField::Absent,
1972 fee_proportional_millionths: 0,
1973 excess_data: Vec::new()
1976 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
1977 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1978 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1979 short_channel_id: 4,
1982 cltv_expiry_delta: (4 << 4) | 1,
1983 htlc_minimum_msat: 0,
1984 htlc_maximum_msat: OptionalField::Absent,
1986 fee_proportional_millionths: 1000000,
1987 excess_data: Vec::new()
1989 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1990 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1991 short_channel_id: 4,
1994 cltv_expiry_delta: (4 << 4) | 2,
1995 htlc_minimum_msat: 0,
1996 htlc_maximum_msat: OptionalField::Absent,
1998 fee_proportional_millionths: 0,
1999 excess_data: Vec::new()
2002 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(13)), 13);
2003 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2004 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2005 short_channel_id: 13,
2008 cltv_expiry_delta: (13 << 4) | 1,
2009 htlc_minimum_msat: 0,
2010 htlc_maximum_msat: OptionalField::Absent,
2012 fee_proportional_millionths: 2000000,
2013 excess_data: Vec::new()
2015 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2016 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2017 short_channel_id: 13,
2020 cltv_expiry_delta: (13 << 4) | 2,
2021 htlc_minimum_msat: 0,
2022 htlc_maximum_msat: OptionalField::Absent,
2024 fee_proportional_millionths: 0,
2025 excess_data: Vec::new()
2028 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
2030 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
2031 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2032 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2033 short_channel_id: 6,
2036 cltv_expiry_delta: (6 << 4) | 1,
2037 htlc_minimum_msat: 0,
2038 htlc_maximum_msat: OptionalField::Absent,
2040 fee_proportional_millionths: 0,
2041 excess_data: Vec::new()
2043 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
2044 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2045 short_channel_id: 6,
2048 cltv_expiry_delta: (6 << 4) | 2,
2049 htlc_minimum_msat: 0,
2050 htlc_maximum_msat: OptionalField::Absent,
2052 fee_proportional_millionths: 0,
2053 excess_data: Vec::new(),
2056 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(11)), 11);
2057 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
2058 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2059 short_channel_id: 11,
2062 cltv_expiry_delta: (11 << 4) | 1,
2063 htlc_minimum_msat: 0,
2064 htlc_maximum_msat: OptionalField::Absent,
2066 fee_proportional_millionths: 0,
2067 excess_data: Vec::new()
2069 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
2070 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2071 short_channel_id: 11,
2074 cltv_expiry_delta: (11 << 4) | 2,
2075 htlc_minimum_msat: 0,
2076 htlc_maximum_msat: OptionalField::Absent,
2078 fee_proportional_millionths: 0,
2079 excess_data: Vec::new()
2082 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(5)), 0);
2084 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
2086 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[5], ChannelFeatures::from_le_bytes(id_to_feature_flags(7)), 7);
2087 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2088 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2089 short_channel_id: 7,
2092 cltv_expiry_delta: (7 << 4) | 1,
2093 htlc_minimum_msat: 0,
2094 htlc_maximum_msat: OptionalField::Absent,
2096 fee_proportional_millionths: 1000000,
2097 excess_data: Vec::new()
2099 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[5], UnsignedChannelUpdate {
2100 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2101 short_channel_id: 7,
2104 cltv_expiry_delta: (7 << 4) | 2,
2105 htlc_minimum_msat: 0,
2106 htlc_maximum_msat: OptionalField::Absent,
2108 fee_proportional_millionths: 0,
2109 excess_data: Vec::new()
2112 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[5], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
2114 (secp_ctx, network_graph, net_graph_msg_handler, chain_monitor, logger)
2118 fn simple_route_test() {
2119 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2120 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2121 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2122 let scorer = test_utils::TestScorer::with_penalty(0);
2123 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2124 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2126 // Simple route to 2 via 1
2128 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) {
2129 assert_eq!(err, "Cannot send a payment of 0 msat");
2130 } else { panic!(); }
2132 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2133 assert_eq!(route.paths[0].len(), 2);
2135 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2136 assert_eq!(route.paths[0][0].short_channel_id, 2);
2137 assert_eq!(route.paths[0][0].fee_msat, 100);
2138 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2139 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2140 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2142 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2143 assert_eq!(route.paths[0][1].short_channel_id, 4);
2144 assert_eq!(route.paths[0][1].fee_msat, 100);
2145 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2146 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2147 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2151 fn invalid_first_hop_test() {
2152 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2153 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2154 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2155 let scorer = test_utils::TestScorer::with_penalty(0);
2156 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2157 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2159 // Simple route to 2 via 1
2161 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
2163 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) =
2164 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) {
2165 assert_eq!(err, "First hop cannot have our_node_pubkey as a destination.");
2166 } else { panic!(); }
2168 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2169 assert_eq!(route.paths[0].len(), 2);
2173 fn htlc_minimum_test() {
2174 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2175 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2176 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2177 let scorer = test_utils::TestScorer::with_penalty(0);
2178 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2179 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2181 // Simple route to 2 via 1
2183 // Disable other paths
2184 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2185 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2186 short_channel_id: 12,
2188 flags: 2, // to disable
2189 cltv_expiry_delta: 0,
2190 htlc_minimum_msat: 0,
2191 htlc_maximum_msat: OptionalField::Absent,
2193 fee_proportional_millionths: 0,
2194 excess_data: Vec::new()
2196 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2197 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2198 short_channel_id: 3,
2200 flags: 2, // to disable
2201 cltv_expiry_delta: 0,
2202 htlc_minimum_msat: 0,
2203 htlc_maximum_msat: OptionalField::Absent,
2205 fee_proportional_millionths: 0,
2206 excess_data: Vec::new()
2208 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2209 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2210 short_channel_id: 13,
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[2], UnsignedChannelUpdate {
2221 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2222 short_channel_id: 6,
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[2], UnsignedChannelUpdate {
2233 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2234 short_channel_id: 7,
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()
2245 // Check against amount_to_transfer_over_msat.
2246 // Set minimal HTLC of 200_000_000 msat.
2247 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2248 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2249 short_channel_id: 2,
2252 cltv_expiry_delta: 0,
2253 htlc_minimum_msat: 200_000_000,
2254 htlc_maximum_msat: OptionalField::Absent,
2256 fee_proportional_millionths: 0,
2257 excess_data: Vec::new()
2260 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
2262 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2263 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2264 short_channel_id: 4,
2267 cltv_expiry_delta: 0,
2268 htlc_minimum_msat: 0,
2269 htlc_maximum_msat: OptionalField::Present(199_999_999),
2271 fee_proportional_millionths: 0,
2272 excess_data: Vec::new()
2275 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
2276 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) {
2277 assert_eq!(err, "Failed to find a path to the given destination");
2278 } else { panic!(); }
2280 // Lift the restriction on the first hop.
2281 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2282 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2283 short_channel_id: 2,
2286 cltv_expiry_delta: 0,
2287 htlc_minimum_msat: 0,
2288 htlc_maximum_msat: OptionalField::Absent,
2290 fee_proportional_millionths: 0,
2291 excess_data: Vec::new()
2294 // A payment above the minimum should pass
2295 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();
2296 assert_eq!(route.paths[0].len(), 2);
2300 fn htlc_minimum_overpay_test() {
2301 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2302 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2303 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
2304 let scorer = test_utils::TestScorer::with_penalty(0);
2305 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2306 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2308 // A route to node#2 via two paths.
2309 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
2310 // Thus, they can't send 60 without overpaying.
2311 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2312 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2313 short_channel_id: 2,
2316 cltv_expiry_delta: 0,
2317 htlc_minimum_msat: 35_000,
2318 htlc_maximum_msat: OptionalField::Present(40_000),
2320 fee_proportional_millionths: 0,
2321 excess_data: Vec::new()
2323 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2324 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2325 short_channel_id: 12,
2328 cltv_expiry_delta: 0,
2329 htlc_minimum_msat: 35_000,
2330 htlc_maximum_msat: OptionalField::Present(40_000),
2332 fee_proportional_millionths: 0,
2333 excess_data: Vec::new()
2337 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2338 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2339 short_channel_id: 13,
2342 cltv_expiry_delta: 0,
2343 htlc_minimum_msat: 0,
2344 htlc_maximum_msat: OptionalField::Absent,
2346 fee_proportional_millionths: 0,
2347 excess_data: Vec::new()
2349 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2350 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2351 short_channel_id: 4,
2354 cltv_expiry_delta: 0,
2355 htlc_minimum_msat: 0,
2356 htlc_maximum_msat: OptionalField::Absent,
2358 fee_proportional_millionths: 0,
2359 excess_data: Vec::new()
2362 // Disable other paths
2363 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2364 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2365 short_channel_id: 1,
2367 flags: 2, // to disable
2368 cltv_expiry_delta: 0,
2369 htlc_minimum_msat: 0,
2370 htlc_maximum_msat: OptionalField::Absent,
2372 fee_proportional_millionths: 0,
2373 excess_data: Vec::new()
2376 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 60_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2377 // Overpay fees to hit htlc_minimum_msat.
2378 let overpaid_fees = route.paths[0][0].fee_msat + route.paths[1][0].fee_msat;
2379 // TODO: this could be better balanced to overpay 10k and not 15k.
2380 assert_eq!(overpaid_fees, 15_000);
2382 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
2383 // while taking even more fee to match htlc_minimum_msat.
2384 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2385 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2386 short_channel_id: 12,
2389 cltv_expiry_delta: 0,
2390 htlc_minimum_msat: 65_000,
2391 htlc_maximum_msat: OptionalField::Present(80_000),
2393 fee_proportional_millionths: 0,
2394 excess_data: Vec::new()
2396 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2397 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2398 short_channel_id: 2,
2401 cltv_expiry_delta: 0,
2402 htlc_minimum_msat: 0,
2403 htlc_maximum_msat: OptionalField::Absent,
2405 fee_proportional_millionths: 0,
2406 excess_data: Vec::new()
2408 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2409 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2410 short_channel_id: 4,
2413 cltv_expiry_delta: 0,
2414 htlc_minimum_msat: 0,
2415 htlc_maximum_msat: OptionalField::Absent,
2417 fee_proportional_millionths: 100_000,
2418 excess_data: Vec::new()
2421 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 60_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2422 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
2423 assert_eq!(route.paths.len(), 1);
2424 assert_eq!(route.paths[0][0].short_channel_id, 12);
2425 let fees = route.paths[0][0].fee_msat;
2426 assert_eq!(fees, 5_000);
2428 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2429 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
2430 // the other channel.
2431 assert_eq!(route.paths.len(), 1);
2432 assert_eq!(route.paths[0][0].short_channel_id, 2);
2433 let fees = route.paths[0][0].fee_msat;
2434 assert_eq!(fees, 5_000);
2438 fn disable_channels_test() {
2439 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2440 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2441 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2442 let scorer = test_utils::TestScorer::with_penalty(0);
2443 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2444 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2446 // // Disable channels 4 and 12 by flags=2
2447 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2448 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2449 short_channel_id: 4,
2451 flags: 2, // to disable
2452 cltv_expiry_delta: 0,
2453 htlc_minimum_msat: 0,
2454 htlc_maximum_msat: OptionalField::Absent,
2456 fee_proportional_millionths: 0,
2457 excess_data: Vec::new()
2459 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2460 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2461 short_channel_id: 12,
2463 flags: 2, // to disable
2464 cltv_expiry_delta: 0,
2465 htlc_minimum_msat: 0,
2466 htlc_maximum_msat: OptionalField::Absent,
2468 fee_proportional_millionths: 0,
2469 excess_data: Vec::new()
2472 // If all the channels require some features we don't understand, route should fail
2473 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) {
2474 assert_eq!(err, "Failed to find a path to the given destination");
2475 } else { panic!(); }
2477 // If we specify a channel to node7, that overrides our local channel view and that gets used
2478 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2479 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();
2480 assert_eq!(route.paths[0].len(), 2);
2482 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2483 assert_eq!(route.paths[0][0].short_channel_id, 42);
2484 assert_eq!(route.paths[0][0].fee_msat, 200);
2485 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2486 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2487 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2489 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2490 assert_eq!(route.paths[0][1].short_channel_id, 13);
2491 assert_eq!(route.paths[0][1].fee_msat, 100);
2492 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2493 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2494 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2498 fn disable_node_test() {
2499 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2500 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2501 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2502 let scorer = test_utils::TestScorer::with_penalty(0);
2503 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2504 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2506 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
2507 let mut unknown_features = NodeFeatures::known();
2508 unknown_features.set_unknown_feature_required();
2509 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
2510 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
2511 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
2513 // If all nodes require some features we don't understand, route should fail
2514 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) {
2515 assert_eq!(err, "Failed to find a path to the given destination");
2516 } else { panic!(); }
2518 // If we specify a channel to node7, that overrides our local channel view and that gets used
2519 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2520 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();
2521 assert_eq!(route.paths[0].len(), 2);
2523 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2524 assert_eq!(route.paths[0][0].short_channel_id, 42);
2525 assert_eq!(route.paths[0][0].fee_msat, 200);
2526 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2527 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2528 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2530 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2531 assert_eq!(route.paths[0][1].short_channel_id, 13);
2532 assert_eq!(route.paths[0][1].fee_msat, 100);
2533 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2534 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2535 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2537 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
2538 // naively) assume that the user checked the feature bits on the invoice, which override
2539 // the node_announcement.
2543 fn our_chans_test() {
2544 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2545 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2546 let scorer = test_utils::TestScorer::with_penalty(0);
2547 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2548 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2550 // Route to 1 via 2 and 3 because our channel to 1 is disabled
2551 let payment_params = PaymentParameters::from_node_id(nodes[0]);
2552 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2553 assert_eq!(route.paths[0].len(), 3);
2555 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2556 assert_eq!(route.paths[0][0].short_channel_id, 2);
2557 assert_eq!(route.paths[0][0].fee_msat, 200);
2558 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2559 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2560 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2562 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2563 assert_eq!(route.paths[0][1].short_channel_id, 4);
2564 assert_eq!(route.paths[0][1].fee_msat, 100);
2565 assert_eq!(route.paths[0][1].cltv_expiry_delta, (3 << 4) | 2);
2566 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2567 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2569 assert_eq!(route.paths[0][2].pubkey, nodes[0]);
2570 assert_eq!(route.paths[0][2].short_channel_id, 3);
2571 assert_eq!(route.paths[0][2].fee_msat, 100);
2572 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
2573 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(1));
2574 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(3));
2576 // If we specify a channel to node7, that overrides our local channel view and that gets used
2577 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2578 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2579 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();
2580 assert_eq!(route.paths[0].len(), 2);
2582 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2583 assert_eq!(route.paths[0][0].short_channel_id, 42);
2584 assert_eq!(route.paths[0][0].fee_msat, 200);
2585 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2586 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2587 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2589 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2590 assert_eq!(route.paths[0][1].short_channel_id, 13);
2591 assert_eq!(route.paths[0][1].fee_msat, 100);
2592 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2593 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2594 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2597 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2598 let zero_fees = RoutingFees {
2600 proportional_millionths: 0,
2602 vec![RouteHint(vec![RouteHintHop {
2603 src_node_id: nodes[3],
2604 short_channel_id: 8,
2606 cltv_expiry_delta: (8 << 4) | 1,
2607 htlc_minimum_msat: None,
2608 htlc_maximum_msat: None,
2610 ]), RouteHint(vec![RouteHintHop {
2611 src_node_id: nodes[4],
2612 short_channel_id: 9,
2615 proportional_millionths: 0,
2617 cltv_expiry_delta: (9 << 4) | 1,
2618 htlc_minimum_msat: None,
2619 htlc_maximum_msat: None,
2620 }]), RouteHint(vec![RouteHintHop {
2621 src_node_id: nodes[5],
2622 short_channel_id: 10,
2624 cltv_expiry_delta: (10 << 4) | 1,
2625 htlc_minimum_msat: None,
2626 htlc_maximum_msat: None,
2630 fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2631 let zero_fees = RoutingFees {
2633 proportional_millionths: 0,
2635 vec![RouteHint(vec![RouteHintHop {
2636 src_node_id: nodes[2],
2637 short_channel_id: 5,
2640 proportional_millionths: 0,
2642 cltv_expiry_delta: (5 << 4) | 1,
2643 htlc_minimum_msat: None,
2644 htlc_maximum_msat: None,
2646 src_node_id: nodes[3],
2647 short_channel_id: 8,
2649 cltv_expiry_delta: (8 << 4) | 1,
2650 htlc_minimum_msat: None,
2651 htlc_maximum_msat: None,
2653 ]), RouteHint(vec![RouteHintHop {
2654 src_node_id: nodes[4],
2655 short_channel_id: 9,
2658 proportional_millionths: 0,
2660 cltv_expiry_delta: (9 << 4) | 1,
2661 htlc_minimum_msat: None,
2662 htlc_maximum_msat: None,
2663 }]), RouteHint(vec![RouteHintHop {
2664 src_node_id: nodes[5],
2665 short_channel_id: 10,
2667 cltv_expiry_delta: (10 << 4) | 1,
2668 htlc_minimum_msat: None,
2669 htlc_maximum_msat: None,
2674 fn partial_route_hint_test() {
2675 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2676 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2677 let scorer = test_utils::TestScorer::with_penalty(0);
2678 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2679 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2681 // Simple test across 2, 3, 5, and 4 via a last_hop channel
2682 // Tests the behaviour when the RouteHint contains a suboptimal hop.
2683 // RouteHint may be partially used by the algo to build the best path.
2685 // First check that last hop can't have its source as the payee.
2686 let invalid_last_hop = RouteHint(vec![RouteHintHop {
2687 src_node_id: nodes[6],
2688 short_channel_id: 8,
2691 proportional_millionths: 0,
2693 cltv_expiry_delta: (8 << 4) | 1,
2694 htlc_minimum_msat: None,
2695 htlc_maximum_msat: None,
2698 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
2699 invalid_last_hops.push(invalid_last_hop);
2701 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(invalid_last_hops);
2702 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) {
2703 assert_eq!(err, "Route hint cannot have the payee as the source.");
2704 } else { panic!(); }
2707 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops_multi_private_channels(&nodes));
2708 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2709 assert_eq!(route.paths[0].len(), 5);
2711 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2712 assert_eq!(route.paths[0][0].short_channel_id, 2);
2713 assert_eq!(route.paths[0][0].fee_msat, 100);
2714 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2715 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2716 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2718 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2719 assert_eq!(route.paths[0][1].short_channel_id, 4);
2720 assert_eq!(route.paths[0][1].fee_msat, 0);
2721 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
2722 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2723 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2725 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2726 assert_eq!(route.paths[0][2].short_channel_id, 6);
2727 assert_eq!(route.paths[0][2].fee_msat, 0);
2728 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
2729 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2730 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2732 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2733 assert_eq!(route.paths[0][3].short_channel_id, 11);
2734 assert_eq!(route.paths[0][3].fee_msat, 0);
2735 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
2736 // If we have a peer in the node map, we'll use their features here since we don't have
2737 // a way of figuring out their features from the invoice:
2738 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2739 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2741 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2742 assert_eq!(route.paths[0][4].short_channel_id, 8);
2743 assert_eq!(route.paths[0][4].fee_msat, 100);
2744 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2745 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2746 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2749 fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2750 let zero_fees = RoutingFees {
2752 proportional_millionths: 0,
2754 vec![RouteHint(vec![RouteHintHop {
2755 src_node_id: nodes[3],
2756 short_channel_id: 8,
2758 cltv_expiry_delta: (8 << 4) | 1,
2759 htlc_minimum_msat: None,
2760 htlc_maximum_msat: None,
2761 }]), RouteHint(vec![
2763 ]), RouteHint(vec![RouteHintHop {
2764 src_node_id: nodes[5],
2765 short_channel_id: 10,
2767 cltv_expiry_delta: (10 << 4) | 1,
2768 htlc_minimum_msat: None,
2769 htlc_maximum_msat: None,
2774 fn ignores_empty_last_hops_test() {
2775 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2776 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2777 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(empty_last_hop(&nodes));
2778 let scorer = test_utils::TestScorer::with_penalty(0);
2779 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2780 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2782 // Test handling of an empty RouteHint passed in Invoice.
2784 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2785 assert_eq!(route.paths[0].len(), 5);
2787 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2788 assert_eq!(route.paths[0][0].short_channel_id, 2);
2789 assert_eq!(route.paths[0][0].fee_msat, 100);
2790 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2791 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2792 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2794 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2795 assert_eq!(route.paths[0][1].short_channel_id, 4);
2796 assert_eq!(route.paths[0][1].fee_msat, 0);
2797 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
2798 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2799 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2801 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2802 assert_eq!(route.paths[0][2].short_channel_id, 6);
2803 assert_eq!(route.paths[0][2].fee_msat, 0);
2804 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
2805 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2806 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2808 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2809 assert_eq!(route.paths[0][3].short_channel_id, 11);
2810 assert_eq!(route.paths[0][3].fee_msat, 0);
2811 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
2812 // If we have a peer in the node map, we'll use their features here since we don't have
2813 // a way of figuring out their features from the invoice:
2814 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2815 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2817 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2818 assert_eq!(route.paths[0][4].short_channel_id, 8);
2819 assert_eq!(route.paths[0][4].fee_msat, 100);
2820 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2821 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2822 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2825 /// Builds a trivial last-hop hint that passes through the two nodes given, with channel 0xff00
2827 fn multi_hop_last_hops_hint(hint_hops: [PublicKey; 2]) -> Vec<RouteHint> {
2828 let zero_fees = RoutingFees {
2830 proportional_millionths: 0,
2832 vec![RouteHint(vec![RouteHintHop {
2833 src_node_id: hint_hops[0],
2834 short_channel_id: 0xff00,
2837 proportional_millionths: 0,
2839 cltv_expiry_delta: (5 << 4) | 1,
2840 htlc_minimum_msat: None,
2841 htlc_maximum_msat: None,
2843 src_node_id: hint_hops[1],
2844 short_channel_id: 0xff01,
2846 cltv_expiry_delta: (8 << 4) | 1,
2847 htlc_minimum_msat: None,
2848 htlc_maximum_msat: None,
2853 fn multi_hint_last_hops_test() {
2854 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2855 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2856 let last_hops = multi_hop_last_hops_hint([nodes[2], nodes[3]]);
2857 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops.clone());
2858 let scorer = test_utils::TestScorer::with_penalty(0);
2859 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2860 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2861 // Test through channels 2, 3, 0xff00, 0xff01.
2862 // Test shows that multiple hop hints are considered.
2864 // Disabling channels 6 & 7 by flags=2
2865 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2866 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2867 short_channel_id: 6,
2869 flags: 2, // to disable
2870 cltv_expiry_delta: 0,
2871 htlc_minimum_msat: 0,
2872 htlc_maximum_msat: OptionalField::Absent,
2874 fee_proportional_millionths: 0,
2875 excess_data: Vec::new()
2877 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2878 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2879 short_channel_id: 7,
2881 flags: 2, // to disable
2882 cltv_expiry_delta: 0,
2883 htlc_minimum_msat: 0,
2884 htlc_maximum_msat: OptionalField::Absent,
2886 fee_proportional_millionths: 0,
2887 excess_data: Vec::new()
2890 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2891 assert_eq!(route.paths[0].len(), 4);
2893 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2894 assert_eq!(route.paths[0][0].short_channel_id, 2);
2895 assert_eq!(route.paths[0][0].fee_msat, 200);
2896 assert_eq!(route.paths[0][0].cltv_expiry_delta, 65);
2897 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2898 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2900 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2901 assert_eq!(route.paths[0][1].short_channel_id, 4);
2902 assert_eq!(route.paths[0][1].fee_msat, 100);
2903 assert_eq!(route.paths[0][1].cltv_expiry_delta, 81);
2904 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2905 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2907 assert_eq!(route.paths[0][2].pubkey, nodes[3]);
2908 assert_eq!(route.paths[0][2].short_channel_id, last_hops[0].0[0].short_channel_id);
2909 assert_eq!(route.paths[0][2].fee_msat, 0);
2910 assert_eq!(route.paths[0][2].cltv_expiry_delta, 129);
2911 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(4));
2912 assert_eq!(route.paths[0][2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2914 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2915 assert_eq!(route.paths[0][3].short_channel_id, last_hops[0].0[1].short_channel_id);
2916 assert_eq!(route.paths[0][3].fee_msat, 100);
2917 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2918 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2919 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2923 fn private_multi_hint_last_hops_test() {
2924 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2925 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2927 let non_announced_privkey = SecretKey::from_slice(&hex::decode(format!("{:02x}", 0xf0).repeat(32)).unwrap()[..]).unwrap();
2928 let non_announced_pubkey = PublicKey::from_secret_key(&secp_ctx, &non_announced_privkey);
2930 let last_hops = multi_hop_last_hops_hint([nodes[2], non_announced_pubkey]);
2931 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops.clone());
2932 let scorer = test_utils::TestScorer::with_penalty(0);
2933 // Test through channels 2, 3, 0xff00, 0xff01.
2934 // Test shows that multiple hop hints are considered.
2936 // Disabling channels 6 & 7 by flags=2
2937 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2938 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2939 short_channel_id: 6,
2941 flags: 2, // to disable
2942 cltv_expiry_delta: 0,
2943 htlc_minimum_msat: 0,
2944 htlc_maximum_msat: OptionalField::Absent,
2946 fee_proportional_millionths: 0,
2947 excess_data: Vec::new()
2949 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2950 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2951 short_channel_id: 7,
2953 flags: 2, // to disable
2954 cltv_expiry_delta: 0,
2955 htlc_minimum_msat: 0,
2956 htlc_maximum_msat: OptionalField::Absent,
2958 fee_proportional_millionths: 0,
2959 excess_data: Vec::new()
2962 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &[42u8; 32]).unwrap();
2963 assert_eq!(route.paths[0].len(), 4);
2965 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2966 assert_eq!(route.paths[0][0].short_channel_id, 2);
2967 assert_eq!(route.paths[0][0].fee_msat, 200);
2968 assert_eq!(route.paths[0][0].cltv_expiry_delta, 65);
2969 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2970 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2972 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2973 assert_eq!(route.paths[0][1].short_channel_id, 4);
2974 assert_eq!(route.paths[0][1].fee_msat, 100);
2975 assert_eq!(route.paths[0][1].cltv_expiry_delta, 81);
2976 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2977 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2979 assert_eq!(route.paths[0][2].pubkey, non_announced_pubkey);
2980 assert_eq!(route.paths[0][2].short_channel_id, last_hops[0].0[0].short_channel_id);
2981 assert_eq!(route.paths[0][2].fee_msat, 0);
2982 assert_eq!(route.paths[0][2].cltv_expiry_delta, 129);
2983 assert_eq!(route.paths[0][2].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2984 assert_eq!(route.paths[0][2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2986 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2987 assert_eq!(route.paths[0][3].short_channel_id, last_hops[0].0[1].short_channel_id);
2988 assert_eq!(route.paths[0][3].fee_msat, 100);
2989 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2990 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2991 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2994 fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2995 let zero_fees = RoutingFees {
2997 proportional_millionths: 0,
2999 vec![RouteHint(vec![RouteHintHop {
3000 src_node_id: nodes[4],
3001 short_channel_id: 11,
3003 cltv_expiry_delta: (11 << 4) | 1,
3004 htlc_minimum_msat: None,
3005 htlc_maximum_msat: None,
3007 src_node_id: nodes[3],
3008 short_channel_id: 8,
3010 cltv_expiry_delta: (8 << 4) | 1,
3011 htlc_minimum_msat: None,
3012 htlc_maximum_msat: None,
3013 }]), RouteHint(vec![RouteHintHop {
3014 src_node_id: nodes[4],
3015 short_channel_id: 9,
3018 proportional_millionths: 0,
3020 cltv_expiry_delta: (9 << 4) | 1,
3021 htlc_minimum_msat: None,
3022 htlc_maximum_msat: None,
3023 }]), RouteHint(vec![RouteHintHop {
3024 src_node_id: nodes[5],
3025 short_channel_id: 10,
3027 cltv_expiry_delta: (10 << 4) | 1,
3028 htlc_minimum_msat: None,
3029 htlc_maximum_msat: None,
3034 fn last_hops_with_public_channel_test() {
3035 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3036 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3037 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops_with_public_channel(&nodes));
3038 let scorer = test_utils::TestScorer::with_penalty(0);
3039 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3040 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3041 // This test shows that public routes can be present in the invoice
3042 // which would be handled in the same manner.
3044 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3045 assert_eq!(route.paths[0].len(), 5);
3047 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3048 assert_eq!(route.paths[0][0].short_channel_id, 2);
3049 assert_eq!(route.paths[0][0].fee_msat, 100);
3050 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
3051 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3052 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3054 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3055 assert_eq!(route.paths[0][1].short_channel_id, 4);
3056 assert_eq!(route.paths[0][1].fee_msat, 0);
3057 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
3058 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3059 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3061 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
3062 assert_eq!(route.paths[0][2].short_channel_id, 6);
3063 assert_eq!(route.paths[0][2].fee_msat, 0);
3064 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
3065 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
3066 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
3068 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
3069 assert_eq!(route.paths[0][3].short_channel_id, 11);
3070 assert_eq!(route.paths[0][3].fee_msat, 0);
3071 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
3072 // If we have a peer in the node map, we'll use their features here since we don't have
3073 // a way of figuring out their features from the invoice:
3074 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
3075 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
3077 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
3078 assert_eq!(route.paths[0][4].short_channel_id, 8);
3079 assert_eq!(route.paths[0][4].fee_msat, 100);
3080 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
3081 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
3082 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3086 fn our_chans_last_hop_connect_test() {
3087 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3088 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3089 let scorer = test_utils::TestScorer::with_penalty(0);
3090 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3091 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3093 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
3094 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3095 let mut last_hops = last_hops(&nodes);
3096 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops.clone());
3097 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();
3098 assert_eq!(route.paths[0].len(), 2);
3100 assert_eq!(route.paths[0][0].pubkey, nodes[3]);
3101 assert_eq!(route.paths[0][0].short_channel_id, 42);
3102 assert_eq!(route.paths[0][0].fee_msat, 0);
3103 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 4) | 1);
3104 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
3105 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3107 assert_eq!(route.paths[0][1].pubkey, nodes[6]);
3108 assert_eq!(route.paths[0][1].short_channel_id, 8);
3109 assert_eq!(route.paths[0][1].fee_msat, 100);
3110 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
3111 assert_eq!(route.paths[0][1].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
3112 assert_eq!(route.paths[0][1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3114 last_hops[0].0[0].fees.base_msat = 1000;
3116 // Revert to via 6 as the fee on 8 goes up
3117 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops);
3118 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3119 assert_eq!(route.paths[0].len(), 4);
3121 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3122 assert_eq!(route.paths[0][0].short_channel_id, 2);
3123 assert_eq!(route.paths[0][0].fee_msat, 200); // fee increased as its % of value transferred across node
3124 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
3125 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3126 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3128 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3129 assert_eq!(route.paths[0][1].short_channel_id, 4);
3130 assert_eq!(route.paths[0][1].fee_msat, 100);
3131 assert_eq!(route.paths[0][1].cltv_expiry_delta, (7 << 4) | 1);
3132 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3133 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3135 assert_eq!(route.paths[0][2].pubkey, nodes[5]);
3136 assert_eq!(route.paths[0][2].short_channel_id, 7);
3137 assert_eq!(route.paths[0][2].fee_msat, 0);
3138 assert_eq!(route.paths[0][2].cltv_expiry_delta, (10 << 4) | 1);
3139 // If we have a peer in the node map, we'll use their features here since we don't have
3140 // a way of figuring out their features from the invoice:
3141 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
3142 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(7));
3144 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
3145 assert_eq!(route.paths[0][3].short_channel_id, 10);
3146 assert_eq!(route.paths[0][3].fee_msat, 100);
3147 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
3148 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
3149 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3151 // ...but still use 8 for larger payments as 6 has a variable feerate
3152 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 2000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3153 assert_eq!(route.paths[0].len(), 5);
3155 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3156 assert_eq!(route.paths[0][0].short_channel_id, 2);
3157 assert_eq!(route.paths[0][0].fee_msat, 3000);
3158 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
3159 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3160 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3162 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3163 assert_eq!(route.paths[0][1].short_channel_id, 4);
3164 assert_eq!(route.paths[0][1].fee_msat, 0);
3165 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
3166 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3167 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3169 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
3170 assert_eq!(route.paths[0][2].short_channel_id, 6);
3171 assert_eq!(route.paths[0][2].fee_msat, 0);
3172 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
3173 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
3174 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
3176 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
3177 assert_eq!(route.paths[0][3].short_channel_id, 11);
3178 assert_eq!(route.paths[0][3].fee_msat, 1000);
3179 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
3180 // If we have a peer in the node map, we'll use their features here since we don't have
3181 // a way of figuring out their features from the invoice:
3182 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
3183 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
3185 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
3186 assert_eq!(route.paths[0][4].short_channel_id, 8);
3187 assert_eq!(route.paths[0][4].fee_msat, 2000);
3188 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
3189 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
3190 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3193 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> {
3194 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
3195 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3196 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3198 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
3199 let last_hops = RouteHint(vec![RouteHintHop {
3200 src_node_id: middle_node_id,
3201 short_channel_id: 8,
3204 proportional_millionths: last_hop_fee_prop,
3206 cltv_expiry_delta: (8 << 4) | 1,
3207 htlc_minimum_msat: None,
3208 htlc_maximum_msat: last_hop_htlc_max,
3210 let payment_params = PaymentParameters::from_node_id(target_node_id).with_route_hints(vec![last_hops]);
3211 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
3212 let scorer = test_utils::TestScorer::with_penalty(0);
3213 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3214 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3215 get_route(&source_node_id, &payment_params, &NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash()).read_only(),
3216 Some(&our_chans.iter().collect::<Vec<_>>()), route_val, 42, &test_utils::TestLogger::new(), &scorer, &random_seed_bytes)
3220 fn unannounced_path_test() {
3221 // We should be able to send a payment to a destination without any help of a routing graph
3222 // if we have a channel with a common counterparty that appears in the first and last hop
3224 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
3226 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3227 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3228 assert_eq!(route.paths[0].len(), 2);
3230 assert_eq!(route.paths[0][0].pubkey, middle_node_id);
3231 assert_eq!(route.paths[0][0].short_channel_id, 42);
3232 assert_eq!(route.paths[0][0].fee_msat, 1001);
3233 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 4) | 1);
3234 assert_eq!(route.paths[0][0].node_features.le_flags(), &[0b11]);
3235 assert_eq!(route.paths[0][0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3237 assert_eq!(route.paths[0][1].pubkey, target_node_id);
3238 assert_eq!(route.paths[0][1].short_channel_id, 8);
3239 assert_eq!(route.paths[0][1].fee_msat, 1000000);
3240 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
3241 assert_eq!(route.paths[0][1].node_features.le_flags(), &[0; 0]); // We dont pass flags in from invoices yet
3242 assert_eq!(route.paths[0][1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3246 fn overflow_unannounced_path_test_liquidity_underflow() {
3247 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
3248 // the last-hop had a fee which overflowed a u64, we'd panic.
3249 // This was due to us adding the first-hop from us unconditionally, causing us to think
3250 // we'd built a path (as our node is in the "best candidate" set), when we had not.
3251 // In this test, we previously hit a subtraction underflow due to having less available
3252 // liquidity at the last hop than 0.
3253 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());
3257 fn overflow_unannounced_path_test_feerate_overflow() {
3258 // This tests for the same case as above, except instead of hitting a subtraction
3259 // underflow, we hit a case where the fee charged at a hop overflowed.
3260 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());
3264 fn available_amount_while_routing_test() {
3265 // Tests whether we choose the correct available channel amount while routing.
3267 let (secp_ctx, network_graph, mut net_graph_msg_handler, chain_monitor, logger) = build_graph();
3268 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3269 let scorer = test_utils::TestScorer::with_penalty(0);
3270 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3271 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3272 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
3274 // We will use a simple single-path route from
3275 // our node to node2 via node0: channels {1, 3}.
3277 // First disable all other paths.
3278 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3279 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3280 short_channel_id: 2,
3283 cltv_expiry_delta: 0,
3284 htlc_minimum_msat: 0,
3285 htlc_maximum_msat: OptionalField::Present(100_000),
3287 fee_proportional_millionths: 0,
3288 excess_data: Vec::new()
3290 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3291 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3292 short_channel_id: 12,
3295 cltv_expiry_delta: 0,
3296 htlc_minimum_msat: 0,
3297 htlc_maximum_msat: OptionalField::Present(100_000),
3299 fee_proportional_millionths: 0,
3300 excess_data: Vec::new()
3303 // Make the first channel (#1) very permissive,
3304 // and we will be testing all limits on the second channel.
3305 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3306 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3307 short_channel_id: 1,
3310 cltv_expiry_delta: 0,
3311 htlc_minimum_msat: 0,
3312 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3314 fee_proportional_millionths: 0,
3315 excess_data: Vec::new()
3318 // First, let's see if routing works if we have absolutely no idea about the available amount.
3319 // In this case, it should be set to 250_000 sats.
3320 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3321 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3322 short_channel_id: 3,
3325 cltv_expiry_delta: 0,
3326 htlc_minimum_msat: 0,
3327 htlc_maximum_msat: OptionalField::Absent,
3329 fee_proportional_millionths: 0,
3330 excess_data: Vec::new()
3334 // Attempt to route more than available results in a failure.
3335 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3336 &our_id, &payment_params, &network_graph.read_only(), None, 250_000_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3337 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3338 } else { panic!(); }
3342 // Now, attempt to route an exact amount we have should be fine.
3343 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();
3344 assert_eq!(route.paths.len(), 1);
3345 let path = route.paths.last().unwrap();
3346 assert_eq!(path.len(), 2);
3347 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3348 assert_eq!(path.last().unwrap().fee_msat, 250_000_000);
3351 // Check that setting outbound_capacity_msat in first_hops limits the channels.
3352 // Disable channel #1 and use another first hop.
3353 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3354 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3355 short_channel_id: 1,
3358 cltv_expiry_delta: 0,
3359 htlc_minimum_msat: 0,
3360 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3362 fee_proportional_millionths: 0,
3363 excess_data: Vec::new()
3366 // Now, limit the first_hop by the outbound_capacity_msat of 200_000 sats.
3367 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
3370 // Attempt to route more than available results in a failure.
3371 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3372 &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) {
3373 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3374 } else { panic!(); }
3378 // Now, attempt to route an exact amount we have should be fine.
3379 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();
3380 assert_eq!(route.paths.len(), 1);
3381 let path = route.paths.last().unwrap();
3382 assert_eq!(path.len(), 2);
3383 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3384 assert_eq!(path.last().unwrap().fee_msat, 200_000_000);
3387 // Enable channel #1 back.
3388 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3389 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3390 short_channel_id: 1,
3393 cltv_expiry_delta: 0,
3394 htlc_minimum_msat: 0,
3395 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3397 fee_proportional_millionths: 0,
3398 excess_data: Vec::new()
3402 // Now let's see if routing works if we know only htlc_maximum_msat.
3403 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3404 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3405 short_channel_id: 3,
3408 cltv_expiry_delta: 0,
3409 htlc_minimum_msat: 0,
3410 htlc_maximum_msat: OptionalField::Present(15_000),
3412 fee_proportional_millionths: 0,
3413 excess_data: Vec::new()
3417 // Attempt to route more than available results in a failure.
3418 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3419 &our_id, &payment_params, &network_graph.read_only(), None, 15_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3420 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3421 } else { panic!(); }
3425 // Now, attempt to route an exact amount we have should be fine.
3426 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 15_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3427 assert_eq!(route.paths.len(), 1);
3428 let path = route.paths.last().unwrap();
3429 assert_eq!(path.len(), 2);
3430 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3431 assert_eq!(path.last().unwrap().fee_msat, 15_000);
3434 // Now let's see if routing works if we know only capacity from the UTXO.
3436 // We can't change UTXO capacity on the fly, so we'll disable
3437 // the existing channel and add another one with the capacity we need.
3438 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3439 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3440 short_channel_id: 3,
3443 cltv_expiry_delta: 0,
3444 htlc_minimum_msat: 0,
3445 htlc_maximum_msat: OptionalField::Absent,
3447 fee_proportional_millionths: 0,
3448 excess_data: Vec::new()
3451 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
3452 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
3453 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
3454 .push_opcode(opcodes::all::OP_PUSHNUM_2)
3455 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
3457 *chain_monitor.utxo_ret.lock().unwrap() = Ok(TxOut { value: 15, script_pubkey: good_script.clone() });
3458 net_graph_msg_handler.add_chain_access(Some(chain_monitor));
3460 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
3461 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3462 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3463 short_channel_id: 333,
3466 cltv_expiry_delta: (3 << 4) | 1,
3467 htlc_minimum_msat: 0,
3468 htlc_maximum_msat: OptionalField::Absent,
3470 fee_proportional_millionths: 0,
3471 excess_data: Vec::new()
3473 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3474 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3475 short_channel_id: 333,
3478 cltv_expiry_delta: (3 << 4) | 2,
3479 htlc_minimum_msat: 0,
3480 htlc_maximum_msat: OptionalField::Absent,
3482 fee_proportional_millionths: 0,
3483 excess_data: Vec::new()
3487 // Attempt to route more than available results in a failure.
3488 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3489 &our_id, &payment_params, &network_graph.read_only(), None, 15_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3490 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3491 } else { panic!(); }
3495 // Now, attempt to route an exact amount we have should be fine.
3496 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 15_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3497 assert_eq!(route.paths.len(), 1);
3498 let path = route.paths.last().unwrap();
3499 assert_eq!(path.len(), 2);
3500 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3501 assert_eq!(path.last().unwrap().fee_msat, 15_000);
3504 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
3505 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3506 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3507 short_channel_id: 333,
3510 cltv_expiry_delta: 0,
3511 htlc_minimum_msat: 0,
3512 htlc_maximum_msat: OptionalField::Present(10_000),
3514 fee_proportional_millionths: 0,
3515 excess_data: Vec::new()
3519 // Attempt to route more than available results in a failure.
3520 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3521 &our_id, &payment_params, &network_graph.read_only(), None, 10_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3522 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3523 } else { panic!(); }
3527 // Now, attempt to route an exact amount we have should be fine.
3528 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 10_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3529 assert_eq!(route.paths.len(), 1);
3530 let path = route.paths.last().unwrap();
3531 assert_eq!(path.len(), 2);
3532 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3533 assert_eq!(path.last().unwrap().fee_msat, 10_000);
3538 fn available_liquidity_last_hop_test() {
3539 // Check that available liquidity properly limits the path even when only
3540 // one of the latter hops is limited.
3541 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3542 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3543 let scorer = test_utils::TestScorer::with_penalty(0);
3544 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3545 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3546 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
3548 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3549 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
3550 // Total capacity: 50 sats.
3552 // Disable other potential paths.
3553 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3554 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3555 short_channel_id: 2,
3558 cltv_expiry_delta: 0,
3559 htlc_minimum_msat: 0,
3560 htlc_maximum_msat: OptionalField::Present(100_000),
3562 fee_proportional_millionths: 0,
3563 excess_data: Vec::new()
3565 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3566 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3567 short_channel_id: 7,
3570 cltv_expiry_delta: 0,
3571 htlc_minimum_msat: 0,
3572 htlc_maximum_msat: OptionalField::Present(100_000),
3574 fee_proportional_millionths: 0,
3575 excess_data: Vec::new()
3580 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3581 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3582 short_channel_id: 12,
3585 cltv_expiry_delta: 0,
3586 htlc_minimum_msat: 0,
3587 htlc_maximum_msat: OptionalField::Present(100_000),
3589 fee_proportional_millionths: 0,
3590 excess_data: Vec::new()
3592 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3593 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3594 short_channel_id: 13,
3597 cltv_expiry_delta: 0,
3598 htlc_minimum_msat: 0,
3599 htlc_maximum_msat: OptionalField::Present(100_000),
3601 fee_proportional_millionths: 0,
3602 excess_data: Vec::new()
3605 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3606 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3607 short_channel_id: 6,
3610 cltv_expiry_delta: 0,
3611 htlc_minimum_msat: 0,
3612 htlc_maximum_msat: OptionalField::Present(50_000),
3614 fee_proportional_millionths: 0,
3615 excess_data: Vec::new()
3617 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3618 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3619 short_channel_id: 11,
3622 cltv_expiry_delta: 0,
3623 htlc_minimum_msat: 0,
3624 htlc_maximum_msat: OptionalField::Present(100_000),
3626 fee_proportional_millionths: 0,
3627 excess_data: Vec::new()
3630 // Attempt to route more than available results in a failure.
3631 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3632 &our_id, &payment_params, &network_graph.read_only(), None, 60_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3633 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3634 } else { panic!(); }
3638 // Now, attempt to route 49 sats (just a bit below the capacity).
3639 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 49_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3640 assert_eq!(route.paths.len(), 1);
3641 let mut total_amount_paid_msat = 0;
3642 for path in &route.paths {
3643 assert_eq!(path.len(), 4);
3644 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3645 total_amount_paid_msat += path.last().unwrap().fee_msat;
3647 assert_eq!(total_amount_paid_msat, 49_000);
3651 // Attempt to route an exact amount is also fine
3652 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3653 assert_eq!(route.paths.len(), 1);
3654 let mut total_amount_paid_msat = 0;
3655 for path in &route.paths {
3656 assert_eq!(path.len(), 4);
3657 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3658 total_amount_paid_msat += path.last().unwrap().fee_msat;
3660 assert_eq!(total_amount_paid_msat, 50_000);
3665 fn ignore_fee_first_hop_test() {
3666 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3667 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3668 let scorer = test_utils::TestScorer::with_penalty(0);
3669 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3670 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3671 let payment_params = PaymentParameters::from_node_id(nodes[2]);
3673 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3674 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3675 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3676 short_channel_id: 1,
3679 cltv_expiry_delta: 0,
3680 htlc_minimum_msat: 0,
3681 htlc_maximum_msat: OptionalField::Present(100_000),
3682 fee_base_msat: 1_000_000,
3683 fee_proportional_millionths: 0,
3684 excess_data: Vec::new()
3686 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3687 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3688 short_channel_id: 3,
3691 cltv_expiry_delta: 0,
3692 htlc_minimum_msat: 0,
3693 htlc_maximum_msat: OptionalField::Present(50_000),
3695 fee_proportional_millionths: 0,
3696 excess_data: Vec::new()
3700 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3701 assert_eq!(route.paths.len(), 1);
3702 let mut total_amount_paid_msat = 0;
3703 for path in &route.paths {
3704 assert_eq!(path.len(), 2);
3705 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3706 total_amount_paid_msat += path.last().unwrap().fee_msat;
3708 assert_eq!(total_amount_paid_msat, 50_000);
3713 fn simple_mpp_route_test() {
3714 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3715 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3716 let scorer = test_utils::TestScorer::with_penalty(0);
3717 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3718 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3719 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
3721 // We need a route consisting of 3 paths:
3722 // From our node to node2 via node0, node7, node1 (three paths one hop each).
3723 // To achieve this, the amount being transferred should be around
3724 // the total capacity of these 3 paths.
3726 // First, we set limits on these (previously unlimited) channels.
3727 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
3729 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3730 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3731 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3732 short_channel_id: 1,
3735 cltv_expiry_delta: 0,
3736 htlc_minimum_msat: 0,
3737 htlc_maximum_msat: OptionalField::Present(100_000),
3739 fee_proportional_millionths: 0,
3740 excess_data: Vec::new()
3742 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3743 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3744 short_channel_id: 3,
3747 cltv_expiry_delta: 0,
3748 htlc_minimum_msat: 0,
3749 htlc_maximum_msat: OptionalField::Present(50_000),
3751 fee_proportional_millionths: 0,
3752 excess_data: Vec::new()
3755 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
3756 // (total limit 60).
3757 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3758 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3759 short_channel_id: 12,
3762 cltv_expiry_delta: 0,
3763 htlc_minimum_msat: 0,
3764 htlc_maximum_msat: OptionalField::Present(60_000),
3766 fee_proportional_millionths: 0,
3767 excess_data: Vec::new()
3769 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3770 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3771 short_channel_id: 13,
3774 cltv_expiry_delta: 0,
3775 htlc_minimum_msat: 0,
3776 htlc_maximum_msat: OptionalField::Present(60_000),
3778 fee_proportional_millionths: 0,
3779 excess_data: Vec::new()
3782 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
3783 // (total capacity 180 sats).
3784 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3785 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3786 short_channel_id: 2,
3789 cltv_expiry_delta: 0,
3790 htlc_minimum_msat: 0,
3791 htlc_maximum_msat: OptionalField::Present(200_000),
3793 fee_proportional_millionths: 0,
3794 excess_data: Vec::new()
3796 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3797 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3798 short_channel_id: 4,
3801 cltv_expiry_delta: 0,
3802 htlc_minimum_msat: 0,
3803 htlc_maximum_msat: OptionalField::Present(180_000),
3805 fee_proportional_millionths: 0,
3806 excess_data: Vec::new()
3810 // Attempt to route more than available results in a failure.
3811 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3812 &our_id, &payment_params, &network_graph.read_only(), None, 300_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3813 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3814 } else { panic!(); }
3818 // Now, attempt to route 250 sats (just a bit below the capacity).
3819 // Our algorithm should provide us with these 3 paths.
3820 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 250_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3821 assert_eq!(route.paths.len(), 3);
3822 let mut total_amount_paid_msat = 0;
3823 for path in &route.paths {
3824 assert_eq!(path.len(), 2);
3825 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3826 total_amount_paid_msat += path.last().unwrap().fee_msat;
3828 assert_eq!(total_amount_paid_msat, 250_000);
3832 // Attempt to route an exact amount is also fine
3833 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 290_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3834 assert_eq!(route.paths.len(), 3);
3835 let mut total_amount_paid_msat = 0;
3836 for path in &route.paths {
3837 assert_eq!(path.len(), 2);
3838 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3839 total_amount_paid_msat += path.last().unwrap().fee_msat;
3841 assert_eq!(total_amount_paid_msat, 290_000);
3846 fn long_mpp_route_test() {
3847 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3848 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3849 let scorer = test_utils::TestScorer::with_penalty(0);
3850 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3851 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3852 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
3854 // We need a route consisting of 3 paths:
3855 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3856 // Note that these paths overlap (channels 5, 12, 13).
3857 // We will route 300 sats.
3858 // Each path will have 100 sats capacity, those channels which
3859 // are used twice will have 200 sats capacity.
3861 // Disable other potential paths.
3862 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3863 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3864 short_channel_id: 2,
3867 cltv_expiry_delta: 0,
3868 htlc_minimum_msat: 0,
3869 htlc_maximum_msat: OptionalField::Present(100_000),
3871 fee_proportional_millionths: 0,
3872 excess_data: Vec::new()
3874 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3875 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3876 short_channel_id: 7,
3879 cltv_expiry_delta: 0,
3880 htlc_minimum_msat: 0,
3881 htlc_maximum_msat: OptionalField::Present(100_000),
3883 fee_proportional_millionths: 0,
3884 excess_data: Vec::new()
3887 // Path via {node0, node2} is channels {1, 3, 5}.
3888 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3889 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3890 short_channel_id: 1,
3893 cltv_expiry_delta: 0,
3894 htlc_minimum_msat: 0,
3895 htlc_maximum_msat: OptionalField::Present(100_000),
3897 fee_proportional_millionths: 0,
3898 excess_data: Vec::new()
3900 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3901 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3902 short_channel_id: 3,
3905 cltv_expiry_delta: 0,
3906 htlc_minimum_msat: 0,
3907 htlc_maximum_msat: OptionalField::Present(100_000),
3909 fee_proportional_millionths: 0,
3910 excess_data: Vec::new()
3913 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3914 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3915 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3916 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3917 short_channel_id: 5,
3920 cltv_expiry_delta: 0,
3921 htlc_minimum_msat: 0,
3922 htlc_maximum_msat: OptionalField::Present(200_000),
3924 fee_proportional_millionths: 0,
3925 excess_data: Vec::new()
3928 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3929 // Add 100 sats to the capacities of {12, 13}, because these channels
3930 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3931 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3932 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3933 short_channel_id: 12,
3936 cltv_expiry_delta: 0,
3937 htlc_minimum_msat: 0,
3938 htlc_maximum_msat: OptionalField::Present(200_000),
3940 fee_proportional_millionths: 0,
3941 excess_data: Vec::new()
3943 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3944 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3945 short_channel_id: 13,
3948 cltv_expiry_delta: 0,
3949 htlc_minimum_msat: 0,
3950 htlc_maximum_msat: OptionalField::Present(200_000),
3952 fee_proportional_millionths: 0,
3953 excess_data: Vec::new()
3956 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3957 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3958 short_channel_id: 6,
3961 cltv_expiry_delta: 0,
3962 htlc_minimum_msat: 0,
3963 htlc_maximum_msat: OptionalField::Present(100_000),
3965 fee_proportional_millionths: 0,
3966 excess_data: Vec::new()
3968 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3969 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3970 short_channel_id: 11,
3973 cltv_expiry_delta: 0,
3974 htlc_minimum_msat: 0,
3975 htlc_maximum_msat: OptionalField::Present(100_000),
3977 fee_proportional_millionths: 0,
3978 excess_data: Vec::new()
3981 // Path via {node7, node2} is channels {12, 13, 5}.
3982 // We already limited them to 200 sats (they are used twice for 100 sats).
3983 // Nothing to do here.
3986 // Attempt to route more than available results in a failure.
3987 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3988 &our_id, &payment_params, &network_graph.read_only(), None, 350_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3989 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3990 } else { panic!(); }
3994 // Now, attempt to route 300 sats (exact amount we can route).
3995 // Our algorithm should provide us with these 3 paths, 100 sats each.
3996 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 300_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3997 assert_eq!(route.paths.len(), 3);
3999 let mut total_amount_paid_msat = 0;
4000 for path in &route.paths {
4001 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
4002 total_amount_paid_msat += path.last().unwrap().fee_msat;
4004 assert_eq!(total_amount_paid_msat, 300_000);
4010 fn mpp_cheaper_route_test() {
4011 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4012 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4013 let scorer = test_utils::TestScorer::with_penalty(0);
4014 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4015 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4016 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
4018 // This test checks that if we have two cheaper paths and one more expensive path,
4019 // so that liquidity-wise any 2 of 3 combination is sufficient,
4020 // two cheaper paths will be taken.
4021 // These paths have equal available liquidity.
4023 // We need a combination of 3 paths:
4024 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
4025 // Note that these paths overlap (channels 5, 12, 13).
4026 // Each path will have 100 sats capacity, those channels which
4027 // are used twice will have 200 sats capacity.
4029 // Disable other potential paths.
4030 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4031 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4032 short_channel_id: 2,
4035 cltv_expiry_delta: 0,
4036 htlc_minimum_msat: 0,
4037 htlc_maximum_msat: OptionalField::Present(100_000),
4039 fee_proportional_millionths: 0,
4040 excess_data: Vec::new()
4042 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4043 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4044 short_channel_id: 7,
4047 cltv_expiry_delta: 0,
4048 htlc_minimum_msat: 0,
4049 htlc_maximum_msat: OptionalField::Present(100_000),
4051 fee_proportional_millionths: 0,
4052 excess_data: Vec::new()
4055 // Path via {node0, node2} is channels {1, 3, 5}.
4056 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4057 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4058 short_channel_id: 1,
4061 cltv_expiry_delta: 0,
4062 htlc_minimum_msat: 0,
4063 htlc_maximum_msat: OptionalField::Present(100_000),
4065 fee_proportional_millionths: 0,
4066 excess_data: Vec::new()
4068 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4069 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4070 short_channel_id: 3,
4073 cltv_expiry_delta: 0,
4074 htlc_minimum_msat: 0,
4075 htlc_maximum_msat: OptionalField::Present(100_000),
4077 fee_proportional_millionths: 0,
4078 excess_data: Vec::new()
4081 // Capacity of 200 sats because this channel will be used by 3rd path as well.
4082 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4083 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4084 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4085 short_channel_id: 5,
4088 cltv_expiry_delta: 0,
4089 htlc_minimum_msat: 0,
4090 htlc_maximum_msat: OptionalField::Present(200_000),
4092 fee_proportional_millionths: 0,
4093 excess_data: Vec::new()
4096 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4097 // Add 100 sats to the capacities of {12, 13}, because these channels
4098 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
4099 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4100 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4101 short_channel_id: 12,
4104 cltv_expiry_delta: 0,
4105 htlc_minimum_msat: 0,
4106 htlc_maximum_msat: OptionalField::Present(200_000),
4108 fee_proportional_millionths: 0,
4109 excess_data: Vec::new()
4111 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4112 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4113 short_channel_id: 13,
4116 cltv_expiry_delta: 0,
4117 htlc_minimum_msat: 0,
4118 htlc_maximum_msat: OptionalField::Present(200_000),
4120 fee_proportional_millionths: 0,
4121 excess_data: Vec::new()
4124 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4125 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4126 short_channel_id: 6,
4129 cltv_expiry_delta: 0,
4130 htlc_minimum_msat: 0,
4131 htlc_maximum_msat: OptionalField::Present(100_000),
4132 fee_base_msat: 1_000,
4133 fee_proportional_millionths: 0,
4134 excess_data: Vec::new()
4136 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4137 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4138 short_channel_id: 11,
4141 cltv_expiry_delta: 0,
4142 htlc_minimum_msat: 0,
4143 htlc_maximum_msat: OptionalField::Present(100_000),
4145 fee_proportional_millionths: 0,
4146 excess_data: Vec::new()
4149 // Path via {node7, node2} is channels {12, 13, 5}.
4150 // We already limited them to 200 sats (they are used twice for 100 sats).
4151 // Nothing to do here.
4154 // Now, attempt to route 180 sats.
4155 // Our algorithm should provide us with these 2 paths.
4156 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 180_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4157 assert_eq!(route.paths.len(), 2);
4159 let mut total_value_transferred_msat = 0;
4160 let mut total_paid_msat = 0;
4161 for path in &route.paths {
4162 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
4163 total_value_transferred_msat += path.last().unwrap().fee_msat;
4165 total_paid_msat += hop.fee_msat;
4168 // If we paid fee, this would be higher.
4169 assert_eq!(total_value_transferred_msat, 180_000);
4170 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
4171 assert_eq!(total_fees_paid, 0);
4176 fn fees_on_mpp_route_test() {
4177 // This test makes sure that MPP algorithm properly takes into account
4178 // fees charged on the channels, by making the fees impactful:
4179 // if the fee is not properly accounted for, the behavior is different.
4180 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4181 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4182 let scorer = test_utils::TestScorer::with_penalty(0);
4183 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4184 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4185 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
4187 // We need a route consisting of 2 paths:
4188 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
4189 // We will route 200 sats, Each path will have 100 sats capacity.
4191 // This test is not particularly stable: e.g.,
4192 // there's a way to route via {node0, node2, node4}.
4193 // It works while pathfinding is deterministic, but can be broken otherwise.
4194 // It's fine to ignore this concern for now.
4196 // Disable other potential paths.
4197 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4198 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4199 short_channel_id: 2,
4202 cltv_expiry_delta: 0,
4203 htlc_minimum_msat: 0,
4204 htlc_maximum_msat: OptionalField::Present(100_000),
4206 fee_proportional_millionths: 0,
4207 excess_data: Vec::new()
4210 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4211 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4212 short_channel_id: 7,
4215 cltv_expiry_delta: 0,
4216 htlc_minimum_msat: 0,
4217 htlc_maximum_msat: OptionalField::Present(100_000),
4219 fee_proportional_millionths: 0,
4220 excess_data: Vec::new()
4223 // Path via {node0, node2} is channels {1, 3, 5}.
4224 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4225 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4226 short_channel_id: 1,
4229 cltv_expiry_delta: 0,
4230 htlc_minimum_msat: 0,
4231 htlc_maximum_msat: OptionalField::Present(100_000),
4233 fee_proportional_millionths: 0,
4234 excess_data: Vec::new()
4236 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4237 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4238 short_channel_id: 3,
4241 cltv_expiry_delta: 0,
4242 htlc_minimum_msat: 0,
4243 htlc_maximum_msat: OptionalField::Present(100_000),
4245 fee_proportional_millionths: 0,
4246 excess_data: Vec::new()
4249 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4250 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4251 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4252 short_channel_id: 5,
4255 cltv_expiry_delta: 0,
4256 htlc_minimum_msat: 0,
4257 htlc_maximum_msat: OptionalField::Present(100_000),
4259 fee_proportional_millionths: 0,
4260 excess_data: Vec::new()
4263 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4264 // All channels should be 100 sats capacity. But for the fee experiment,
4265 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
4266 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
4267 // 100 sats (and pay 150 sats in fees for the use of channel 6),
4268 // so no matter how large are other channels,
4269 // the whole path will be limited by 100 sats with just these 2 conditions:
4270 // - channel 12 capacity is 250 sats
4271 // - fee for channel 6 is 150 sats
4272 // Let's test this by enforcing these 2 conditions and removing other limits.
4273 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4274 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4275 short_channel_id: 12,
4278 cltv_expiry_delta: 0,
4279 htlc_minimum_msat: 0,
4280 htlc_maximum_msat: OptionalField::Present(250_000),
4282 fee_proportional_millionths: 0,
4283 excess_data: Vec::new()
4285 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4286 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4287 short_channel_id: 13,
4290 cltv_expiry_delta: 0,
4291 htlc_minimum_msat: 0,
4292 htlc_maximum_msat: OptionalField::Absent,
4294 fee_proportional_millionths: 0,
4295 excess_data: Vec::new()
4298 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4299 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4300 short_channel_id: 6,
4303 cltv_expiry_delta: 0,
4304 htlc_minimum_msat: 0,
4305 htlc_maximum_msat: OptionalField::Absent,
4306 fee_base_msat: 150_000,
4307 fee_proportional_millionths: 0,
4308 excess_data: Vec::new()
4310 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4311 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4312 short_channel_id: 11,
4315 cltv_expiry_delta: 0,
4316 htlc_minimum_msat: 0,
4317 htlc_maximum_msat: OptionalField::Absent,
4319 fee_proportional_millionths: 0,
4320 excess_data: Vec::new()
4324 // Attempt to route more than available results in a failure.
4325 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4326 &our_id, &payment_params, &network_graph.read_only(), None, 210_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
4327 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4328 } else { panic!(); }
4332 // Now, attempt to route 200 sats (exact amount we can route).
4333 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 200_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4334 assert_eq!(route.paths.len(), 2);
4336 let mut total_amount_paid_msat = 0;
4337 for path in &route.paths {
4338 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
4339 total_amount_paid_msat += path.last().unwrap().fee_msat;
4341 assert_eq!(total_amount_paid_msat, 200_000);
4342 assert_eq!(route.get_total_fees(), 150_000);
4347 fn mpp_with_last_hops() {
4348 // Previously, if we tried to send an MPP payment to a destination which was only reachable
4349 // via a single last-hop route hint, we'd fail to route if we first collected routes
4350 // totaling close but not quite enough to fund the full payment.
4352 // This was because we considered last-hop hints to have exactly the sought payment amount
4353 // instead of the amount we were trying to collect, needlessly limiting our path searching
4354 // at the very first hop.
4356 // Specifically, this interacted with our "all paths must fund at least 5% of total target"
4357 // criterion to cause us to refuse all routes at the last hop hint which would be considered
4358 // to only have the remaining to-collect amount in available liquidity.
4360 // This bug appeared in production in some specific channel configurations.
4361 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4362 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4363 let scorer = test_utils::TestScorer::with_penalty(0);
4364 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4365 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4366 let payment_params = PaymentParameters::from_node_id(PublicKey::from_slice(&[02; 33]).unwrap()).with_features(InvoiceFeatures::known())
4367 .with_route_hints(vec![RouteHint(vec![RouteHintHop {
4368 src_node_id: nodes[2],
4369 short_channel_id: 42,
4370 fees: RoutingFees { base_msat: 0, proportional_millionths: 0 },
4371 cltv_expiry_delta: 42,
4372 htlc_minimum_msat: None,
4373 htlc_maximum_msat: None,
4376 // Keep only two paths from us to nodes[2], both with a 99sat HTLC maximum, with one with
4377 // no fee and one with a 1msat fee. Previously, trying to route 100 sats to nodes[2] here
4378 // would first use the no-fee route and then fail to find a path along the second route as
4379 // we think we can only send up to 1 additional sat over the last-hop but refuse to as its
4380 // under 5% of our payment amount.
4381 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4382 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4383 short_channel_id: 1,
4386 cltv_expiry_delta: (5 << 4) | 5,
4387 htlc_minimum_msat: 0,
4388 htlc_maximum_msat: OptionalField::Present(99_000),
4389 fee_base_msat: u32::max_value(),
4390 fee_proportional_millionths: u32::max_value(),
4391 excess_data: Vec::new()
4393 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4394 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4395 short_channel_id: 2,
4398 cltv_expiry_delta: (5 << 4) | 3,
4399 htlc_minimum_msat: 0,
4400 htlc_maximum_msat: OptionalField::Present(99_000),
4401 fee_base_msat: u32::max_value(),
4402 fee_proportional_millionths: u32::max_value(),
4403 excess_data: Vec::new()
4405 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4406 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4407 short_channel_id: 4,
4410 cltv_expiry_delta: (4 << 4) | 1,
4411 htlc_minimum_msat: 0,
4412 htlc_maximum_msat: OptionalField::Absent,
4414 fee_proportional_millionths: 0,
4415 excess_data: Vec::new()
4417 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4418 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4419 short_channel_id: 13,
4421 flags: 0|2, // Channel disabled
4422 cltv_expiry_delta: (13 << 4) | 1,
4423 htlc_minimum_msat: 0,
4424 htlc_maximum_msat: OptionalField::Absent,
4426 fee_proportional_millionths: 2000000,
4427 excess_data: Vec::new()
4430 // Get a route for 100 sats and check that we found the MPP route no problem and didn't
4432 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4433 assert_eq!(route.paths.len(), 2);
4434 // Paths are somewhat randomly ordered, but:
4435 // * the first is channel 2 (1 msat fee) -> channel 4 -> channel 42
4436 // * the second is channel 1 (0 fee, but 99 sat maximum) -> channel 3 -> channel 42
4437 assert_eq!(route.paths[0][0].short_channel_id, 2);
4438 assert_eq!(route.paths[0][0].fee_msat, 1);
4439 assert_eq!(route.paths[0][2].fee_msat, 1_000);
4440 assert_eq!(route.paths[1][0].short_channel_id, 1);
4441 assert_eq!(route.paths[1][0].fee_msat, 0);
4442 assert_eq!(route.paths[1][2].fee_msat, 99_000);
4443 assert_eq!(route.get_total_fees(), 1);
4444 assert_eq!(route.get_total_amount(), 100_000);
4448 fn drop_lowest_channel_mpp_route_test() {
4449 // This test checks that low-capacity channel is dropped when after
4450 // path finding we realize that we found more capacity than we need.
4451 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4452 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4453 let scorer = test_utils::TestScorer::with_penalty(0);
4454 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4455 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4456 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
4458 // We need a route consisting of 3 paths:
4459 // From our node to node2 via node0, node7, node1 (three paths one hop each).
4461 // The first and the second paths should be sufficient, but the third should be
4462 // cheaper, so that we select it but drop later.
4464 // First, we set limits on these (previously unlimited) channels.
4465 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
4467 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
4468 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4469 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4470 short_channel_id: 1,
4473 cltv_expiry_delta: 0,
4474 htlc_minimum_msat: 0,
4475 htlc_maximum_msat: OptionalField::Present(100_000),
4477 fee_proportional_millionths: 0,
4478 excess_data: Vec::new()
4480 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4481 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4482 short_channel_id: 3,
4485 cltv_expiry_delta: 0,
4486 htlc_minimum_msat: 0,
4487 htlc_maximum_msat: OptionalField::Present(50_000),
4489 fee_proportional_millionths: 0,
4490 excess_data: Vec::new()
4493 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
4494 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4495 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4496 short_channel_id: 12,
4499 cltv_expiry_delta: 0,
4500 htlc_minimum_msat: 0,
4501 htlc_maximum_msat: OptionalField::Present(60_000),
4503 fee_proportional_millionths: 0,
4504 excess_data: Vec::new()
4506 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4507 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4508 short_channel_id: 13,
4511 cltv_expiry_delta: 0,
4512 htlc_minimum_msat: 0,
4513 htlc_maximum_msat: OptionalField::Present(60_000),
4515 fee_proportional_millionths: 0,
4516 excess_data: Vec::new()
4519 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
4520 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4521 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4522 short_channel_id: 2,
4525 cltv_expiry_delta: 0,
4526 htlc_minimum_msat: 0,
4527 htlc_maximum_msat: OptionalField::Present(20_000),
4529 fee_proportional_millionths: 0,
4530 excess_data: Vec::new()
4532 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4533 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4534 short_channel_id: 4,
4537 cltv_expiry_delta: 0,
4538 htlc_minimum_msat: 0,
4539 htlc_maximum_msat: OptionalField::Present(20_000),
4541 fee_proportional_millionths: 0,
4542 excess_data: Vec::new()
4546 // Attempt to route more than available results in a failure.
4547 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4548 &our_id, &payment_params, &network_graph.read_only(), None, 150_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
4549 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4550 } else { panic!(); }
4554 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
4555 // Our algorithm should provide us with these 3 paths.
4556 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 125_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4557 assert_eq!(route.paths.len(), 3);
4558 let mut total_amount_paid_msat = 0;
4559 for path in &route.paths {
4560 assert_eq!(path.len(), 2);
4561 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4562 total_amount_paid_msat += path.last().unwrap().fee_msat;
4564 assert_eq!(total_amount_paid_msat, 125_000);
4568 // Attempt to route without the last small cheap channel
4569 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4570 assert_eq!(route.paths.len(), 2);
4571 let mut total_amount_paid_msat = 0;
4572 for path in &route.paths {
4573 assert_eq!(path.len(), 2);
4574 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4575 total_amount_paid_msat += path.last().unwrap().fee_msat;
4577 assert_eq!(total_amount_paid_msat, 90_000);
4582 fn min_criteria_consistency() {
4583 // Test that we don't use an inconsistent metric between updating and walking nodes during
4584 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
4585 // was updated with a different criterion from the heap sorting, resulting in loops in
4586 // calculated paths. We test for that specific case here.
4588 // We construct a network that looks like this:
4590 // node2 -1(3)2- node3
4594 // node1 -1(5)2- node4 -1(1)2- node6
4600 // We create a loop on the side of our real path - our destination is node 6, with a
4601 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
4602 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
4603 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
4604 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
4605 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
4606 // "previous hop" being set to node 3, creating a loop in the path.
4607 let secp_ctx = Secp256k1::new();
4608 let logger = Arc::new(test_utils::TestLogger::new());
4609 let network = Arc::new(NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash()));
4610 let net_graph_msg_handler = NetGraphMsgHandler::new(Arc::clone(&network), None, Arc::clone(&logger));
4611 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4612 let scorer = test_utils::TestScorer::with_penalty(0);
4613 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4614 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4615 let payment_params = PaymentParameters::from_node_id(nodes[6]);
4617 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
4618 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4619 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4620 short_channel_id: 6,
4623 cltv_expiry_delta: (6 << 4) | 0,
4624 htlc_minimum_msat: 0,
4625 htlc_maximum_msat: OptionalField::Absent,
4627 fee_proportional_millionths: 0,
4628 excess_data: Vec::new()
4630 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
4632 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4633 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4634 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4635 short_channel_id: 5,
4638 cltv_expiry_delta: (5 << 4) | 0,
4639 htlc_minimum_msat: 0,
4640 htlc_maximum_msat: OptionalField::Absent,
4642 fee_proportional_millionths: 0,
4643 excess_data: Vec::new()
4645 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
4647 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
4648 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4649 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4650 short_channel_id: 4,
4653 cltv_expiry_delta: (4 << 4) | 0,
4654 htlc_minimum_msat: 0,
4655 htlc_maximum_msat: OptionalField::Absent,
4657 fee_proportional_millionths: 0,
4658 excess_data: Vec::new()
4660 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
4662 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
4663 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
4664 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4665 short_channel_id: 3,
4668 cltv_expiry_delta: (3 << 4) | 0,
4669 htlc_minimum_msat: 0,
4670 htlc_maximum_msat: OptionalField::Absent,
4672 fee_proportional_millionths: 0,
4673 excess_data: Vec::new()
4675 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
4677 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
4678 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4679 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4680 short_channel_id: 2,
4683 cltv_expiry_delta: (2 << 4) | 0,
4684 htlc_minimum_msat: 0,
4685 htlc_maximum_msat: OptionalField::Absent,
4687 fee_proportional_millionths: 0,
4688 excess_data: Vec::new()
4691 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
4692 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4693 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4694 short_channel_id: 1,
4697 cltv_expiry_delta: (1 << 4) | 0,
4698 htlc_minimum_msat: 100,
4699 htlc_maximum_msat: OptionalField::Absent,
4701 fee_proportional_millionths: 0,
4702 excess_data: Vec::new()
4704 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
4707 // Now ensure the route flows simply over nodes 1 and 4 to 6.
4708 let route = get_route(&our_id, &payment_params, &network.read_only(), None, 10_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4709 assert_eq!(route.paths.len(), 1);
4710 assert_eq!(route.paths[0].len(), 3);
4712 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
4713 assert_eq!(route.paths[0][0].short_channel_id, 6);
4714 assert_eq!(route.paths[0][0].fee_msat, 100);
4715 assert_eq!(route.paths[0][0].cltv_expiry_delta, (5 << 4) | 0);
4716 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(1));
4717 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(6));
4719 assert_eq!(route.paths[0][1].pubkey, nodes[4]);
4720 assert_eq!(route.paths[0][1].short_channel_id, 5);
4721 assert_eq!(route.paths[0][1].fee_msat, 0);
4722 assert_eq!(route.paths[0][1].cltv_expiry_delta, (1 << 4) | 0);
4723 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(4));
4724 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(5));
4726 assert_eq!(route.paths[0][2].pubkey, nodes[6]);
4727 assert_eq!(route.paths[0][2].short_channel_id, 1);
4728 assert_eq!(route.paths[0][2].fee_msat, 10_000);
4729 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
4730 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
4731 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(1));
4737 fn exact_fee_liquidity_limit() {
4738 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
4739 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
4740 // we calculated fees on a higher value, resulting in us ignoring such paths.
4741 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4742 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
4743 let scorer = test_utils::TestScorer::with_penalty(0);
4744 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4745 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4746 let payment_params = PaymentParameters::from_node_id(nodes[2]);
4748 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
4750 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4751 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4752 short_channel_id: 2,
4755 cltv_expiry_delta: 0,
4756 htlc_minimum_msat: 0,
4757 htlc_maximum_msat: OptionalField::Present(85_000),
4759 fee_proportional_millionths: 0,
4760 excess_data: Vec::new()
4763 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4764 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4765 short_channel_id: 12,
4768 cltv_expiry_delta: (4 << 4) | 1,
4769 htlc_minimum_msat: 0,
4770 htlc_maximum_msat: OptionalField::Present(270_000),
4772 fee_proportional_millionths: 1000000,
4773 excess_data: Vec::new()
4777 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
4778 // 200% fee charged channel 13 in the 1-to-2 direction.
4779 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4780 assert_eq!(route.paths.len(), 1);
4781 assert_eq!(route.paths[0].len(), 2);
4783 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
4784 assert_eq!(route.paths[0][0].short_channel_id, 12);
4785 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
4786 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
4787 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
4788 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
4790 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
4791 assert_eq!(route.paths[0][1].short_channel_id, 13);
4792 assert_eq!(route.paths[0][1].fee_msat, 90_000);
4793 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
4794 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
4795 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
4800 fn htlc_max_reduction_below_min() {
4801 // Test that if, while walking the graph, we reduce the value being sent to meet an
4802 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
4803 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
4804 // resulting in us thinking there is no possible path, even if other paths exist.
4805 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4806 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4807 let scorer = test_utils::TestScorer::with_penalty(0);
4808 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4809 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4810 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
4812 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
4813 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
4814 // then try to send 90_000.
4815 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4816 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4817 short_channel_id: 2,
4820 cltv_expiry_delta: 0,
4821 htlc_minimum_msat: 0,
4822 htlc_maximum_msat: OptionalField::Present(80_000),
4824 fee_proportional_millionths: 0,
4825 excess_data: Vec::new()
4827 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4828 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4829 short_channel_id: 4,
4832 cltv_expiry_delta: (4 << 4) | 1,
4833 htlc_minimum_msat: 90_000,
4834 htlc_maximum_msat: OptionalField::Absent,
4836 fee_proportional_millionths: 0,
4837 excess_data: Vec::new()
4841 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
4842 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
4843 // expensive) channels 12-13 path.
4844 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4845 assert_eq!(route.paths.len(), 1);
4846 assert_eq!(route.paths[0].len(), 2);
4848 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
4849 assert_eq!(route.paths[0][0].short_channel_id, 12);
4850 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
4851 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
4852 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
4853 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
4855 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
4856 assert_eq!(route.paths[0][1].short_channel_id, 13);
4857 assert_eq!(route.paths[0][1].fee_msat, 90_000);
4858 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
4859 assert_eq!(route.paths[0][1].node_features.le_flags(), InvoiceFeatures::known().le_flags());
4860 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
4865 fn multiple_direct_first_hops() {
4866 // Previously we'd only ever considered one first hop path per counterparty.
4867 // However, as we don't restrict users to one channel per peer, we really need to support
4868 // looking at all first hop paths.
4869 // Here we test that we do not ignore all-but-the-last first hop paths per counterparty (as
4870 // we used to do by overwriting the `first_hop_targets` hashmap entry) and that we can MPP
4871 // route over multiple channels with the same first hop.
4872 let secp_ctx = Secp256k1::new();
4873 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4874 let logger = Arc::new(test_utils::TestLogger::new());
4875 let network_graph = NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash());
4876 let scorer = test_utils::TestScorer::with_penalty(0);
4877 let payment_params = PaymentParameters::from_node_id(nodes[0]).with_features(InvoiceFeatures::known());
4878 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4879 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4882 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
4883 &get_channel_details(Some(3), nodes[0], InitFeatures::known(), 200_000),
4884 &get_channel_details(Some(2), nodes[0], InitFeatures::known(), 10_000),
4885 ]), 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4886 assert_eq!(route.paths.len(), 1);
4887 assert_eq!(route.paths[0].len(), 1);
4889 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
4890 assert_eq!(route.paths[0][0].short_channel_id, 3);
4891 assert_eq!(route.paths[0][0].fee_msat, 100_000);
4894 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
4895 &get_channel_details(Some(3), nodes[0], InitFeatures::known(), 50_000),
4896 &get_channel_details(Some(2), nodes[0], InitFeatures::known(), 50_000),
4897 ]), 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4898 assert_eq!(route.paths.len(), 2);
4899 assert_eq!(route.paths[0].len(), 1);
4900 assert_eq!(route.paths[1].len(), 1);
4902 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
4903 assert_eq!(route.paths[0][0].short_channel_id, 3);
4904 assert_eq!(route.paths[0][0].fee_msat, 50_000);
4906 assert_eq!(route.paths[1][0].pubkey, nodes[0]);
4907 assert_eq!(route.paths[1][0].short_channel_id, 2);
4908 assert_eq!(route.paths[1][0].fee_msat, 50_000);
4913 fn prefers_shorter_route_with_higher_fees() {
4914 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4915 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4916 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
4918 // Without penalizing each hop 100 msats, a longer path with lower fees is chosen.
4919 let scorer = test_utils::TestScorer::with_penalty(0);
4920 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4921 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4922 let route = get_route(
4923 &our_id, &payment_params, &network_graph.read_only(), None, 100, 42,
4924 Arc::clone(&logger), &scorer, &random_seed_bytes
4926 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4928 assert_eq!(route.get_total_fees(), 100);
4929 assert_eq!(route.get_total_amount(), 100);
4930 assert_eq!(path, vec![2, 4, 6, 11, 8]);
4932 // Applying a 100 msat penalty to each hop results in taking channels 7 and 10 to nodes[6]
4933 // from nodes[2] rather than channel 6, 11, and 8, even though the longer path is cheaper.
4934 let scorer = test_utils::TestScorer::with_penalty(100);
4935 let route = get_route(
4936 &our_id, &payment_params, &network_graph.read_only(), None, 100, 42,
4937 Arc::clone(&logger), &scorer, &random_seed_bytes
4939 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4941 assert_eq!(route.get_total_fees(), 300);
4942 assert_eq!(route.get_total_amount(), 100);
4943 assert_eq!(path, vec![2, 4, 7, 10]);
4946 struct BadChannelScorer {
4947 short_channel_id: u64,
4951 impl Writeable for BadChannelScorer {
4952 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), ::io::Error> { unimplemented!() }
4954 impl Score for BadChannelScorer {
4955 fn channel_penalty_msat(&self, short_channel_id: u64, _send_amt: u64, _capacity_msat: u64, _source: &NodeId, _target: &NodeId) -> u64 {
4956 if short_channel_id == self.short_channel_id { u64::max_value() } else { 0 }
4959 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
4960 fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
4963 struct BadNodeScorer {
4968 impl Writeable for BadNodeScorer {
4969 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), ::io::Error> { unimplemented!() }
4972 impl Score for BadNodeScorer {
4973 fn channel_penalty_msat(&self, _short_channel_id: u64, _send_amt: u64, _capacity_msat: u64, _source: &NodeId, target: &NodeId) -> u64 {
4974 if *target == self.node_id { u64::max_value() } else { 0 }
4977 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
4978 fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
4982 fn avoids_routing_through_bad_channels_and_nodes() {
4983 let (secp_ctx, network, _, _, logger) = build_graph();
4984 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4985 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
4986 let network_graph = network.read_only();
4988 // A path to nodes[6] exists when no penalties are applied to any channel.
4989 let scorer = test_utils::TestScorer::with_penalty(0);
4990 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4991 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4992 let route = get_route(
4993 &our_id, &payment_params, &network_graph, None, 100, 42,
4994 Arc::clone(&logger), &scorer, &random_seed_bytes
4996 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4998 assert_eq!(route.get_total_fees(), 100);
4999 assert_eq!(route.get_total_amount(), 100);
5000 assert_eq!(path, vec![2, 4, 6, 11, 8]);
5002 // A different path to nodes[6] exists if channel 6 cannot be routed over.
5003 let scorer = BadChannelScorer { short_channel_id: 6 };
5004 let route = get_route(
5005 &our_id, &payment_params, &network_graph, None, 100, 42,
5006 Arc::clone(&logger), &scorer, &random_seed_bytes
5008 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5010 assert_eq!(route.get_total_fees(), 300);
5011 assert_eq!(route.get_total_amount(), 100);
5012 assert_eq!(path, vec![2, 4, 7, 10]);
5014 // A path to nodes[6] does not exist if nodes[2] cannot be routed through.
5015 let scorer = BadNodeScorer { node_id: NodeId::from_pubkey(&nodes[2]) };
5017 &our_id, &payment_params, &network_graph, None, 100, 42,
5018 Arc::clone(&logger), &scorer, &random_seed_bytes
5020 Err(LightningError { err, .. } ) => {
5021 assert_eq!(err, "Failed to find a path to the given destination");
5023 Ok(_) => panic!("Expected error"),
5028 fn total_fees_single_path() {
5032 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5033 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5034 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5037 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5038 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5039 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5042 pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
5043 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5044 short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0
5047 payment_params: None,
5050 assert_eq!(route.get_total_fees(), 250);
5051 assert_eq!(route.get_total_amount(), 225);
5055 fn total_fees_multi_path() {
5059 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5060 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5061 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5064 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5065 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5066 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5070 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5071 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5072 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5075 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5076 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5077 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5080 payment_params: None,
5083 assert_eq!(route.get_total_fees(), 200);
5084 assert_eq!(route.get_total_amount(), 300);
5088 fn total_empty_route_no_panic() {
5089 // In an earlier version of `Route::get_total_fees` and `Route::get_total_amount`, they
5090 // would both panic if the route was completely empty. We test to ensure they return 0
5091 // here, even though its somewhat nonsensical as a route.
5092 let route = Route { paths: Vec::new(), payment_params: None };
5094 assert_eq!(route.get_total_fees(), 0);
5095 assert_eq!(route.get_total_amount(), 0);
5099 fn limits_total_cltv_delta() {
5100 let (secp_ctx, network, _, _, logger) = build_graph();
5101 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5102 let network_graph = network.read_only();
5104 let scorer = test_utils::TestScorer::with_penalty(0);
5106 // Make sure that generally there is at least one route available
5107 let feasible_max_total_cltv_delta = 1008;
5108 let feasible_payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes))
5109 .with_max_total_cltv_expiry_delta(feasible_max_total_cltv_delta);
5110 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5111 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5112 let route = get_route(&our_id, &feasible_payment_params, &network_graph, None, 100, 0, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5113 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5114 assert_ne!(path.len(), 0);
5116 // But not if we exclude all paths on the basis of their accumulated CLTV delta
5117 let fail_max_total_cltv_delta = 23;
5118 let fail_payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes))
5119 .with_max_total_cltv_expiry_delta(fail_max_total_cltv_delta);
5120 match get_route(&our_id, &fail_payment_params, &network_graph, None, 100, 0, Arc::clone(&logger), &scorer, &random_seed_bytes)
5122 Err(LightningError { err, .. } ) => {
5123 assert_eq!(err, "Failed to find a path to the given destination");
5125 Ok(_) => panic!("Expected error"),
5130 fn adds_and_limits_cltv_offset() {
5131 let (secp_ctx, network_graph, _, _, logger) = build_graph();
5132 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5134 let scorer = test_utils::TestScorer::with_penalty(0);
5136 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
5137 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5138 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5139 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5140 assert_eq!(route.paths.len(), 1);
5142 let cltv_expiry_deltas_before = route.paths[0].iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5144 // Check whether the offset added to the last hop by default is in [1 .. DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA]
5145 let mut route_default = route.clone();
5146 add_random_cltv_offset(&mut route_default, &payment_params, &network_graph.read_only(), &random_seed_bytes);
5147 let cltv_expiry_deltas_default = route_default.paths[0].iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5148 assert_eq!(cltv_expiry_deltas_before.split_last().unwrap().1, cltv_expiry_deltas_default.split_last().unwrap().1);
5149 assert!(cltv_expiry_deltas_default.last() > cltv_expiry_deltas_before.last());
5150 assert!(cltv_expiry_deltas_default.last().unwrap() <= &DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA);
5152 // Check that no offset is added when we restrict the max_total_cltv_expiry_delta
5153 let mut route_limited = route.clone();
5154 let limited_max_total_cltv_expiry_delta = cltv_expiry_deltas_before.iter().sum();
5155 let limited_payment_params = payment_params.with_max_total_cltv_expiry_delta(limited_max_total_cltv_expiry_delta);
5156 add_random_cltv_offset(&mut route_limited, &limited_payment_params, &network_graph.read_only(), &random_seed_bytes);
5157 let cltv_expiry_deltas_limited = route_limited.paths[0].iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5158 assert_eq!(cltv_expiry_deltas_before, cltv_expiry_deltas_limited);
5162 fn adds_plausible_cltv_offset() {
5163 let (secp_ctx, network, _, _, logger) = build_graph();
5164 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5165 let network_graph = network.read_only();
5166 let network_nodes = network_graph.nodes();
5167 let network_channels = network_graph.channels();
5168 let scorer = test_utils::TestScorer::with_penalty(0);
5169 let payment_params = PaymentParameters::from_node_id(nodes[3]);
5170 let keys_manager = test_utils::TestKeysInterface::new(&[4u8; 32], Network::Testnet);
5171 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5173 let mut route = get_route(&our_id, &payment_params, &network_graph, None, 100, 0,
5174 Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5175 add_random_cltv_offset(&mut route, &payment_params, &network_graph, &random_seed_bytes);
5177 let mut path_plausibility = vec![];
5179 for p in route.paths {
5180 // 1. Select random observation point
5181 let mut prng = ChaCha20::new(&random_seed_bytes, &[0u8; 12]);
5182 let mut random_bytes = [0u8; ::core::mem::size_of::<usize>()];
5184 prng.process_in_place(&mut random_bytes);
5185 let random_path_index = usize::from_be_bytes(random_bytes).wrapping_rem(p.len());
5186 let observation_point = NodeId::from_pubkey(&p.get(random_path_index).unwrap().pubkey);
5188 // 2. Calculate what CLTV expiry delta we would observe there
5189 let observed_cltv_expiry_delta: u32 = p[random_path_index..].iter().map(|h| h.cltv_expiry_delta).sum();
5191 // 3. Starting from the observation point, find candidate paths
5192 let mut candidates: VecDeque<(NodeId, Vec<u32>)> = VecDeque::new();
5193 candidates.push_back((observation_point, vec![]));
5195 let mut found_plausible_candidate = false;
5197 'candidate_loop: while let Some((cur_node_id, cur_path_cltv_deltas)) = candidates.pop_front() {
5198 if let Some(remaining) = observed_cltv_expiry_delta.checked_sub(cur_path_cltv_deltas.iter().sum::<u32>()) {
5199 if remaining == 0 || remaining.wrapping_rem(40) == 0 || remaining.wrapping_rem(144) == 0 {
5200 found_plausible_candidate = true;
5201 break 'candidate_loop;
5205 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
5206 for channel_id in &cur_node.channels {
5207 if let Some(channel_info) = network_channels.get(&channel_id) {
5208 if let Some((dir_info, next_id)) = channel_info.as_directed_from(&cur_node_id) {
5209 if let Some(channel_update_info) = dir_info.direction() {
5210 let next_cltv_expiry_delta = channel_update_info.cltv_expiry_delta as u32;
5211 if cur_path_cltv_deltas.iter().sum::<u32>()
5212 .saturating_add(next_cltv_expiry_delta) <= observed_cltv_expiry_delta {
5213 let mut new_path_cltv_deltas = cur_path_cltv_deltas.clone();
5214 new_path_cltv_deltas.push(next_cltv_expiry_delta);
5215 candidates.push_back((*next_id, new_path_cltv_deltas));
5224 path_plausibility.push(found_plausible_candidate);
5226 assert!(path_plausibility.iter().all(|x| *x));
5229 #[cfg(not(feature = "no-std"))]
5230 pub(super) fn random_init_seed() -> u64 {
5231 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
5232 use core::hash::{BuildHasher, Hasher};
5233 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
5234 println!("Using seed of {}", seed);
5237 #[cfg(not(feature = "no-std"))]
5238 use util::ser::Readable;
5241 #[cfg(not(feature = "no-std"))]
5242 fn generate_routes() {
5243 use routing::scoring::{ProbabilisticScorer, ProbabilisticScoringParameters};
5245 let mut d = match super::test_utils::get_route_file() {
5252 let graph = NetworkGraph::read(&mut d).unwrap();
5253 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5254 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5256 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
5257 let mut seed = random_init_seed() as usize;
5258 let nodes = graph.read_only().nodes().clone();
5259 'load_endpoints: for _ in 0..10 {
5261 seed = seed.overflowing_mul(0xdeadbeef).0;
5262 let src = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5263 seed = seed.overflowing_mul(0xdeadbeef).0;
5264 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5265 let payment_params = PaymentParameters::from_node_id(dst);
5266 let amt = seed as u64 % 200_000_000;
5267 let params = ProbabilisticScoringParameters::default();
5268 let scorer = ProbabilisticScorer::new(params, &graph);
5269 if get_route(src, &payment_params, &graph.read_only(), None, amt, 42, &test_utils::TestLogger::new(), &scorer, &random_seed_bytes).is_ok() {
5270 continue 'load_endpoints;
5277 #[cfg(not(feature = "no-std"))]
5278 fn generate_routes_mpp() {
5279 use routing::scoring::{ProbabilisticScorer, ProbabilisticScoringParameters};
5281 let mut d = match super::test_utils::get_route_file() {
5288 let graph = NetworkGraph::read(&mut d).unwrap();
5289 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5290 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5292 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
5293 let mut seed = random_init_seed() as usize;
5294 let nodes = graph.read_only().nodes().clone();
5295 'load_endpoints: for _ in 0..10 {
5297 seed = seed.overflowing_mul(0xdeadbeef).0;
5298 let src = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5299 seed = seed.overflowing_mul(0xdeadbeef).0;
5300 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5301 let payment_params = PaymentParameters::from_node_id(dst).with_features(InvoiceFeatures::known());
5302 let amt = seed as u64 % 200_000_000;
5303 let params = ProbabilisticScoringParameters::default();
5304 let scorer = ProbabilisticScorer::new(params, &graph);
5305 if get_route(src, &payment_params, &graph.read_only(), None, amt, 42, &test_utils::TestLogger::new(), &scorer, &random_seed_bytes).is_ok() {
5306 continue 'load_endpoints;
5313 #[cfg(all(test, not(feature = "no-std")))]
5314 pub(crate) mod test_utils {
5316 /// Tries to open a network graph file, or panics with a URL to fetch it.
5317 pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
5318 let res = File::open("net_graph-2021-05-31.bin") // By default we're run in RL/lightning
5319 .or_else(|_| File::open("lightning/net_graph-2021-05-31.bin")) // We may be run manually in RL/
5320 .or_else(|_| { // Fall back to guessing based on the binary location
5321 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
5322 let mut path = std::env::current_exe().unwrap();
5323 path.pop(); // lightning-...
5325 path.pop(); // debug
5326 path.pop(); // target
5327 path.push("lightning");
5328 path.push("net_graph-2021-05-31.bin");
5329 eprintln!("{}", path.to_str().unwrap());
5332 .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");
5333 #[cfg(require_route_graph_test)]
5334 return Ok(res.unwrap());
5335 #[cfg(not(require_route_graph_test))]
5340 #[cfg(all(test, feature = "_bench_unstable", not(feature = "no-std")))]
5343 use bitcoin::hashes::Hash;
5344 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
5345 use chain::transaction::OutPoint;
5346 use chain::keysinterface::{KeysManager,KeysInterface};
5347 use ln::channelmanager::{ChannelCounterparty, ChannelDetails};
5348 use ln::features::{InitFeatures, InvoiceFeatures};
5349 use routing::scoring::{FixedPenaltyScorer, ProbabilisticScorer, ProbabilisticScoringParameters, Scorer};
5350 use util::logger::{Logger, Record};
5354 struct DummyLogger {}
5355 impl Logger for DummyLogger {
5356 fn log(&self, _record: &Record) {}
5359 fn read_network_graph() -> NetworkGraph {
5360 let mut d = test_utils::get_route_file().unwrap();
5361 NetworkGraph::read(&mut d).unwrap()
5364 fn payer_pubkey() -> PublicKey {
5365 let secp_ctx = Secp256k1::new();
5366 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
5370 fn first_hop(node_id: PublicKey) -> ChannelDetails {
5372 channel_id: [0; 32],
5373 counterparty: ChannelCounterparty {
5374 features: InitFeatures::known(),
5376 unspendable_punishment_reserve: 0,
5377 forwarding_info: None,
5379 funding_txo: Some(OutPoint {
5380 txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0
5382 short_channel_id: Some(1),
5383 inbound_scid_alias: None,
5384 channel_value_satoshis: 10_000_000,
5386 balance_msat: 10_000_000,
5387 outbound_capacity_msat: 10_000_000,
5388 inbound_capacity_msat: 0,
5389 unspendable_punishment_reserve: None,
5390 confirmations_required: None,
5391 force_close_spend_delay: None,
5393 is_funding_locked: true,
5400 fn generate_routes_with_zero_penalty_scorer(bench: &mut Bencher) {
5401 let network_graph = read_network_graph();
5402 let scorer = FixedPenaltyScorer::with_penalty(0);
5403 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::empty());
5407 fn generate_mpp_routes_with_zero_penalty_scorer(bench: &mut Bencher) {
5408 let network_graph = read_network_graph();
5409 let scorer = FixedPenaltyScorer::with_penalty(0);
5410 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::known());
5414 fn generate_routes_with_default_scorer(bench: &mut Bencher) {
5415 let network_graph = read_network_graph();
5416 let scorer = Scorer::default();
5417 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::empty());
5421 fn generate_mpp_routes_with_default_scorer(bench: &mut Bencher) {
5422 let network_graph = read_network_graph();
5423 let scorer = Scorer::default();
5424 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::known());
5428 fn generate_routes_with_probabilistic_scorer(bench: &mut Bencher) {
5429 let network_graph = read_network_graph();
5430 let params = ProbabilisticScoringParameters::default();
5431 let scorer = ProbabilisticScorer::new(params, &network_graph);
5432 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::empty());
5436 fn generate_mpp_routes_with_probabilistic_scorer(bench: &mut Bencher) {
5437 let network_graph = read_network_graph();
5438 let params = ProbabilisticScoringParameters::default();
5439 let scorer = ProbabilisticScorer::new(params, &network_graph);
5440 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::known());
5443 fn generate_routes<S: Score>(
5444 bench: &mut Bencher, graph: &NetworkGraph, mut scorer: S, features: InvoiceFeatures
5446 let nodes = graph.read_only().nodes().clone();
5447 let payer = payer_pubkey();
5448 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
5449 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5451 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
5452 let mut routes = Vec::new();
5453 let mut route_endpoints = Vec::new();
5454 let mut seed: usize = 0xdeadbeef;
5455 'load_endpoints: for _ in 0..150 {
5458 let src = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5460 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5461 let params = PaymentParameters::from_node_id(dst).with_features(features.clone());
5462 let first_hop = first_hop(src);
5463 let amt = seed as u64 % 1_000_000;
5464 if let Ok(route) = get_route(&payer, ¶ms, &graph.read_only(), Some(&[&first_hop]), amt, 42, &DummyLogger{}, &scorer, &random_seed_bytes) {
5466 route_endpoints.push((first_hop, params, amt));
5467 continue 'load_endpoints;
5472 // ...and seed the scorer with success and failure data...
5473 for route in routes {
5474 let amount = route.get_total_amount();
5475 if amount < 250_000 {
5476 for path in route.paths {
5477 scorer.payment_path_successful(&path.iter().collect::<Vec<_>>());
5479 } else if amount > 750_000 {
5480 for path in route.paths {
5481 let short_channel_id = path[path.len() / 2].short_channel_id;
5482 scorer.payment_path_failed(&path.iter().collect::<Vec<_>>(), short_channel_id);
5487 // Because we've changed channel scores, its possible we'll take different routes to the
5488 // selected destinations, possibly causing us to fail because, eg, the newly-selected path
5489 // requires a too-high CLTV delta.
5490 route_endpoints.retain(|(first_hop, params, amt)| {
5491 get_route(&payer, params, &graph.read_only(), Some(&[first_hop]), *amt, 42, &DummyLogger{}, &scorer, &random_seed_bytes).is_ok()
5493 route_endpoints.truncate(100);
5494 assert_eq!(route_endpoints.len(), 100);
5496 // ...then benchmark finding paths between the nodes we learned.
5499 let (first_hop, params, amt) = &route_endpoints[idx % route_endpoints.len()];
5500 assert!(get_route(&payer, params, &graph.read_only(), Some(&[first_hop]), *amt, 42, &DummyLogger{}, &scorer, &random_seed_bytes).is_ok());