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});
674 // The general routing idea is the following:
675 // 1. Fill first/last hops communicated by the caller.
676 // 2. Attempt to construct a path from payer to payee for transferring
677 // any ~sufficient (described later) value.
678 // If succeed, remember which channels were used and how much liquidity they have available,
679 // so that future paths don't rely on the same liquidity.
680 // 3. Proceed to the next step if:
681 // - we hit the recommended target value;
682 // - OR if we could not construct a new path. Any next attempt will fail too.
683 // Otherwise, repeat step 2.
684 // 4. See if we managed to collect paths which aggregately are able to transfer target value
685 // (not recommended value).
686 // 5. If yes, proceed. If not, fail routing.
687 // 6. Randomly combine paths into routes having enough to fulfill the payment. (TODO: knapsack)
688 // 7. Of all the found paths, select only those with the lowest total fee.
689 // 8. The last path in every selected route is likely to be more than we need.
690 // Reduce its value-to-transfer and recompute fees.
691 // 9. Choose the best route by the lowest total fee.
693 // As for the actual search algorithm,
694 // we do a payee-to-payer pseudo-Dijkstra's sorting by each node's distance from the payee
695 // plus the minimum per-HTLC fee to get from it to another node (aka "shitty pseudo-A*").
697 // We are not a faithful Dijkstra's implementation because we can change values which impact
698 // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
699 // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) than
700 // the value we are currently attempting to send over a path, we simply reduce the value being
701 // sent along the path for any hops after that channel. This may imply that later fees (which
702 // we've already tabulated) are lower because a smaller value is passing through the channels
703 // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
704 // channels which were selected earlier (and which may still be used for other paths without a
705 // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
708 // One potentially problematic case for this algorithm would be if there are many
709 // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
710 // graph walking), we may never find a path which is not liquidity-limited and has lower
711 // proportional fee (and only lower absolute fee when considering the ultimate value sent).
712 // Because we only consider paths with at least 5% of the total value being sent, the damage
713 // from such a case should be limited, however this could be further reduced in the future by
714 // calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
715 // limits for the purposes of fee calculation.
717 // Alternatively, we could store more detailed path information in the heap (targets, below)
718 // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
719 // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
720 // and practically (as we would need to store dynamically-allocated path information in heap
721 // objects, increasing malloc traffic and indirect memory access significantly). Further, the
722 // results of such an algorithm would likely be biased towards lower-value paths.
724 // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
725 // outside of our current search value, running a path search more times to gather candidate
726 // paths at different values. While this may be acceptable, further path searches may increase
727 // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
728 // graph for candidate paths, calculating the maximum value which can realistically be sent at
729 // the same time, remaining generic across different payment values.
731 // TODO: There are a few tweaks we could do, including possibly pre-calculating more stuff
732 // to use as the A* heuristic beyond just the cost to get one node further than the current
735 let network_channels = network_graph.channels();
736 let network_nodes = network_graph.nodes();
738 // Allow MPP only if we have a features set from somewhere that indicates the payee supports
739 // it. If the payee supports it they're supposed to include it in the invoice, so that should
741 let allow_mpp = if let Some(features) = &payment_params.features {
742 features.supports_basic_mpp()
743 } else if let Some(node) = network_nodes.get(&payee_node_id) {
744 if let Some(node_info) = node.announcement_info.as_ref() {
745 node_info.features.supports_basic_mpp()
748 log_trace!(logger, "Searching for a route from payer {} to payee {} {} MPP and {} first hops {}overriding the network graph", our_node_pubkey,
749 payment_params.payee_pubkey, if allow_mpp { "with" } else { "without" },
750 first_hops.map(|hops| hops.len()).unwrap_or(0), if first_hops.is_some() { "" } else { "not " });
753 // Prepare the data we'll use for payee-to-payer search by
754 // inserting first hops suggested by the caller as targets.
755 // Our search will then attempt to reach them while traversing from the payee node.
756 let mut first_hop_targets: HashMap<_, Vec<&ChannelDetails>> =
757 HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
758 if let Some(hops) = first_hops {
760 if chan.short_channel_id.is_none() {
761 panic!("first_hops should be filled in with usable channels, not pending ones");
763 if chan.counterparty.node_id == *our_node_pubkey {
764 return Err(LightningError{err: "First hop cannot have our_node_pubkey as a destination.".to_owned(), action: ErrorAction::IgnoreError});
767 .entry(NodeId::from_pubkey(&chan.counterparty.node_id))
768 .or_insert(Vec::new())
771 if first_hop_targets.is_empty() {
772 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
776 // The main heap containing all candidate next-hops sorted by their score (max(A* fee,
777 // htlc_minimum)). Ideally this would be a heap which allowed cheap score reduction instead of
778 // adding duplicate entries when we find a better path to a given node.
779 let mut targets = BinaryHeap::new();
781 // Map from node_id to information about the best current path to that node, including feerate
783 let mut dist = HashMap::with_capacity(network_nodes.len());
785 // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
786 // indicating that we may wish to try again with a higher value, potentially paying to meet an
787 // htlc_minimum with extra fees while still finding a cheaper path.
788 let mut hit_minimum_limit;
790 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
791 // We start with a path_value of the exact amount we want, and if that generates a route we may
792 // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
793 // amount we want in total across paths, selecting the best subset at the end.
794 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
795 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
796 let mut path_value_msat = final_value_msat;
798 // We don't want multiple paths (as per MPP) share liquidity of the same channels.
799 // This map allows paths to be aware of the channel use by other paths in the same call.
800 // This would help to make a better path finding decisions and not "overbook" channels.
801 // It is unaware of the directions (except for `outbound_capacity_msat` in `first_hops`).
802 let mut bookkept_channels_liquidity_available_msat = HashMap::with_capacity(network_nodes.len());
804 // Keeping track of how much value we already collected across other paths. Helps to decide:
805 // - how much a new path should be transferring (upper bound);
806 // - whether a channel should be disregarded because
807 // it's available liquidity is too small comparing to how much more we need to collect;
808 // - when we want to stop looking for new paths.
809 let mut already_collected_value_msat = 0;
811 log_trace!(logger, "Building path from {} (payee) to {} (us/payer) for value {} msat.", payment_params.payee_pubkey, our_node_pubkey, final_value_msat);
813 macro_rules! add_entry {
814 // Adds entry which goes from $src_node_id to $dest_node_id over the $candidate hop.
815 // $next_hops_fee_msat represents the fees paid for using all the channels *after* this one,
816 // since that value has to be transferred over this channel.
817 // Returns whether this channel caused an update to `targets`.
818 ( $candidate: expr, $src_node_id: expr, $dest_node_id: expr, $next_hops_fee_msat: expr,
819 $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr,
820 $next_hops_path_penalty_msat: expr, $next_hops_cltv_delta: expr ) => { {
821 // We "return" whether we updated the path at the end, via this:
822 let mut did_add_update_path_to_src_node = false;
823 // Channels to self should not be used. This is more of belt-and-suspenders, because in
824 // practice these cases should be caught earlier:
825 // - for regular channels at channel announcement (TODO)
826 // - for first and last hops early in get_route
827 if $src_node_id != $dest_node_id {
828 let short_channel_id = $candidate.short_channel_id();
829 let available_liquidity_msat = bookkept_channels_liquidity_available_msat
830 .entry(short_channel_id)
831 .or_insert_with(|| $candidate.effective_capacity().as_msat());
833 // It is tricky to substract $next_hops_fee_msat from available liquidity here.
834 // It may be misleading because we might later choose to reduce the value transferred
835 // over these channels, and the channel which was insufficient might become sufficient.
836 // Worst case: we drop a good channel here because it can't cover the high following
837 // fees caused by one expensive channel, but then this channel could have been used
838 // if the amount being transferred over this path is lower.
839 // We do this for now, but this is a subject for removal.
840 if let Some(available_value_contribution_msat) = available_liquidity_msat.checked_sub($next_hops_fee_msat) {
842 // Routing Fragmentation Mitigation heuristic:
844 // Routing fragmentation across many payment paths increases the overall routing
845 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
846 // Taking too many smaller paths also increases the chance of payment failure.
847 // Thus to avoid this effect, we require from our collected links to provide
848 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
850 // This requirement is currently 5% of the remaining-to-be-collected value.
851 // This means as we successfully advance in our collection,
852 // the absolute liquidity contribution is lowered,
853 // thus increasing the number of potential channels to be selected.
855 // Derive the minimal liquidity contribution with a ratio of 20 (5%, rounded up)
856 // or 100% if we're not allowed to do multipath payments.
857 let minimal_value_contribution_msat: u64 = if allow_mpp {
858 (recommended_value_msat - already_collected_value_msat + 19) / 20
862 // Verify the liquidity offered by this channel complies to the minimal contribution.
863 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
865 // Do not consider candidates that exceed the maximum total cltv expiry limit.
866 // In order to already account for some of the privacy enhancing random CLTV
867 // expiry delta offset we add on top later, we subtract a rough estimate
868 // (2*MEDIAN_HOP_CLTV_EXPIRY_DELTA) here.
869 let max_total_cltv_expiry_delta = payment_params.max_total_cltv_expiry_delta
870 .checked_sub(2*MEDIAN_HOP_CLTV_EXPIRY_DELTA)
871 .unwrap_or(payment_params.max_total_cltv_expiry_delta);
872 let hop_total_cltv_delta = ($next_hops_cltv_delta as u32)
873 .checked_add($candidate.cltv_expiry_delta())
874 .unwrap_or(u32::max_value());
875 let doesnt_exceed_cltv_delta_limit = hop_total_cltv_delta <= max_total_cltv_expiry_delta;
877 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
878 // Includes paying fees for the use of the following channels.
879 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
880 Some(result) => result,
881 // Can't overflow due to how the values were computed right above.
882 None => unreachable!(),
884 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
885 let over_path_minimum_msat = amount_to_transfer_over_msat >= $candidate.htlc_minimum_msat() &&
886 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
888 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
889 // bother considering this channel.
890 // Since we're choosing amount_to_transfer_over_msat as maximum possible, it can
891 // be only reduced later (not increased), so this channel should just be skipped
892 // as not sufficient.
893 if !over_path_minimum_msat && doesnt_exceed_cltv_delta_limit {
894 hit_minimum_limit = true;
895 } else if contributes_sufficient_value && doesnt_exceed_cltv_delta_limit {
896 // Note that low contribution here (limited by available_liquidity_msat)
897 // might violate htlc_minimum_msat on the hops which are next along the
898 // payment path (upstream to the payee). To avoid that, we recompute
899 // path fees knowing the final path contribution after constructing it.
900 let path_htlc_minimum_msat = compute_fees($next_hops_path_htlc_minimum_msat, $candidate.fees())
901 .and_then(|fee_msat| fee_msat.checked_add($next_hops_path_htlc_minimum_msat))
902 .map(|fee_msat| cmp::max(fee_msat, $candidate.htlc_minimum_msat()))
903 .unwrap_or_else(|| u64::max_value());
904 let hm_entry = dist.entry($src_node_id);
905 let old_entry = hm_entry.or_insert_with(|| {
906 // If there was previously no known way to access the source node
907 // (recall it goes payee-to-payer) of short_channel_id, first add a
908 // semi-dummy record just to compute the fees to reach the source node.
909 // This will affect our decision on selecting short_channel_id
910 // as a way to reach the $dest_node_id.
911 let mut fee_base_msat = 0;
912 let mut fee_proportional_millionths = 0;
913 if let Some(Some(fees)) = network_nodes.get(&$src_node_id).map(|node| node.lowest_inbound_channel_fees) {
914 fee_base_msat = fees.base_msat;
915 fee_proportional_millionths = fees.proportional_millionths;
918 node_id: $dest_node_id.clone(),
919 candidate: $candidate.clone(),
921 src_lowest_inbound_fees: RoutingFees {
922 base_msat: fee_base_msat,
923 proportional_millionths: fee_proportional_millionths,
925 next_hops_fee_msat: u64::max_value(),
926 hop_use_fee_msat: u64::max_value(),
927 total_fee_msat: u64::max_value(),
928 path_htlc_minimum_msat,
929 path_penalty_msat: u64::max_value(),
930 was_processed: false,
931 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
932 value_contribution_msat,
936 #[allow(unused_mut)] // We only use the mut in cfg(test)
937 let mut should_process = !old_entry.was_processed;
938 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
940 // In test/fuzzing builds, we do extra checks to make sure the skipping
941 // of already-seen nodes only happens in cases we expect (see below).
942 if !should_process { should_process = true; }
946 let mut hop_use_fee_msat = 0;
947 let mut total_fee_msat = $next_hops_fee_msat;
949 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
950 // will have the same effective-fee
951 if $src_node_id != our_node_id {
952 match compute_fees(amount_to_transfer_over_msat, $candidate.fees()) {
953 // max_value means we'll always fail
954 // the old_entry.total_fee_msat > total_fee_msat check
955 None => total_fee_msat = u64::max_value(),
957 hop_use_fee_msat = fee_msat;
958 total_fee_msat += hop_use_fee_msat;
959 // When calculating the lowest inbound fees to a node, we
960 // calculate fees here not based on the actual value we think
961 // will flow over this channel, but on the minimum value that
962 // we'll accept flowing over it. The minimum accepted value
963 // is a constant through each path collection run, ensuring
964 // consistent basis. Otherwise we may later find a
965 // different path to the source node that is more expensive,
966 // but which we consider to be cheaper because we are capacity
967 // constrained and the relative fee becomes lower.
968 match compute_fees(minimal_value_contribution_msat, old_entry.src_lowest_inbound_fees)
969 .map(|a| a.checked_add(total_fee_msat)) {
974 total_fee_msat = u64::max_value();
981 let path_penalty_msat = $next_hops_path_penalty_msat.checked_add(
982 scorer.channel_penalty_msat(short_channel_id, amount_to_transfer_over_msat, *available_liquidity_msat,
983 &$src_node_id, &$dest_node_id)).unwrap_or_else(|| u64::max_value());
984 let new_graph_node = RouteGraphNode {
985 node_id: $src_node_id,
986 lowest_fee_to_peer_through_node: total_fee_msat,
987 lowest_fee_to_node: $next_hops_fee_msat as u64 + hop_use_fee_msat,
988 total_cltv_delta: hop_total_cltv_delta,
989 value_contribution_msat: value_contribution_msat,
990 path_htlc_minimum_msat,
994 // Update the way of reaching $src_node_id with the given short_channel_id (from $dest_node_id),
995 // if this way is cheaper than the already known
996 // (considering the cost to "reach" this channel from the route destination,
997 // the cost of using this channel,
998 // and the cost of routing to the source node of this channel).
999 // Also, consider that htlc_minimum_msat_difference, because we might end up
1000 // paying it. Consider the following exploit:
1001 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
1002 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
1003 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
1004 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
1006 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
1007 // but it may require additional tracking - we don't want to double-count
1008 // the fees included in $next_hops_path_htlc_minimum_msat, but also
1009 // can't use something that may decrease on future hops.
1010 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat)
1011 .checked_add(old_entry.path_penalty_msat)
1012 .unwrap_or_else(|| u64::max_value());
1013 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat)
1014 .checked_add(path_penalty_msat)
1015 .unwrap_or_else(|| u64::max_value());
1017 if !old_entry.was_processed && new_cost < old_cost {
1018 targets.push(new_graph_node);
1019 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
1020 old_entry.hop_use_fee_msat = hop_use_fee_msat;
1021 old_entry.total_fee_msat = total_fee_msat;
1022 old_entry.node_id = $dest_node_id.clone();
1023 old_entry.candidate = $candidate.clone();
1024 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
1025 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
1026 old_entry.path_penalty_msat = path_penalty_msat;
1027 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
1029 old_entry.value_contribution_msat = value_contribution_msat;
1031 did_add_update_path_to_src_node = true;
1032 } else if old_entry.was_processed && new_cost < old_cost {
1033 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
1035 // If we're skipping processing a node which was previously
1036 // processed even though we found another path to it with a
1037 // cheaper fee, check that it was because the second path we
1038 // found (which we are processing now) has a lower value
1039 // contribution due to an HTLC minimum limit.
1041 // e.g. take a graph with two paths from node 1 to node 2, one
1042 // through channel A, and one through channel B. Channel A and
1043 // B are both in the to-process heap, with their scores set by
1044 // a higher htlc_minimum than fee.
1045 // Channel A is processed first, and the channels onwards from
1046 // node 1 are added to the to-process heap. Thereafter, we pop
1047 // Channel B off of the heap, note that it has a much more
1048 // restrictive htlc_maximum_msat, and recalculate the fees for
1049 // all of node 1's channels using the new, reduced, amount.
1051 // This would be bogus - we'd be selecting a higher-fee path
1052 // with a lower htlc_maximum_msat instead of the one we'd
1053 // already decided to use.
1054 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
1056 value_contribution_msat + path_penalty_msat <
1057 old_entry.value_contribution_msat + old_entry.path_penalty_msat
1065 did_add_update_path_to_src_node
1069 let empty_node_features = NodeFeatures::empty();
1070 // Find ways (channels with destination) to reach a given node and store them
1071 // in the corresponding data structures (routing graph etc).
1072 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
1073 // meaning how much will be paid in fees after this node (to the best of our knowledge).
1074 // This data can later be helpful to optimize routing (pay lower fees).
1075 macro_rules! add_entries_to_cheapest_to_target_node {
1076 ( $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 ) => {
1077 let skip_node = if let Some(elem) = dist.get_mut(&$node_id) {
1078 let was_processed = elem.was_processed;
1079 elem.was_processed = true;
1082 // Entries are added to dist in add_entry!() when there is a channel from a node.
1083 // Because there are no channels from payee, it will not have a dist entry at this point.
1084 // If we're processing any other node, it is always be the result of a channel from it.
1085 assert_eq!($node_id, payee_node_id);
1090 if let Some(first_channels) = first_hop_targets.get(&$node_id) {
1091 for details in first_channels {
1092 let candidate = CandidateRouteHop::FirstHop { details };
1093 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);
1097 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
1100 &empty_node_features
1103 if !features.requires_unknown_bits() {
1104 for chan_id in $node.channels.iter() {
1105 let chan = network_channels.get(chan_id).unwrap();
1106 if !chan.features.requires_unknown_bits() {
1107 let (directed_channel, source) =
1108 chan.as_directed_to(&$node_id).expect("inconsistent NetworkGraph");
1109 if first_hops.is_none() || *source != our_node_id {
1110 if let Some(direction) = directed_channel.direction() {
1111 if direction.enabled {
1112 let candidate = CandidateRouteHop::PublicHop {
1113 info: directed_channel.with_update().unwrap(),
1114 short_channel_id: *chan_id,
1116 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);
1127 let mut payment_paths = Vec::<PaymentPath>::new();
1129 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
1130 'paths_collection: loop {
1131 // For every new path, start from scratch, except
1132 // bookkept_channels_liquidity_available_msat, which will improve
1133 // the further iterations of path finding. Also don't erase first_hop_targets.
1136 hit_minimum_limit = false;
1138 // If first hop is a private channel and the only way to reach the payee, this is the only
1139 // place where it could be added.
1140 if let Some(first_channels) = first_hop_targets.get(&payee_node_id) {
1141 for details in first_channels {
1142 let candidate = CandidateRouteHop::FirstHop { details };
1143 let added = add_entry!(candidate, our_node_id, payee_node_id, 0, path_value_msat, 0, 0u64, 0);
1144 log_trace!(logger, "{} direct route to payee via SCID {}", if added { "Added" } else { "Skipped" }, candidate.short_channel_id());
1148 // Add the payee as a target, so that the payee-to-payer
1149 // search algorithm knows what to start with.
1150 match network_nodes.get(&payee_node_id) {
1151 // The payee is not in our network graph, so nothing to add here.
1152 // There is still a chance of reaching them via last_hops though,
1153 // so don't yet fail the payment here.
1154 // If not, targets.pop() will not even let us enter the loop in step 2.
1157 add_entries_to_cheapest_to_target_node!(node, payee_node_id, 0, path_value_msat, 0, 0u64, 0);
1162 // If a caller provided us with last hops, add them to routing targets. Since this happens
1163 // earlier than general path finding, they will be somewhat prioritized, although currently
1164 // it matters only if the fees are exactly the same.
1165 for route in payment_params.route_hints.iter().filter(|route| !route.0.is_empty()) {
1166 let first_hop_in_route = &(route.0)[0];
1167 let have_hop_src_in_graph =
1168 // Only add the hops in this route to our candidate set if either
1169 // we have a direct channel to the first hop or the first hop is
1170 // in the regular network graph.
1171 first_hop_targets.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some() ||
1172 network_nodes.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some();
1173 if have_hop_src_in_graph {
1174 // We start building the path from reverse, i.e., from payee
1175 // to the first RouteHintHop in the path.
1176 let hop_iter = route.0.iter().rev();
1177 let prev_hop_iter = core::iter::once(&payment_params.payee_pubkey).chain(
1178 route.0.iter().skip(1).rev().map(|hop| &hop.src_node_id));
1179 let mut hop_used = true;
1180 let mut aggregate_next_hops_fee_msat: u64 = 0;
1181 let mut aggregate_next_hops_path_htlc_minimum_msat: u64 = 0;
1182 let mut aggregate_next_hops_path_penalty_msat: u64 = 0;
1183 let mut aggregate_next_hops_cltv_delta: u32 = 0;
1185 for (idx, (hop, prev_hop_id)) in hop_iter.zip(prev_hop_iter).enumerate() {
1186 let source = NodeId::from_pubkey(&hop.src_node_id);
1187 let target = NodeId::from_pubkey(&prev_hop_id);
1188 let candidate = network_channels
1189 .get(&hop.short_channel_id)
1190 .and_then(|channel| channel.as_directed_to(&target))
1191 .and_then(|(channel, _)| channel.with_update())
1192 .map(|info| CandidateRouteHop::PublicHop {
1194 short_channel_id: hop.short_channel_id,
1196 .unwrap_or_else(|| CandidateRouteHop::PrivateHop { hint: hop });
1197 let capacity_msat = candidate.effective_capacity().as_msat();
1198 aggregate_next_hops_path_penalty_msat = aggregate_next_hops_path_penalty_msat
1199 .checked_add(scorer.channel_penalty_msat(hop.short_channel_id, final_value_msat, capacity_msat, &source, &target))
1200 .unwrap_or_else(|| u64::max_value());
1202 aggregate_next_hops_cltv_delta = aggregate_next_hops_cltv_delta
1203 .checked_add(hop.cltv_expiry_delta as u32)
1204 .unwrap_or_else(|| u32::max_value());
1206 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) {
1207 // If this hop was not used then there is no use checking the preceding hops
1208 // in the RouteHint. We can break by just searching for a direct channel between
1209 // last checked hop and first_hop_targets
1213 // Searching for a direct channel between last checked hop and first_hop_targets
1214 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&prev_hop_id)) {
1215 for details in first_channels {
1216 let candidate = CandidateRouteHop::FirstHop { details };
1217 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);
1225 // In the next values of the iterator, the aggregate fees already reflects
1226 // the sum of value sent from payer (final_value_msat) and routing fees
1227 // for the last node in the RouteHint. We need to just add the fees to
1228 // route through the current node so that the preceeding node (next iteration)
1230 let hops_fee = compute_fees(aggregate_next_hops_fee_msat + final_value_msat, hop.fees)
1231 .map_or(None, |inc| inc.checked_add(aggregate_next_hops_fee_msat));
1232 aggregate_next_hops_fee_msat = if let Some(val) = hops_fee { val } else { break; };
1234 let hop_htlc_minimum_msat = candidate.htlc_minimum_msat();
1235 let hop_htlc_minimum_msat_inc = if let Some(val) = compute_fees(aggregate_next_hops_path_htlc_minimum_msat, hop.fees) { val } else { break; };
1236 let hops_path_htlc_minimum = aggregate_next_hops_path_htlc_minimum_msat
1237 .checked_add(hop_htlc_minimum_msat_inc);
1238 aggregate_next_hops_path_htlc_minimum_msat = if let Some(val) = hops_path_htlc_minimum { cmp::max(hop_htlc_minimum_msat, val) } else { break; };
1240 if idx == route.0.len() - 1 {
1241 // The last hop in this iterator is the first hop in
1242 // overall RouteHint.
1243 // If this hop connects to a node with which we have a direct channel,
1244 // ignore the network graph and, if the last hop was added, add our
1245 // direct channel to the candidate set.
1247 // Note that we *must* check if the last hop was added as `add_entry`
1248 // always assumes that the third argument is a node to which we have a
1250 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&hop.src_node_id)) {
1251 for details in first_channels {
1252 let candidate = CandidateRouteHop::FirstHop { details };
1253 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);
1261 log_trace!(logger, "Starting main path collection loop with {} nodes pre-filled from first/last hops.", targets.len());
1263 // At this point, targets are filled with the data from first and
1264 // last hops communicated by the caller, and the payment receiver.
1265 let mut found_new_path = false;
1268 // If this loop terminates due the exhaustion of targets, two situations are possible:
1269 // - not enough outgoing liquidity:
1270 // 0 < already_collected_value_msat < final_value_msat
1271 // - enough outgoing liquidity:
1272 // final_value_msat <= already_collected_value_msat < recommended_value_msat
1273 // Both these cases (and other cases except reaching recommended_value_msat) mean that
1274 // paths_collection will be stopped because found_new_path==false.
1275 // This is not necessarily a routing failure.
1276 '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() {
1278 // Since we're going payee-to-payer, hitting our node as a target means we should stop
1279 // traversing the graph and arrange the path out of what we found.
1280 if node_id == our_node_id {
1281 let mut new_entry = dist.remove(&our_node_id).unwrap();
1282 let mut ordered_hops = vec!((new_entry.clone(), NodeFeatures::empty()));
1285 let mut features_set = false;
1286 if let Some(first_channels) = first_hop_targets.get(&ordered_hops.last().unwrap().0.node_id) {
1287 for details in first_channels {
1288 if details.short_channel_id.unwrap() == ordered_hops.last().unwrap().0.candidate.short_channel_id() {
1289 ordered_hops.last_mut().unwrap().1 = details.counterparty.features.to_context();
1290 features_set = true;
1296 if let Some(node) = network_nodes.get(&ordered_hops.last().unwrap().0.node_id) {
1297 if let Some(node_info) = node.announcement_info.as_ref() {
1298 ordered_hops.last_mut().unwrap().1 = node_info.features.clone();
1300 ordered_hops.last_mut().unwrap().1 = NodeFeatures::empty();
1303 // We can fill in features for everything except hops which were
1304 // provided via the invoice we're paying. We could guess based on the
1305 // recipient's features but for now we simply avoid guessing at all.
1309 // Means we succesfully traversed from the payer to the payee, now
1310 // save this path for the payment route. Also, update the liquidity
1311 // remaining on the used hops, so that we take them into account
1312 // while looking for more paths.
1313 if ordered_hops.last().unwrap().0.node_id == payee_node_id {
1317 new_entry = match dist.remove(&ordered_hops.last().unwrap().0.node_id) {
1318 Some(payment_hop) => payment_hop,
1319 // We can't arrive at None because, if we ever add an entry to targets,
1320 // we also fill in the entry in dist (see add_entry!).
1321 None => unreachable!(),
1323 // We "propagate" the fees one hop backward (topologically) here,
1324 // so that fees paid for a HTLC forwarding on the current channel are
1325 // associated with the previous channel (where they will be subtracted).
1326 ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
1327 ordered_hops.push((new_entry.clone(), NodeFeatures::empty()));
1329 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
1330 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
1332 log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: \n {:#?}",
1333 ordered_hops.len(), value_contribution_msat, ordered_hops.iter().map(|h| &(h.0)).collect::<Vec<&PathBuildingHop>>());
1335 let mut payment_path = PaymentPath {hops: ordered_hops};
1337 // We could have possibly constructed a slightly inconsistent path: since we reduce
1338 // value being transferred along the way, we could have violated htlc_minimum_msat
1339 // on some channels we already passed (assuming dest->source direction). Here, we
1340 // recompute the fees again, so that if that's the case, we match the currently
1341 // underpaid htlc_minimum_msat with fees.
1342 payment_path.update_value_and_recompute_fees(cmp::min(value_contribution_msat, final_value_msat));
1344 // Since a path allows to transfer as much value as
1345 // the smallest channel it has ("bottleneck"), we should recompute
1346 // the fees so sender HTLC don't overpay fees when traversing
1347 // larger channels than the bottleneck. This may happen because
1348 // when we were selecting those channels we were not aware how much value
1349 // this path will transfer, and the relative fee for them
1350 // might have been computed considering a larger value.
1351 // Remember that we used these channels so that we don't rely
1352 // on the same liquidity in future paths.
1353 let mut prevented_redundant_path_selection = false;
1354 for (payment_hop, _) in payment_path.hops.iter() {
1355 let channel_liquidity_available_msat = bookkept_channels_liquidity_available_msat.get_mut(&payment_hop.candidate.short_channel_id()).unwrap();
1356 let mut spent_on_hop_msat = value_contribution_msat;
1357 let next_hops_fee_msat = payment_hop.next_hops_fee_msat;
1358 spent_on_hop_msat += next_hops_fee_msat;
1359 if spent_on_hop_msat == *channel_liquidity_available_msat {
1360 // If this path used all of this channel's available liquidity, we know
1361 // this path will not be selected again in the next loop iteration.
1362 prevented_redundant_path_selection = true;
1364 *channel_liquidity_available_msat -= spent_on_hop_msat;
1366 if !prevented_redundant_path_selection {
1367 // If we weren't capped by hitting a liquidity limit on a channel in the path,
1368 // we'll probably end up picking the same path again on the next iteration.
1369 // Decrease the available liquidity of a hop in the middle of the path.
1370 let victim_scid = payment_path.hops[(payment_path.hops.len() - 1) / 2].0.candidate.short_channel_id();
1371 log_trace!(logger, "Disabling channel {} for future path building iterations to avoid duplicates.", victim_scid);
1372 let victim_liquidity = bookkept_channels_liquidity_available_msat.get_mut(&victim_scid).unwrap();
1373 *victim_liquidity = 0;
1376 // Track the total amount all our collected paths allow to send so that we:
1377 // - know when to stop looking for more paths
1378 // - know which of the hops are useless considering how much more sats we need
1379 // (contributes_sufficient_value)
1380 already_collected_value_msat += value_contribution_msat;
1382 payment_paths.push(payment_path);
1383 found_new_path = true;
1384 break 'path_construction;
1387 // If we found a path back to the payee, we shouldn't try to process it again. This is
1388 // the equivalent of the `elem.was_processed` check in
1389 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
1390 if node_id == payee_node_id { continue 'path_construction; }
1392 // Otherwise, since the current target node is not us,
1393 // keep "unrolling" the payment graph from payee to payer by
1394 // finding a way to reach the current target from the payer side.
1395 match network_nodes.get(&node_id) {
1398 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);
1404 // If we don't support MPP, no use trying to gather more value ever.
1405 break 'paths_collection;
1409 // Stop either when the recommended value is reached or if no new path was found in this
1411 // In the latter case, making another path finding attempt won't help,
1412 // because we deterministically terminated the search due to low liquidity.
1413 if already_collected_value_msat >= recommended_value_msat || !found_new_path {
1414 log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
1415 already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
1416 break 'paths_collection;
1417 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
1418 // Further, if this was our first walk of the graph, and we weren't limited by an
1419 // htlc_minimum_msat, return immediately because this path should suffice. If we were
1420 // limited by an htlc_minimum_msat value, find another path with a higher value,
1421 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
1422 // still keeping a lower total fee than this path.
1423 if !hit_minimum_limit {
1424 log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
1425 break 'paths_collection;
1427 log_trace!(logger, "Collected our payment amount on the first pass, but running again to collect extra paths with a potentially higher limit.");
1428 path_value_msat = recommended_value_msat;
1433 if payment_paths.len() == 0 {
1434 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1437 if already_collected_value_msat < final_value_msat {
1438 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1441 // Sort by total fees and take the best paths.
1442 payment_paths.sort_by_key(|path| path.get_total_fee_paid_msat());
1443 if payment_paths.len() > 50 {
1444 payment_paths.truncate(50);
1447 // Draw multiple sufficient routes by randomly combining the selected paths.
1448 let mut drawn_routes = Vec::new();
1449 for i in 0..payment_paths.len() {
1450 let mut cur_route = Vec::<PaymentPath>::new();
1451 let mut aggregate_route_value_msat = 0;
1454 // TODO: real random shuffle
1455 // Currently just starts with i_th and goes up to i-1_th in a looped way.
1456 let cur_payment_paths = [&payment_paths[i..], &payment_paths[..i]].concat();
1459 for payment_path in cur_payment_paths {
1460 cur_route.push(payment_path.clone());
1461 aggregate_route_value_msat += payment_path.get_value_msat();
1462 if aggregate_route_value_msat > final_value_msat {
1463 // Last path likely overpaid. Substract it from the most expensive
1464 // (in terms of proportional fee) path in this route and recompute fees.
1465 // This might be not the most economically efficient way, but fewer paths
1466 // also makes routing more reliable.
1467 let mut overpaid_value_msat = aggregate_route_value_msat - final_value_msat;
1469 // First, drop some expensive low-value paths entirely if possible.
1470 // Sort by value so that we drop many really-low values first, since
1471 // fewer paths is better: the payment is less likely to fail.
1472 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1473 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1474 cur_route.sort_by_key(|path| path.get_value_msat());
1475 // We should make sure that at least 1 path left.
1476 let mut paths_left = cur_route.len();
1477 cur_route.retain(|path| {
1478 if paths_left == 1 {
1481 let mut keep = true;
1482 let path_value_msat = path.get_value_msat();
1483 if path_value_msat <= overpaid_value_msat {
1485 overpaid_value_msat -= path_value_msat;
1491 if overpaid_value_msat == 0 {
1495 assert!(cur_route.len() > 0);
1498 // Now, substract the overpaid value from the most-expensive path.
1499 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1500 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1501 cur_route.sort_by_key(|path| { path.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>() });
1502 let expensive_payment_path = cur_route.first_mut().unwrap();
1503 // We already dropped all the small channels above, meaning all the
1504 // remaining channels are larger than remaining overpaid_value_msat.
1505 // Thus, this can't be negative.
1506 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
1507 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
1511 drawn_routes.push(cur_route);
1515 // Select the best route by lowest total fee.
1516 drawn_routes.sort_by_key(|paths| paths.iter().map(|path| path.get_total_fee_paid_msat()).sum::<u64>());
1517 let mut selected_paths = Vec::<Vec<Result<RouteHop, LightningError>>>::new();
1518 for payment_path in drawn_routes.first().unwrap() {
1519 let mut path = payment_path.hops.iter().map(|(payment_hop, node_features)| {
1521 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)})?,
1522 node_features: node_features.clone(),
1523 short_channel_id: payment_hop.candidate.short_channel_id(),
1524 channel_features: payment_hop.candidate.features(),
1525 fee_msat: payment_hop.fee_msat,
1526 cltv_expiry_delta: payment_hop.candidate.cltv_expiry_delta(),
1528 }).collect::<Vec<_>>();
1529 // Propagate the cltv_expiry_delta one hop backwards since the delta from the current hop is
1530 // applicable for the previous hop.
1531 path.iter_mut().rev().fold(final_cltv_expiry_delta, |prev_cltv_expiry_delta, hop| {
1532 core::mem::replace(&mut hop.as_mut().unwrap().cltv_expiry_delta, prev_cltv_expiry_delta)
1534 selected_paths.push(path);
1537 if let Some(features) = &payment_params.features {
1538 for path in selected_paths.iter_mut() {
1539 if let Ok(route_hop) = path.last_mut().unwrap() {
1540 route_hop.node_features = features.to_context();
1546 paths: selected_paths.into_iter().map(|path| path.into_iter().collect()).collect::<Result<Vec<_>, _>>()?,
1547 payment_params: Some(payment_params.clone()),
1549 log_info!(logger, "Got route to {}: {}", payment_params.payee_pubkey, log_route!(route));
1553 // When an adversarial intermediary node observes a payment, it may be able to infer its
1554 // destination, if the remaining CLTV expiry delta exactly matches a feasible path in the network
1555 // graph. In order to improve privacy, this method obfuscates the CLTV expiry deltas along the
1556 // payment path by adding a randomized 'shadow route' offset to the final hop.
1557 fn add_random_cltv_offset(route: &mut Route, payment_params: &PaymentParameters, network_graph: &ReadOnlyNetworkGraph, random_seed_bytes: &[u8; 32]) {
1558 let network_channels = network_graph.channels();
1559 let network_nodes = network_graph.nodes();
1561 for path in route.paths.iter_mut() {
1562 let mut shadow_ctlv_expiry_delta_offset: u32 = 0;
1564 // Choose the last publicly known node as the starting point for the random walk
1565 if let Some(starting_hop) = path.iter().rev().find(|h| network_nodes.contains_key(&NodeId::from_pubkey(&h.pubkey))) {
1566 let mut cur_node_id = NodeId::from_pubkey(&starting_hop.pubkey);
1568 // Init PRNG with path nonce
1569 let mut path_nonce = [0u8; 12];
1570 path_nonce.copy_from_slice(&cur_node_id.as_slice()[..12]);
1571 let mut prng = ChaCha20::new(random_seed_bytes, &path_nonce);
1572 let mut random_path_bytes = [0u8; ::core::mem::size_of::<usize>()];
1574 // Pick a random path length in [1 .. 3]
1575 prng.process_in_place(&mut random_path_bytes);
1576 let random_walk_length = usize::from_be_bytes(random_path_bytes).wrapping_rem(3).wrapping_add(1);
1578 for _random_hop in 0..random_walk_length {
1579 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
1580 // Randomly choose the next hop
1581 prng.process_in_place(&mut random_path_bytes);
1582 if let Some(random_channel) = usize::from_be_bytes(random_path_bytes).checked_rem(cur_node.channels.len())
1583 .and_then(|index| cur_node.channels.get(index))
1584 .and_then(|id| network_channels.get(id)) {
1585 random_channel.as_directed_from(&cur_node_id).map(|(dir_info, next_id)| {
1586 dir_info.direction().map(|channel_update_info|
1587 shadow_ctlv_expiry_delta_offset = shadow_ctlv_expiry_delta_offset
1588 .checked_add(channel_update_info.cltv_expiry_delta.into())
1589 .unwrap_or(shadow_ctlv_expiry_delta_offset));
1590 cur_node_id = *next_id;
1596 // If the entire path is private, choose a random offset from multiples of
1597 // MEDIAN_HOP_CLTV_EXPIRY_DELTA
1598 let mut prng = ChaCha20::new(random_seed_bytes, &[0u8; 8]);
1599 let mut random_bytes = [0u8; 4];
1600 prng.process_in_place(&mut random_bytes);
1601 let random_walk_length = u32::from_be_bytes(random_bytes).wrapping_rem(3).wrapping_add(1);
1602 shadow_ctlv_expiry_delta_offset = random_walk_length * MEDIAN_HOP_CLTV_EXPIRY_DELTA;
1605 // Limit the total offset to reduce the worst-case locked liquidity timevalue
1606 const MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET: u32 = 3*144;
1607 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET);
1609 // Limit the offset so we never exceed the max_total_cltv_expiry_delta. To improve plausibility,
1610 // we choose the limit to be the largest possible multiple of MEDIAN_HOP_CLTV_EXPIRY_DELTA.
1611 let path_total_cltv_expiry_delta: u32 = path.iter().map(|h| h.cltv_expiry_delta).sum();
1612 let mut max_path_offset = payment_params.max_total_cltv_expiry_delta - path_total_cltv_expiry_delta;
1613 max_path_offset = cmp::max(
1614 max_path_offset - (max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA),
1615 max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA);
1616 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, max_path_offset);
1618 // Add 'shadow' CLTV offset to the final hop
1619 if let Some(last_hop) = path.last_mut() {
1620 last_hop.cltv_expiry_delta = last_hop.cltv_expiry_delta
1621 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(last_hop.cltv_expiry_delta);
1628 use routing::network_graph::{NetworkGraph, NetGraphMsgHandler, NodeId};
1629 use routing::router::{get_route, add_random_cltv_offset, PaymentParameters, Route, RouteHint, RouteHintHop, RouteHop, RoutingFees, DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA};
1630 use routing::scoring::Score;
1631 use chain::transaction::OutPoint;
1632 use chain::keysinterface::KeysInterface;
1633 use ln::features::{ChannelFeatures, InitFeatures, InvoiceFeatures, NodeFeatures};
1634 use ln::msgs::{ErrorAction, LightningError, OptionalField, UnsignedChannelAnnouncement, ChannelAnnouncement, RoutingMessageHandler,
1635 NodeAnnouncement, UnsignedNodeAnnouncement, ChannelUpdate, UnsignedChannelUpdate};
1636 use ln::channelmanager;
1637 use util::test_utils;
1638 use util::chacha20::ChaCha20;
1639 use util::ser::Writeable;
1641 use util::ser::Writer;
1643 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
1644 use bitcoin::hashes::Hash;
1645 use bitcoin::network::constants::Network;
1646 use bitcoin::blockdata::constants::genesis_block;
1647 use bitcoin::blockdata::script::Builder;
1648 use bitcoin::blockdata::opcodes;
1649 use bitcoin::blockdata::transaction::TxOut;
1653 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
1654 use bitcoin::secp256k1::{Secp256k1, All};
1657 use sync::{self, Arc};
1659 fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
1660 features: InitFeatures, outbound_capacity_msat: u64) -> channelmanager::ChannelDetails {
1661 channelmanager::ChannelDetails {
1662 channel_id: [0; 32],
1663 counterparty: channelmanager::ChannelCounterparty {
1666 unspendable_punishment_reserve: 0,
1667 forwarding_info: None,
1669 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
1671 inbound_scid_alias: None,
1672 channel_value_satoshis: 0,
1675 outbound_capacity_msat,
1676 inbound_capacity_msat: 42,
1677 unspendable_punishment_reserve: None,
1678 confirmations_required: None,
1679 force_close_spend_delay: None,
1680 is_outbound: true, is_funding_locked: true,
1681 is_usable: true, is_public: true,
1685 // Using the same keys for LN and BTC ids
1687 net_graph_msg_handler: &NetGraphMsgHandler<Arc<NetworkGraph>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1688 secp_ctx: &Secp256k1<All>, node_1_privkey: &SecretKey, node_2_privkey: &SecretKey, features: ChannelFeatures, short_channel_id: u64
1690 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1691 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1693 let unsigned_announcement = UnsignedChannelAnnouncement {
1695 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1699 bitcoin_key_1: node_id_1,
1700 bitcoin_key_2: node_id_2,
1701 excess_data: Vec::new(),
1704 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1705 let valid_announcement = ChannelAnnouncement {
1706 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1707 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1708 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1709 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1710 contents: unsigned_announcement.clone(),
1712 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1713 Ok(res) => assert!(res),
1719 net_graph_msg_handler: &NetGraphMsgHandler<Arc<NetworkGraph>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1720 secp_ctx: &Secp256k1<All>, node_privkey: &SecretKey, update: UnsignedChannelUpdate
1722 let msghash = hash_to_message!(&Sha256dHash::hash(&update.encode()[..])[..]);
1723 let valid_channel_update = ChannelUpdate {
1724 signature: secp_ctx.sign(&msghash, node_privkey),
1725 contents: update.clone()
1728 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1729 Ok(res) => assert!(res),
1734 fn add_or_update_node(
1735 net_graph_msg_handler: &NetGraphMsgHandler<Arc<NetworkGraph>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1736 secp_ctx: &Secp256k1<All>, node_privkey: &SecretKey, features: NodeFeatures, timestamp: u32
1738 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
1739 let unsigned_announcement = UnsignedNodeAnnouncement {
1745 addresses: Vec::new(),
1746 excess_address_data: Vec::new(),
1747 excess_data: Vec::new(),
1749 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1750 let valid_announcement = NodeAnnouncement {
1751 signature: secp_ctx.sign(&msghash, node_privkey),
1752 contents: unsigned_announcement.clone()
1755 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1761 fn get_nodes(secp_ctx: &Secp256k1<All>) -> (SecretKey, PublicKey, Vec<SecretKey>, Vec<PublicKey>) {
1762 let privkeys: Vec<SecretKey> = (2..10).map(|i| {
1763 SecretKey::from_slice(&hex::decode(format!("{:02x}", i).repeat(32)).unwrap()[..]).unwrap()
1766 let pubkeys = privkeys.iter().map(|secret| PublicKey::from_secret_key(&secp_ctx, secret)).collect();
1768 let our_privkey = SecretKey::from_slice(&hex::decode("01".repeat(32)).unwrap()[..]).unwrap();
1769 let our_id = PublicKey::from_secret_key(&secp_ctx, &our_privkey);
1771 (our_privkey, our_id, privkeys, pubkeys)
1774 fn id_to_feature_flags(id: u8) -> Vec<u8> {
1775 // Set the feature flags to the id'th odd (ie non-required) feature bit so that we can
1776 // test for it later.
1777 let idx = (id - 1) * 2 + 1;
1779 vec![1 << (idx - 8*3), 0, 0, 0]
1780 } else if idx > 8*2 {
1781 vec![1 << (idx - 8*2), 0, 0]
1782 } else if idx > 8*1 {
1783 vec![1 << (idx - 8*1), 0]
1789 fn build_graph() -> (
1791 sync::Arc<NetworkGraph>,
1792 NetGraphMsgHandler<sync::Arc<NetworkGraph>, sync::Arc<test_utils::TestChainSource>, sync::Arc<crate::util::test_utils::TestLogger>>,
1793 sync::Arc<test_utils::TestChainSource>,
1794 sync::Arc<test_utils::TestLogger>,
1796 let secp_ctx = Secp256k1::new();
1797 let logger = Arc::new(test_utils::TestLogger::new());
1798 let chain_monitor = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1799 let network_graph = Arc::new(NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash()));
1800 let net_graph_msg_handler = NetGraphMsgHandler::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
1801 // Build network from our_id to node6:
1803 // -1(1)2- node0 -1(3)2-
1805 // our_id -1(12)2- node7 -1(13)2--- node2
1807 // -1(2)2- node1 -1(4)2-
1810 // chan1 1-to-2: disabled
1811 // chan1 2-to-1: enabled, 0 fee
1813 // chan2 1-to-2: enabled, ignored fee
1814 // chan2 2-to-1: enabled, 0 fee
1816 // chan3 1-to-2: enabled, 0 fee
1817 // chan3 2-to-1: enabled, 100 msat fee
1819 // chan4 1-to-2: enabled, 100% fee
1820 // chan4 2-to-1: enabled, 0 fee
1822 // chan12 1-to-2: enabled, ignored fee
1823 // chan12 2-to-1: enabled, 0 fee
1825 // chan13 1-to-2: enabled, 200% fee
1826 // chan13 2-to-1: enabled, 0 fee
1829 // -1(5)2- node3 -1(8)2--
1833 // node2--1(6)2- node4 -1(9)2--- node6 (not in global route map)
1835 // -1(7)2- node5 -1(10)2-
1837 // Channels 5, 8, 9 and 10 are private channels.
1839 // chan5 1-to-2: enabled, 100 msat fee
1840 // chan5 2-to-1: enabled, 0 fee
1842 // chan6 1-to-2: enabled, 0 fee
1843 // chan6 2-to-1: enabled, 0 fee
1845 // chan7 1-to-2: enabled, 100% fee
1846 // chan7 2-to-1: enabled, 0 fee
1848 // chan8 1-to-2: enabled, variable fee (0 then 1000 msat)
1849 // chan8 2-to-1: enabled, 0 fee
1851 // chan9 1-to-2: enabled, 1001 msat fee
1852 // chan9 2-to-1: enabled, 0 fee
1854 // chan10 1-to-2: enabled, 0 fee
1855 // chan10 2-to-1: enabled, 0 fee
1857 // chan11 1-to-2: enabled, 0 fee
1858 // chan11 2-to-1: enabled, 0 fee
1860 let (our_privkey, _, privkeys, _) = get_nodes(&secp_ctx);
1862 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[0], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
1863 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1864 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1865 short_channel_id: 1,
1868 cltv_expiry_delta: 0,
1869 htlc_minimum_msat: 0,
1870 htlc_maximum_msat: OptionalField::Absent,
1872 fee_proportional_millionths: 0,
1873 excess_data: Vec::new()
1876 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
1878 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
1879 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1880 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1881 short_channel_id: 2,
1884 cltv_expiry_delta: (5 << 4) | 3,
1885 htlc_minimum_msat: 0,
1886 htlc_maximum_msat: OptionalField::Absent,
1887 fee_base_msat: u32::max_value(),
1888 fee_proportional_millionths: u32::max_value(),
1889 excess_data: Vec::new()
1891 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1892 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1893 short_channel_id: 2,
1896 cltv_expiry_delta: 0,
1897 htlc_minimum_msat: 0,
1898 htlc_maximum_msat: OptionalField::Absent,
1900 fee_proportional_millionths: 0,
1901 excess_data: Vec::new()
1904 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
1906 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[7], ChannelFeatures::from_le_bytes(id_to_feature_flags(12)), 12);
1907 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1908 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1909 short_channel_id: 12,
1912 cltv_expiry_delta: (5 << 4) | 3,
1913 htlc_minimum_msat: 0,
1914 htlc_maximum_msat: OptionalField::Absent,
1915 fee_base_msat: u32::max_value(),
1916 fee_proportional_millionths: u32::max_value(),
1917 excess_data: Vec::new()
1919 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1920 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1921 short_channel_id: 12,
1924 cltv_expiry_delta: 0,
1925 htlc_minimum_msat: 0,
1926 htlc_maximum_msat: OptionalField::Absent,
1928 fee_proportional_millionths: 0,
1929 excess_data: Vec::new()
1932 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], NodeFeatures::from_le_bytes(id_to_feature_flags(8)), 0);
1934 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
1935 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1936 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1937 short_channel_id: 3,
1940 cltv_expiry_delta: (3 << 4) | 1,
1941 htlc_minimum_msat: 0,
1942 htlc_maximum_msat: OptionalField::Absent,
1944 fee_proportional_millionths: 0,
1945 excess_data: Vec::new()
1947 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1948 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1949 short_channel_id: 3,
1952 cltv_expiry_delta: (3 << 4) | 2,
1953 htlc_minimum_msat: 0,
1954 htlc_maximum_msat: OptionalField::Absent,
1956 fee_proportional_millionths: 0,
1957 excess_data: Vec::new()
1960 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
1961 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1962 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1963 short_channel_id: 4,
1966 cltv_expiry_delta: (4 << 4) | 1,
1967 htlc_minimum_msat: 0,
1968 htlc_maximum_msat: OptionalField::Absent,
1970 fee_proportional_millionths: 1000000,
1971 excess_data: Vec::new()
1973 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1974 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1975 short_channel_id: 4,
1978 cltv_expiry_delta: (4 << 4) | 2,
1979 htlc_minimum_msat: 0,
1980 htlc_maximum_msat: OptionalField::Absent,
1982 fee_proportional_millionths: 0,
1983 excess_data: Vec::new()
1986 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(13)), 13);
1987 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1988 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1989 short_channel_id: 13,
1992 cltv_expiry_delta: (13 << 4) | 1,
1993 htlc_minimum_msat: 0,
1994 htlc_maximum_msat: OptionalField::Absent,
1996 fee_proportional_millionths: 2000000,
1997 excess_data: Vec::new()
1999 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2000 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2001 short_channel_id: 13,
2004 cltv_expiry_delta: (13 << 4) | 2,
2005 htlc_minimum_msat: 0,
2006 htlc_maximum_msat: OptionalField::Absent,
2008 fee_proportional_millionths: 0,
2009 excess_data: Vec::new()
2012 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
2014 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
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: 6,
2020 cltv_expiry_delta: (6 << 4) | 1,
2021 htlc_minimum_msat: 0,
2022 htlc_maximum_msat: OptionalField::Absent,
2024 fee_proportional_millionths: 0,
2025 excess_data: Vec::new()
2027 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
2028 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2029 short_channel_id: 6,
2032 cltv_expiry_delta: (6 << 4) | 2,
2033 htlc_minimum_msat: 0,
2034 htlc_maximum_msat: OptionalField::Absent,
2036 fee_proportional_millionths: 0,
2037 excess_data: Vec::new(),
2040 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(11)), 11);
2041 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
2042 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2043 short_channel_id: 11,
2046 cltv_expiry_delta: (11 << 4) | 1,
2047 htlc_minimum_msat: 0,
2048 htlc_maximum_msat: OptionalField::Absent,
2050 fee_proportional_millionths: 0,
2051 excess_data: Vec::new()
2053 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
2054 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2055 short_channel_id: 11,
2058 cltv_expiry_delta: (11 << 4) | 2,
2059 htlc_minimum_msat: 0,
2060 htlc_maximum_msat: OptionalField::Absent,
2062 fee_proportional_millionths: 0,
2063 excess_data: Vec::new()
2066 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(5)), 0);
2068 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
2070 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[5], ChannelFeatures::from_le_bytes(id_to_feature_flags(7)), 7);
2071 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2072 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2073 short_channel_id: 7,
2076 cltv_expiry_delta: (7 << 4) | 1,
2077 htlc_minimum_msat: 0,
2078 htlc_maximum_msat: OptionalField::Absent,
2080 fee_proportional_millionths: 1000000,
2081 excess_data: Vec::new()
2083 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[5], UnsignedChannelUpdate {
2084 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2085 short_channel_id: 7,
2088 cltv_expiry_delta: (7 << 4) | 2,
2089 htlc_minimum_msat: 0,
2090 htlc_maximum_msat: OptionalField::Absent,
2092 fee_proportional_millionths: 0,
2093 excess_data: Vec::new()
2096 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[5], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
2098 (secp_ctx, network_graph, net_graph_msg_handler, chain_monitor, logger)
2102 fn simple_route_test() {
2103 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2104 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2105 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2106 let scorer = test_utils::TestScorer::with_penalty(0);
2107 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2108 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2110 // Simple route to 2 via 1
2112 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) {
2113 assert_eq!(err, "Cannot send a payment of 0 msat");
2114 } else { panic!(); }
2116 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2117 assert_eq!(route.paths[0].len(), 2);
2119 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2120 assert_eq!(route.paths[0][0].short_channel_id, 2);
2121 assert_eq!(route.paths[0][0].fee_msat, 100);
2122 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2123 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2124 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2126 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2127 assert_eq!(route.paths[0][1].short_channel_id, 4);
2128 assert_eq!(route.paths[0][1].fee_msat, 100);
2129 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2130 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2131 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2135 fn invalid_first_hop_test() {
2136 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2137 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2138 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2139 let scorer = test_utils::TestScorer::with_penalty(0);
2140 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2141 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2143 // Simple route to 2 via 1
2145 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
2147 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) =
2148 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) {
2149 assert_eq!(err, "First hop cannot have our_node_pubkey as a destination.");
2150 } else { panic!(); }
2152 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2153 assert_eq!(route.paths[0].len(), 2);
2157 fn htlc_minimum_test() {
2158 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2159 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2160 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2161 let scorer = test_utils::TestScorer::with_penalty(0);
2162 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2163 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2165 // Simple route to 2 via 1
2167 // Disable other paths
2168 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2169 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2170 short_channel_id: 12,
2172 flags: 2, // to disable
2173 cltv_expiry_delta: 0,
2174 htlc_minimum_msat: 0,
2175 htlc_maximum_msat: OptionalField::Absent,
2177 fee_proportional_millionths: 0,
2178 excess_data: Vec::new()
2180 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2181 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2182 short_channel_id: 3,
2184 flags: 2, // to disable
2185 cltv_expiry_delta: 0,
2186 htlc_minimum_msat: 0,
2187 htlc_maximum_msat: OptionalField::Absent,
2189 fee_proportional_millionths: 0,
2190 excess_data: Vec::new()
2192 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2193 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2194 short_channel_id: 13,
2196 flags: 2, // to disable
2197 cltv_expiry_delta: 0,
2198 htlc_minimum_msat: 0,
2199 htlc_maximum_msat: OptionalField::Absent,
2201 fee_proportional_millionths: 0,
2202 excess_data: Vec::new()
2204 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2205 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2206 short_channel_id: 6,
2208 flags: 2, // to disable
2209 cltv_expiry_delta: 0,
2210 htlc_minimum_msat: 0,
2211 htlc_maximum_msat: OptionalField::Absent,
2213 fee_proportional_millionths: 0,
2214 excess_data: Vec::new()
2216 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2217 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2218 short_channel_id: 7,
2220 flags: 2, // to disable
2221 cltv_expiry_delta: 0,
2222 htlc_minimum_msat: 0,
2223 htlc_maximum_msat: OptionalField::Absent,
2225 fee_proportional_millionths: 0,
2226 excess_data: Vec::new()
2229 // Check against amount_to_transfer_over_msat.
2230 // Set minimal HTLC of 200_000_000 msat.
2231 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2232 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2233 short_channel_id: 2,
2236 cltv_expiry_delta: 0,
2237 htlc_minimum_msat: 200_000_000,
2238 htlc_maximum_msat: OptionalField::Absent,
2240 fee_proportional_millionths: 0,
2241 excess_data: Vec::new()
2244 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
2246 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2247 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2248 short_channel_id: 4,
2251 cltv_expiry_delta: 0,
2252 htlc_minimum_msat: 0,
2253 htlc_maximum_msat: OptionalField::Present(199_999_999),
2255 fee_proportional_millionths: 0,
2256 excess_data: Vec::new()
2259 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
2260 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) {
2261 assert_eq!(err, "Failed to find a path to the given destination");
2262 } else { panic!(); }
2264 // Lift the restriction on the first hop.
2265 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2266 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2267 short_channel_id: 2,
2270 cltv_expiry_delta: 0,
2271 htlc_minimum_msat: 0,
2272 htlc_maximum_msat: OptionalField::Absent,
2274 fee_proportional_millionths: 0,
2275 excess_data: Vec::new()
2278 // A payment above the minimum should pass
2279 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();
2280 assert_eq!(route.paths[0].len(), 2);
2284 fn htlc_minimum_overpay_test() {
2285 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2286 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2287 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
2288 let scorer = test_utils::TestScorer::with_penalty(0);
2289 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2290 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2292 // A route to node#2 via two paths.
2293 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
2294 // Thus, they can't send 60 without overpaying.
2295 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2296 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2297 short_channel_id: 2,
2300 cltv_expiry_delta: 0,
2301 htlc_minimum_msat: 35_000,
2302 htlc_maximum_msat: OptionalField::Present(40_000),
2304 fee_proportional_millionths: 0,
2305 excess_data: Vec::new()
2307 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2308 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2309 short_channel_id: 12,
2312 cltv_expiry_delta: 0,
2313 htlc_minimum_msat: 35_000,
2314 htlc_maximum_msat: OptionalField::Present(40_000),
2316 fee_proportional_millionths: 0,
2317 excess_data: Vec::new()
2321 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2322 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2323 short_channel_id: 13,
2326 cltv_expiry_delta: 0,
2327 htlc_minimum_msat: 0,
2328 htlc_maximum_msat: OptionalField::Absent,
2330 fee_proportional_millionths: 0,
2331 excess_data: Vec::new()
2333 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2334 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2335 short_channel_id: 4,
2338 cltv_expiry_delta: 0,
2339 htlc_minimum_msat: 0,
2340 htlc_maximum_msat: OptionalField::Absent,
2342 fee_proportional_millionths: 0,
2343 excess_data: Vec::new()
2346 // Disable other paths
2347 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2348 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2349 short_channel_id: 1,
2351 flags: 2, // to disable
2352 cltv_expiry_delta: 0,
2353 htlc_minimum_msat: 0,
2354 htlc_maximum_msat: OptionalField::Absent,
2356 fee_proportional_millionths: 0,
2357 excess_data: Vec::new()
2360 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 60_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2361 // Overpay fees to hit htlc_minimum_msat.
2362 let overpaid_fees = route.paths[0][0].fee_msat + route.paths[1][0].fee_msat;
2363 // TODO: this could be better balanced to overpay 10k and not 15k.
2364 assert_eq!(overpaid_fees, 15_000);
2366 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
2367 // while taking even more fee to match htlc_minimum_msat.
2368 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2369 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2370 short_channel_id: 12,
2373 cltv_expiry_delta: 0,
2374 htlc_minimum_msat: 65_000,
2375 htlc_maximum_msat: OptionalField::Present(80_000),
2377 fee_proportional_millionths: 0,
2378 excess_data: Vec::new()
2380 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2381 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2382 short_channel_id: 2,
2385 cltv_expiry_delta: 0,
2386 htlc_minimum_msat: 0,
2387 htlc_maximum_msat: OptionalField::Absent,
2389 fee_proportional_millionths: 0,
2390 excess_data: Vec::new()
2392 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2393 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2394 short_channel_id: 4,
2397 cltv_expiry_delta: 0,
2398 htlc_minimum_msat: 0,
2399 htlc_maximum_msat: OptionalField::Absent,
2401 fee_proportional_millionths: 100_000,
2402 excess_data: Vec::new()
2405 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 60_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2406 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
2407 assert_eq!(route.paths.len(), 1);
2408 assert_eq!(route.paths[0][0].short_channel_id, 12);
2409 let fees = route.paths[0][0].fee_msat;
2410 assert_eq!(fees, 5_000);
2412 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2413 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
2414 // the other channel.
2415 assert_eq!(route.paths.len(), 1);
2416 assert_eq!(route.paths[0][0].short_channel_id, 2);
2417 let fees = route.paths[0][0].fee_msat;
2418 assert_eq!(fees, 5_000);
2422 fn disable_channels_test() {
2423 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2424 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2425 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2426 let scorer = test_utils::TestScorer::with_penalty(0);
2427 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2428 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2430 // // Disable channels 4 and 12 by flags=2
2431 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2432 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2433 short_channel_id: 4,
2435 flags: 2, // to disable
2436 cltv_expiry_delta: 0,
2437 htlc_minimum_msat: 0,
2438 htlc_maximum_msat: OptionalField::Absent,
2440 fee_proportional_millionths: 0,
2441 excess_data: Vec::new()
2443 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2444 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2445 short_channel_id: 12,
2447 flags: 2, // to disable
2448 cltv_expiry_delta: 0,
2449 htlc_minimum_msat: 0,
2450 htlc_maximum_msat: OptionalField::Absent,
2452 fee_proportional_millionths: 0,
2453 excess_data: Vec::new()
2456 // If all the channels require some features we don't understand, route should fail
2457 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) {
2458 assert_eq!(err, "Failed to find a path to the given destination");
2459 } else { panic!(); }
2461 // If we specify a channel to node7, that overrides our local channel view and that gets used
2462 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2463 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();
2464 assert_eq!(route.paths[0].len(), 2);
2466 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2467 assert_eq!(route.paths[0][0].short_channel_id, 42);
2468 assert_eq!(route.paths[0][0].fee_msat, 200);
2469 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2470 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2471 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2473 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2474 assert_eq!(route.paths[0][1].short_channel_id, 13);
2475 assert_eq!(route.paths[0][1].fee_msat, 100);
2476 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2477 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2478 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2482 fn disable_node_test() {
2483 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2484 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2485 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2486 let scorer = test_utils::TestScorer::with_penalty(0);
2487 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2488 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2490 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
2491 let unknown_features = NodeFeatures::known().set_unknown_feature_required();
2492 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
2493 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
2494 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
2496 // If all nodes require some features we don't understand, route should fail
2497 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
2498 assert_eq!(err, "Failed to find a path to the given destination");
2499 } else { panic!(); }
2501 // If we specify a channel to node7, that overrides our local channel view and that gets used
2502 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2503 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&our_chans.iter().collect::<Vec<_>>()), 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2504 assert_eq!(route.paths[0].len(), 2);
2506 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2507 assert_eq!(route.paths[0][0].short_channel_id, 42);
2508 assert_eq!(route.paths[0][0].fee_msat, 200);
2509 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2510 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2511 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2513 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2514 assert_eq!(route.paths[0][1].short_channel_id, 13);
2515 assert_eq!(route.paths[0][1].fee_msat, 100);
2516 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2517 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2518 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2520 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
2521 // naively) assume that the user checked the feature bits on the invoice, which override
2522 // the node_announcement.
2526 fn our_chans_test() {
2527 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2528 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2529 let scorer = test_utils::TestScorer::with_penalty(0);
2530 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2531 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2533 // Route to 1 via 2 and 3 because our channel to 1 is disabled
2534 let payment_params = PaymentParameters::from_node_id(nodes[0]);
2535 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2536 assert_eq!(route.paths[0].len(), 3);
2538 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2539 assert_eq!(route.paths[0][0].short_channel_id, 2);
2540 assert_eq!(route.paths[0][0].fee_msat, 200);
2541 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2542 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2543 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2545 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2546 assert_eq!(route.paths[0][1].short_channel_id, 4);
2547 assert_eq!(route.paths[0][1].fee_msat, 100);
2548 assert_eq!(route.paths[0][1].cltv_expiry_delta, (3 << 4) | 2);
2549 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2550 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2552 assert_eq!(route.paths[0][2].pubkey, nodes[0]);
2553 assert_eq!(route.paths[0][2].short_channel_id, 3);
2554 assert_eq!(route.paths[0][2].fee_msat, 100);
2555 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
2556 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(1));
2557 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(3));
2559 // If we specify a channel to node7, that overrides our local channel view and that gets used
2560 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2561 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2562 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();
2563 assert_eq!(route.paths[0].len(), 2);
2565 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2566 assert_eq!(route.paths[0][0].short_channel_id, 42);
2567 assert_eq!(route.paths[0][0].fee_msat, 200);
2568 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2569 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2570 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2572 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2573 assert_eq!(route.paths[0][1].short_channel_id, 13);
2574 assert_eq!(route.paths[0][1].fee_msat, 100);
2575 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2576 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2577 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2580 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2581 let zero_fees = RoutingFees {
2583 proportional_millionths: 0,
2585 vec![RouteHint(vec![RouteHintHop {
2586 src_node_id: nodes[3],
2587 short_channel_id: 8,
2589 cltv_expiry_delta: (8 << 4) | 1,
2590 htlc_minimum_msat: None,
2591 htlc_maximum_msat: None,
2593 ]), RouteHint(vec![RouteHintHop {
2594 src_node_id: nodes[4],
2595 short_channel_id: 9,
2598 proportional_millionths: 0,
2600 cltv_expiry_delta: (9 << 4) | 1,
2601 htlc_minimum_msat: None,
2602 htlc_maximum_msat: None,
2603 }]), RouteHint(vec![RouteHintHop {
2604 src_node_id: nodes[5],
2605 short_channel_id: 10,
2607 cltv_expiry_delta: (10 << 4) | 1,
2608 htlc_minimum_msat: None,
2609 htlc_maximum_msat: None,
2613 fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2614 let zero_fees = RoutingFees {
2616 proportional_millionths: 0,
2618 vec![RouteHint(vec![RouteHintHop {
2619 src_node_id: nodes[2],
2620 short_channel_id: 5,
2623 proportional_millionths: 0,
2625 cltv_expiry_delta: (5 << 4) | 1,
2626 htlc_minimum_msat: None,
2627 htlc_maximum_msat: None,
2629 src_node_id: nodes[3],
2630 short_channel_id: 8,
2632 cltv_expiry_delta: (8 << 4) | 1,
2633 htlc_minimum_msat: None,
2634 htlc_maximum_msat: None,
2636 ]), RouteHint(vec![RouteHintHop {
2637 src_node_id: nodes[4],
2638 short_channel_id: 9,
2641 proportional_millionths: 0,
2643 cltv_expiry_delta: (9 << 4) | 1,
2644 htlc_minimum_msat: None,
2645 htlc_maximum_msat: None,
2646 }]), RouteHint(vec![RouteHintHop {
2647 src_node_id: nodes[5],
2648 short_channel_id: 10,
2650 cltv_expiry_delta: (10 << 4) | 1,
2651 htlc_minimum_msat: None,
2652 htlc_maximum_msat: None,
2657 fn partial_route_hint_test() {
2658 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2659 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2660 let scorer = test_utils::TestScorer::with_penalty(0);
2661 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2662 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2664 // Simple test across 2, 3, 5, and 4 via a last_hop channel
2665 // Tests the behaviour when the RouteHint contains a suboptimal hop.
2666 // RouteHint may be partially used by the algo to build the best path.
2668 // First check that last hop can't have its source as the payee.
2669 let invalid_last_hop = RouteHint(vec![RouteHintHop {
2670 src_node_id: nodes[6],
2671 short_channel_id: 8,
2674 proportional_millionths: 0,
2676 cltv_expiry_delta: (8 << 4) | 1,
2677 htlc_minimum_msat: None,
2678 htlc_maximum_msat: None,
2681 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
2682 invalid_last_hops.push(invalid_last_hop);
2684 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(invalid_last_hops);
2685 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) {
2686 assert_eq!(err, "Route hint cannot have the payee as the source.");
2687 } else { panic!(); }
2690 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops_multi_private_channels(&nodes));
2691 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2692 assert_eq!(route.paths[0].len(), 5);
2694 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2695 assert_eq!(route.paths[0][0].short_channel_id, 2);
2696 assert_eq!(route.paths[0][0].fee_msat, 100);
2697 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2698 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2699 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2701 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2702 assert_eq!(route.paths[0][1].short_channel_id, 4);
2703 assert_eq!(route.paths[0][1].fee_msat, 0);
2704 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
2705 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2706 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2708 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2709 assert_eq!(route.paths[0][2].short_channel_id, 6);
2710 assert_eq!(route.paths[0][2].fee_msat, 0);
2711 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
2712 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2713 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2715 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2716 assert_eq!(route.paths[0][3].short_channel_id, 11);
2717 assert_eq!(route.paths[0][3].fee_msat, 0);
2718 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
2719 // If we have a peer in the node map, we'll use their features here since we don't have
2720 // a way of figuring out their features from the invoice:
2721 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2722 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2724 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2725 assert_eq!(route.paths[0][4].short_channel_id, 8);
2726 assert_eq!(route.paths[0][4].fee_msat, 100);
2727 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2728 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2729 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2732 fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2733 let zero_fees = RoutingFees {
2735 proportional_millionths: 0,
2737 vec![RouteHint(vec![RouteHintHop {
2738 src_node_id: nodes[3],
2739 short_channel_id: 8,
2741 cltv_expiry_delta: (8 << 4) | 1,
2742 htlc_minimum_msat: None,
2743 htlc_maximum_msat: None,
2744 }]), RouteHint(vec![
2746 ]), RouteHint(vec![RouteHintHop {
2747 src_node_id: nodes[5],
2748 short_channel_id: 10,
2750 cltv_expiry_delta: (10 << 4) | 1,
2751 htlc_minimum_msat: None,
2752 htlc_maximum_msat: None,
2757 fn ignores_empty_last_hops_test() {
2758 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2759 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2760 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(empty_last_hop(&nodes));
2761 let scorer = test_utils::TestScorer::with_penalty(0);
2762 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2763 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2765 // Test handling of an empty RouteHint passed in Invoice.
2767 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2768 assert_eq!(route.paths[0].len(), 5);
2770 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2771 assert_eq!(route.paths[0][0].short_channel_id, 2);
2772 assert_eq!(route.paths[0][0].fee_msat, 100);
2773 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2774 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2775 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2777 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2778 assert_eq!(route.paths[0][1].short_channel_id, 4);
2779 assert_eq!(route.paths[0][1].fee_msat, 0);
2780 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
2781 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2782 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2784 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2785 assert_eq!(route.paths[0][2].short_channel_id, 6);
2786 assert_eq!(route.paths[0][2].fee_msat, 0);
2787 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
2788 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2789 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2791 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2792 assert_eq!(route.paths[0][3].short_channel_id, 11);
2793 assert_eq!(route.paths[0][3].fee_msat, 0);
2794 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
2795 // If we have a peer in the node map, we'll use their features here since we don't have
2796 // a way of figuring out their features from the invoice:
2797 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2798 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2800 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2801 assert_eq!(route.paths[0][4].short_channel_id, 8);
2802 assert_eq!(route.paths[0][4].fee_msat, 100);
2803 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2804 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2805 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2808 /// Builds a trivial last-hop hint that passes through the two nodes given, with channel 0xff00
2810 fn multi_hop_last_hops_hint(hint_hops: [PublicKey; 2]) -> Vec<RouteHint> {
2811 let zero_fees = RoutingFees {
2813 proportional_millionths: 0,
2815 vec![RouteHint(vec![RouteHintHop {
2816 src_node_id: hint_hops[0],
2817 short_channel_id: 0xff00,
2820 proportional_millionths: 0,
2822 cltv_expiry_delta: (5 << 4) | 1,
2823 htlc_minimum_msat: None,
2824 htlc_maximum_msat: None,
2826 src_node_id: hint_hops[1],
2827 short_channel_id: 0xff01,
2829 cltv_expiry_delta: (8 << 4) | 1,
2830 htlc_minimum_msat: None,
2831 htlc_maximum_msat: None,
2836 fn multi_hint_last_hops_test() {
2837 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2838 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2839 let last_hops = multi_hop_last_hops_hint([nodes[2], nodes[3]]);
2840 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops.clone());
2841 let scorer = test_utils::TestScorer::with_penalty(0);
2842 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2843 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2844 // Test through channels 2, 3, 0xff00, 0xff01.
2845 // Test shows that multiple hop hints are considered.
2847 // Disabling channels 6 & 7 by flags=2
2848 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2849 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2850 short_channel_id: 6,
2852 flags: 2, // to disable
2853 cltv_expiry_delta: 0,
2854 htlc_minimum_msat: 0,
2855 htlc_maximum_msat: OptionalField::Absent,
2857 fee_proportional_millionths: 0,
2858 excess_data: Vec::new()
2860 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2861 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2862 short_channel_id: 7,
2864 flags: 2, // to disable
2865 cltv_expiry_delta: 0,
2866 htlc_minimum_msat: 0,
2867 htlc_maximum_msat: OptionalField::Absent,
2869 fee_proportional_millionths: 0,
2870 excess_data: Vec::new()
2873 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2874 assert_eq!(route.paths[0].len(), 4);
2876 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2877 assert_eq!(route.paths[0][0].short_channel_id, 2);
2878 assert_eq!(route.paths[0][0].fee_msat, 200);
2879 assert_eq!(route.paths[0][0].cltv_expiry_delta, 65);
2880 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2881 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2883 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2884 assert_eq!(route.paths[0][1].short_channel_id, 4);
2885 assert_eq!(route.paths[0][1].fee_msat, 100);
2886 assert_eq!(route.paths[0][1].cltv_expiry_delta, 81);
2887 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2888 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2890 assert_eq!(route.paths[0][2].pubkey, nodes[3]);
2891 assert_eq!(route.paths[0][2].short_channel_id, last_hops[0].0[0].short_channel_id);
2892 assert_eq!(route.paths[0][2].fee_msat, 0);
2893 assert_eq!(route.paths[0][2].cltv_expiry_delta, 129);
2894 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(4));
2895 assert_eq!(route.paths[0][2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2897 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2898 assert_eq!(route.paths[0][3].short_channel_id, last_hops[0].0[1].short_channel_id);
2899 assert_eq!(route.paths[0][3].fee_msat, 100);
2900 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2901 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2902 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2906 fn private_multi_hint_last_hops_test() {
2907 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2908 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2910 let non_announced_privkey = SecretKey::from_slice(&hex::decode(format!("{:02x}", 0xf0).repeat(32)).unwrap()[..]).unwrap();
2911 let non_announced_pubkey = PublicKey::from_secret_key(&secp_ctx, &non_announced_privkey);
2913 let last_hops = multi_hop_last_hops_hint([nodes[2], non_announced_pubkey]);
2914 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops.clone());
2915 let scorer = test_utils::TestScorer::with_penalty(0);
2916 // Test through channels 2, 3, 0xff00, 0xff01.
2917 // Test shows that multiple hop hints are considered.
2919 // Disabling channels 6 & 7 by flags=2
2920 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2921 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2922 short_channel_id: 6,
2924 flags: 2, // to disable
2925 cltv_expiry_delta: 0,
2926 htlc_minimum_msat: 0,
2927 htlc_maximum_msat: OptionalField::Absent,
2929 fee_proportional_millionths: 0,
2930 excess_data: Vec::new()
2932 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2933 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2934 short_channel_id: 7,
2936 flags: 2, // to disable
2937 cltv_expiry_delta: 0,
2938 htlc_minimum_msat: 0,
2939 htlc_maximum_msat: OptionalField::Absent,
2941 fee_proportional_millionths: 0,
2942 excess_data: Vec::new()
2945 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &[42u8; 32]).unwrap();
2946 assert_eq!(route.paths[0].len(), 4);
2948 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2949 assert_eq!(route.paths[0][0].short_channel_id, 2);
2950 assert_eq!(route.paths[0][0].fee_msat, 200);
2951 assert_eq!(route.paths[0][0].cltv_expiry_delta, 65);
2952 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2953 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2955 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2956 assert_eq!(route.paths[0][1].short_channel_id, 4);
2957 assert_eq!(route.paths[0][1].fee_msat, 100);
2958 assert_eq!(route.paths[0][1].cltv_expiry_delta, 81);
2959 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2960 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2962 assert_eq!(route.paths[0][2].pubkey, non_announced_pubkey);
2963 assert_eq!(route.paths[0][2].short_channel_id, last_hops[0].0[0].short_channel_id);
2964 assert_eq!(route.paths[0][2].fee_msat, 0);
2965 assert_eq!(route.paths[0][2].cltv_expiry_delta, 129);
2966 assert_eq!(route.paths[0][2].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2967 assert_eq!(route.paths[0][2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2969 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2970 assert_eq!(route.paths[0][3].short_channel_id, last_hops[0].0[1].short_channel_id);
2971 assert_eq!(route.paths[0][3].fee_msat, 100);
2972 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2973 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2974 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2977 fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2978 let zero_fees = RoutingFees {
2980 proportional_millionths: 0,
2982 vec![RouteHint(vec![RouteHintHop {
2983 src_node_id: nodes[4],
2984 short_channel_id: 11,
2986 cltv_expiry_delta: (11 << 4) | 1,
2987 htlc_minimum_msat: None,
2988 htlc_maximum_msat: None,
2990 src_node_id: nodes[3],
2991 short_channel_id: 8,
2993 cltv_expiry_delta: (8 << 4) | 1,
2994 htlc_minimum_msat: None,
2995 htlc_maximum_msat: None,
2996 }]), RouteHint(vec![RouteHintHop {
2997 src_node_id: nodes[4],
2998 short_channel_id: 9,
3001 proportional_millionths: 0,
3003 cltv_expiry_delta: (9 << 4) | 1,
3004 htlc_minimum_msat: None,
3005 htlc_maximum_msat: None,
3006 }]), RouteHint(vec![RouteHintHop {
3007 src_node_id: nodes[5],
3008 short_channel_id: 10,
3010 cltv_expiry_delta: (10 << 4) | 1,
3011 htlc_minimum_msat: None,
3012 htlc_maximum_msat: None,
3017 fn last_hops_with_public_channel_test() {
3018 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3019 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3020 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops_with_public_channel(&nodes));
3021 let scorer = test_utils::TestScorer::with_penalty(0);
3022 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3023 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3024 // This test shows that public routes can be present in the invoice
3025 // which would be handled in the same manner.
3027 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3028 assert_eq!(route.paths[0].len(), 5);
3030 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3031 assert_eq!(route.paths[0][0].short_channel_id, 2);
3032 assert_eq!(route.paths[0][0].fee_msat, 100);
3033 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
3034 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3035 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3037 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3038 assert_eq!(route.paths[0][1].short_channel_id, 4);
3039 assert_eq!(route.paths[0][1].fee_msat, 0);
3040 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
3041 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3042 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3044 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
3045 assert_eq!(route.paths[0][2].short_channel_id, 6);
3046 assert_eq!(route.paths[0][2].fee_msat, 0);
3047 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
3048 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
3049 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
3051 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
3052 assert_eq!(route.paths[0][3].short_channel_id, 11);
3053 assert_eq!(route.paths[0][3].fee_msat, 0);
3054 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
3055 // If we have a peer in the node map, we'll use their features here since we don't have
3056 // a way of figuring out their features from the invoice:
3057 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
3058 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
3060 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
3061 assert_eq!(route.paths[0][4].short_channel_id, 8);
3062 assert_eq!(route.paths[0][4].fee_msat, 100);
3063 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
3064 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
3065 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3069 fn our_chans_last_hop_connect_test() {
3070 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3071 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3072 let scorer = test_utils::TestScorer::with_penalty(0);
3073 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3074 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3076 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
3077 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3078 let mut last_hops = last_hops(&nodes);
3079 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops.clone());
3080 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();
3081 assert_eq!(route.paths[0].len(), 2);
3083 assert_eq!(route.paths[0][0].pubkey, nodes[3]);
3084 assert_eq!(route.paths[0][0].short_channel_id, 42);
3085 assert_eq!(route.paths[0][0].fee_msat, 0);
3086 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 4) | 1);
3087 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
3088 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3090 assert_eq!(route.paths[0][1].pubkey, nodes[6]);
3091 assert_eq!(route.paths[0][1].short_channel_id, 8);
3092 assert_eq!(route.paths[0][1].fee_msat, 100);
3093 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
3094 assert_eq!(route.paths[0][1].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
3095 assert_eq!(route.paths[0][1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3097 last_hops[0].0[0].fees.base_msat = 1000;
3099 // Revert to via 6 as the fee on 8 goes up
3100 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops);
3101 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3102 assert_eq!(route.paths[0].len(), 4);
3104 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3105 assert_eq!(route.paths[0][0].short_channel_id, 2);
3106 assert_eq!(route.paths[0][0].fee_msat, 200); // fee increased as its % of value transferred across node
3107 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
3108 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3109 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3111 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3112 assert_eq!(route.paths[0][1].short_channel_id, 4);
3113 assert_eq!(route.paths[0][1].fee_msat, 100);
3114 assert_eq!(route.paths[0][1].cltv_expiry_delta, (7 << 4) | 1);
3115 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3116 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3118 assert_eq!(route.paths[0][2].pubkey, nodes[5]);
3119 assert_eq!(route.paths[0][2].short_channel_id, 7);
3120 assert_eq!(route.paths[0][2].fee_msat, 0);
3121 assert_eq!(route.paths[0][2].cltv_expiry_delta, (10 << 4) | 1);
3122 // If we have a peer in the node map, we'll use their features here since we don't have
3123 // a way of figuring out their features from the invoice:
3124 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
3125 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(7));
3127 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
3128 assert_eq!(route.paths[0][3].short_channel_id, 10);
3129 assert_eq!(route.paths[0][3].fee_msat, 100);
3130 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
3131 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
3132 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3134 // ...but still use 8 for larger payments as 6 has a variable feerate
3135 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 2000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3136 assert_eq!(route.paths[0].len(), 5);
3138 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3139 assert_eq!(route.paths[0][0].short_channel_id, 2);
3140 assert_eq!(route.paths[0][0].fee_msat, 3000);
3141 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
3142 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3143 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3145 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3146 assert_eq!(route.paths[0][1].short_channel_id, 4);
3147 assert_eq!(route.paths[0][1].fee_msat, 0);
3148 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
3149 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3150 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3152 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
3153 assert_eq!(route.paths[0][2].short_channel_id, 6);
3154 assert_eq!(route.paths[0][2].fee_msat, 0);
3155 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
3156 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
3157 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
3159 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
3160 assert_eq!(route.paths[0][3].short_channel_id, 11);
3161 assert_eq!(route.paths[0][3].fee_msat, 1000);
3162 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
3163 // If we have a peer in the node map, we'll use their features here since we don't have
3164 // a way of figuring out their features from the invoice:
3165 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
3166 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
3168 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
3169 assert_eq!(route.paths[0][4].short_channel_id, 8);
3170 assert_eq!(route.paths[0][4].fee_msat, 2000);
3171 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
3172 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
3173 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3176 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> {
3177 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
3178 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3179 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3181 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
3182 let last_hops = RouteHint(vec![RouteHintHop {
3183 src_node_id: middle_node_id,
3184 short_channel_id: 8,
3187 proportional_millionths: last_hop_fee_prop,
3189 cltv_expiry_delta: (8 << 4) | 1,
3190 htlc_minimum_msat: None,
3191 htlc_maximum_msat: last_hop_htlc_max,
3193 let payment_params = PaymentParameters::from_node_id(target_node_id).with_route_hints(vec![last_hops]);
3194 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
3195 let scorer = test_utils::TestScorer::with_penalty(0);
3196 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3197 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3198 get_route(&source_node_id, &payment_params, &NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash()).read_only(),
3199 Some(&our_chans.iter().collect::<Vec<_>>()), route_val, 42, &test_utils::TestLogger::new(), &scorer, &random_seed_bytes)
3203 fn unannounced_path_test() {
3204 // We should be able to send a payment to a destination without any help of a routing graph
3205 // if we have a channel with a common counterparty that appears in the first and last hop
3207 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
3209 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3210 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3211 assert_eq!(route.paths[0].len(), 2);
3213 assert_eq!(route.paths[0][0].pubkey, middle_node_id);
3214 assert_eq!(route.paths[0][0].short_channel_id, 42);
3215 assert_eq!(route.paths[0][0].fee_msat, 1001);
3216 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 4) | 1);
3217 assert_eq!(route.paths[0][0].node_features.le_flags(), &[0b11]);
3218 assert_eq!(route.paths[0][0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3220 assert_eq!(route.paths[0][1].pubkey, target_node_id);
3221 assert_eq!(route.paths[0][1].short_channel_id, 8);
3222 assert_eq!(route.paths[0][1].fee_msat, 1000000);
3223 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
3224 assert_eq!(route.paths[0][1].node_features.le_flags(), &[0; 0]); // We dont pass flags in from invoices yet
3225 assert_eq!(route.paths[0][1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3229 fn overflow_unannounced_path_test_liquidity_underflow() {
3230 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
3231 // the last-hop had a fee which overflowed a u64, we'd panic.
3232 // This was due to us adding the first-hop from us unconditionally, causing us to think
3233 // we'd built a path (as our node is in the "best candidate" set), when we had not.
3234 // In this test, we previously hit a subtraction underflow due to having less available
3235 // liquidity at the last hop than 0.
3236 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());
3240 fn overflow_unannounced_path_test_feerate_overflow() {
3241 // This tests for the same case as above, except instead of hitting a subtraction
3242 // underflow, we hit a case where the fee charged at a hop overflowed.
3243 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());
3247 fn available_amount_while_routing_test() {
3248 // Tests whether we choose the correct available channel amount while routing.
3250 let (secp_ctx, network_graph, mut net_graph_msg_handler, chain_monitor, logger) = build_graph();
3251 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3252 let scorer = test_utils::TestScorer::with_penalty(0);
3253 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3254 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3255 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
3257 // We will use a simple single-path route from
3258 // our node to node2 via node0: channels {1, 3}.
3260 // First disable all other paths.
3261 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3262 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3263 short_channel_id: 2,
3266 cltv_expiry_delta: 0,
3267 htlc_minimum_msat: 0,
3268 htlc_maximum_msat: OptionalField::Present(100_000),
3270 fee_proportional_millionths: 0,
3271 excess_data: Vec::new()
3273 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3274 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3275 short_channel_id: 12,
3278 cltv_expiry_delta: 0,
3279 htlc_minimum_msat: 0,
3280 htlc_maximum_msat: OptionalField::Present(100_000),
3282 fee_proportional_millionths: 0,
3283 excess_data: Vec::new()
3286 // Make the first channel (#1) very permissive,
3287 // and we will be testing all limits on the second channel.
3288 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3289 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3290 short_channel_id: 1,
3293 cltv_expiry_delta: 0,
3294 htlc_minimum_msat: 0,
3295 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3297 fee_proportional_millionths: 0,
3298 excess_data: Vec::new()
3301 // First, let's see if routing works if we have absolutely no idea about the available amount.
3302 // In this case, it should be set to 250_000 sats.
3303 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3304 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3305 short_channel_id: 3,
3308 cltv_expiry_delta: 0,
3309 htlc_minimum_msat: 0,
3310 htlc_maximum_msat: OptionalField::Absent,
3312 fee_proportional_millionths: 0,
3313 excess_data: Vec::new()
3317 // Attempt to route more than available results in a failure.
3318 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3319 &our_id, &payment_params, &network_graph.read_only(), None, 250_000_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3320 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3321 } else { panic!(); }
3325 // Now, attempt to route an exact amount we have should be fine.
3326 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();
3327 assert_eq!(route.paths.len(), 1);
3328 let path = route.paths.last().unwrap();
3329 assert_eq!(path.len(), 2);
3330 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3331 assert_eq!(path.last().unwrap().fee_msat, 250_000_000);
3334 // Check that setting outbound_capacity_msat in first_hops limits the channels.
3335 // Disable channel #1 and use another first hop.
3336 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3337 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3338 short_channel_id: 1,
3341 cltv_expiry_delta: 0,
3342 htlc_minimum_msat: 0,
3343 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3345 fee_proportional_millionths: 0,
3346 excess_data: Vec::new()
3349 // Now, limit the first_hop by the outbound_capacity_msat of 200_000 sats.
3350 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
3353 // Attempt to route more than available results in a failure.
3354 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3355 &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) {
3356 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3357 } else { panic!(); }
3361 // Now, attempt to route an exact amount we have should be fine.
3362 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();
3363 assert_eq!(route.paths.len(), 1);
3364 let path = route.paths.last().unwrap();
3365 assert_eq!(path.len(), 2);
3366 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3367 assert_eq!(path.last().unwrap().fee_msat, 200_000_000);
3370 // Enable channel #1 back.
3371 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3372 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3373 short_channel_id: 1,
3376 cltv_expiry_delta: 0,
3377 htlc_minimum_msat: 0,
3378 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3380 fee_proportional_millionths: 0,
3381 excess_data: Vec::new()
3385 // Now let's see if routing works if we know only htlc_maximum_msat.
3386 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3387 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3388 short_channel_id: 3,
3391 cltv_expiry_delta: 0,
3392 htlc_minimum_msat: 0,
3393 htlc_maximum_msat: OptionalField::Present(15_000),
3395 fee_proportional_millionths: 0,
3396 excess_data: Vec::new()
3400 // Attempt to route more than available results in a failure.
3401 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3402 &our_id, &payment_params, &network_graph.read_only(), None, 15_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3403 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3404 } else { panic!(); }
3408 // Now, attempt to route an exact amount we have should be fine.
3409 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 15_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3410 assert_eq!(route.paths.len(), 1);
3411 let path = route.paths.last().unwrap();
3412 assert_eq!(path.len(), 2);
3413 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3414 assert_eq!(path.last().unwrap().fee_msat, 15_000);
3417 // Now let's see if routing works if we know only capacity from the UTXO.
3419 // We can't change UTXO capacity on the fly, so we'll disable
3420 // the existing channel and add another one with the capacity we need.
3421 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3422 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3423 short_channel_id: 3,
3426 cltv_expiry_delta: 0,
3427 htlc_minimum_msat: 0,
3428 htlc_maximum_msat: OptionalField::Absent,
3430 fee_proportional_millionths: 0,
3431 excess_data: Vec::new()
3434 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
3435 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
3436 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
3437 .push_opcode(opcodes::all::OP_PUSHNUM_2)
3438 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
3440 *chain_monitor.utxo_ret.lock().unwrap() = Ok(TxOut { value: 15, script_pubkey: good_script.clone() });
3441 net_graph_msg_handler.add_chain_access(Some(chain_monitor));
3443 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
3444 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3445 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3446 short_channel_id: 333,
3449 cltv_expiry_delta: (3 << 4) | 1,
3450 htlc_minimum_msat: 0,
3451 htlc_maximum_msat: OptionalField::Absent,
3453 fee_proportional_millionths: 0,
3454 excess_data: Vec::new()
3456 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3457 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3458 short_channel_id: 333,
3461 cltv_expiry_delta: (3 << 4) | 2,
3462 htlc_minimum_msat: 0,
3463 htlc_maximum_msat: OptionalField::Absent,
3465 fee_proportional_millionths: 0,
3466 excess_data: Vec::new()
3470 // Attempt to route more than available results in a failure.
3471 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3472 &our_id, &payment_params, &network_graph.read_only(), None, 15_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3473 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3474 } else { panic!(); }
3478 // Now, attempt to route an exact amount we have should be fine.
3479 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 15_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3480 assert_eq!(route.paths.len(), 1);
3481 let path = route.paths.last().unwrap();
3482 assert_eq!(path.len(), 2);
3483 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3484 assert_eq!(path.last().unwrap().fee_msat, 15_000);
3487 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
3488 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3489 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3490 short_channel_id: 333,
3493 cltv_expiry_delta: 0,
3494 htlc_minimum_msat: 0,
3495 htlc_maximum_msat: OptionalField::Present(10_000),
3497 fee_proportional_millionths: 0,
3498 excess_data: Vec::new()
3502 // Attempt to route more than available results in a failure.
3503 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3504 &our_id, &payment_params, &network_graph.read_only(), None, 10_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3505 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3506 } else { panic!(); }
3510 // Now, attempt to route an exact amount we have should be fine.
3511 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 10_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3512 assert_eq!(route.paths.len(), 1);
3513 let path = route.paths.last().unwrap();
3514 assert_eq!(path.len(), 2);
3515 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3516 assert_eq!(path.last().unwrap().fee_msat, 10_000);
3521 fn available_liquidity_last_hop_test() {
3522 // Check that available liquidity properly limits the path even when only
3523 // one of the latter hops is limited.
3524 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3525 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3526 let scorer = test_utils::TestScorer::with_penalty(0);
3527 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3528 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3529 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
3531 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3532 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
3533 // Total capacity: 50 sats.
3535 // Disable other potential paths.
3536 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3537 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3538 short_channel_id: 2,
3541 cltv_expiry_delta: 0,
3542 htlc_minimum_msat: 0,
3543 htlc_maximum_msat: OptionalField::Present(100_000),
3545 fee_proportional_millionths: 0,
3546 excess_data: Vec::new()
3548 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3549 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3550 short_channel_id: 7,
3553 cltv_expiry_delta: 0,
3554 htlc_minimum_msat: 0,
3555 htlc_maximum_msat: OptionalField::Present(100_000),
3557 fee_proportional_millionths: 0,
3558 excess_data: Vec::new()
3563 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3564 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3565 short_channel_id: 12,
3568 cltv_expiry_delta: 0,
3569 htlc_minimum_msat: 0,
3570 htlc_maximum_msat: OptionalField::Present(100_000),
3572 fee_proportional_millionths: 0,
3573 excess_data: Vec::new()
3575 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3576 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3577 short_channel_id: 13,
3580 cltv_expiry_delta: 0,
3581 htlc_minimum_msat: 0,
3582 htlc_maximum_msat: OptionalField::Present(100_000),
3584 fee_proportional_millionths: 0,
3585 excess_data: Vec::new()
3588 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3589 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3590 short_channel_id: 6,
3593 cltv_expiry_delta: 0,
3594 htlc_minimum_msat: 0,
3595 htlc_maximum_msat: OptionalField::Present(50_000),
3597 fee_proportional_millionths: 0,
3598 excess_data: Vec::new()
3600 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3601 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3602 short_channel_id: 11,
3605 cltv_expiry_delta: 0,
3606 htlc_minimum_msat: 0,
3607 htlc_maximum_msat: OptionalField::Present(100_000),
3609 fee_proportional_millionths: 0,
3610 excess_data: Vec::new()
3613 // Attempt to route more than available results in a failure.
3614 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3615 &our_id, &payment_params, &network_graph.read_only(), None, 60_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3616 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3617 } else { panic!(); }
3621 // Now, attempt to route 49 sats (just a bit below the capacity).
3622 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 49_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3623 assert_eq!(route.paths.len(), 1);
3624 let mut total_amount_paid_msat = 0;
3625 for path in &route.paths {
3626 assert_eq!(path.len(), 4);
3627 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3628 total_amount_paid_msat += path.last().unwrap().fee_msat;
3630 assert_eq!(total_amount_paid_msat, 49_000);
3634 // Attempt to route an exact amount is also fine
3635 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3636 assert_eq!(route.paths.len(), 1);
3637 let mut total_amount_paid_msat = 0;
3638 for path in &route.paths {
3639 assert_eq!(path.len(), 4);
3640 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3641 total_amount_paid_msat += path.last().unwrap().fee_msat;
3643 assert_eq!(total_amount_paid_msat, 50_000);
3648 fn ignore_fee_first_hop_test() {
3649 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3650 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3651 let scorer = test_utils::TestScorer::with_penalty(0);
3652 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3653 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3654 let payment_params = PaymentParameters::from_node_id(nodes[2]);
3656 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3657 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3658 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3659 short_channel_id: 1,
3662 cltv_expiry_delta: 0,
3663 htlc_minimum_msat: 0,
3664 htlc_maximum_msat: OptionalField::Present(100_000),
3665 fee_base_msat: 1_000_000,
3666 fee_proportional_millionths: 0,
3667 excess_data: Vec::new()
3669 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3670 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3671 short_channel_id: 3,
3674 cltv_expiry_delta: 0,
3675 htlc_minimum_msat: 0,
3676 htlc_maximum_msat: OptionalField::Present(50_000),
3678 fee_proportional_millionths: 0,
3679 excess_data: Vec::new()
3683 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3684 assert_eq!(route.paths.len(), 1);
3685 let mut total_amount_paid_msat = 0;
3686 for path in &route.paths {
3687 assert_eq!(path.len(), 2);
3688 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3689 total_amount_paid_msat += path.last().unwrap().fee_msat;
3691 assert_eq!(total_amount_paid_msat, 50_000);
3696 fn simple_mpp_route_test() {
3697 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3698 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3699 let scorer = test_utils::TestScorer::with_penalty(0);
3700 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3701 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3702 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
3704 // We need a route consisting of 3 paths:
3705 // From our node to node2 via node0, node7, node1 (three paths one hop each).
3706 // To achieve this, the amount being transferred should be around
3707 // the total capacity of these 3 paths.
3709 // First, we set limits on these (previously unlimited) channels.
3710 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
3712 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3713 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3714 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3715 short_channel_id: 1,
3718 cltv_expiry_delta: 0,
3719 htlc_minimum_msat: 0,
3720 htlc_maximum_msat: OptionalField::Present(100_000),
3722 fee_proportional_millionths: 0,
3723 excess_data: Vec::new()
3725 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3726 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3727 short_channel_id: 3,
3730 cltv_expiry_delta: 0,
3731 htlc_minimum_msat: 0,
3732 htlc_maximum_msat: OptionalField::Present(50_000),
3734 fee_proportional_millionths: 0,
3735 excess_data: Vec::new()
3738 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
3739 // (total limit 60).
3740 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3741 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3742 short_channel_id: 12,
3745 cltv_expiry_delta: 0,
3746 htlc_minimum_msat: 0,
3747 htlc_maximum_msat: OptionalField::Present(60_000),
3749 fee_proportional_millionths: 0,
3750 excess_data: Vec::new()
3752 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3753 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3754 short_channel_id: 13,
3757 cltv_expiry_delta: 0,
3758 htlc_minimum_msat: 0,
3759 htlc_maximum_msat: OptionalField::Present(60_000),
3761 fee_proportional_millionths: 0,
3762 excess_data: Vec::new()
3765 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
3766 // (total capacity 180 sats).
3767 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3768 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3769 short_channel_id: 2,
3772 cltv_expiry_delta: 0,
3773 htlc_minimum_msat: 0,
3774 htlc_maximum_msat: OptionalField::Present(200_000),
3776 fee_proportional_millionths: 0,
3777 excess_data: Vec::new()
3779 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3780 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3781 short_channel_id: 4,
3784 cltv_expiry_delta: 0,
3785 htlc_minimum_msat: 0,
3786 htlc_maximum_msat: OptionalField::Present(180_000),
3788 fee_proportional_millionths: 0,
3789 excess_data: Vec::new()
3793 // Attempt to route more than available results in a failure.
3794 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3795 &our_id, &payment_params, &network_graph.read_only(), None, 300_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3796 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3797 } else { panic!(); }
3801 // Now, attempt to route 250 sats (just a bit below the capacity).
3802 // Our algorithm should provide us with these 3 paths.
3803 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 250_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3804 assert_eq!(route.paths.len(), 3);
3805 let mut total_amount_paid_msat = 0;
3806 for path in &route.paths {
3807 assert_eq!(path.len(), 2);
3808 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3809 total_amount_paid_msat += path.last().unwrap().fee_msat;
3811 assert_eq!(total_amount_paid_msat, 250_000);
3815 // Attempt to route an exact amount is also fine
3816 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 290_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3817 assert_eq!(route.paths.len(), 3);
3818 let mut total_amount_paid_msat = 0;
3819 for path in &route.paths {
3820 assert_eq!(path.len(), 2);
3821 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3822 total_amount_paid_msat += path.last().unwrap().fee_msat;
3824 assert_eq!(total_amount_paid_msat, 290_000);
3829 fn long_mpp_route_test() {
3830 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3831 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3832 let scorer = test_utils::TestScorer::with_penalty(0);
3833 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3834 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3835 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
3837 // We need a route consisting of 3 paths:
3838 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3839 // Note that these paths overlap (channels 5, 12, 13).
3840 // We will route 300 sats.
3841 // Each path will have 100 sats capacity, those channels which
3842 // are used twice will have 200 sats capacity.
3844 // Disable other potential paths.
3845 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3846 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3847 short_channel_id: 2,
3850 cltv_expiry_delta: 0,
3851 htlc_minimum_msat: 0,
3852 htlc_maximum_msat: OptionalField::Present(100_000),
3854 fee_proportional_millionths: 0,
3855 excess_data: Vec::new()
3857 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3858 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3859 short_channel_id: 7,
3862 cltv_expiry_delta: 0,
3863 htlc_minimum_msat: 0,
3864 htlc_maximum_msat: OptionalField::Present(100_000),
3866 fee_proportional_millionths: 0,
3867 excess_data: Vec::new()
3870 // Path via {node0, node2} is channels {1, 3, 5}.
3871 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3872 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3873 short_channel_id: 1,
3876 cltv_expiry_delta: 0,
3877 htlc_minimum_msat: 0,
3878 htlc_maximum_msat: OptionalField::Present(100_000),
3880 fee_proportional_millionths: 0,
3881 excess_data: Vec::new()
3883 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3884 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3885 short_channel_id: 3,
3888 cltv_expiry_delta: 0,
3889 htlc_minimum_msat: 0,
3890 htlc_maximum_msat: OptionalField::Present(100_000),
3892 fee_proportional_millionths: 0,
3893 excess_data: Vec::new()
3896 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3897 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3898 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3899 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3900 short_channel_id: 5,
3903 cltv_expiry_delta: 0,
3904 htlc_minimum_msat: 0,
3905 htlc_maximum_msat: OptionalField::Present(200_000),
3907 fee_proportional_millionths: 0,
3908 excess_data: Vec::new()
3911 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3912 // Add 100 sats to the capacities of {12, 13}, because these channels
3913 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3914 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3915 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3916 short_channel_id: 12,
3919 cltv_expiry_delta: 0,
3920 htlc_minimum_msat: 0,
3921 htlc_maximum_msat: OptionalField::Present(200_000),
3923 fee_proportional_millionths: 0,
3924 excess_data: Vec::new()
3926 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3927 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3928 short_channel_id: 13,
3931 cltv_expiry_delta: 0,
3932 htlc_minimum_msat: 0,
3933 htlc_maximum_msat: OptionalField::Present(200_000),
3935 fee_proportional_millionths: 0,
3936 excess_data: Vec::new()
3939 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3940 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3941 short_channel_id: 6,
3944 cltv_expiry_delta: 0,
3945 htlc_minimum_msat: 0,
3946 htlc_maximum_msat: OptionalField::Present(100_000),
3948 fee_proportional_millionths: 0,
3949 excess_data: Vec::new()
3951 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3952 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3953 short_channel_id: 11,
3956 cltv_expiry_delta: 0,
3957 htlc_minimum_msat: 0,
3958 htlc_maximum_msat: OptionalField::Present(100_000),
3960 fee_proportional_millionths: 0,
3961 excess_data: Vec::new()
3964 // Path via {node7, node2} is channels {12, 13, 5}.
3965 // We already limited them to 200 sats (they are used twice for 100 sats).
3966 // Nothing to do here.
3969 // Attempt to route more than available results in a failure.
3970 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3971 &our_id, &payment_params, &network_graph.read_only(), None, 350_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3972 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3973 } else { panic!(); }
3977 // Now, attempt to route 300 sats (exact amount we can route).
3978 // Our algorithm should provide us with these 3 paths, 100 sats each.
3979 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 300_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3980 assert_eq!(route.paths.len(), 3);
3982 let mut total_amount_paid_msat = 0;
3983 for path in &route.paths {
3984 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3985 total_amount_paid_msat += path.last().unwrap().fee_msat;
3987 assert_eq!(total_amount_paid_msat, 300_000);
3993 fn mpp_cheaper_route_test() {
3994 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3995 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3996 let scorer = test_utils::TestScorer::with_penalty(0);
3997 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3998 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3999 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
4001 // This test checks that if we have two cheaper paths and one more expensive path,
4002 // so that liquidity-wise any 2 of 3 combination is sufficient,
4003 // two cheaper paths will be taken.
4004 // These paths have equal available liquidity.
4006 // We need a combination of 3 paths:
4007 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
4008 // Note that these paths overlap (channels 5, 12, 13).
4009 // Each path will have 100 sats capacity, those channels which
4010 // are used twice will have 200 sats capacity.
4012 // Disable other potential paths.
4013 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4014 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4015 short_channel_id: 2,
4018 cltv_expiry_delta: 0,
4019 htlc_minimum_msat: 0,
4020 htlc_maximum_msat: OptionalField::Present(100_000),
4022 fee_proportional_millionths: 0,
4023 excess_data: Vec::new()
4025 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4026 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4027 short_channel_id: 7,
4030 cltv_expiry_delta: 0,
4031 htlc_minimum_msat: 0,
4032 htlc_maximum_msat: OptionalField::Present(100_000),
4034 fee_proportional_millionths: 0,
4035 excess_data: Vec::new()
4038 // Path via {node0, node2} is channels {1, 3, 5}.
4039 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4040 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4041 short_channel_id: 1,
4044 cltv_expiry_delta: 0,
4045 htlc_minimum_msat: 0,
4046 htlc_maximum_msat: OptionalField::Present(100_000),
4048 fee_proportional_millionths: 0,
4049 excess_data: Vec::new()
4051 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4052 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4053 short_channel_id: 3,
4056 cltv_expiry_delta: 0,
4057 htlc_minimum_msat: 0,
4058 htlc_maximum_msat: OptionalField::Present(100_000),
4060 fee_proportional_millionths: 0,
4061 excess_data: Vec::new()
4064 // Capacity of 200 sats because this channel will be used by 3rd path as well.
4065 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4066 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4067 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4068 short_channel_id: 5,
4071 cltv_expiry_delta: 0,
4072 htlc_minimum_msat: 0,
4073 htlc_maximum_msat: OptionalField::Present(200_000),
4075 fee_proportional_millionths: 0,
4076 excess_data: Vec::new()
4079 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4080 // Add 100 sats to the capacities of {12, 13}, because these channels
4081 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
4082 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4083 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4084 short_channel_id: 12,
4087 cltv_expiry_delta: 0,
4088 htlc_minimum_msat: 0,
4089 htlc_maximum_msat: OptionalField::Present(200_000),
4091 fee_proportional_millionths: 0,
4092 excess_data: Vec::new()
4094 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4095 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4096 short_channel_id: 13,
4099 cltv_expiry_delta: 0,
4100 htlc_minimum_msat: 0,
4101 htlc_maximum_msat: OptionalField::Present(200_000),
4103 fee_proportional_millionths: 0,
4104 excess_data: Vec::new()
4107 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4108 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4109 short_channel_id: 6,
4112 cltv_expiry_delta: 0,
4113 htlc_minimum_msat: 0,
4114 htlc_maximum_msat: OptionalField::Present(100_000),
4115 fee_base_msat: 1_000,
4116 fee_proportional_millionths: 0,
4117 excess_data: Vec::new()
4119 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4120 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4121 short_channel_id: 11,
4124 cltv_expiry_delta: 0,
4125 htlc_minimum_msat: 0,
4126 htlc_maximum_msat: OptionalField::Present(100_000),
4128 fee_proportional_millionths: 0,
4129 excess_data: Vec::new()
4132 // Path via {node7, node2} is channels {12, 13, 5}.
4133 // We already limited them to 200 sats (they are used twice for 100 sats).
4134 // Nothing to do here.
4137 // Now, attempt to route 180 sats.
4138 // Our algorithm should provide us with these 2 paths.
4139 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 180_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4140 assert_eq!(route.paths.len(), 2);
4142 let mut total_value_transferred_msat = 0;
4143 let mut total_paid_msat = 0;
4144 for path in &route.paths {
4145 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
4146 total_value_transferred_msat += path.last().unwrap().fee_msat;
4148 total_paid_msat += hop.fee_msat;
4151 // If we paid fee, this would be higher.
4152 assert_eq!(total_value_transferred_msat, 180_000);
4153 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
4154 assert_eq!(total_fees_paid, 0);
4159 fn fees_on_mpp_route_test() {
4160 // This test makes sure that MPP algorithm properly takes into account
4161 // fees charged on the channels, by making the fees impactful:
4162 // if the fee is not properly accounted for, the behavior is different.
4163 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4164 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4165 let scorer = test_utils::TestScorer::with_penalty(0);
4166 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4167 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4168 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
4170 // We need a route consisting of 2 paths:
4171 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
4172 // We will route 200 sats, Each path will have 100 sats capacity.
4174 // This test is not particularly stable: e.g.,
4175 // there's a way to route via {node0, node2, node4}.
4176 // It works while pathfinding is deterministic, but can be broken otherwise.
4177 // It's fine to ignore this concern for now.
4179 // Disable other potential paths.
4180 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4181 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4182 short_channel_id: 2,
4185 cltv_expiry_delta: 0,
4186 htlc_minimum_msat: 0,
4187 htlc_maximum_msat: OptionalField::Present(100_000),
4189 fee_proportional_millionths: 0,
4190 excess_data: Vec::new()
4193 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4194 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4195 short_channel_id: 7,
4198 cltv_expiry_delta: 0,
4199 htlc_minimum_msat: 0,
4200 htlc_maximum_msat: OptionalField::Present(100_000),
4202 fee_proportional_millionths: 0,
4203 excess_data: Vec::new()
4206 // Path via {node0, node2} is channels {1, 3, 5}.
4207 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4208 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4209 short_channel_id: 1,
4212 cltv_expiry_delta: 0,
4213 htlc_minimum_msat: 0,
4214 htlc_maximum_msat: OptionalField::Present(100_000),
4216 fee_proportional_millionths: 0,
4217 excess_data: Vec::new()
4219 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4220 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4221 short_channel_id: 3,
4224 cltv_expiry_delta: 0,
4225 htlc_minimum_msat: 0,
4226 htlc_maximum_msat: OptionalField::Present(100_000),
4228 fee_proportional_millionths: 0,
4229 excess_data: Vec::new()
4232 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4233 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4234 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4235 short_channel_id: 5,
4238 cltv_expiry_delta: 0,
4239 htlc_minimum_msat: 0,
4240 htlc_maximum_msat: OptionalField::Present(100_000),
4242 fee_proportional_millionths: 0,
4243 excess_data: Vec::new()
4246 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4247 // All channels should be 100 sats capacity. But for the fee experiment,
4248 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
4249 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
4250 // 100 sats (and pay 150 sats in fees for the use of channel 6),
4251 // so no matter how large are other channels,
4252 // the whole path will be limited by 100 sats with just these 2 conditions:
4253 // - channel 12 capacity is 250 sats
4254 // - fee for channel 6 is 150 sats
4255 // Let's test this by enforcing these 2 conditions and removing other limits.
4256 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4257 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4258 short_channel_id: 12,
4261 cltv_expiry_delta: 0,
4262 htlc_minimum_msat: 0,
4263 htlc_maximum_msat: OptionalField::Present(250_000),
4265 fee_proportional_millionths: 0,
4266 excess_data: Vec::new()
4268 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4269 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4270 short_channel_id: 13,
4273 cltv_expiry_delta: 0,
4274 htlc_minimum_msat: 0,
4275 htlc_maximum_msat: OptionalField::Absent,
4277 fee_proportional_millionths: 0,
4278 excess_data: Vec::new()
4281 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4282 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4283 short_channel_id: 6,
4286 cltv_expiry_delta: 0,
4287 htlc_minimum_msat: 0,
4288 htlc_maximum_msat: OptionalField::Absent,
4289 fee_base_msat: 150_000,
4290 fee_proportional_millionths: 0,
4291 excess_data: Vec::new()
4293 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4294 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4295 short_channel_id: 11,
4298 cltv_expiry_delta: 0,
4299 htlc_minimum_msat: 0,
4300 htlc_maximum_msat: OptionalField::Absent,
4302 fee_proportional_millionths: 0,
4303 excess_data: Vec::new()
4307 // Attempt to route more than available results in a failure.
4308 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4309 &our_id, &payment_params, &network_graph.read_only(), None, 210_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
4310 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4311 } else { panic!(); }
4315 // Now, attempt to route 200 sats (exact amount we can route).
4316 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 200_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4317 assert_eq!(route.paths.len(), 2);
4319 let mut total_amount_paid_msat = 0;
4320 for path in &route.paths {
4321 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
4322 total_amount_paid_msat += path.last().unwrap().fee_msat;
4324 assert_eq!(total_amount_paid_msat, 200_000);
4325 assert_eq!(route.get_total_fees(), 150_000);
4330 fn mpp_with_last_hops() {
4331 // Previously, if we tried to send an MPP payment to a destination which was only reachable
4332 // via a single last-hop route hint, we'd fail to route if we first collected routes
4333 // totaling close but not quite enough to fund the full payment.
4335 // This was because we considered last-hop hints to have exactly the sought payment amount
4336 // instead of the amount we were trying to collect, needlessly limiting our path searching
4337 // at the very first hop.
4339 // Specifically, this interacted with our "all paths must fund at least 5% of total target"
4340 // criterion to cause us to refuse all routes at the last hop hint which would be considered
4341 // to only have the remaining to-collect amount in available liquidity.
4343 // This bug appeared in production in some specific channel configurations.
4344 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4345 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4346 let scorer = test_utils::TestScorer::with_penalty(0);
4347 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4348 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4349 let payment_params = PaymentParameters::from_node_id(PublicKey::from_slice(&[02; 33]).unwrap()).with_features(InvoiceFeatures::known())
4350 .with_route_hints(vec![RouteHint(vec![RouteHintHop {
4351 src_node_id: nodes[2],
4352 short_channel_id: 42,
4353 fees: RoutingFees { base_msat: 0, proportional_millionths: 0 },
4354 cltv_expiry_delta: 42,
4355 htlc_minimum_msat: None,
4356 htlc_maximum_msat: None,
4359 // Keep only two paths from us to nodes[2], both with a 99sat HTLC maximum, with one with
4360 // no fee and one with a 1msat fee. Previously, trying to route 100 sats to nodes[2] here
4361 // would first use the no-fee route and then fail to find a path along the second route as
4362 // we think we can only send up to 1 additional sat over the last-hop but refuse to as its
4363 // under 5% of our payment amount.
4364 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4365 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4366 short_channel_id: 1,
4369 cltv_expiry_delta: (5 << 4) | 5,
4370 htlc_minimum_msat: 0,
4371 htlc_maximum_msat: OptionalField::Present(99_000),
4372 fee_base_msat: u32::max_value(),
4373 fee_proportional_millionths: u32::max_value(),
4374 excess_data: Vec::new()
4376 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4377 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4378 short_channel_id: 2,
4381 cltv_expiry_delta: (5 << 4) | 3,
4382 htlc_minimum_msat: 0,
4383 htlc_maximum_msat: OptionalField::Present(99_000),
4384 fee_base_msat: u32::max_value(),
4385 fee_proportional_millionths: u32::max_value(),
4386 excess_data: Vec::new()
4388 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4389 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4390 short_channel_id: 4,
4393 cltv_expiry_delta: (4 << 4) | 1,
4394 htlc_minimum_msat: 0,
4395 htlc_maximum_msat: OptionalField::Absent,
4397 fee_proportional_millionths: 0,
4398 excess_data: Vec::new()
4400 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4401 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4402 short_channel_id: 13,
4404 flags: 0|2, // Channel disabled
4405 cltv_expiry_delta: (13 << 4) | 1,
4406 htlc_minimum_msat: 0,
4407 htlc_maximum_msat: OptionalField::Absent,
4409 fee_proportional_millionths: 2000000,
4410 excess_data: Vec::new()
4413 // Get a route for 100 sats and check that we found the MPP route no problem and didn't
4415 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4416 assert_eq!(route.paths.len(), 2);
4417 // Paths are somewhat randomly ordered, but:
4418 // * the first is channel 2 (1 msat fee) -> channel 4 -> channel 42
4419 // * the second is channel 1 (0 fee, but 99 sat maximum) -> channel 3 -> channel 42
4420 assert_eq!(route.paths[0][0].short_channel_id, 2);
4421 assert_eq!(route.paths[0][0].fee_msat, 1);
4422 assert_eq!(route.paths[0][2].fee_msat, 1_000);
4423 assert_eq!(route.paths[1][0].short_channel_id, 1);
4424 assert_eq!(route.paths[1][0].fee_msat, 0);
4425 assert_eq!(route.paths[1][2].fee_msat, 99_000);
4426 assert_eq!(route.get_total_fees(), 1);
4427 assert_eq!(route.get_total_amount(), 100_000);
4431 fn drop_lowest_channel_mpp_route_test() {
4432 // This test checks that low-capacity channel is dropped when after
4433 // path finding we realize that we found more capacity than we need.
4434 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4435 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4436 let scorer = test_utils::TestScorer::with_penalty(0);
4437 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4438 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4439 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
4441 // We need a route consisting of 3 paths:
4442 // From our node to node2 via node0, node7, node1 (three paths one hop each).
4444 // The first and the second paths should be sufficient, but the third should be
4445 // cheaper, so that we select it but drop later.
4447 // First, we set limits on these (previously unlimited) channels.
4448 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
4450 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
4451 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4452 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4453 short_channel_id: 1,
4456 cltv_expiry_delta: 0,
4457 htlc_minimum_msat: 0,
4458 htlc_maximum_msat: OptionalField::Present(100_000),
4460 fee_proportional_millionths: 0,
4461 excess_data: Vec::new()
4463 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4464 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4465 short_channel_id: 3,
4468 cltv_expiry_delta: 0,
4469 htlc_minimum_msat: 0,
4470 htlc_maximum_msat: OptionalField::Present(50_000),
4472 fee_proportional_millionths: 0,
4473 excess_data: Vec::new()
4476 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
4477 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4478 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4479 short_channel_id: 12,
4482 cltv_expiry_delta: 0,
4483 htlc_minimum_msat: 0,
4484 htlc_maximum_msat: OptionalField::Present(60_000),
4486 fee_proportional_millionths: 0,
4487 excess_data: Vec::new()
4489 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4490 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4491 short_channel_id: 13,
4494 cltv_expiry_delta: 0,
4495 htlc_minimum_msat: 0,
4496 htlc_maximum_msat: OptionalField::Present(60_000),
4498 fee_proportional_millionths: 0,
4499 excess_data: Vec::new()
4502 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
4503 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4504 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4505 short_channel_id: 2,
4508 cltv_expiry_delta: 0,
4509 htlc_minimum_msat: 0,
4510 htlc_maximum_msat: OptionalField::Present(20_000),
4512 fee_proportional_millionths: 0,
4513 excess_data: Vec::new()
4515 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4516 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4517 short_channel_id: 4,
4520 cltv_expiry_delta: 0,
4521 htlc_minimum_msat: 0,
4522 htlc_maximum_msat: OptionalField::Present(20_000),
4524 fee_proportional_millionths: 0,
4525 excess_data: Vec::new()
4529 // Attempt to route more than available results in a failure.
4530 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4531 &our_id, &payment_params, &network_graph.read_only(), None, 150_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
4532 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4533 } else { panic!(); }
4537 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
4538 // Our algorithm should provide us with these 3 paths.
4539 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 125_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4540 assert_eq!(route.paths.len(), 3);
4541 let mut total_amount_paid_msat = 0;
4542 for path in &route.paths {
4543 assert_eq!(path.len(), 2);
4544 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4545 total_amount_paid_msat += path.last().unwrap().fee_msat;
4547 assert_eq!(total_amount_paid_msat, 125_000);
4551 // Attempt to route without the last small cheap channel
4552 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4553 assert_eq!(route.paths.len(), 2);
4554 let mut total_amount_paid_msat = 0;
4555 for path in &route.paths {
4556 assert_eq!(path.len(), 2);
4557 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4558 total_amount_paid_msat += path.last().unwrap().fee_msat;
4560 assert_eq!(total_amount_paid_msat, 90_000);
4565 fn min_criteria_consistency() {
4566 // Test that we don't use an inconsistent metric between updating and walking nodes during
4567 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
4568 // was updated with a different criterion from the heap sorting, resulting in loops in
4569 // calculated paths. We test for that specific case here.
4571 // We construct a network that looks like this:
4573 // node2 -1(3)2- node3
4577 // node1 -1(5)2- node4 -1(1)2- node6
4583 // We create a loop on the side of our real path - our destination is node 6, with a
4584 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
4585 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
4586 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
4587 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
4588 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
4589 // "previous hop" being set to node 3, creating a loop in the path.
4590 let secp_ctx = Secp256k1::new();
4591 let logger = Arc::new(test_utils::TestLogger::new());
4592 let network = Arc::new(NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash()));
4593 let net_graph_msg_handler = NetGraphMsgHandler::new(Arc::clone(&network), None, Arc::clone(&logger));
4594 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4595 let scorer = test_utils::TestScorer::with_penalty(0);
4596 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4597 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4598 let payment_params = PaymentParameters::from_node_id(nodes[6]);
4600 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
4601 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4602 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4603 short_channel_id: 6,
4606 cltv_expiry_delta: (6 << 4) | 0,
4607 htlc_minimum_msat: 0,
4608 htlc_maximum_msat: OptionalField::Absent,
4610 fee_proportional_millionths: 0,
4611 excess_data: Vec::new()
4613 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
4615 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4616 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4617 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4618 short_channel_id: 5,
4621 cltv_expiry_delta: (5 << 4) | 0,
4622 htlc_minimum_msat: 0,
4623 htlc_maximum_msat: OptionalField::Absent,
4625 fee_proportional_millionths: 0,
4626 excess_data: Vec::new()
4628 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
4630 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
4631 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4632 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4633 short_channel_id: 4,
4636 cltv_expiry_delta: (4 << 4) | 0,
4637 htlc_minimum_msat: 0,
4638 htlc_maximum_msat: OptionalField::Absent,
4640 fee_proportional_millionths: 0,
4641 excess_data: Vec::new()
4643 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
4645 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
4646 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
4647 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4648 short_channel_id: 3,
4651 cltv_expiry_delta: (3 << 4) | 0,
4652 htlc_minimum_msat: 0,
4653 htlc_maximum_msat: OptionalField::Absent,
4655 fee_proportional_millionths: 0,
4656 excess_data: Vec::new()
4658 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
4660 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
4661 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4662 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4663 short_channel_id: 2,
4666 cltv_expiry_delta: (2 << 4) | 0,
4667 htlc_minimum_msat: 0,
4668 htlc_maximum_msat: OptionalField::Absent,
4670 fee_proportional_millionths: 0,
4671 excess_data: Vec::new()
4674 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
4675 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4676 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4677 short_channel_id: 1,
4680 cltv_expiry_delta: (1 << 4) | 0,
4681 htlc_minimum_msat: 100,
4682 htlc_maximum_msat: OptionalField::Absent,
4684 fee_proportional_millionths: 0,
4685 excess_data: Vec::new()
4687 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
4690 // Now ensure the route flows simply over nodes 1 and 4 to 6.
4691 let route = get_route(&our_id, &payment_params, &network.read_only(), None, 10_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4692 assert_eq!(route.paths.len(), 1);
4693 assert_eq!(route.paths[0].len(), 3);
4695 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
4696 assert_eq!(route.paths[0][0].short_channel_id, 6);
4697 assert_eq!(route.paths[0][0].fee_msat, 100);
4698 assert_eq!(route.paths[0][0].cltv_expiry_delta, (5 << 4) | 0);
4699 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(1));
4700 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(6));
4702 assert_eq!(route.paths[0][1].pubkey, nodes[4]);
4703 assert_eq!(route.paths[0][1].short_channel_id, 5);
4704 assert_eq!(route.paths[0][1].fee_msat, 0);
4705 assert_eq!(route.paths[0][1].cltv_expiry_delta, (1 << 4) | 0);
4706 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(4));
4707 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(5));
4709 assert_eq!(route.paths[0][2].pubkey, nodes[6]);
4710 assert_eq!(route.paths[0][2].short_channel_id, 1);
4711 assert_eq!(route.paths[0][2].fee_msat, 10_000);
4712 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
4713 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
4714 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(1));
4720 fn exact_fee_liquidity_limit() {
4721 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
4722 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
4723 // we calculated fees on a higher value, resulting in us ignoring such paths.
4724 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4725 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
4726 let scorer = test_utils::TestScorer::with_penalty(0);
4727 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4728 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4729 let payment_params = PaymentParameters::from_node_id(nodes[2]);
4731 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
4733 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4734 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4735 short_channel_id: 2,
4738 cltv_expiry_delta: 0,
4739 htlc_minimum_msat: 0,
4740 htlc_maximum_msat: OptionalField::Present(85_000),
4742 fee_proportional_millionths: 0,
4743 excess_data: Vec::new()
4746 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4747 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4748 short_channel_id: 12,
4751 cltv_expiry_delta: (4 << 4) | 1,
4752 htlc_minimum_msat: 0,
4753 htlc_maximum_msat: OptionalField::Present(270_000),
4755 fee_proportional_millionths: 1000000,
4756 excess_data: Vec::new()
4760 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
4761 // 200% fee charged channel 13 in the 1-to-2 direction.
4762 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4763 assert_eq!(route.paths.len(), 1);
4764 assert_eq!(route.paths[0].len(), 2);
4766 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
4767 assert_eq!(route.paths[0][0].short_channel_id, 12);
4768 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
4769 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
4770 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
4771 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
4773 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
4774 assert_eq!(route.paths[0][1].short_channel_id, 13);
4775 assert_eq!(route.paths[0][1].fee_msat, 90_000);
4776 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
4777 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
4778 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
4783 fn htlc_max_reduction_below_min() {
4784 // Test that if, while walking the graph, we reduce the value being sent to meet an
4785 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
4786 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
4787 // resulting in us thinking there is no possible path, even if other paths exist.
4788 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4789 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4790 let scorer = test_utils::TestScorer::with_penalty(0);
4791 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4792 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4793 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
4795 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
4796 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
4797 // then try to send 90_000.
4798 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4799 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4800 short_channel_id: 2,
4803 cltv_expiry_delta: 0,
4804 htlc_minimum_msat: 0,
4805 htlc_maximum_msat: OptionalField::Present(80_000),
4807 fee_proportional_millionths: 0,
4808 excess_data: Vec::new()
4810 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4811 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4812 short_channel_id: 4,
4815 cltv_expiry_delta: (4 << 4) | 1,
4816 htlc_minimum_msat: 90_000,
4817 htlc_maximum_msat: OptionalField::Absent,
4819 fee_proportional_millionths: 0,
4820 excess_data: Vec::new()
4824 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
4825 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
4826 // expensive) channels 12-13 path.
4827 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4828 assert_eq!(route.paths.len(), 1);
4829 assert_eq!(route.paths[0].len(), 2);
4831 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
4832 assert_eq!(route.paths[0][0].short_channel_id, 12);
4833 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
4834 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
4835 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
4836 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
4838 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
4839 assert_eq!(route.paths[0][1].short_channel_id, 13);
4840 assert_eq!(route.paths[0][1].fee_msat, 90_000);
4841 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
4842 assert_eq!(route.paths[0][1].node_features.le_flags(), InvoiceFeatures::known().le_flags());
4843 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
4848 fn multiple_direct_first_hops() {
4849 // Previously we'd only ever considered one first hop path per counterparty.
4850 // However, as we don't restrict users to one channel per peer, we really need to support
4851 // looking at all first hop paths.
4852 // Here we test that we do not ignore all-but-the-last first hop paths per counterparty (as
4853 // we used to do by overwriting the `first_hop_targets` hashmap entry) and that we can MPP
4854 // route over multiple channels with the same first hop.
4855 let secp_ctx = Secp256k1::new();
4856 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4857 let logger = Arc::new(test_utils::TestLogger::new());
4858 let network_graph = NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash());
4859 let scorer = test_utils::TestScorer::with_penalty(0);
4860 let payment_params = PaymentParameters::from_node_id(nodes[0]).with_features(InvoiceFeatures::known());
4861 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4862 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4865 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
4866 &get_channel_details(Some(3), nodes[0], InitFeatures::known(), 200_000),
4867 &get_channel_details(Some(2), nodes[0], InitFeatures::known(), 10_000),
4868 ]), 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4869 assert_eq!(route.paths.len(), 1);
4870 assert_eq!(route.paths[0].len(), 1);
4872 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
4873 assert_eq!(route.paths[0][0].short_channel_id, 3);
4874 assert_eq!(route.paths[0][0].fee_msat, 100_000);
4877 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
4878 &get_channel_details(Some(3), nodes[0], InitFeatures::known(), 50_000),
4879 &get_channel_details(Some(2), nodes[0], InitFeatures::known(), 50_000),
4880 ]), 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4881 assert_eq!(route.paths.len(), 2);
4882 assert_eq!(route.paths[0].len(), 1);
4883 assert_eq!(route.paths[1].len(), 1);
4885 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
4886 assert_eq!(route.paths[0][0].short_channel_id, 3);
4887 assert_eq!(route.paths[0][0].fee_msat, 50_000);
4889 assert_eq!(route.paths[1][0].pubkey, nodes[0]);
4890 assert_eq!(route.paths[1][0].short_channel_id, 2);
4891 assert_eq!(route.paths[1][0].fee_msat, 50_000);
4896 fn prefers_shorter_route_with_higher_fees() {
4897 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4898 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4899 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
4901 // Without penalizing each hop 100 msats, a longer path with lower fees is chosen.
4902 let scorer = test_utils::TestScorer::with_penalty(0);
4903 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4904 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4905 let route = get_route(
4906 &our_id, &payment_params, &network_graph.read_only(), None, 100, 42,
4907 Arc::clone(&logger), &scorer, &random_seed_bytes
4909 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4911 assert_eq!(route.get_total_fees(), 100);
4912 assert_eq!(route.get_total_amount(), 100);
4913 assert_eq!(path, vec![2, 4, 6, 11, 8]);
4915 // Applying a 100 msat penalty to each hop results in taking channels 7 and 10 to nodes[6]
4916 // from nodes[2] rather than channel 6, 11, and 8, even though the longer path is cheaper.
4917 let scorer = test_utils::TestScorer::with_penalty(100);
4918 let route = get_route(
4919 &our_id, &payment_params, &network_graph.read_only(), None, 100, 42,
4920 Arc::clone(&logger), &scorer, &random_seed_bytes
4922 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4924 assert_eq!(route.get_total_fees(), 300);
4925 assert_eq!(route.get_total_amount(), 100);
4926 assert_eq!(path, vec![2, 4, 7, 10]);
4929 struct BadChannelScorer {
4930 short_channel_id: u64,
4934 impl Writeable for BadChannelScorer {
4935 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), ::io::Error> { unimplemented!() }
4937 impl Score for BadChannelScorer {
4938 fn channel_penalty_msat(&self, short_channel_id: u64, _send_amt: u64, _capacity_msat: u64, _source: &NodeId, _target: &NodeId) -> u64 {
4939 if short_channel_id == self.short_channel_id { u64::max_value() } else { 0 }
4942 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
4943 fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
4946 struct BadNodeScorer {
4951 impl Writeable for BadNodeScorer {
4952 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), ::io::Error> { unimplemented!() }
4955 impl Score for BadNodeScorer {
4956 fn channel_penalty_msat(&self, _short_channel_id: u64, _send_amt: u64, _capacity_msat: u64, _source: &NodeId, target: &NodeId) -> u64 {
4957 if *target == self.node_id { u64::max_value() } else { 0 }
4960 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
4961 fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
4965 fn avoids_routing_through_bad_channels_and_nodes() {
4966 let (secp_ctx, network, _, _, logger) = build_graph();
4967 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4968 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
4969 let network_graph = network.read_only();
4971 // A path to nodes[6] exists when no penalties are applied to any channel.
4972 let scorer = test_utils::TestScorer::with_penalty(0);
4973 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4974 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4975 let route = get_route(
4976 &our_id, &payment_params, &network_graph, None, 100, 42,
4977 Arc::clone(&logger), &scorer, &random_seed_bytes
4979 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4981 assert_eq!(route.get_total_fees(), 100);
4982 assert_eq!(route.get_total_amount(), 100);
4983 assert_eq!(path, vec![2, 4, 6, 11, 8]);
4985 // A different path to nodes[6] exists if channel 6 cannot be routed over.
4986 let scorer = BadChannelScorer { short_channel_id: 6 };
4987 let route = get_route(
4988 &our_id, &payment_params, &network_graph, None, 100, 42,
4989 Arc::clone(&logger), &scorer, &random_seed_bytes
4991 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4993 assert_eq!(route.get_total_fees(), 300);
4994 assert_eq!(route.get_total_amount(), 100);
4995 assert_eq!(path, vec![2, 4, 7, 10]);
4997 // A path to nodes[6] does not exist if nodes[2] cannot be routed through.
4998 let scorer = BadNodeScorer { node_id: NodeId::from_pubkey(&nodes[2]) };
5000 &our_id, &payment_params, &network_graph, None, 100, 42,
5001 Arc::clone(&logger), &scorer, &random_seed_bytes
5003 Err(LightningError { err, .. } ) => {
5004 assert_eq!(err, "Failed to find a path to the given destination");
5006 Ok(_) => panic!("Expected error"),
5011 fn total_fees_single_path() {
5015 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5016 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5017 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5020 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5021 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5022 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5025 pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
5026 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5027 short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0
5030 payment_params: None,
5033 assert_eq!(route.get_total_fees(), 250);
5034 assert_eq!(route.get_total_amount(), 225);
5038 fn total_fees_multi_path() {
5042 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5043 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5044 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5047 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5048 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5049 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5053 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5054 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5055 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5058 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5059 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5060 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5063 payment_params: None,
5066 assert_eq!(route.get_total_fees(), 200);
5067 assert_eq!(route.get_total_amount(), 300);
5071 fn total_empty_route_no_panic() {
5072 // In an earlier version of `Route::get_total_fees` and `Route::get_total_amount`, they
5073 // would both panic if the route was completely empty. We test to ensure they return 0
5074 // here, even though its somewhat nonsensical as a route.
5075 let route = Route { paths: Vec::new(), payment_params: None };
5077 assert_eq!(route.get_total_fees(), 0);
5078 assert_eq!(route.get_total_amount(), 0);
5082 fn limits_total_cltv_delta() {
5083 let (secp_ctx, network, _, _, logger) = build_graph();
5084 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5085 let network_graph = network.read_only();
5087 let scorer = test_utils::TestScorer::with_penalty(0);
5089 // Make sure that generally there is at least one route available
5090 let feasible_max_total_cltv_delta = 1008;
5091 let feasible_payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes))
5092 .with_max_total_cltv_expiry_delta(feasible_max_total_cltv_delta);
5093 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5094 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5095 let route = get_route(&our_id, &feasible_payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5096 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5097 assert_ne!(path.len(), 0);
5099 // But not if we exclude all paths on the basis of their accumulated CLTV delta
5100 let fail_max_total_cltv_delta = 23;
5101 let fail_payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes))
5102 .with_max_total_cltv_expiry_delta(fail_max_total_cltv_delta);
5103 match get_route(&our_id, &fail_payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes)
5105 Err(LightningError { err, .. } ) => {
5106 assert_eq!(err, "Failed to find a path to the given destination");
5108 Ok(_) => panic!("Expected error"),
5113 fn adds_and_limits_cltv_offset() {
5114 let (secp_ctx, network_graph, _, _, logger) = build_graph();
5115 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5117 let scorer = test_utils::TestScorer::with_penalty(0);
5119 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
5120 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5121 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5122 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5123 assert_eq!(route.paths.len(), 1);
5125 let cltv_expiry_deltas_before = route.paths[0].iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5127 // Check whether the offset added to the last hop by default is in [1 .. DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA]
5128 let mut route_default = route.clone();
5129 add_random_cltv_offset(&mut route_default, &payment_params, &network_graph.read_only(), &random_seed_bytes);
5130 let cltv_expiry_deltas_default = route_default.paths[0].iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5131 assert_eq!(cltv_expiry_deltas_before.split_last().unwrap().1, cltv_expiry_deltas_default.split_last().unwrap().1);
5132 assert!(cltv_expiry_deltas_default.last() > cltv_expiry_deltas_before.last());
5133 assert!(cltv_expiry_deltas_default.last().unwrap() <= &DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA);
5135 // Check that no offset is added when we restrict the max_total_cltv_expiry_delta
5136 let mut route_limited = route.clone();
5137 let limited_max_total_cltv_expiry_delta = cltv_expiry_deltas_before.iter().sum();
5138 let limited_payment_params = payment_params.with_max_total_cltv_expiry_delta(limited_max_total_cltv_expiry_delta);
5139 add_random_cltv_offset(&mut route_limited, &limited_payment_params, &network_graph.read_only(), &random_seed_bytes);
5140 let cltv_expiry_deltas_limited = route_limited.paths[0].iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5141 assert_eq!(cltv_expiry_deltas_before, cltv_expiry_deltas_limited);
5145 fn adds_plausible_cltv_offset() {
5146 let (secp_ctx, network, _, _, logger) = build_graph();
5147 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5148 let network_graph = network.read_only();
5149 let network_nodes = network_graph.nodes();
5150 let network_channels = network_graph.channels();
5151 let scorer = test_utils::TestScorer::with_penalty(0);
5152 let payment_params = PaymentParameters::from_node_id(nodes[3]);
5153 let keys_manager = test_utils::TestKeysInterface::new(&[4u8; 32], Network::Testnet);
5154 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5156 let mut route = get_route(&our_id, &payment_params, &network_graph, None, 100, 0,
5157 Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5158 add_random_cltv_offset(&mut route, &payment_params, &network_graph, &random_seed_bytes);
5160 let mut path_plausibility = vec![];
5162 for p in route.paths {
5163 // 1. Select random observation point
5164 let mut prng = ChaCha20::new(&random_seed_bytes, &[0u8; 12]);
5165 let mut random_bytes = [0u8; ::core::mem::size_of::<usize>()];
5167 prng.process_in_place(&mut random_bytes);
5168 let random_path_index = usize::from_be_bytes(random_bytes).wrapping_rem(p.len());
5169 let observation_point = NodeId::from_pubkey(&p.get(random_path_index).unwrap().pubkey);
5171 // 2. Calculate what CLTV expiry delta we would observe there
5172 let observed_cltv_expiry_delta: u32 = p[random_path_index..].iter().map(|h| h.cltv_expiry_delta).sum();
5174 // 3. Starting from the observation point, find candidate paths
5175 let mut candidates: VecDeque<(NodeId, Vec<u32>)> = VecDeque::new();
5176 candidates.push_back((observation_point, vec![]));
5178 let mut found_plausible_candidate = false;
5180 'candidate_loop: while let Some((cur_node_id, cur_path_cltv_deltas)) = candidates.pop_front() {
5181 if let Some(remaining) = observed_cltv_expiry_delta.checked_sub(cur_path_cltv_deltas.iter().sum::<u32>()) {
5182 if remaining == 0 || remaining.wrapping_rem(40) == 0 || remaining.wrapping_rem(144) == 0 {
5183 found_plausible_candidate = true;
5184 break 'candidate_loop;
5188 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
5189 for channel_id in &cur_node.channels {
5190 if let Some(channel_info) = network_channels.get(&channel_id) {
5191 if let Some((dir_info, next_id)) = channel_info.as_directed_from(&cur_node_id) {
5192 if let Some(channel_update_info) = dir_info.direction() {
5193 let next_cltv_expiry_delta = channel_update_info.cltv_expiry_delta as u32;
5194 if cur_path_cltv_deltas.iter().sum::<u32>()
5195 .saturating_add(next_cltv_expiry_delta) <= observed_cltv_expiry_delta {
5196 let mut new_path_cltv_deltas = cur_path_cltv_deltas.clone();
5197 new_path_cltv_deltas.push(next_cltv_expiry_delta);
5198 candidates.push_back((*next_id, new_path_cltv_deltas));
5207 path_plausibility.push(found_plausible_candidate);
5209 assert!(path_plausibility.iter().all(|x| *x));
5212 #[cfg(not(feature = "no-std"))]
5213 pub(super) fn random_init_seed() -> u64 {
5214 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
5215 use core::hash::{BuildHasher, Hasher};
5216 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
5217 println!("Using seed of {}", seed);
5220 #[cfg(not(feature = "no-std"))]
5221 use util::ser::Readable;
5224 #[cfg(not(feature = "no-std"))]
5225 fn generate_routes() {
5226 use routing::scoring::{ProbabilisticScorer, ProbabilisticScoringParameters};
5228 let mut d = match super::test_utils::get_route_file() {
5235 let graph = NetworkGraph::read(&mut d).unwrap();
5236 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5237 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5239 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
5240 let mut seed = random_init_seed() as usize;
5241 let nodes = graph.read_only().nodes().clone();
5242 'load_endpoints: for _ in 0..10 {
5244 seed = seed.overflowing_mul(0xdeadbeef).0;
5245 let src = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5246 seed = seed.overflowing_mul(0xdeadbeef).0;
5247 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5248 let payment_params = PaymentParameters::from_node_id(dst);
5249 let amt = seed as u64 % 200_000_000;
5250 let params = ProbabilisticScoringParameters::default();
5251 let scorer = ProbabilisticScorer::new(params, &graph);
5252 if get_route(src, &payment_params, &graph.read_only(), None, amt, 42, &test_utils::TestLogger::new(), &scorer, &random_seed_bytes).is_ok() {
5253 continue 'load_endpoints;
5260 #[cfg(not(feature = "no-std"))]
5261 fn generate_routes_mpp() {
5262 use routing::scoring::{ProbabilisticScorer, ProbabilisticScoringParameters};
5264 let mut d = match super::test_utils::get_route_file() {
5271 let graph = NetworkGraph::read(&mut d).unwrap();
5272 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5273 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5275 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
5276 let mut seed = random_init_seed() as usize;
5277 let nodes = graph.read_only().nodes().clone();
5278 'load_endpoints: for _ in 0..10 {
5280 seed = seed.overflowing_mul(0xdeadbeef).0;
5281 let src = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5282 seed = seed.overflowing_mul(0xdeadbeef).0;
5283 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5284 let payment_params = PaymentParameters::from_node_id(dst).with_features(InvoiceFeatures::known());
5285 let amt = seed as u64 % 200_000_000;
5286 let params = ProbabilisticScoringParameters::default();
5287 let scorer = ProbabilisticScorer::new(params, &graph);
5288 if get_route(src, &payment_params, &graph.read_only(), None, amt, 42, &test_utils::TestLogger::new(), &scorer, &random_seed_bytes).is_ok() {
5289 continue 'load_endpoints;
5296 #[cfg(all(test, not(feature = "no-std")))]
5297 pub(crate) mod test_utils {
5299 /// Tries to open a network graph file, or panics with a URL to fetch it.
5300 pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
5301 let res = File::open("net_graph-2021-05-31.bin") // By default we're run in RL/lightning
5302 .or_else(|_| File::open("lightning/net_graph-2021-05-31.bin")) // We may be run manually in RL/
5303 .or_else(|_| { // Fall back to guessing based on the binary location
5304 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
5305 let mut path = std::env::current_exe().unwrap();
5306 path.pop(); // lightning-...
5308 path.pop(); // debug
5309 path.pop(); // target
5310 path.push("lightning");
5311 path.push("net_graph-2021-05-31.bin");
5312 eprintln!("{}", path.to_str().unwrap());
5315 .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");
5316 #[cfg(require_route_graph_test)]
5317 return Ok(res.unwrap());
5318 #[cfg(not(require_route_graph_test))]
5323 #[cfg(all(test, feature = "_bench_unstable", not(feature = "no-std")))]
5326 use bitcoin::hashes::Hash;
5327 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
5328 use chain::transaction::OutPoint;
5329 use chain::keysinterface::{KeysManager,KeysInterface};
5330 use ln::channelmanager::{ChannelCounterparty, ChannelDetails};
5331 use ln::features::{InitFeatures, InvoiceFeatures};
5332 use routing::scoring::{FixedPenaltyScorer, ProbabilisticScorer, ProbabilisticScoringParameters, Scorer};
5333 use util::logger::{Logger, Record};
5337 struct DummyLogger {}
5338 impl Logger for DummyLogger {
5339 fn log(&self, _record: &Record) {}
5342 fn read_network_graph() -> NetworkGraph {
5343 let mut d = test_utils::get_route_file().unwrap();
5344 NetworkGraph::read(&mut d).unwrap()
5347 fn payer_pubkey() -> PublicKey {
5348 let secp_ctx = Secp256k1::new();
5349 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
5353 fn first_hop(node_id: PublicKey) -> ChannelDetails {
5355 channel_id: [0; 32],
5356 counterparty: ChannelCounterparty {
5357 features: InitFeatures::known(),
5359 unspendable_punishment_reserve: 0,
5360 forwarding_info: None,
5362 funding_txo: Some(OutPoint {
5363 txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0
5365 short_channel_id: Some(1),
5366 inbound_scid_alias: None,
5367 channel_value_satoshis: 10_000_000,
5369 balance_msat: 10_000_000,
5370 outbound_capacity_msat: 10_000_000,
5371 inbound_capacity_msat: 0,
5372 unspendable_punishment_reserve: None,
5373 confirmations_required: None,
5374 force_close_spend_delay: None,
5376 is_funding_locked: true,
5383 fn generate_routes_with_zero_penalty_scorer(bench: &mut Bencher) {
5384 let network_graph = read_network_graph();
5385 let scorer = FixedPenaltyScorer::with_penalty(0);
5386 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::empty());
5390 fn generate_mpp_routes_with_zero_penalty_scorer(bench: &mut Bencher) {
5391 let network_graph = read_network_graph();
5392 let scorer = FixedPenaltyScorer::with_penalty(0);
5393 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::known());
5397 fn generate_routes_with_default_scorer(bench: &mut Bencher) {
5398 let network_graph = read_network_graph();
5399 let scorer = Scorer::default();
5400 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::empty());
5404 fn generate_mpp_routes_with_default_scorer(bench: &mut Bencher) {
5405 let network_graph = read_network_graph();
5406 let scorer = Scorer::default();
5407 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::known());
5411 fn generate_routes_with_probabilistic_scorer(bench: &mut Bencher) {
5412 let network_graph = read_network_graph();
5413 let params = ProbabilisticScoringParameters::default();
5414 let scorer = ProbabilisticScorer::new(params, &network_graph);
5415 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::empty());
5419 fn generate_mpp_routes_with_probabilistic_scorer(bench: &mut Bencher) {
5420 let network_graph = read_network_graph();
5421 let params = ProbabilisticScoringParameters::default();
5422 let scorer = ProbabilisticScorer::new(params, &network_graph);
5423 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::known());
5426 fn generate_routes<S: Score>(
5427 bench: &mut Bencher, graph: &NetworkGraph, mut scorer: S, features: InvoiceFeatures
5429 let nodes = graph.read_only().nodes().clone();
5430 let payer = payer_pubkey();
5431 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
5432 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5434 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
5435 let mut routes = Vec::new();
5436 let mut route_endpoints = Vec::new();
5437 let mut seed: usize = 0xdeadbeef;
5438 'load_endpoints: for _ in 0..100 {
5441 let src = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5443 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5444 let params = PaymentParameters::from_node_id(dst).with_features(features.clone());
5445 let first_hop = first_hop(src);
5446 let amt = seed as u64 % 1_000_000;
5447 if let Ok(route) = get_route(&payer, ¶ms, &graph.read_only(), Some(&[&first_hop]), amt, 42, &DummyLogger{}, &scorer, &random_seed_bytes) {
5449 route_endpoints.push((first_hop, params, amt));
5450 continue 'load_endpoints;
5455 // ...and seed the scorer with success and failure data...
5456 for route in routes {
5457 let amount = route.get_total_amount();
5458 if amount < 250_000 {
5459 for path in route.paths {
5460 scorer.payment_path_successful(&path.iter().collect::<Vec<_>>());
5462 } else if amount > 750_000 {
5463 for path in route.paths {
5464 let short_channel_id = path[path.len() / 2].short_channel_id;
5465 scorer.payment_path_failed(&path.iter().collect::<Vec<_>>(), short_channel_id);
5470 // ...then benchmark finding paths between the nodes we learned.
5473 let (first_hop, params, amt) = &route_endpoints[idx % route_endpoints.len()];
5474 assert!(get_route(&payer, params, &graph.read_only(), Some(&[first_hop]), *amt, 42, &DummyLogger{}, &scorer, &random_seed_bytes).is_ok());