1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! The top-level routing/network map tracking logic lives here.
12 //! You probably want to create a NetGraphMsgHandler and use that as your RoutingMessageHandler and then
13 //! interrogate it to get routes for your own payments.
15 use bitcoin::secp256k1::key::PublicKey;
17 use ln::channelmanager::ChannelDetails;
18 use ln::features::{ChannelFeatures, InvoiceFeatures, NodeFeatures};
19 use ln::msgs::{DecodeError, ErrorAction, LightningError, MAX_VALUE_MSAT};
20 use routing::scoring::Score;
21 use routing::network_graph::{DirectedChannelInfoWithUpdate, EffectiveCapacity, NetworkGraph, ReadOnlyNetworkGraph, NodeId, RoutingFees};
22 use util::ser::{Writeable, Readable};
23 use util::logger::{Level, Logger};
24 use util::chacha20::ChaCha20;
28 use alloc::collections::BinaryHeap;
33 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
35 /// The node_id of the node at this hop.
36 pub pubkey: PublicKey,
37 /// The node_announcement features of the node at this hop. For the last hop, these may be
38 /// amended to match the features present in the invoice this node generated.
39 pub node_features: NodeFeatures,
40 /// The channel that should be used from the previous hop to reach this node.
41 pub short_channel_id: u64,
42 /// The channel_announcement features of the channel that should be used from the previous hop
43 /// to reach this node.
44 pub channel_features: ChannelFeatures,
45 /// The fee taken on this hop (for paying for the use of the *next* channel in the path).
46 /// For the last hop, this should be the full value of the payment (might be more than
47 /// requested if we had to match htlc_minimum_msat).
49 /// The CLTV delta added for this hop. For the last hop, this should be the full CLTV value
50 /// expected at the destination, in excess of the current block height.
51 pub cltv_expiry_delta: u32,
54 impl_writeable_tlv_based!(RouteHop, {
55 (0, pubkey, required),
56 (2, node_features, required),
57 (4, short_channel_id, required),
58 (6, channel_features, required),
59 (8, fee_msat, required),
60 (10, cltv_expiry_delta, required),
63 /// A route directs a payment from the sender (us) to the recipient. If the recipient supports MPP,
64 /// it can take multiple paths. Each path is composed of one or more hops through the network.
65 #[derive(Clone, Hash, PartialEq, Eq)]
67 /// The list of routes taken for a single (potentially-)multi-part payment. The pubkey of the
68 /// last RouteHop in each path must be the same.
69 /// Each entry represents a list of hops, NOT INCLUDING our own, where the last hop is the
70 /// destination. Thus, this must always be at least length one. While the maximum length of any
71 /// given path is variable, keeping the length of any path to less than 20 should currently
72 /// ensure it is viable.
73 pub paths: Vec<Vec<RouteHop>>,
74 /// The `payment_params` parameter passed to [`find_route`].
75 /// This is used by `ChannelManager` to track information which may be required for retries,
76 /// provided back to you via [`Event::PaymentPathFailed`].
78 /// [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed
79 pub payment_params: Option<PaymentParameters>,
82 pub(crate) trait RoutePath {
83 /// Gets the fees for a given path, excluding any excess paid to the recipient.
84 fn get_path_fees(&self) -> u64;
86 impl RoutePath for Vec<RouteHop> {
87 fn get_path_fees(&self) -> u64 {
88 // Do not count last hop of each path since that's the full value of the payment
89 self.split_last().map(|(_, path_prefix)| path_prefix).unwrap_or(&[])
90 .iter().map(|hop| &hop.fee_msat)
96 /// Returns the total amount of fees paid on this [`Route`].
98 /// This doesn't include any extra payment made to the recipient, which can happen in excess of
99 /// the amount passed to [`find_route`]'s `params.final_value_msat`.
100 pub fn get_total_fees(&self) -> u64 {
101 self.paths.iter().map(|path| path.get_path_fees()).sum()
104 /// Returns the total amount paid on this [`Route`], excluding the fees.
105 pub fn get_total_amount(&self) -> u64 {
106 return self.paths.iter()
107 .map(|path| path.split_last().map(|(hop, _)| hop.fee_msat).unwrap_or(0))
112 const SERIALIZATION_VERSION: u8 = 1;
113 const MIN_SERIALIZATION_VERSION: u8 = 1;
115 impl Writeable for Route {
116 fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
117 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
118 (self.paths.len() as u64).write(writer)?;
119 for hops in self.paths.iter() {
120 (hops.len() as u8).write(writer)?;
121 for hop in hops.iter() {
125 write_tlv_fields!(writer, {
126 (1, self.payment_params, option),
132 impl Readable for Route {
133 fn read<R: io::Read>(reader: &mut R) -> Result<Route, DecodeError> {
134 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
135 let path_count: u64 = Readable::read(reader)?;
136 let mut paths = Vec::with_capacity(cmp::min(path_count, 128) as usize);
137 for _ in 0..path_count {
138 let hop_count: u8 = Readable::read(reader)?;
139 let mut hops = Vec::with_capacity(hop_count as usize);
140 for _ in 0..hop_count {
141 hops.push(Readable::read(reader)?);
145 let mut payment_params = None;
146 read_tlv_fields!(reader, {
147 (1, payment_params, option),
149 Ok(Route { paths, payment_params })
153 /// Parameters needed to find a [`Route`].
155 /// Passed to [`find_route`] and also provided in [`Event::PaymentPathFailed`] for retrying a failed
158 /// [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed
159 #[derive(Clone, Debug)]
160 pub struct RouteParameters {
161 /// The parameters of the failed payment path.
162 pub payment_params: PaymentParameters,
164 /// The amount in msats sent on the failed payment path.
165 pub final_value_msat: u64,
167 /// The CLTV on the final hop of the failed payment path.
168 pub final_cltv_expiry_delta: u32,
171 impl_writeable_tlv_based!(RouteParameters, {
172 (0, payment_params, required),
173 (2, final_value_msat, required),
174 (4, final_cltv_expiry_delta, required),
177 /// Maximum total CTLV difference we allow for a full payment path.
178 pub const DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA: u32 = 1008;
180 /// The median hop CLTV expiry delta currently seen in the network.
181 const MEDIAN_HOP_CLTV_EXPIRY_DELTA: u32 = 40;
183 /// The recipient of a payment.
184 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
185 pub struct PaymentParameters {
186 /// The node id of the payee.
187 pub payee_pubkey: PublicKey,
189 /// Features supported by the payee.
191 /// May be set from the payee's invoice or via [`for_keysend`]. May be `None` if the invoice
192 /// does not contain any features.
194 /// [`for_keysend`]: Self::for_keysend
195 pub features: Option<InvoiceFeatures>,
197 /// Hints for routing to the payee, containing channels connecting the payee to public nodes.
198 pub route_hints: Vec<RouteHint>,
200 /// Expiration of a payment to the payee, in seconds relative to the UNIX epoch.
201 pub expiry_time: Option<u64>,
203 /// The maximum total CLTV delta we accept for the route.
204 pub max_total_cltv_expiry_delta: u32,
207 impl_writeable_tlv_based!(PaymentParameters, {
208 (0, payee_pubkey, required),
209 (1, max_total_cltv_expiry_delta, (default_value, DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA)),
210 (2, features, option),
211 (4, route_hints, vec_type),
212 (6, expiry_time, option),
215 impl PaymentParameters {
216 /// Creates a payee with the node id of the given `pubkey`.
217 pub fn from_node_id(payee_pubkey: PublicKey) -> Self {
223 max_total_cltv_expiry_delta: DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA,
227 /// Creates a payee with the node id of the given `pubkey` to use for keysend payments.
228 pub fn for_keysend(payee_pubkey: PublicKey) -> Self {
229 Self::from_node_id(payee_pubkey).with_features(InvoiceFeatures::for_keysend())
232 /// Includes the payee's features.
234 /// (C-not exported) since bindings don't support move semantics
235 pub fn with_features(self, features: InvoiceFeatures) -> Self {
236 Self { features: Some(features), ..self }
239 /// Includes hints for routing to the payee.
241 /// (C-not exported) since bindings don't support move semantics
242 pub fn with_route_hints(self, route_hints: Vec<RouteHint>) -> Self {
243 Self { route_hints, ..self }
246 /// Includes a payment expiration in seconds relative to the UNIX epoch.
248 /// (C-not exported) since bindings don't support move semantics
249 pub fn with_expiry_time(self, expiry_time: u64) -> Self {
250 Self { expiry_time: Some(expiry_time), ..self }
253 /// Includes a limit for the total CLTV expiry delta which is considered during routing
255 /// (C-not exported) since bindings don't support move semantics
256 pub fn with_max_total_cltv_expiry_delta(self, max_total_cltv_expiry_delta: u32) -> Self {
257 Self { max_total_cltv_expiry_delta, ..self }
261 /// A list of hops along a payment path terminating with a channel to the recipient.
262 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
263 pub struct RouteHint(pub Vec<RouteHintHop>);
265 impl Writeable for RouteHint {
266 fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
267 (self.0.len() as u64).write(writer)?;
268 for hop in self.0.iter() {
275 impl Readable for RouteHint {
276 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
277 let hop_count: u64 = Readable::read(reader)?;
278 let mut hops = Vec::with_capacity(cmp::min(hop_count, 16) as usize);
279 for _ in 0..hop_count {
280 hops.push(Readable::read(reader)?);
286 /// A channel descriptor for a hop along a payment path.
287 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
288 pub struct RouteHintHop {
289 /// The node_id of the non-target end of the route
290 pub src_node_id: PublicKey,
291 /// The short_channel_id of this channel
292 pub short_channel_id: u64,
293 /// The fees which must be paid to use this channel
294 pub fees: RoutingFees,
295 /// The difference in CLTV values between this node and the next node.
296 pub cltv_expiry_delta: u16,
297 /// The minimum value, in msat, which must be relayed to the next hop.
298 pub htlc_minimum_msat: Option<u64>,
299 /// The maximum value in msat available for routing with a single HTLC.
300 pub htlc_maximum_msat: Option<u64>,
303 impl_writeable_tlv_based!(RouteHintHop, {
304 (0, src_node_id, required),
305 (1, htlc_minimum_msat, option),
306 (2, short_channel_id, required),
307 (3, htlc_maximum_msat, option),
309 (6, cltv_expiry_delta, required),
312 #[derive(Eq, PartialEq)]
313 struct RouteGraphNode {
315 lowest_fee_to_peer_through_node: u64,
316 lowest_fee_to_node: u64,
317 total_cltv_delta: u32,
318 // The maximum value a yet-to-be-constructed payment path might flow through this node.
319 // This value is upper-bounded by us by:
320 // - how much is needed for a path being constructed
321 // - how much value can channels following this node (up to the destination) can contribute,
322 // considering their capacity and fees
323 value_contribution_msat: u64,
324 /// The effective htlc_minimum_msat at this hop. If a later hop on the path had a higher HTLC
325 /// minimum, we use it, plus the fees required at each earlier hop to meet it.
326 path_htlc_minimum_msat: u64,
327 /// All penalties incurred from this hop on the way to the destination, as calculated using
329 path_penalty_msat: u64,
332 impl cmp::Ord for RouteGraphNode {
333 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
334 let other_score = cmp::max(other.lowest_fee_to_peer_through_node, other.path_htlc_minimum_msat)
335 .checked_add(other.path_penalty_msat)
336 .unwrap_or_else(|| u64::max_value());
337 let self_score = cmp::max(self.lowest_fee_to_peer_through_node, self.path_htlc_minimum_msat)
338 .checked_add(self.path_penalty_msat)
339 .unwrap_or_else(|| u64::max_value());
340 other_score.cmp(&self_score).then_with(|| other.node_id.cmp(&self.node_id))
344 impl cmp::PartialOrd for RouteGraphNode {
345 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
346 Some(self.cmp(other))
350 /// A wrapper around the various hop representations.
352 /// Used to construct a [`PathBuildingHop`] and to estimate [`EffectiveCapacity`].
353 #[derive(Clone, Debug)]
354 enum CandidateRouteHop<'a> {
355 /// A hop from the payer, where the outbound liquidity is known.
357 details: &'a ChannelDetails,
359 /// A hop found in the [`NetworkGraph`], where the channel capacity may or may not be known.
361 info: DirectedChannelInfoWithUpdate<'a>,
362 short_channel_id: u64,
364 /// A hop to the payee found in the payment invoice, though not necessarily a direct channel.
366 hint: &'a RouteHintHop,
370 impl<'a> CandidateRouteHop<'a> {
371 fn short_channel_id(&self) -> u64 {
373 CandidateRouteHop::FirstHop { details } => details.short_channel_id.unwrap(),
374 CandidateRouteHop::PublicHop { short_channel_id, .. } => *short_channel_id,
375 CandidateRouteHop::PrivateHop { hint } => hint.short_channel_id,
379 // NOTE: This may alloc memory so avoid calling it in a hot code path.
380 fn features(&self) -> ChannelFeatures {
382 CandidateRouteHop::FirstHop { details } => details.counterparty.features.to_context(),
383 CandidateRouteHop::PublicHop { info, .. } => info.channel().features.clone(),
384 CandidateRouteHop::PrivateHop { .. } => ChannelFeatures::empty(),
388 fn cltv_expiry_delta(&self) -> u32 {
390 CandidateRouteHop::FirstHop { .. } => 0,
391 CandidateRouteHop::PublicHop { info, .. } => info.direction().cltv_expiry_delta as u32,
392 CandidateRouteHop::PrivateHop { hint } => hint.cltv_expiry_delta as u32,
396 fn htlc_minimum_msat(&self) -> u64 {
398 CandidateRouteHop::FirstHop { .. } => 0,
399 CandidateRouteHop::PublicHop { info, .. } => info.direction().htlc_minimum_msat,
400 CandidateRouteHop::PrivateHop { hint } => hint.htlc_minimum_msat.unwrap_or(0),
404 fn fees(&self) -> RoutingFees {
406 CandidateRouteHop::FirstHop { .. } => RoutingFees {
407 base_msat: 0, proportional_millionths: 0,
409 CandidateRouteHop::PublicHop { info, .. } => info.direction().fees,
410 CandidateRouteHop::PrivateHop { hint } => hint.fees,
414 fn effective_capacity(&self) -> EffectiveCapacity {
416 CandidateRouteHop::FirstHop { details } => EffectiveCapacity::ExactLiquidity {
417 liquidity_msat: details.outbound_capacity_msat,
419 CandidateRouteHop::PublicHop { info, .. } => info.effective_capacity(),
420 CandidateRouteHop::PrivateHop { .. } => EffectiveCapacity::Infinite,
425 /// It's useful to keep track of the hops associated with the fees required to use them,
426 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
427 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
428 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
430 struct PathBuildingHop<'a> {
431 // Note that this should be dropped in favor of loading it from CandidateRouteHop, but doing so
432 // is a larger refactor and will require careful performance analysis.
434 candidate: CandidateRouteHop<'a>,
437 /// Minimal fees required to route to the source node of the current hop via any of its inbound channels.
438 src_lowest_inbound_fees: RoutingFees,
439 /// All the fees paid *after* this channel on the way to the destination
440 next_hops_fee_msat: u64,
441 /// Fee paid for the use of the current channel (see candidate.fees()).
442 /// The value will be actually deducted from the counterparty balance on the previous link.
443 hop_use_fee_msat: u64,
444 /// Used to compare channels when choosing the for routing.
445 /// Includes paying for the use of a hop and the following hops, as well as
446 /// an estimated cost of reaching this hop.
447 /// Might get stale when fees are recomputed. Primarily for internal use.
449 /// A mirror of the same field in RouteGraphNode. Note that this is only used during the graph
450 /// walk and may be invalid thereafter.
451 path_htlc_minimum_msat: u64,
452 /// All penalties incurred from this channel on the way to the destination, as calculated using
454 path_penalty_msat: u64,
455 /// If we've already processed a node as the best node, we shouldn't process it again. Normally
456 /// we'd just ignore it if we did as all channels would have a higher new fee, but because we
457 /// may decrease the amounts in use as we walk the graph, the actual calculated fee may
458 /// decrease as well. Thus, we have to explicitly track which nodes have been processed and
459 /// avoid processing them again.
461 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
462 // In tests, we apply further sanity checks on cases where we skip nodes we already processed
463 // to ensure it is specifically in cases where the fee has gone down because of a decrease in
464 // value_contribution_msat, which requires tracking it here. See comments below where it is
465 // used for more info.
466 value_contribution_msat: u64,
469 impl<'a> core::fmt::Debug for PathBuildingHop<'a> {
470 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
471 f.debug_struct("PathBuildingHop")
472 .field("node_id", &self.node_id)
473 .field("short_channel_id", &self.candidate.short_channel_id())
474 .field("total_fee_msat", &self.total_fee_msat)
475 .field("next_hops_fee_msat", &self.next_hops_fee_msat)
476 .field("hop_use_fee_msat", &self.hop_use_fee_msat)
477 .field("total_fee_msat - (next_hops_fee_msat + hop_use_fee_msat)", &(&self.total_fee_msat - (&self.next_hops_fee_msat + &self.hop_use_fee_msat)))
478 .field("path_penalty_msat", &self.path_penalty_msat)
479 .field("path_htlc_minimum_msat", &self.path_htlc_minimum_msat)
480 .field("cltv_expiry_delta", &self.candidate.cltv_expiry_delta())
485 // Instantiated with a list of hops with correct data in them collected during path finding,
486 // an instance of this struct should be further modified only via given methods.
488 struct PaymentPath<'a> {
489 hops: Vec<(PathBuildingHop<'a>, NodeFeatures)>,
492 impl<'a> PaymentPath<'a> {
493 // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
494 fn get_value_msat(&self) -> u64 {
495 self.hops.last().unwrap().0.fee_msat
498 fn get_total_fee_paid_msat(&self) -> u64 {
499 if self.hops.len() < 1 {
503 // Can't use next_hops_fee_msat because it gets outdated.
504 for (i, (hop, _)) in self.hops.iter().enumerate() {
505 if i != self.hops.len() - 1 {
506 result += hop.fee_msat;
512 // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
513 // to change fees may result in an inconsistency.
515 // Sometimes we call this function right after constructing a path which is inconsistent in
516 // that it the value being transferred has decreased while we were doing path finding, leading
517 // to the fees being paid not lining up with the actual limits.
519 // Note that this function is not aware of the available_liquidity limit, and thus does not
520 // support increasing the value being transferred.
521 fn update_value_and_recompute_fees(&mut self, value_msat: u64) {
522 assert!(value_msat <= self.hops.last().unwrap().0.fee_msat);
524 let mut total_fee_paid_msat = 0 as u64;
525 for i in (0..self.hops.len()).rev() {
526 let last_hop = i == self.hops.len() - 1;
528 // For non-last-hop, this value will represent the fees paid on the current hop. It
529 // will consist of the fees for the use of the next hop, and extra fees to match
530 // htlc_minimum_msat of the current channel. Last hop is handled separately.
531 let mut cur_hop_fees_msat = 0;
533 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().0.hop_use_fee_msat;
536 let mut cur_hop = &mut self.hops.get_mut(i).unwrap().0;
537 cur_hop.next_hops_fee_msat = total_fee_paid_msat;
538 // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
539 // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
540 // set it too high just to maliciously take more fees by exploiting this
541 // match htlc_minimum_msat logic.
542 let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
543 if let Some(extra_fees_msat) = cur_hop.candidate.htlc_minimum_msat().checked_sub(cur_hop_transferred_amount_msat) {
544 // Note that there is a risk that *previous hops* (those closer to us, as we go
545 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
547 // This might make us end up with a broken route, although this should be super-rare
548 // in practice, both because of how healthy channels look like, and how we pick
549 // channels in add_entry.
550 // Also, this can't be exploited more heavily than *announce a free path and fail
552 cur_hop_transferred_amount_msat += extra_fees_msat;
553 total_fee_paid_msat += extra_fees_msat;
554 cur_hop_fees_msat += extra_fees_msat;
558 // Final hop is a special case: it usually has just value_msat (by design), but also
559 // it still could overpay for the htlc_minimum_msat.
560 cur_hop.fee_msat = cur_hop_transferred_amount_msat;
562 // Propagate updated fees for the use of the channels to one hop back, where they
563 // will be actually paid (fee_msat). The last hop is handled above separately.
564 cur_hop.fee_msat = cur_hop_fees_msat;
567 // Fee for the use of the current hop which will be deducted on the previous hop.
568 // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
569 // this channel is free for us.
571 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.candidate.fees()) {
572 cur_hop.hop_use_fee_msat = new_fee;
573 total_fee_paid_msat += new_fee;
575 // It should not be possible because this function is called only to reduce the
576 // value. In that case, compute_fee was already called with the same fees for
577 // larger amount and there was no overflow.
585 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
586 let proportional_fee_millions =
587 amount_msat.checked_mul(channel_fees.proportional_millionths as u64);
588 if let Some(new_fee) = proportional_fee_millions.and_then(|part| {
589 (channel_fees.base_msat as u64).checked_add(part / 1_000_000) }) {
593 // This function may be (indirectly) called without any verification,
594 // with channel_fees provided by a caller. We should handle it gracefully.
599 /// Finds a route from us (payer) to the given target node (payee).
601 /// If the payee provided features in their invoice, they should be provided via `params.payee`.
602 /// Without this, MPP will only be used if the payee's features are available in the network graph.
604 /// Private routing paths between a public node and the target may be included in `params.payee`.
606 /// If some channels aren't announced, it may be useful to fill in `first_hops` with the results
607 /// from [`ChannelManager::list_usable_channels`]. If it is filled in, the view of our local
608 /// channels from [`NetworkGraph`] will be ignored, and only those in `first_hops` will be used.
610 /// The fees on channels from us to the next hop are ignored as they are assumed to all be equal.
611 /// However, the enabled/disabled bit on such channels as well as the `htlc_minimum_msat` /
612 /// `htlc_maximum_msat` *are* checked as they may change based on the receiving node.
616 /// May be used to re-compute a [`Route`] when handling a [`Event::PaymentPathFailed`]. Any
617 /// adjustments to the [`NetworkGraph`] and channel scores should be made prior to calling this
622 /// Panics if first_hops contains channels without short_channel_ids;
623 /// [`ChannelManager::list_usable_channels`] will never include such channels.
625 /// [`ChannelManager::list_usable_channels`]: crate::ln::channelmanager::ChannelManager::list_usable_channels
626 /// [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed
627 pub fn find_route<L: Deref, S: Score>(
628 our_node_pubkey: &PublicKey, route_params: &RouteParameters, network: &NetworkGraph,
629 first_hops: Option<&[&ChannelDetails]>, logger: L, scorer: &S, random_seed_bytes: &[u8; 32]
630 ) -> Result<Route, LightningError>
631 where L::Target: Logger {
632 let network_graph = network.read_only();
634 our_node_pubkey, &route_params.payment_params, &network_graph, first_hops, route_params.final_value_msat,
635 route_params.final_cltv_expiry_delta, logger, scorer, random_seed_bytes
638 add_random_cltv_offset(&mut route, &route_params.payment_params, &network_graph, random_seed_bytes);
641 Err(err) => Err(err),
645 pub(crate) fn get_route<L: Deref, S: Score>(
646 our_node_pubkey: &PublicKey, payment_params: &PaymentParameters, network_graph: &ReadOnlyNetworkGraph,
647 first_hops: Option<&[&ChannelDetails]>, final_value_msat: u64, final_cltv_expiry_delta: u32,
648 logger: L, scorer: &S, _random_seed_bytes: &[u8; 32]
649 ) -> Result<Route, LightningError>
650 where L::Target: Logger {
651 let payee_node_id = NodeId::from_pubkey(&payment_params.payee_pubkey);
652 let our_node_id = NodeId::from_pubkey(&our_node_pubkey);
654 if payee_node_id == our_node_id {
655 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
658 if final_value_msat > MAX_VALUE_MSAT {
659 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
662 if final_value_msat == 0 {
663 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
666 for route in payment_params.route_hints.iter() {
667 for hop in &route.0 {
668 if hop.src_node_id == payment_params.payee_pubkey {
669 return Err(LightningError{err: "Route hint cannot have the payee as the source.".to_owned(), action: ErrorAction::IgnoreError});
673 if payment_params.max_total_cltv_expiry_delta <= final_cltv_expiry_delta {
674 return Err(LightningError{err: "Can't find a route where the maximum total CLTV expiry delta is below the final CLTV expiry.".to_owned(), action: ErrorAction::IgnoreError});
677 // The general routing idea is the following:
678 // 1. Fill first/last hops communicated by the caller.
679 // 2. Attempt to construct a path from payer to payee for transferring
680 // any ~sufficient (described later) value.
681 // If succeed, remember which channels were used and how much liquidity they have available,
682 // so that future paths don't rely on the same liquidity.
683 // 3. Proceed to the next step if:
684 // - we hit the recommended target value;
685 // - OR if we could not construct a new path. Any next attempt will fail too.
686 // Otherwise, repeat step 2.
687 // 4. See if we managed to collect paths which aggregately are able to transfer target value
688 // (not recommended value).
689 // 5. If yes, proceed. If not, fail routing.
690 // 6. Randomly combine paths into routes having enough to fulfill the payment. (TODO: knapsack)
691 // 7. Of all the found paths, select only those with the lowest total fee.
692 // 8. The last path in every selected route is likely to be more than we need.
693 // Reduce its value-to-transfer and recompute fees.
694 // 9. Choose the best route by the lowest total fee.
696 // As for the actual search algorithm,
697 // we do a payee-to-payer pseudo-Dijkstra's sorting by each node's distance from the payee
698 // plus the minimum per-HTLC fee to get from it to another node (aka "shitty pseudo-A*").
700 // We are not a faithful Dijkstra's implementation because we can change values which impact
701 // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
702 // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) than
703 // the value we are currently attempting to send over a path, we simply reduce the value being
704 // sent along the path for any hops after that channel. This may imply that later fees (which
705 // we've already tabulated) are lower because a smaller value is passing through the channels
706 // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
707 // channels which were selected earlier (and which may still be used for other paths without a
708 // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
711 // One potentially problematic case for this algorithm would be if there are many
712 // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
713 // graph walking), we may never find a path which is not liquidity-limited and has lower
714 // proportional fee (and only lower absolute fee when considering the ultimate value sent).
715 // Because we only consider paths with at least 5% of the total value being sent, the damage
716 // from such a case should be limited, however this could be further reduced in the future by
717 // calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
718 // limits for the purposes of fee calculation.
720 // Alternatively, we could store more detailed path information in the heap (targets, below)
721 // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
722 // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
723 // and practically (as we would need to store dynamically-allocated path information in heap
724 // objects, increasing malloc traffic and indirect memory access significantly). Further, the
725 // results of such an algorithm would likely be biased towards lower-value paths.
727 // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
728 // outside of our current search value, running a path search more times to gather candidate
729 // paths at different values. While this may be acceptable, further path searches may increase
730 // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
731 // graph for candidate paths, calculating the maximum value which can realistically be sent at
732 // the same time, remaining generic across different payment values.
734 // TODO: There are a few tweaks we could do, including possibly pre-calculating more stuff
735 // to use as the A* heuristic beyond just the cost to get one node further than the current
738 let network_channels = network_graph.channels();
739 let network_nodes = network_graph.nodes();
741 // Allow MPP only if we have a features set from somewhere that indicates the payee supports
742 // it. If the payee supports it they're supposed to include it in the invoice, so that should
744 let allow_mpp = if let Some(features) = &payment_params.features {
745 features.supports_basic_mpp()
746 } else if let Some(node) = network_nodes.get(&payee_node_id) {
747 if let Some(node_info) = node.announcement_info.as_ref() {
748 node_info.features.supports_basic_mpp()
751 log_trace!(logger, "Searching for a route from payer {} to payee {} {} MPP and {} first hops {}overriding the network graph", our_node_pubkey,
752 payment_params.payee_pubkey, if allow_mpp { "with" } else { "without" },
753 first_hops.map(|hops| hops.len()).unwrap_or(0), if first_hops.is_some() { "" } else { "not " });
756 // Prepare the data we'll use for payee-to-payer search by
757 // inserting first hops suggested by the caller as targets.
758 // Our search will then attempt to reach them while traversing from the payee node.
759 let mut first_hop_targets: HashMap<_, Vec<&ChannelDetails>> =
760 HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
761 if let Some(hops) = first_hops {
763 if chan.short_channel_id.is_none() {
764 panic!("first_hops should be filled in with usable channels, not pending ones");
766 if chan.counterparty.node_id == *our_node_pubkey {
767 return Err(LightningError{err: "First hop cannot have our_node_pubkey as a destination.".to_owned(), action: ErrorAction::IgnoreError});
770 .entry(NodeId::from_pubkey(&chan.counterparty.node_id))
771 .or_insert(Vec::new())
774 if first_hop_targets.is_empty() {
775 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
779 // The main heap containing all candidate next-hops sorted by their score (max(A* fee,
780 // htlc_minimum)). Ideally this would be a heap which allowed cheap score reduction instead of
781 // adding duplicate entries when we find a better path to a given node.
782 let mut targets = BinaryHeap::new();
784 // Map from node_id to information about the best current path to that node, including feerate
786 let mut dist = HashMap::with_capacity(network_nodes.len());
788 // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
789 // indicating that we may wish to try again with a higher value, potentially paying to meet an
790 // htlc_minimum with extra fees while still finding a cheaper path.
791 let mut hit_minimum_limit;
793 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
794 // We start with a path_value of the exact amount we want, and if that generates a route we may
795 // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
796 // amount we want in total across paths, selecting the best subset at the end.
797 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
798 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
799 let mut path_value_msat = final_value_msat;
801 // We don't want multiple paths (as per MPP) share liquidity of the same channels.
802 // This map allows paths to be aware of the channel use by other paths in the same call.
803 // This would help to make a better path finding decisions and not "overbook" channels.
804 // It is unaware of the directions (except for `outbound_capacity_msat` in `first_hops`).
805 let mut bookkept_channels_liquidity_available_msat = HashMap::with_capacity(network_nodes.len());
807 // Keeping track of how much value we already collected across other paths. Helps to decide:
808 // - how much a new path should be transferring (upper bound);
809 // - whether a channel should be disregarded because
810 // it's available liquidity is too small comparing to how much more we need to collect;
811 // - when we want to stop looking for new paths.
812 let mut already_collected_value_msat = 0;
814 log_trace!(logger, "Building path from {} (payee) to {} (us/payer) for value {} msat.", payment_params.payee_pubkey, our_node_pubkey, final_value_msat);
816 macro_rules! add_entry {
817 // Adds entry which goes from $src_node_id to $dest_node_id over the $candidate hop.
818 // $next_hops_fee_msat represents the fees paid for using all the channels *after* this one,
819 // since that value has to be transferred over this channel.
820 // Returns whether this channel caused an update to `targets`.
821 ( $candidate: expr, $src_node_id: expr, $dest_node_id: expr, $next_hops_fee_msat: expr,
822 $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr,
823 $next_hops_path_penalty_msat: expr, $next_hops_cltv_delta: expr ) => { {
824 // We "return" whether we updated the path at the end, via this:
825 let mut did_add_update_path_to_src_node = false;
826 // Channels to self should not be used. This is more of belt-and-suspenders, because in
827 // practice these cases should be caught earlier:
828 // - for regular channels at channel announcement (TODO)
829 // - for first and last hops early in get_route
830 if $src_node_id != $dest_node_id {
831 let short_channel_id = $candidate.short_channel_id();
832 let available_liquidity_msat = bookkept_channels_liquidity_available_msat
833 .entry(short_channel_id)
834 .or_insert_with(|| $candidate.effective_capacity().as_msat());
836 // It is tricky to substract $next_hops_fee_msat from available liquidity here.
837 // It may be misleading because we might later choose to reduce the value transferred
838 // over these channels, and the channel which was insufficient might become sufficient.
839 // Worst case: we drop a good channel here because it can't cover the high following
840 // fees caused by one expensive channel, but then this channel could have been used
841 // if the amount being transferred over this path is lower.
842 // We do this for now, but this is a subject for removal.
843 if let Some(available_value_contribution_msat) = available_liquidity_msat.checked_sub($next_hops_fee_msat) {
845 // Routing Fragmentation Mitigation heuristic:
847 // Routing fragmentation across many payment paths increases the overall routing
848 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
849 // Taking too many smaller paths also increases the chance of payment failure.
850 // Thus to avoid this effect, we require from our collected links to provide
851 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
853 // This requirement is currently 5% of the remaining-to-be-collected value.
854 // This means as we successfully advance in our collection,
855 // the absolute liquidity contribution is lowered,
856 // thus increasing the number of potential channels to be selected.
858 // Derive the minimal liquidity contribution with a ratio of 20 (5%, rounded up)
859 // or 100% if we're not allowed to do multipath payments.
860 let minimal_value_contribution_msat: u64 = if allow_mpp {
861 (recommended_value_msat - already_collected_value_msat + 19) / 20
865 // Verify the liquidity offered by this channel complies to the minimal contribution.
866 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
868 // Do not consider candidates that exceed the maximum total cltv expiry limit.
869 // In order to already account for some of the privacy enhancing random CLTV
870 // expiry delta offset we add on top later, we subtract a rough estimate
871 // (2*MEDIAN_HOP_CLTV_EXPIRY_DELTA) here.
872 let max_total_cltv_expiry_delta = (payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta)
873 .checked_sub(2*MEDIAN_HOP_CLTV_EXPIRY_DELTA)
874 .unwrap_or(payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta);
875 let hop_total_cltv_delta = ($next_hops_cltv_delta as u32)
876 .checked_add($candidate.cltv_expiry_delta())
877 .unwrap_or(u32::max_value());
878 let doesnt_exceed_cltv_delta_limit = hop_total_cltv_delta <= max_total_cltv_expiry_delta;
880 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
881 // Includes paying fees for the use of the following channels.
882 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
883 Some(result) => result,
884 // Can't overflow due to how the values were computed right above.
885 None => unreachable!(),
887 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
888 let over_path_minimum_msat = amount_to_transfer_over_msat >= $candidate.htlc_minimum_msat() &&
889 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
891 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
892 // bother considering this channel.
893 // Since we're choosing amount_to_transfer_over_msat as maximum possible, it can
894 // be only reduced later (not increased), so this channel should just be skipped
895 // as not sufficient.
896 if !over_path_minimum_msat && doesnt_exceed_cltv_delta_limit {
897 hit_minimum_limit = true;
898 } else if contributes_sufficient_value && doesnt_exceed_cltv_delta_limit {
899 // Note that low contribution here (limited by available_liquidity_msat)
900 // might violate htlc_minimum_msat on the hops which are next along the
901 // payment path (upstream to the payee). To avoid that, we recompute
902 // path fees knowing the final path contribution after constructing it.
903 let path_htlc_minimum_msat = compute_fees($next_hops_path_htlc_minimum_msat, $candidate.fees())
904 .and_then(|fee_msat| fee_msat.checked_add($next_hops_path_htlc_minimum_msat))
905 .map(|fee_msat| cmp::max(fee_msat, $candidate.htlc_minimum_msat()))
906 .unwrap_or_else(|| u64::max_value());
907 let hm_entry = dist.entry($src_node_id);
908 let old_entry = hm_entry.or_insert_with(|| {
909 // If there was previously no known way to access the source node
910 // (recall it goes payee-to-payer) of short_channel_id, first add a
911 // semi-dummy record just to compute the fees to reach the source node.
912 // This will affect our decision on selecting short_channel_id
913 // as a way to reach the $dest_node_id.
914 let mut fee_base_msat = 0;
915 let mut fee_proportional_millionths = 0;
916 if let Some(Some(fees)) = network_nodes.get(&$src_node_id).map(|node| node.lowest_inbound_channel_fees) {
917 fee_base_msat = fees.base_msat;
918 fee_proportional_millionths = fees.proportional_millionths;
921 node_id: $dest_node_id.clone(),
922 candidate: $candidate.clone(),
924 src_lowest_inbound_fees: RoutingFees {
925 base_msat: fee_base_msat,
926 proportional_millionths: fee_proportional_millionths,
928 next_hops_fee_msat: u64::max_value(),
929 hop_use_fee_msat: u64::max_value(),
930 total_fee_msat: u64::max_value(),
931 path_htlc_minimum_msat,
932 path_penalty_msat: u64::max_value(),
933 was_processed: false,
934 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
935 value_contribution_msat,
939 #[allow(unused_mut)] // We only use the mut in cfg(test)
940 let mut should_process = !old_entry.was_processed;
941 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
943 // In test/fuzzing builds, we do extra checks to make sure the skipping
944 // of already-seen nodes only happens in cases we expect (see below).
945 if !should_process { should_process = true; }
949 let mut hop_use_fee_msat = 0;
950 let mut total_fee_msat = $next_hops_fee_msat;
952 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
953 // will have the same effective-fee
954 if $src_node_id != our_node_id {
955 match compute_fees(amount_to_transfer_over_msat, $candidate.fees()) {
956 // max_value means we'll always fail
957 // the old_entry.total_fee_msat > total_fee_msat check
958 None => total_fee_msat = u64::max_value(),
960 hop_use_fee_msat = fee_msat;
961 total_fee_msat += hop_use_fee_msat;
962 // When calculating the lowest inbound fees to a node, we
963 // calculate fees here not based on the actual value we think
964 // will flow over this channel, but on the minimum value that
965 // we'll accept flowing over it. The minimum accepted value
966 // is a constant through each path collection run, ensuring
967 // consistent basis. Otherwise we may later find a
968 // different path to the source node that is more expensive,
969 // but which we consider to be cheaper because we are capacity
970 // constrained and the relative fee becomes lower.
971 match compute_fees(minimal_value_contribution_msat, old_entry.src_lowest_inbound_fees)
972 .map(|a| a.checked_add(total_fee_msat)) {
977 total_fee_msat = u64::max_value();
984 let path_penalty_msat = $next_hops_path_penalty_msat.checked_add(
985 scorer.channel_penalty_msat(short_channel_id, amount_to_transfer_over_msat, *available_liquidity_msat,
986 &$src_node_id, &$dest_node_id)).unwrap_or_else(|| u64::max_value());
987 let new_graph_node = RouteGraphNode {
988 node_id: $src_node_id,
989 lowest_fee_to_peer_through_node: total_fee_msat,
990 lowest_fee_to_node: $next_hops_fee_msat as u64 + hop_use_fee_msat,
991 total_cltv_delta: hop_total_cltv_delta,
992 value_contribution_msat: value_contribution_msat,
993 path_htlc_minimum_msat,
997 // Update the way of reaching $src_node_id with the given short_channel_id (from $dest_node_id),
998 // if this way is cheaper than the already known
999 // (considering the cost to "reach" this channel from the route destination,
1000 // the cost of using this channel,
1001 // and the cost of routing to the source node of this channel).
1002 // Also, consider that htlc_minimum_msat_difference, because we might end up
1003 // paying it. Consider the following exploit:
1004 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
1005 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
1006 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
1007 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
1009 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
1010 // but it may require additional tracking - we don't want to double-count
1011 // the fees included in $next_hops_path_htlc_minimum_msat, but also
1012 // can't use something that may decrease on future hops.
1013 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat)
1014 .checked_add(old_entry.path_penalty_msat)
1015 .unwrap_or_else(|| u64::max_value());
1016 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat)
1017 .checked_add(path_penalty_msat)
1018 .unwrap_or_else(|| u64::max_value());
1020 if !old_entry.was_processed && new_cost < old_cost {
1021 targets.push(new_graph_node);
1022 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
1023 old_entry.hop_use_fee_msat = hop_use_fee_msat;
1024 old_entry.total_fee_msat = total_fee_msat;
1025 old_entry.node_id = $dest_node_id.clone();
1026 old_entry.candidate = $candidate.clone();
1027 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
1028 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
1029 old_entry.path_penalty_msat = path_penalty_msat;
1030 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
1032 old_entry.value_contribution_msat = value_contribution_msat;
1034 did_add_update_path_to_src_node = true;
1035 } else if old_entry.was_processed && new_cost < old_cost {
1036 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
1038 // If we're skipping processing a node which was previously
1039 // processed even though we found another path to it with a
1040 // cheaper fee, check that it was because the second path we
1041 // found (which we are processing now) has a lower value
1042 // contribution due to an HTLC minimum limit.
1044 // e.g. take a graph with two paths from node 1 to node 2, one
1045 // through channel A, and one through channel B. Channel A and
1046 // B are both in the to-process heap, with their scores set by
1047 // a higher htlc_minimum than fee.
1048 // Channel A is processed first, and the channels onwards from
1049 // node 1 are added to the to-process heap. Thereafter, we pop
1050 // Channel B off of the heap, note that it has a much more
1051 // restrictive htlc_maximum_msat, and recalculate the fees for
1052 // all of node 1's channels using the new, reduced, amount.
1054 // This would be bogus - we'd be selecting a higher-fee path
1055 // with a lower htlc_maximum_msat instead of the one we'd
1056 // already decided to use.
1057 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
1059 value_contribution_msat + path_penalty_msat <
1060 old_entry.value_contribution_msat + old_entry.path_penalty_msat
1068 did_add_update_path_to_src_node
1072 let empty_node_features = NodeFeatures::empty();
1073 // Find ways (channels with destination) to reach a given node and store them
1074 // in the corresponding data structures (routing graph etc).
1075 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
1076 // meaning how much will be paid in fees after this node (to the best of our knowledge).
1077 // This data can later be helpful to optimize routing (pay lower fees).
1078 macro_rules! add_entries_to_cheapest_to_target_node {
1079 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr, $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr, $next_hops_path_penalty_msat: expr, $next_hops_cltv_delta: expr ) => {
1080 let skip_node = if let Some(elem) = dist.get_mut(&$node_id) {
1081 let was_processed = elem.was_processed;
1082 elem.was_processed = true;
1085 // Entries are added to dist in add_entry!() when there is a channel from a node.
1086 // Because there are no channels from payee, it will not have a dist entry at this point.
1087 // If we're processing any other node, it is always be the result of a channel from it.
1088 assert_eq!($node_id, payee_node_id);
1093 if let Some(first_channels) = first_hop_targets.get(&$node_id) {
1094 for details in first_channels {
1095 let candidate = CandidateRouteHop::FirstHop { details };
1096 add_entry!(candidate, our_node_id, $node_id, $fee_to_target_msat, $next_hops_value_contribution, $next_hops_path_htlc_minimum_msat, $next_hops_path_penalty_msat, $next_hops_cltv_delta);
1100 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
1103 &empty_node_features
1106 if !features.requires_unknown_bits() {
1107 for chan_id in $node.channels.iter() {
1108 let chan = network_channels.get(chan_id).unwrap();
1109 if !chan.features.requires_unknown_bits() {
1110 let (directed_channel, source) =
1111 chan.as_directed_to(&$node_id).expect("inconsistent NetworkGraph");
1112 if first_hops.is_none() || *source != our_node_id {
1113 if let Some(direction) = directed_channel.direction() {
1114 if direction.enabled {
1115 let candidate = CandidateRouteHop::PublicHop {
1116 info: directed_channel.with_update().unwrap(),
1117 short_channel_id: *chan_id,
1119 add_entry!(candidate, *source, $node_id, $fee_to_target_msat, $next_hops_value_contribution, $next_hops_path_htlc_minimum_msat, $next_hops_path_penalty_msat, $next_hops_cltv_delta);
1130 let mut payment_paths = Vec::<PaymentPath>::new();
1132 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
1133 'paths_collection: loop {
1134 // For every new path, start from scratch, except
1135 // bookkept_channels_liquidity_available_msat, which will improve
1136 // the further iterations of path finding. Also don't erase first_hop_targets.
1139 hit_minimum_limit = false;
1141 // If first hop is a private channel and the only way to reach the payee, this is the only
1142 // place where it could be added.
1143 if let Some(first_channels) = first_hop_targets.get(&payee_node_id) {
1144 for details in first_channels {
1145 let candidate = CandidateRouteHop::FirstHop { details };
1146 let added = add_entry!(candidate, our_node_id, payee_node_id, 0, path_value_msat, 0, 0u64, 0);
1147 log_trace!(logger, "{} direct route to payee via SCID {}", if added { "Added" } else { "Skipped" }, candidate.short_channel_id());
1151 // Add the payee as a target, so that the payee-to-payer
1152 // search algorithm knows what to start with.
1153 match network_nodes.get(&payee_node_id) {
1154 // The payee is not in our network graph, so nothing to add here.
1155 // There is still a chance of reaching them via last_hops though,
1156 // so don't yet fail the payment here.
1157 // If not, targets.pop() will not even let us enter the loop in step 2.
1160 add_entries_to_cheapest_to_target_node!(node, payee_node_id, 0, path_value_msat, 0, 0u64, 0);
1165 // If a caller provided us with last hops, add them to routing targets. Since this happens
1166 // earlier than general path finding, they will be somewhat prioritized, although currently
1167 // it matters only if the fees are exactly the same.
1168 for route in payment_params.route_hints.iter().filter(|route| !route.0.is_empty()) {
1169 let first_hop_in_route = &(route.0)[0];
1170 let have_hop_src_in_graph =
1171 // Only add the hops in this route to our candidate set if either
1172 // we have a direct channel to the first hop or the first hop is
1173 // in the regular network graph.
1174 first_hop_targets.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some() ||
1175 network_nodes.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some();
1176 if have_hop_src_in_graph {
1177 // We start building the path from reverse, i.e., from payee
1178 // to the first RouteHintHop in the path.
1179 let hop_iter = route.0.iter().rev();
1180 let prev_hop_iter = core::iter::once(&payment_params.payee_pubkey).chain(
1181 route.0.iter().skip(1).rev().map(|hop| &hop.src_node_id));
1182 let mut hop_used = true;
1183 let mut aggregate_next_hops_fee_msat: u64 = 0;
1184 let mut aggregate_next_hops_path_htlc_minimum_msat: u64 = 0;
1185 let mut aggregate_next_hops_path_penalty_msat: u64 = 0;
1186 let mut aggregate_next_hops_cltv_delta: u32 = 0;
1188 for (idx, (hop, prev_hop_id)) in hop_iter.zip(prev_hop_iter).enumerate() {
1189 let source = NodeId::from_pubkey(&hop.src_node_id);
1190 let target = NodeId::from_pubkey(&prev_hop_id);
1191 let candidate = network_channels
1192 .get(&hop.short_channel_id)
1193 .and_then(|channel| channel.as_directed_to(&target))
1194 .and_then(|(channel, _)| channel.with_update())
1195 .map(|info| CandidateRouteHop::PublicHop {
1197 short_channel_id: hop.short_channel_id,
1199 .unwrap_or_else(|| CandidateRouteHop::PrivateHop { hint: hop });
1200 let capacity_msat = candidate.effective_capacity().as_msat();
1201 aggregate_next_hops_path_penalty_msat = aggregate_next_hops_path_penalty_msat
1202 .checked_add(scorer.channel_penalty_msat(hop.short_channel_id, final_value_msat, capacity_msat, &source, &target))
1203 .unwrap_or_else(|| u64::max_value());
1205 aggregate_next_hops_cltv_delta = aggregate_next_hops_cltv_delta
1206 .checked_add(hop.cltv_expiry_delta as u32)
1207 .unwrap_or_else(|| u32::max_value());
1209 if !add_entry!(candidate, source, target, aggregate_next_hops_fee_msat, path_value_msat, aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat, aggregate_next_hops_cltv_delta) {
1210 // If this hop was not used then there is no use checking the preceding hops
1211 // in the RouteHint. We can break by just searching for a direct channel between
1212 // last checked hop and first_hop_targets
1216 // Searching for a direct channel between last checked hop and first_hop_targets
1217 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&prev_hop_id)) {
1218 for details in first_channels {
1219 let candidate = CandidateRouteHop::FirstHop { details };
1220 add_entry!(candidate, our_node_id, NodeId::from_pubkey(&prev_hop_id), aggregate_next_hops_fee_msat, path_value_msat, aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat, aggregate_next_hops_cltv_delta);
1228 // In the next values of the iterator, the aggregate fees already reflects
1229 // the sum of value sent from payer (final_value_msat) and routing fees
1230 // for the last node in the RouteHint. We need to just add the fees to
1231 // route through the current node so that the preceeding node (next iteration)
1233 let hops_fee = compute_fees(aggregate_next_hops_fee_msat + final_value_msat, hop.fees)
1234 .map_or(None, |inc| inc.checked_add(aggregate_next_hops_fee_msat));
1235 aggregate_next_hops_fee_msat = if let Some(val) = hops_fee { val } else { break; };
1237 let hop_htlc_minimum_msat = candidate.htlc_minimum_msat();
1238 let hop_htlc_minimum_msat_inc = if let Some(val) = compute_fees(aggregate_next_hops_path_htlc_minimum_msat, hop.fees) { val } else { break; };
1239 let hops_path_htlc_minimum = aggregate_next_hops_path_htlc_minimum_msat
1240 .checked_add(hop_htlc_minimum_msat_inc);
1241 aggregate_next_hops_path_htlc_minimum_msat = if let Some(val) = hops_path_htlc_minimum { cmp::max(hop_htlc_minimum_msat, val) } else { break; };
1243 if idx == route.0.len() - 1 {
1244 // The last hop in this iterator is the first hop in
1245 // overall RouteHint.
1246 // If this hop connects to a node with which we have a direct channel,
1247 // ignore the network graph and, if the last hop was added, add our
1248 // direct channel to the candidate set.
1250 // Note that we *must* check if the last hop was added as `add_entry`
1251 // always assumes that the third argument is a node to which we have a
1253 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&hop.src_node_id)) {
1254 for details in first_channels {
1255 let candidate = CandidateRouteHop::FirstHop { details };
1256 add_entry!(candidate, our_node_id, NodeId::from_pubkey(&hop.src_node_id), aggregate_next_hops_fee_msat, path_value_msat, aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat, aggregate_next_hops_cltv_delta);
1264 log_trace!(logger, "Starting main path collection loop with {} nodes pre-filled from first/last hops.", targets.len());
1266 // At this point, targets are filled with the data from first and
1267 // last hops communicated by the caller, and the payment receiver.
1268 let mut found_new_path = false;
1271 // If this loop terminates due the exhaustion of targets, two situations are possible:
1272 // - not enough outgoing liquidity:
1273 // 0 < already_collected_value_msat < final_value_msat
1274 // - enough outgoing liquidity:
1275 // final_value_msat <= already_collected_value_msat < recommended_value_msat
1276 // Both these cases (and other cases except reaching recommended_value_msat) mean that
1277 // paths_collection will be stopped because found_new_path==false.
1278 // This is not necessarily a routing failure.
1279 'path_construction: while let Some(RouteGraphNode { node_id, lowest_fee_to_node, total_cltv_delta, value_contribution_msat, path_htlc_minimum_msat, path_penalty_msat, .. }) = targets.pop() {
1281 // Since we're going payee-to-payer, hitting our node as a target means we should stop
1282 // traversing the graph and arrange the path out of what we found.
1283 if node_id == our_node_id {
1284 let mut new_entry = dist.remove(&our_node_id).unwrap();
1285 let mut ordered_hops = vec!((new_entry.clone(), NodeFeatures::empty()));
1288 let mut features_set = false;
1289 if let Some(first_channels) = first_hop_targets.get(&ordered_hops.last().unwrap().0.node_id) {
1290 for details in first_channels {
1291 if details.short_channel_id.unwrap() == ordered_hops.last().unwrap().0.candidate.short_channel_id() {
1292 ordered_hops.last_mut().unwrap().1 = details.counterparty.features.to_context();
1293 features_set = true;
1299 if let Some(node) = network_nodes.get(&ordered_hops.last().unwrap().0.node_id) {
1300 if let Some(node_info) = node.announcement_info.as_ref() {
1301 ordered_hops.last_mut().unwrap().1 = node_info.features.clone();
1303 ordered_hops.last_mut().unwrap().1 = NodeFeatures::empty();
1306 // We can fill in features for everything except hops which were
1307 // provided via the invoice we're paying. We could guess based on the
1308 // recipient's features but for now we simply avoid guessing at all.
1312 // Means we succesfully traversed from the payer to the payee, now
1313 // save this path for the payment route. Also, update the liquidity
1314 // remaining on the used hops, so that we take them into account
1315 // while looking for more paths.
1316 if ordered_hops.last().unwrap().0.node_id == payee_node_id {
1320 new_entry = match dist.remove(&ordered_hops.last().unwrap().0.node_id) {
1321 Some(payment_hop) => payment_hop,
1322 // We can't arrive at None because, if we ever add an entry to targets,
1323 // we also fill in the entry in dist (see add_entry!).
1324 None => unreachable!(),
1326 // We "propagate" the fees one hop backward (topologically) here,
1327 // so that fees paid for a HTLC forwarding on the current channel are
1328 // associated with the previous channel (where they will be subtracted).
1329 ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
1330 ordered_hops.push((new_entry.clone(), NodeFeatures::empty()));
1332 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
1333 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
1335 log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: \n {:#?}",
1336 ordered_hops.len(), value_contribution_msat, ordered_hops.iter().map(|h| &(h.0)).collect::<Vec<&PathBuildingHop>>());
1338 let mut payment_path = PaymentPath {hops: ordered_hops};
1340 // We could have possibly constructed a slightly inconsistent path: since we reduce
1341 // value being transferred along the way, we could have violated htlc_minimum_msat
1342 // on some channels we already passed (assuming dest->source direction). Here, we
1343 // recompute the fees again, so that if that's the case, we match the currently
1344 // underpaid htlc_minimum_msat with fees.
1345 payment_path.update_value_and_recompute_fees(cmp::min(value_contribution_msat, final_value_msat));
1347 // Since a path allows to transfer as much value as
1348 // the smallest channel it has ("bottleneck"), we should recompute
1349 // the fees so sender HTLC don't overpay fees when traversing
1350 // larger channels than the bottleneck. This may happen because
1351 // when we were selecting those channels we were not aware how much value
1352 // this path will transfer, and the relative fee for them
1353 // might have been computed considering a larger value.
1354 // Remember that we used these channels so that we don't rely
1355 // on the same liquidity in future paths.
1356 let mut prevented_redundant_path_selection = false;
1357 for (payment_hop, _) in payment_path.hops.iter() {
1358 let channel_liquidity_available_msat = bookkept_channels_liquidity_available_msat.get_mut(&payment_hop.candidate.short_channel_id()).unwrap();
1359 let mut spent_on_hop_msat = value_contribution_msat;
1360 let next_hops_fee_msat = payment_hop.next_hops_fee_msat;
1361 spent_on_hop_msat += next_hops_fee_msat;
1362 if spent_on_hop_msat == *channel_liquidity_available_msat {
1363 // If this path used all of this channel's available liquidity, we know
1364 // this path will not be selected again in the next loop iteration.
1365 prevented_redundant_path_selection = true;
1367 *channel_liquidity_available_msat -= spent_on_hop_msat;
1369 if !prevented_redundant_path_selection {
1370 // If we weren't capped by hitting a liquidity limit on a channel in the path,
1371 // we'll probably end up picking the same path again on the next iteration.
1372 // Decrease the available liquidity of a hop in the middle of the path.
1373 let victim_scid = payment_path.hops[(payment_path.hops.len() - 1) / 2].0.candidate.short_channel_id();
1374 log_trace!(logger, "Disabling channel {} for future path building iterations to avoid duplicates.", victim_scid);
1375 let victim_liquidity = bookkept_channels_liquidity_available_msat.get_mut(&victim_scid).unwrap();
1376 *victim_liquidity = 0;
1379 // Track the total amount all our collected paths allow to send so that we:
1380 // - know when to stop looking for more paths
1381 // - know which of the hops are useless considering how much more sats we need
1382 // (contributes_sufficient_value)
1383 already_collected_value_msat += value_contribution_msat;
1385 payment_paths.push(payment_path);
1386 found_new_path = true;
1387 break 'path_construction;
1390 // If we found a path back to the payee, we shouldn't try to process it again. This is
1391 // the equivalent of the `elem.was_processed` check in
1392 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
1393 if node_id == payee_node_id { continue 'path_construction; }
1395 // Otherwise, since the current target node is not us,
1396 // keep "unrolling" the payment graph from payee to payer by
1397 // finding a way to reach the current target from the payer side.
1398 match network_nodes.get(&node_id) {
1401 add_entries_to_cheapest_to_target_node!(node, node_id, lowest_fee_to_node, value_contribution_msat, path_htlc_minimum_msat, path_penalty_msat, total_cltv_delta);
1407 // If we don't support MPP, no use trying to gather more value ever.
1408 break 'paths_collection;
1412 // Stop either when the recommended value is reached or if no new path was found in this
1414 // In the latter case, making another path finding attempt won't help,
1415 // because we deterministically terminated the search due to low liquidity.
1416 if already_collected_value_msat >= recommended_value_msat || !found_new_path {
1417 log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
1418 already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
1419 break 'paths_collection;
1420 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
1421 // Further, if this was our first walk of the graph, and we weren't limited by an
1422 // htlc_minimum_msat, return immediately because this path should suffice. If we were
1423 // limited by an htlc_minimum_msat value, find another path with a higher value,
1424 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
1425 // still keeping a lower total fee than this path.
1426 if !hit_minimum_limit {
1427 log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
1428 break 'paths_collection;
1430 log_trace!(logger, "Collected our payment amount on the first pass, but running again to collect extra paths with a potentially higher limit.");
1431 path_value_msat = recommended_value_msat;
1436 if payment_paths.len() == 0 {
1437 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1440 if already_collected_value_msat < final_value_msat {
1441 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1444 // Sort by total fees and take the best paths.
1445 payment_paths.sort_by_key(|path| path.get_total_fee_paid_msat());
1446 if payment_paths.len() > 50 {
1447 payment_paths.truncate(50);
1450 // Draw multiple sufficient routes by randomly combining the selected paths.
1451 let mut drawn_routes = Vec::new();
1452 for i in 0..payment_paths.len() {
1453 let mut cur_route = Vec::<PaymentPath>::new();
1454 let mut aggregate_route_value_msat = 0;
1457 // TODO: real random shuffle
1458 // Currently just starts with i_th and goes up to i-1_th in a looped way.
1459 let cur_payment_paths = [&payment_paths[i..], &payment_paths[..i]].concat();
1462 for payment_path in cur_payment_paths {
1463 cur_route.push(payment_path.clone());
1464 aggregate_route_value_msat += payment_path.get_value_msat();
1465 if aggregate_route_value_msat > final_value_msat {
1466 // Last path likely overpaid. Substract it from the most expensive
1467 // (in terms of proportional fee) path in this route and recompute fees.
1468 // This might be not the most economically efficient way, but fewer paths
1469 // also makes routing more reliable.
1470 let mut overpaid_value_msat = aggregate_route_value_msat - final_value_msat;
1472 // First, drop some expensive low-value paths entirely if possible.
1473 // Sort by value so that we drop many really-low values first, since
1474 // fewer paths is better: the payment is less likely to fail.
1475 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1476 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1477 cur_route.sort_by_key(|path| path.get_value_msat());
1478 // We should make sure that at least 1 path left.
1479 let mut paths_left = cur_route.len();
1480 cur_route.retain(|path| {
1481 if paths_left == 1 {
1484 let mut keep = true;
1485 let path_value_msat = path.get_value_msat();
1486 if path_value_msat <= overpaid_value_msat {
1488 overpaid_value_msat -= path_value_msat;
1494 if overpaid_value_msat == 0 {
1498 assert!(cur_route.len() > 0);
1501 // Now, substract the overpaid value from the most-expensive path.
1502 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1503 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1504 cur_route.sort_by_key(|path| { path.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>() });
1505 let expensive_payment_path = cur_route.first_mut().unwrap();
1506 // We already dropped all the small channels above, meaning all the
1507 // remaining channels are larger than remaining overpaid_value_msat.
1508 // Thus, this can't be negative.
1509 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
1510 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
1514 drawn_routes.push(cur_route);
1518 // Select the best route by lowest total fee.
1519 drawn_routes.sort_by_key(|paths| paths.iter().map(|path| path.get_total_fee_paid_msat()).sum::<u64>());
1520 let mut selected_paths = Vec::<Vec<Result<RouteHop, LightningError>>>::new();
1521 for payment_path in drawn_routes.first().unwrap() {
1522 let mut path = payment_path.hops.iter().map(|(payment_hop, node_features)| {
1524 pubkey: PublicKey::from_slice(payment_hop.node_id.as_slice()).map_err(|_| LightningError{err: format!("Public key {:?} is invalid", &payment_hop.node_id), action: ErrorAction::IgnoreAndLog(Level::Trace)})?,
1525 node_features: node_features.clone(),
1526 short_channel_id: payment_hop.candidate.short_channel_id(),
1527 channel_features: payment_hop.candidate.features(),
1528 fee_msat: payment_hop.fee_msat,
1529 cltv_expiry_delta: payment_hop.candidate.cltv_expiry_delta(),
1531 }).collect::<Vec<_>>();
1532 // Propagate the cltv_expiry_delta one hop backwards since the delta from the current hop is
1533 // applicable for the previous hop.
1534 path.iter_mut().rev().fold(final_cltv_expiry_delta, |prev_cltv_expiry_delta, hop| {
1535 core::mem::replace(&mut hop.as_mut().unwrap().cltv_expiry_delta, prev_cltv_expiry_delta)
1537 selected_paths.push(path);
1540 if let Some(features) = &payment_params.features {
1541 for path in selected_paths.iter_mut() {
1542 if let Ok(route_hop) = path.last_mut().unwrap() {
1543 route_hop.node_features = features.to_context();
1549 paths: selected_paths.into_iter().map(|path| path.into_iter().collect()).collect::<Result<Vec<_>, _>>()?,
1550 payment_params: Some(payment_params.clone()),
1552 log_info!(logger, "Got route to {}: {}", payment_params.payee_pubkey, log_route!(route));
1556 // When an adversarial intermediary node observes a payment, it may be able to infer its
1557 // destination, if the remaining CLTV expiry delta exactly matches a feasible path in the network
1558 // graph. In order to improve privacy, this method obfuscates the CLTV expiry deltas along the
1559 // payment path by adding a randomized 'shadow route' offset to the final hop.
1560 fn add_random_cltv_offset(route: &mut Route, payment_params: &PaymentParameters, network_graph: &ReadOnlyNetworkGraph, random_seed_bytes: &[u8; 32]) {
1561 let network_channels = network_graph.channels();
1562 let network_nodes = network_graph.nodes();
1564 for path in route.paths.iter_mut() {
1565 let mut shadow_ctlv_expiry_delta_offset: u32 = 0;
1567 // Choose the last publicly known node as the starting point for the random walk
1568 if let Some(starting_hop) = path.iter().rev().find(|h| network_nodes.contains_key(&NodeId::from_pubkey(&h.pubkey))) {
1569 let mut cur_node_id = NodeId::from_pubkey(&starting_hop.pubkey);
1571 // Init PRNG with path nonce
1572 let mut path_nonce = [0u8; 12];
1573 path_nonce.copy_from_slice(&cur_node_id.as_slice()[..12]);
1574 let mut prng = ChaCha20::new(random_seed_bytes, &path_nonce);
1575 let mut random_path_bytes = [0u8; ::core::mem::size_of::<usize>()];
1577 // Pick a random path length in [1 .. 3]
1578 prng.process_in_place(&mut random_path_bytes);
1579 let random_walk_length = usize::from_be_bytes(random_path_bytes).wrapping_rem(3).wrapping_add(1);
1581 for _random_hop in 0..random_walk_length {
1582 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
1583 // Randomly choose the next hop
1584 prng.process_in_place(&mut random_path_bytes);
1585 if let Some(random_channel) = usize::from_be_bytes(random_path_bytes).checked_rem(cur_node.channels.len())
1586 .and_then(|index| cur_node.channels.get(index))
1587 .and_then(|id| network_channels.get(id)) {
1588 random_channel.as_directed_from(&cur_node_id).map(|(dir_info, next_id)| {
1589 dir_info.direction().map(|channel_update_info|
1590 shadow_ctlv_expiry_delta_offset = shadow_ctlv_expiry_delta_offset
1591 .checked_add(channel_update_info.cltv_expiry_delta.into())
1592 .unwrap_or(shadow_ctlv_expiry_delta_offset));
1593 cur_node_id = *next_id;
1599 // If the entire path is private, choose a random offset from multiples of
1600 // MEDIAN_HOP_CLTV_EXPIRY_DELTA
1601 let mut prng = ChaCha20::new(random_seed_bytes, &[0u8; 8]);
1602 let mut random_bytes = [0u8; 4];
1603 prng.process_in_place(&mut random_bytes);
1604 let random_walk_length = u32::from_be_bytes(random_bytes).wrapping_rem(3).wrapping_add(1);
1605 shadow_ctlv_expiry_delta_offset = random_walk_length * MEDIAN_HOP_CLTV_EXPIRY_DELTA;
1608 // Limit the total offset to reduce the worst-case locked liquidity timevalue
1609 const MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET: u32 = 3*144;
1610 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET);
1612 // Limit the offset so we never exceed the max_total_cltv_expiry_delta. To improve plausibility,
1613 // we choose the limit to be the largest possible multiple of MEDIAN_HOP_CLTV_EXPIRY_DELTA.
1614 let path_total_cltv_expiry_delta: u32 = path.iter().map(|h| h.cltv_expiry_delta).sum();
1615 let mut max_path_offset = payment_params.max_total_cltv_expiry_delta - path_total_cltv_expiry_delta;
1616 max_path_offset = cmp::max(
1617 max_path_offset - (max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA),
1618 max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA);
1619 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, max_path_offset);
1621 // Add 'shadow' CLTV offset to the final hop
1622 if let Some(last_hop) = path.last_mut() {
1623 last_hop.cltv_expiry_delta = last_hop.cltv_expiry_delta
1624 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(last_hop.cltv_expiry_delta);
1631 use routing::network_graph::{NetworkGraph, NetGraphMsgHandler, NodeId};
1632 use routing::router::{get_route, add_random_cltv_offset, PaymentParameters, Route, RouteHint, RouteHintHop, RouteHop, RoutingFees, DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA};
1633 use routing::scoring::Score;
1634 use chain::transaction::OutPoint;
1635 use chain::keysinterface::KeysInterface;
1636 use ln::features::{ChannelFeatures, InitFeatures, InvoiceFeatures, NodeFeatures};
1637 use ln::msgs::{ErrorAction, LightningError, OptionalField, UnsignedChannelAnnouncement, ChannelAnnouncement, RoutingMessageHandler,
1638 NodeAnnouncement, UnsignedNodeAnnouncement, ChannelUpdate, UnsignedChannelUpdate};
1639 use ln::channelmanager;
1640 use util::test_utils;
1641 use util::chacha20::ChaCha20;
1642 use util::ser::Writeable;
1644 use util::ser::Writer;
1646 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
1647 use bitcoin::hashes::Hash;
1648 use bitcoin::network::constants::Network;
1649 use bitcoin::blockdata::constants::genesis_block;
1650 use bitcoin::blockdata::script::Builder;
1651 use bitcoin::blockdata::opcodes;
1652 use bitcoin::blockdata::transaction::TxOut;
1656 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
1657 use bitcoin::secp256k1::{Secp256k1, All};
1660 use sync::{self, Arc};
1662 fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
1663 features: InitFeatures, outbound_capacity_msat: u64) -> channelmanager::ChannelDetails {
1664 channelmanager::ChannelDetails {
1665 channel_id: [0; 32],
1666 counterparty: channelmanager::ChannelCounterparty {
1669 unspendable_punishment_reserve: 0,
1670 forwarding_info: None,
1672 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
1674 inbound_scid_alias: None,
1675 channel_value_satoshis: 0,
1678 outbound_capacity_msat,
1679 inbound_capacity_msat: 42,
1680 unspendable_punishment_reserve: None,
1681 confirmations_required: None,
1682 force_close_spend_delay: None,
1683 is_outbound: true, is_funding_locked: true,
1684 is_usable: true, is_public: true,
1688 // Using the same keys for LN and BTC ids
1690 net_graph_msg_handler: &NetGraphMsgHandler<Arc<NetworkGraph>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1691 secp_ctx: &Secp256k1<All>, node_1_privkey: &SecretKey, node_2_privkey: &SecretKey, features: ChannelFeatures, short_channel_id: u64
1693 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1694 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1696 let unsigned_announcement = UnsignedChannelAnnouncement {
1698 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1702 bitcoin_key_1: node_id_1,
1703 bitcoin_key_2: node_id_2,
1704 excess_data: Vec::new(),
1707 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1708 let valid_announcement = ChannelAnnouncement {
1709 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1710 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1711 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1712 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1713 contents: unsigned_announcement.clone(),
1715 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1716 Ok(res) => assert!(res),
1722 net_graph_msg_handler: &NetGraphMsgHandler<Arc<NetworkGraph>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1723 secp_ctx: &Secp256k1<All>, node_privkey: &SecretKey, update: UnsignedChannelUpdate
1725 let msghash = hash_to_message!(&Sha256dHash::hash(&update.encode()[..])[..]);
1726 let valid_channel_update = ChannelUpdate {
1727 signature: secp_ctx.sign(&msghash, node_privkey),
1728 contents: update.clone()
1731 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1732 Ok(res) => assert!(res),
1737 fn add_or_update_node(
1738 net_graph_msg_handler: &NetGraphMsgHandler<Arc<NetworkGraph>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1739 secp_ctx: &Secp256k1<All>, node_privkey: &SecretKey, features: NodeFeatures, timestamp: u32
1741 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
1742 let unsigned_announcement = UnsignedNodeAnnouncement {
1748 addresses: Vec::new(),
1749 excess_address_data: Vec::new(),
1750 excess_data: Vec::new(),
1752 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1753 let valid_announcement = NodeAnnouncement {
1754 signature: secp_ctx.sign(&msghash, node_privkey),
1755 contents: unsigned_announcement.clone()
1758 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1764 fn get_nodes(secp_ctx: &Secp256k1<All>) -> (SecretKey, PublicKey, Vec<SecretKey>, Vec<PublicKey>) {
1765 let privkeys: Vec<SecretKey> = (2..10).map(|i| {
1766 SecretKey::from_slice(&hex::decode(format!("{:02x}", i).repeat(32)).unwrap()[..]).unwrap()
1769 let pubkeys = privkeys.iter().map(|secret| PublicKey::from_secret_key(&secp_ctx, secret)).collect();
1771 let our_privkey = SecretKey::from_slice(&hex::decode("01".repeat(32)).unwrap()[..]).unwrap();
1772 let our_id = PublicKey::from_secret_key(&secp_ctx, &our_privkey);
1774 (our_privkey, our_id, privkeys, pubkeys)
1777 fn id_to_feature_flags(id: u8) -> Vec<u8> {
1778 // Set the feature flags to the id'th odd (ie non-required) feature bit so that we can
1779 // test for it later.
1780 let idx = (id - 1) * 2 + 1;
1782 vec![1 << (idx - 8*3), 0, 0, 0]
1783 } else if idx > 8*2 {
1784 vec![1 << (idx - 8*2), 0, 0]
1785 } else if idx > 8*1 {
1786 vec![1 << (idx - 8*1), 0]
1792 fn build_graph() -> (
1794 sync::Arc<NetworkGraph>,
1795 NetGraphMsgHandler<sync::Arc<NetworkGraph>, sync::Arc<test_utils::TestChainSource>, sync::Arc<crate::util::test_utils::TestLogger>>,
1796 sync::Arc<test_utils::TestChainSource>,
1797 sync::Arc<test_utils::TestLogger>,
1799 let secp_ctx = Secp256k1::new();
1800 let logger = Arc::new(test_utils::TestLogger::new());
1801 let chain_monitor = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1802 let network_graph = Arc::new(NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash()));
1803 let net_graph_msg_handler = NetGraphMsgHandler::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
1804 // Build network from our_id to node6:
1806 // -1(1)2- node0 -1(3)2-
1808 // our_id -1(12)2- node7 -1(13)2--- node2
1810 // -1(2)2- node1 -1(4)2-
1813 // chan1 1-to-2: disabled
1814 // chan1 2-to-1: enabled, 0 fee
1816 // chan2 1-to-2: enabled, ignored fee
1817 // chan2 2-to-1: enabled, 0 fee
1819 // chan3 1-to-2: enabled, 0 fee
1820 // chan3 2-to-1: enabled, 100 msat fee
1822 // chan4 1-to-2: enabled, 100% fee
1823 // chan4 2-to-1: enabled, 0 fee
1825 // chan12 1-to-2: enabled, ignored fee
1826 // chan12 2-to-1: enabled, 0 fee
1828 // chan13 1-to-2: enabled, 200% fee
1829 // chan13 2-to-1: enabled, 0 fee
1832 // -1(5)2- node3 -1(8)2--
1836 // node2--1(6)2- node4 -1(9)2--- node6 (not in global route map)
1838 // -1(7)2- node5 -1(10)2-
1840 // Channels 5, 8, 9 and 10 are private channels.
1842 // chan5 1-to-2: enabled, 100 msat fee
1843 // chan5 2-to-1: enabled, 0 fee
1845 // chan6 1-to-2: enabled, 0 fee
1846 // chan6 2-to-1: enabled, 0 fee
1848 // chan7 1-to-2: enabled, 100% fee
1849 // chan7 2-to-1: enabled, 0 fee
1851 // chan8 1-to-2: enabled, variable fee (0 then 1000 msat)
1852 // chan8 2-to-1: enabled, 0 fee
1854 // chan9 1-to-2: enabled, 1001 msat fee
1855 // chan9 2-to-1: enabled, 0 fee
1857 // chan10 1-to-2: enabled, 0 fee
1858 // chan10 2-to-1: enabled, 0 fee
1860 // chan11 1-to-2: enabled, 0 fee
1861 // chan11 2-to-1: enabled, 0 fee
1863 let (our_privkey, _, privkeys, _) = get_nodes(&secp_ctx);
1865 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[0], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
1866 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1867 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1868 short_channel_id: 1,
1871 cltv_expiry_delta: 0,
1872 htlc_minimum_msat: 0,
1873 htlc_maximum_msat: OptionalField::Absent,
1875 fee_proportional_millionths: 0,
1876 excess_data: Vec::new()
1879 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
1881 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
1882 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1883 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1884 short_channel_id: 2,
1887 cltv_expiry_delta: (5 << 4) | 3,
1888 htlc_minimum_msat: 0,
1889 htlc_maximum_msat: OptionalField::Absent,
1890 fee_base_msat: u32::max_value(),
1891 fee_proportional_millionths: u32::max_value(),
1892 excess_data: Vec::new()
1894 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1895 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1896 short_channel_id: 2,
1899 cltv_expiry_delta: 0,
1900 htlc_minimum_msat: 0,
1901 htlc_maximum_msat: OptionalField::Absent,
1903 fee_proportional_millionths: 0,
1904 excess_data: Vec::new()
1907 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
1909 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[7], ChannelFeatures::from_le_bytes(id_to_feature_flags(12)), 12);
1910 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1911 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1912 short_channel_id: 12,
1915 cltv_expiry_delta: (5 << 4) | 3,
1916 htlc_minimum_msat: 0,
1917 htlc_maximum_msat: OptionalField::Absent,
1918 fee_base_msat: u32::max_value(),
1919 fee_proportional_millionths: u32::max_value(),
1920 excess_data: Vec::new()
1922 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1923 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1924 short_channel_id: 12,
1927 cltv_expiry_delta: 0,
1928 htlc_minimum_msat: 0,
1929 htlc_maximum_msat: OptionalField::Absent,
1931 fee_proportional_millionths: 0,
1932 excess_data: Vec::new()
1935 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], NodeFeatures::from_le_bytes(id_to_feature_flags(8)), 0);
1937 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
1938 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1939 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1940 short_channel_id: 3,
1943 cltv_expiry_delta: (3 << 4) | 1,
1944 htlc_minimum_msat: 0,
1945 htlc_maximum_msat: OptionalField::Absent,
1947 fee_proportional_millionths: 0,
1948 excess_data: Vec::new()
1950 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1951 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1952 short_channel_id: 3,
1955 cltv_expiry_delta: (3 << 4) | 2,
1956 htlc_minimum_msat: 0,
1957 htlc_maximum_msat: OptionalField::Absent,
1959 fee_proportional_millionths: 0,
1960 excess_data: Vec::new()
1963 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
1964 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1965 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1966 short_channel_id: 4,
1969 cltv_expiry_delta: (4 << 4) | 1,
1970 htlc_minimum_msat: 0,
1971 htlc_maximum_msat: OptionalField::Absent,
1973 fee_proportional_millionths: 1000000,
1974 excess_data: Vec::new()
1976 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1977 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1978 short_channel_id: 4,
1981 cltv_expiry_delta: (4 << 4) | 2,
1982 htlc_minimum_msat: 0,
1983 htlc_maximum_msat: OptionalField::Absent,
1985 fee_proportional_millionths: 0,
1986 excess_data: Vec::new()
1989 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(13)), 13);
1990 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1991 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1992 short_channel_id: 13,
1995 cltv_expiry_delta: (13 << 4) | 1,
1996 htlc_minimum_msat: 0,
1997 htlc_maximum_msat: OptionalField::Absent,
1999 fee_proportional_millionths: 2000000,
2000 excess_data: Vec::new()
2002 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2003 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2004 short_channel_id: 13,
2007 cltv_expiry_delta: (13 << 4) | 2,
2008 htlc_minimum_msat: 0,
2009 htlc_maximum_msat: OptionalField::Absent,
2011 fee_proportional_millionths: 0,
2012 excess_data: Vec::new()
2015 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
2017 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
2018 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2019 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2020 short_channel_id: 6,
2023 cltv_expiry_delta: (6 << 4) | 1,
2024 htlc_minimum_msat: 0,
2025 htlc_maximum_msat: OptionalField::Absent,
2027 fee_proportional_millionths: 0,
2028 excess_data: Vec::new()
2030 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
2031 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2032 short_channel_id: 6,
2035 cltv_expiry_delta: (6 << 4) | 2,
2036 htlc_minimum_msat: 0,
2037 htlc_maximum_msat: OptionalField::Absent,
2039 fee_proportional_millionths: 0,
2040 excess_data: Vec::new(),
2043 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(11)), 11);
2044 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
2045 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2046 short_channel_id: 11,
2049 cltv_expiry_delta: (11 << 4) | 1,
2050 htlc_minimum_msat: 0,
2051 htlc_maximum_msat: OptionalField::Absent,
2053 fee_proportional_millionths: 0,
2054 excess_data: Vec::new()
2056 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
2057 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2058 short_channel_id: 11,
2061 cltv_expiry_delta: (11 << 4) | 2,
2062 htlc_minimum_msat: 0,
2063 htlc_maximum_msat: OptionalField::Absent,
2065 fee_proportional_millionths: 0,
2066 excess_data: Vec::new()
2069 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(5)), 0);
2071 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
2073 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[5], ChannelFeatures::from_le_bytes(id_to_feature_flags(7)), 7);
2074 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2075 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2076 short_channel_id: 7,
2079 cltv_expiry_delta: (7 << 4) | 1,
2080 htlc_minimum_msat: 0,
2081 htlc_maximum_msat: OptionalField::Absent,
2083 fee_proportional_millionths: 1000000,
2084 excess_data: Vec::new()
2086 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[5], UnsignedChannelUpdate {
2087 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2088 short_channel_id: 7,
2091 cltv_expiry_delta: (7 << 4) | 2,
2092 htlc_minimum_msat: 0,
2093 htlc_maximum_msat: OptionalField::Absent,
2095 fee_proportional_millionths: 0,
2096 excess_data: Vec::new()
2099 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[5], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
2101 (secp_ctx, network_graph, net_graph_msg_handler, chain_monitor, logger)
2105 fn simple_route_test() {
2106 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2107 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2108 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2109 let scorer = test_utils::TestScorer::with_penalty(0);
2110 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2111 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2113 // Simple route to 2 via 1
2115 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) {
2116 assert_eq!(err, "Cannot send a payment of 0 msat");
2117 } else { panic!(); }
2119 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2120 assert_eq!(route.paths[0].len(), 2);
2122 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2123 assert_eq!(route.paths[0][0].short_channel_id, 2);
2124 assert_eq!(route.paths[0][0].fee_msat, 100);
2125 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2126 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2127 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2129 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2130 assert_eq!(route.paths[0][1].short_channel_id, 4);
2131 assert_eq!(route.paths[0][1].fee_msat, 100);
2132 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2133 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2134 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2138 fn invalid_first_hop_test() {
2139 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2140 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2141 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2142 let scorer = test_utils::TestScorer::with_penalty(0);
2143 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2144 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2146 // Simple route to 2 via 1
2148 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
2150 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) =
2151 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) {
2152 assert_eq!(err, "First hop cannot have our_node_pubkey as a destination.");
2153 } else { panic!(); }
2155 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2156 assert_eq!(route.paths[0].len(), 2);
2160 fn htlc_minimum_test() {
2161 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2162 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2163 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2164 let scorer = test_utils::TestScorer::with_penalty(0);
2165 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2166 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2168 // Simple route to 2 via 1
2170 // Disable other paths
2171 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2172 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2173 short_channel_id: 12,
2175 flags: 2, // to disable
2176 cltv_expiry_delta: 0,
2177 htlc_minimum_msat: 0,
2178 htlc_maximum_msat: OptionalField::Absent,
2180 fee_proportional_millionths: 0,
2181 excess_data: Vec::new()
2183 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2184 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2185 short_channel_id: 3,
2187 flags: 2, // to disable
2188 cltv_expiry_delta: 0,
2189 htlc_minimum_msat: 0,
2190 htlc_maximum_msat: OptionalField::Absent,
2192 fee_proportional_millionths: 0,
2193 excess_data: Vec::new()
2195 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2196 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2197 short_channel_id: 13,
2199 flags: 2, // to disable
2200 cltv_expiry_delta: 0,
2201 htlc_minimum_msat: 0,
2202 htlc_maximum_msat: OptionalField::Absent,
2204 fee_proportional_millionths: 0,
2205 excess_data: Vec::new()
2207 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2208 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2209 short_channel_id: 6,
2211 flags: 2, // to disable
2212 cltv_expiry_delta: 0,
2213 htlc_minimum_msat: 0,
2214 htlc_maximum_msat: OptionalField::Absent,
2216 fee_proportional_millionths: 0,
2217 excess_data: Vec::new()
2219 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2220 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2221 short_channel_id: 7,
2223 flags: 2, // to disable
2224 cltv_expiry_delta: 0,
2225 htlc_minimum_msat: 0,
2226 htlc_maximum_msat: OptionalField::Absent,
2228 fee_proportional_millionths: 0,
2229 excess_data: Vec::new()
2232 // Check against amount_to_transfer_over_msat.
2233 // Set minimal HTLC of 200_000_000 msat.
2234 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2235 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2236 short_channel_id: 2,
2239 cltv_expiry_delta: 0,
2240 htlc_minimum_msat: 200_000_000,
2241 htlc_maximum_msat: OptionalField::Absent,
2243 fee_proportional_millionths: 0,
2244 excess_data: Vec::new()
2247 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
2249 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2250 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2251 short_channel_id: 4,
2254 cltv_expiry_delta: 0,
2255 htlc_minimum_msat: 0,
2256 htlc_maximum_msat: OptionalField::Present(199_999_999),
2258 fee_proportional_millionths: 0,
2259 excess_data: Vec::new()
2262 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
2263 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) {
2264 assert_eq!(err, "Failed to find a path to the given destination");
2265 } else { panic!(); }
2267 // Lift the restriction on the first hop.
2268 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2269 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2270 short_channel_id: 2,
2273 cltv_expiry_delta: 0,
2274 htlc_minimum_msat: 0,
2275 htlc_maximum_msat: OptionalField::Absent,
2277 fee_proportional_millionths: 0,
2278 excess_data: Vec::new()
2281 // A payment above the minimum should pass
2282 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();
2283 assert_eq!(route.paths[0].len(), 2);
2287 fn htlc_minimum_overpay_test() {
2288 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2289 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2290 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
2291 let scorer = test_utils::TestScorer::with_penalty(0);
2292 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2293 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2295 // A route to node#2 via two paths.
2296 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
2297 // Thus, they can't send 60 without overpaying.
2298 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2299 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2300 short_channel_id: 2,
2303 cltv_expiry_delta: 0,
2304 htlc_minimum_msat: 35_000,
2305 htlc_maximum_msat: OptionalField::Present(40_000),
2307 fee_proportional_millionths: 0,
2308 excess_data: Vec::new()
2310 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2311 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2312 short_channel_id: 12,
2315 cltv_expiry_delta: 0,
2316 htlc_minimum_msat: 35_000,
2317 htlc_maximum_msat: OptionalField::Present(40_000),
2319 fee_proportional_millionths: 0,
2320 excess_data: Vec::new()
2324 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2325 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2326 short_channel_id: 13,
2329 cltv_expiry_delta: 0,
2330 htlc_minimum_msat: 0,
2331 htlc_maximum_msat: OptionalField::Absent,
2333 fee_proportional_millionths: 0,
2334 excess_data: Vec::new()
2336 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2337 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2338 short_channel_id: 4,
2341 cltv_expiry_delta: 0,
2342 htlc_minimum_msat: 0,
2343 htlc_maximum_msat: OptionalField::Absent,
2345 fee_proportional_millionths: 0,
2346 excess_data: Vec::new()
2349 // Disable other paths
2350 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2351 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2352 short_channel_id: 1,
2354 flags: 2, // to disable
2355 cltv_expiry_delta: 0,
2356 htlc_minimum_msat: 0,
2357 htlc_maximum_msat: OptionalField::Absent,
2359 fee_proportional_millionths: 0,
2360 excess_data: Vec::new()
2363 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 60_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2364 // Overpay fees to hit htlc_minimum_msat.
2365 let overpaid_fees = route.paths[0][0].fee_msat + route.paths[1][0].fee_msat;
2366 // TODO: this could be better balanced to overpay 10k and not 15k.
2367 assert_eq!(overpaid_fees, 15_000);
2369 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
2370 // while taking even more fee to match htlc_minimum_msat.
2371 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2372 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2373 short_channel_id: 12,
2376 cltv_expiry_delta: 0,
2377 htlc_minimum_msat: 65_000,
2378 htlc_maximum_msat: OptionalField::Present(80_000),
2380 fee_proportional_millionths: 0,
2381 excess_data: Vec::new()
2383 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2384 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2385 short_channel_id: 2,
2388 cltv_expiry_delta: 0,
2389 htlc_minimum_msat: 0,
2390 htlc_maximum_msat: OptionalField::Absent,
2392 fee_proportional_millionths: 0,
2393 excess_data: Vec::new()
2395 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2396 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2397 short_channel_id: 4,
2400 cltv_expiry_delta: 0,
2401 htlc_minimum_msat: 0,
2402 htlc_maximum_msat: OptionalField::Absent,
2404 fee_proportional_millionths: 100_000,
2405 excess_data: Vec::new()
2408 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 60_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2409 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
2410 assert_eq!(route.paths.len(), 1);
2411 assert_eq!(route.paths[0][0].short_channel_id, 12);
2412 let fees = route.paths[0][0].fee_msat;
2413 assert_eq!(fees, 5_000);
2415 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2416 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
2417 // the other channel.
2418 assert_eq!(route.paths.len(), 1);
2419 assert_eq!(route.paths[0][0].short_channel_id, 2);
2420 let fees = route.paths[0][0].fee_msat;
2421 assert_eq!(fees, 5_000);
2425 fn disable_channels_test() {
2426 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2427 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2428 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2429 let scorer = test_utils::TestScorer::with_penalty(0);
2430 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2431 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2433 // // Disable channels 4 and 12 by flags=2
2434 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2435 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2436 short_channel_id: 4,
2438 flags: 2, // to disable
2439 cltv_expiry_delta: 0,
2440 htlc_minimum_msat: 0,
2441 htlc_maximum_msat: OptionalField::Absent,
2443 fee_proportional_millionths: 0,
2444 excess_data: Vec::new()
2446 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2447 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2448 short_channel_id: 12,
2450 flags: 2, // to disable
2451 cltv_expiry_delta: 0,
2452 htlc_minimum_msat: 0,
2453 htlc_maximum_msat: OptionalField::Absent,
2455 fee_proportional_millionths: 0,
2456 excess_data: Vec::new()
2459 // If all the channels require some features we don't understand, route should fail
2460 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) {
2461 assert_eq!(err, "Failed to find a path to the given destination");
2462 } else { panic!(); }
2464 // If we specify a channel to node7, that overrides our local channel view and that gets used
2465 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2466 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();
2467 assert_eq!(route.paths[0].len(), 2);
2469 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2470 assert_eq!(route.paths[0][0].short_channel_id, 42);
2471 assert_eq!(route.paths[0][0].fee_msat, 200);
2472 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2473 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2474 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2476 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2477 assert_eq!(route.paths[0][1].short_channel_id, 13);
2478 assert_eq!(route.paths[0][1].fee_msat, 100);
2479 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2480 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2481 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2485 fn disable_node_test() {
2486 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2487 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2488 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2489 let scorer = test_utils::TestScorer::with_penalty(0);
2490 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2491 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2493 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
2494 let mut unknown_features = NodeFeatures::known();
2495 unknown_features.set_unknown_feature_required();
2496 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
2497 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
2498 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
2500 // If all nodes require some features we don't understand, route should fail
2501 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) {
2502 assert_eq!(err, "Failed to find a path to the given destination");
2503 } else { panic!(); }
2505 // If we specify a channel to node7, that overrides our local channel view and that gets used
2506 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2507 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&our_chans.iter().collect::<Vec<_>>()), 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2508 assert_eq!(route.paths[0].len(), 2);
2510 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2511 assert_eq!(route.paths[0][0].short_channel_id, 42);
2512 assert_eq!(route.paths[0][0].fee_msat, 200);
2513 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2514 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2515 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2517 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2518 assert_eq!(route.paths[0][1].short_channel_id, 13);
2519 assert_eq!(route.paths[0][1].fee_msat, 100);
2520 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2521 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2522 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2524 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
2525 // naively) assume that the user checked the feature bits on the invoice, which override
2526 // the node_announcement.
2530 fn our_chans_test() {
2531 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2532 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2533 let scorer = test_utils::TestScorer::with_penalty(0);
2534 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2535 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2537 // Route to 1 via 2 and 3 because our channel to 1 is disabled
2538 let payment_params = PaymentParameters::from_node_id(nodes[0]);
2539 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2540 assert_eq!(route.paths[0].len(), 3);
2542 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2543 assert_eq!(route.paths[0][0].short_channel_id, 2);
2544 assert_eq!(route.paths[0][0].fee_msat, 200);
2545 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2546 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2547 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2549 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2550 assert_eq!(route.paths[0][1].short_channel_id, 4);
2551 assert_eq!(route.paths[0][1].fee_msat, 100);
2552 assert_eq!(route.paths[0][1].cltv_expiry_delta, (3 << 4) | 2);
2553 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2554 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2556 assert_eq!(route.paths[0][2].pubkey, nodes[0]);
2557 assert_eq!(route.paths[0][2].short_channel_id, 3);
2558 assert_eq!(route.paths[0][2].fee_msat, 100);
2559 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
2560 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(1));
2561 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(3));
2563 // If we specify a channel to node7, that overrides our local channel view and that gets used
2564 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2565 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2566 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();
2567 assert_eq!(route.paths[0].len(), 2);
2569 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2570 assert_eq!(route.paths[0][0].short_channel_id, 42);
2571 assert_eq!(route.paths[0][0].fee_msat, 200);
2572 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2573 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2574 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2576 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2577 assert_eq!(route.paths[0][1].short_channel_id, 13);
2578 assert_eq!(route.paths[0][1].fee_msat, 100);
2579 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2580 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2581 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2584 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2585 let zero_fees = RoutingFees {
2587 proportional_millionths: 0,
2589 vec![RouteHint(vec![RouteHintHop {
2590 src_node_id: nodes[3],
2591 short_channel_id: 8,
2593 cltv_expiry_delta: (8 << 4) | 1,
2594 htlc_minimum_msat: None,
2595 htlc_maximum_msat: None,
2597 ]), RouteHint(vec![RouteHintHop {
2598 src_node_id: nodes[4],
2599 short_channel_id: 9,
2602 proportional_millionths: 0,
2604 cltv_expiry_delta: (9 << 4) | 1,
2605 htlc_minimum_msat: None,
2606 htlc_maximum_msat: None,
2607 }]), RouteHint(vec![RouteHintHop {
2608 src_node_id: nodes[5],
2609 short_channel_id: 10,
2611 cltv_expiry_delta: (10 << 4) | 1,
2612 htlc_minimum_msat: None,
2613 htlc_maximum_msat: None,
2617 fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2618 let zero_fees = RoutingFees {
2620 proportional_millionths: 0,
2622 vec![RouteHint(vec![RouteHintHop {
2623 src_node_id: nodes[2],
2624 short_channel_id: 5,
2627 proportional_millionths: 0,
2629 cltv_expiry_delta: (5 << 4) | 1,
2630 htlc_minimum_msat: None,
2631 htlc_maximum_msat: None,
2633 src_node_id: nodes[3],
2634 short_channel_id: 8,
2636 cltv_expiry_delta: (8 << 4) | 1,
2637 htlc_minimum_msat: None,
2638 htlc_maximum_msat: None,
2640 ]), RouteHint(vec![RouteHintHop {
2641 src_node_id: nodes[4],
2642 short_channel_id: 9,
2645 proportional_millionths: 0,
2647 cltv_expiry_delta: (9 << 4) | 1,
2648 htlc_minimum_msat: None,
2649 htlc_maximum_msat: None,
2650 }]), RouteHint(vec![RouteHintHop {
2651 src_node_id: nodes[5],
2652 short_channel_id: 10,
2654 cltv_expiry_delta: (10 << 4) | 1,
2655 htlc_minimum_msat: None,
2656 htlc_maximum_msat: None,
2661 fn partial_route_hint_test() {
2662 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2663 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2664 let scorer = test_utils::TestScorer::with_penalty(0);
2665 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2666 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2668 // Simple test across 2, 3, 5, and 4 via a last_hop channel
2669 // Tests the behaviour when the RouteHint contains a suboptimal hop.
2670 // RouteHint may be partially used by the algo to build the best path.
2672 // First check that last hop can't have its source as the payee.
2673 let invalid_last_hop = RouteHint(vec![RouteHintHop {
2674 src_node_id: nodes[6],
2675 short_channel_id: 8,
2678 proportional_millionths: 0,
2680 cltv_expiry_delta: (8 << 4) | 1,
2681 htlc_minimum_msat: None,
2682 htlc_maximum_msat: None,
2685 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
2686 invalid_last_hops.push(invalid_last_hop);
2688 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(invalid_last_hops);
2689 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) {
2690 assert_eq!(err, "Route hint cannot have the payee as the source.");
2691 } else { panic!(); }
2694 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops_multi_private_channels(&nodes));
2695 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2696 assert_eq!(route.paths[0].len(), 5);
2698 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2699 assert_eq!(route.paths[0][0].short_channel_id, 2);
2700 assert_eq!(route.paths[0][0].fee_msat, 100);
2701 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2702 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2703 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2705 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2706 assert_eq!(route.paths[0][1].short_channel_id, 4);
2707 assert_eq!(route.paths[0][1].fee_msat, 0);
2708 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
2709 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2710 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2712 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2713 assert_eq!(route.paths[0][2].short_channel_id, 6);
2714 assert_eq!(route.paths[0][2].fee_msat, 0);
2715 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
2716 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2717 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2719 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2720 assert_eq!(route.paths[0][3].short_channel_id, 11);
2721 assert_eq!(route.paths[0][3].fee_msat, 0);
2722 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
2723 // If we have a peer in the node map, we'll use their features here since we don't have
2724 // a way of figuring out their features from the invoice:
2725 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2726 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2728 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2729 assert_eq!(route.paths[0][4].short_channel_id, 8);
2730 assert_eq!(route.paths[0][4].fee_msat, 100);
2731 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2732 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2733 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2736 fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2737 let zero_fees = RoutingFees {
2739 proportional_millionths: 0,
2741 vec![RouteHint(vec![RouteHintHop {
2742 src_node_id: nodes[3],
2743 short_channel_id: 8,
2745 cltv_expiry_delta: (8 << 4) | 1,
2746 htlc_minimum_msat: None,
2747 htlc_maximum_msat: None,
2748 }]), RouteHint(vec![
2750 ]), RouteHint(vec![RouteHintHop {
2751 src_node_id: nodes[5],
2752 short_channel_id: 10,
2754 cltv_expiry_delta: (10 << 4) | 1,
2755 htlc_minimum_msat: None,
2756 htlc_maximum_msat: None,
2761 fn ignores_empty_last_hops_test() {
2762 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2763 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2764 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(empty_last_hop(&nodes));
2765 let scorer = test_utils::TestScorer::with_penalty(0);
2766 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2767 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2769 // Test handling of an empty RouteHint passed in Invoice.
2771 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2772 assert_eq!(route.paths[0].len(), 5);
2774 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2775 assert_eq!(route.paths[0][0].short_channel_id, 2);
2776 assert_eq!(route.paths[0][0].fee_msat, 100);
2777 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2778 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2779 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2781 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2782 assert_eq!(route.paths[0][1].short_channel_id, 4);
2783 assert_eq!(route.paths[0][1].fee_msat, 0);
2784 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
2785 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2786 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2788 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2789 assert_eq!(route.paths[0][2].short_channel_id, 6);
2790 assert_eq!(route.paths[0][2].fee_msat, 0);
2791 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
2792 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2793 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2795 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2796 assert_eq!(route.paths[0][3].short_channel_id, 11);
2797 assert_eq!(route.paths[0][3].fee_msat, 0);
2798 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
2799 // If we have a peer in the node map, we'll use their features here since we don't have
2800 // a way of figuring out their features from the invoice:
2801 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2802 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2804 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2805 assert_eq!(route.paths[0][4].short_channel_id, 8);
2806 assert_eq!(route.paths[0][4].fee_msat, 100);
2807 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2808 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2809 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2812 /// Builds a trivial last-hop hint that passes through the two nodes given, with channel 0xff00
2814 fn multi_hop_last_hops_hint(hint_hops: [PublicKey; 2]) -> Vec<RouteHint> {
2815 let zero_fees = RoutingFees {
2817 proportional_millionths: 0,
2819 vec![RouteHint(vec![RouteHintHop {
2820 src_node_id: hint_hops[0],
2821 short_channel_id: 0xff00,
2824 proportional_millionths: 0,
2826 cltv_expiry_delta: (5 << 4) | 1,
2827 htlc_minimum_msat: None,
2828 htlc_maximum_msat: None,
2830 src_node_id: hint_hops[1],
2831 short_channel_id: 0xff01,
2833 cltv_expiry_delta: (8 << 4) | 1,
2834 htlc_minimum_msat: None,
2835 htlc_maximum_msat: None,
2840 fn multi_hint_last_hops_test() {
2841 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2842 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2843 let last_hops = multi_hop_last_hops_hint([nodes[2], nodes[3]]);
2844 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops.clone());
2845 let scorer = test_utils::TestScorer::with_penalty(0);
2846 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2847 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2848 // Test through channels 2, 3, 0xff00, 0xff01.
2849 // Test shows that multiple hop hints are considered.
2851 // Disabling channels 6 & 7 by flags=2
2852 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2853 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2854 short_channel_id: 6,
2856 flags: 2, // to disable
2857 cltv_expiry_delta: 0,
2858 htlc_minimum_msat: 0,
2859 htlc_maximum_msat: OptionalField::Absent,
2861 fee_proportional_millionths: 0,
2862 excess_data: Vec::new()
2864 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2865 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2866 short_channel_id: 7,
2868 flags: 2, // to disable
2869 cltv_expiry_delta: 0,
2870 htlc_minimum_msat: 0,
2871 htlc_maximum_msat: OptionalField::Absent,
2873 fee_proportional_millionths: 0,
2874 excess_data: Vec::new()
2877 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2878 assert_eq!(route.paths[0].len(), 4);
2880 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2881 assert_eq!(route.paths[0][0].short_channel_id, 2);
2882 assert_eq!(route.paths[0][0].fee_msat, 200);
2883 assert_eq!(route.paths[0][0].cltv_expiry_delta, 65);
2884 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2885 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2887 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2888 assert_eq!(route.paths[0][1].short_channel_id, 4);
2889 assert_eq!(route.paths[0][1].fee_msat, 100);
2890 assert_eq!(route.paths[0][1].cltv_expiry_delta, 81);
2891 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2892 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2894 assert_eq!(route.paths[0][2].pubkey, nodes[3]);
2895 assert_eq!(route.paths[0][2].short_channel_id, last_hops[0].0[0].short_channel_id);
2896 assert_eq!(route.paths[0][2].fee_msat, 0);
2897 assert_eq!(route.paths[0][2].cltv_expiry_delta, 129);
2898 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(4));
2899 assert_eq!(route.paths[0][2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2901 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2902 assert_eq!(route.paths[0][3].short_channel_id, last_hops[0].0[1].short_channel_id);
2903 assert_eq!(route.paths[0][3].fee_msat, 100);
2904 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2905 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2906 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2910 fn private_multi_hint_last_hops_test() {
2911 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2912 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2914 let non_announced_privkey = SecretKey::from_slice(&hex::decode(format!("{:02x}", 0xf0).repeat(32)).unwrap()[..]).unwrap();
2915 let non_announced_pubkey = PublicKey::from_secret_key(&secp_ctx, &non_announced_privkey);
2917 let last_hops = multi_hop_last_hops_hint([nodes[2], non_announced_pubkey]);
2918 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops.clone());
2919 let scorer = test_utils::TestScorer::with_penalty(0);
2920 // Test through channels 2, 3, 0xff00, 0xff01.
2921 // Test shows that multiple hop hints are considered.
2923 // Disabling channels 6 & 7 by flags=2
2924 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2925 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2926 short_channel_id: 6,
2928 flags: 2, // to disable
2929 cltv_expiry_delta: 0,
2930 htlc_minimum_msat: 0,
2931 htlc_maximum_msat: OptionalField::Absent,
2933 fee_proportional_millionths: 0,
2934 excess_data: Vec::new()
2936 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2937 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2938 short_channel_id: 7,
2940 flags: 2, // to disable
2941 cltv_expiry_delta: 0,
2942 htlc_minimum_msat: 0,
2943 htlc_maximum_msat: OptionalField::Absent,
2945 fee_proportional_millionths: 0,
2946 excess_data: Vec::new()
2949 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &[42u8; 32]).unwrap();
2950 assert_eq!(route.paths[0].len(), 4);
2952 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2953 assert_eq!(route.paths[0][0].short_channel_id, 2);
2954 assert_eq!(route.paths[0][0].fee_msat, 200);
2955 assert_eq!(route.paths[0][0].cltv_expiry_delta, 65);
2956 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2957 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2959 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2960 assert_eq!(route.paths[0][1].short_channel_id, 4);
2961 assert_eq!(route.paths[0][1].fee_msat, 100);
2962 assert_eq!(route.paths[0][1].cltv_expiry_delta, 81);
2963 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2964 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2966 assert_eq!(route.paths[0][2].pubkey, non_announced_pubkey);
2967 assert_eq!(route.paths[0][2].short_channel_id, last_hops[0].0[0].short_channel_id);
2968 assert_eq!(route.paths[0][2].fee_msat, 0);
2969 assert_eq!(route.paths[0][2].cltv_expiry_delta, 129);
2970 assert_eq!(route.paths[0][2].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2971 assert_eq!(route.paths[0][2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2973 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2974 assert_eq!(route.paths[0][3].short_channel_id, last_hops[0].0[1].short_channel_id);
2975 assert_eq!(route.paths[0][3].fee_msat, 100);
2976 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2977 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2978 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2981 fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2982 let zero_fees = RoutingFees {
2984 proportional_millionths: 0,
2986 vec![RouteHint(vec![RouteHintHop {
2987 src_node_id: nodes[4],
2988 short_channel_id: 11,
2990 cltv_expiry_delta: (11 << 4) | 1,
2991 htlc_minimum_msat: None,
2992 htlc_maximum_msat: None,
2994 src_node_id: nodes[3],
2995 short_channel_id: 8,
2997 cltv_expiry_delta: (8 << 4) | 1,
2998 htlc_minimum_msat: None,
2999 htlc_maximum_msat: None,
3000 }]), RouteHint(vec![RouteHintHop {
3001 src_node_id: nodes[4],
3002 short_channel_id: 9,
3005 proportional_millionths: 0,
3007 cltv_expiry_delta: (9 << 4) | 1,
3008 htlc_minimum_msat: None,
3009 htlc_maximum_msat: None,
3010 }]), RouteHint(vec![RouteHintHop {
3011 src_node_id: nodes[5],
3012 short_channel_id: 10,
3014 cltv_expiry_delta: (10 << 4) | 1,
3015 htlc_minimum_msat: None,
3016 htlc_maximum_msat: None,
3021 fn last_hops_with_public_channel_test() {
3022 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3023 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3024 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops_with_public_channel(&nodes));
3025 let scorer = test_utils::TestScorer::with_penalty(0);
3026 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3027 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3028 // This test shows that public routes can be present in the invoice
3029 // which would be handled in the same manner.
3031 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3032 assert_eq!(route.paths[0].len(), 5);
3034 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3035 assert_eq!(route.paths[0][0].short_channel_id, 2);
3036 assert_eq!(route.paths[0][0].fee_msat, 100);
3037 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
3038 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3039 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3041 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3042 assert_eq!(route.paths[0][1].short_channel_id, 4);
3043 assert_eq!(route.paths[0][1].fee_msat, 0);
3044 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
3045 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3046 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3048 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
3049 assert_eq!(route.paths[0][2].short_channel_id, 6);
3050 assert_eq!(route.paths[0][2].fee_msat, 0);
3051 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
3052 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
3053 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
3055 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
3056 assert_eq!(route.paths[0][3].short_channel_id, 11);
3057 assert_eq!(route.paths[0][3].fee_msat, 0);
3058 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
3059 // If we have a peer in the node map, we'll use their features here since we don't have
3060 // a way of figuring out their features from the invoice:
3061 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
3062 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
3064 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
3065 assert_eq!(route.paths[0][4].short_channel_id, 8);
3066 assert_eq!(route.paths[0][4].fee_msat, 100);
3067 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
3068 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
3069 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3073 fn our_chans_last_hop_connect_test() {
3074 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3075 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3076 let scorer = test_utils::TestScorer::with_penalty(0);
3077 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3078 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3080 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
3081 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3082 let mut last_hops = last_hops(&nodes);
3083 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops.clone());
3084 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();
3085 assert_eq!(route.paths[0].len(), 2);
3087 assert_eq!(route.paths[0][0].pubkey, nodes[3]);
3088 assert_eq!(route.paths[0][0].short_channel_id, 42);
3089 assert_eq!(route.paths[0][0].fee_msat, 0);
3090 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 4) | 1);
3091 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
3092 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3094 assert_eq!(route.paths[0][1].pubkey, nodes[6]);
3095 assert_eq!(route.paths[0][1].short_channel_id, 8);
3096 assert_eq!(route.paths[0][1].fee_msat, 100);
3097 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
3098 assert_eq!(route.paths[0][1].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
3099 assert_eq!(route.paths[0][1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3101 last_hops[0].0[0].fees.base_msat = 1000;
3103 // Revert to via 6 as the fee on 8 goes up
3104 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops);
3105 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3106 assert_eq!(route.paths[0].len(), 4);
3108 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3109 assert_eq!(route.paths[0][0].short_channel_id, 2);
3110 assert_eq!(route.paths[0][0].fee_msat, 200); // fee increased as its % of value transferred across node
3111 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
3112 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3113 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3115 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3116 assert_eq!(route.paths[0][1].short_channel_id, 4);
3117 assert_eq!(route.paths[0][1].fee_msat, 100);
3118 assert_eq!(route.paths[0][1].cltv_expiry_delta, (7 << 4) | 1);
3119 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3120 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3122 assert_eq!(route.paths[0][2].pubkey, nodes[5]);
3123 assert_eq!(route.paths[0][2].short_channel_id, 7);
3124 assert_eq!(route.paths[0][2].fee_msat, 0);
3125 assert_eq!(route.paths[0][2].cltv_expiry_delta, (10 << 4) | 1);
3126 // If we have a peer in the node map, we'll use their features here since we don't have
3127 // a way of figuring out their features from the invoice:
3128 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
3129 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(7));
3131 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
3132 assert_eq!(route.paths[0][3].short_channel_id, 10);
3133 assert_eq!(route.paths[0][3].fee_msat, 100);
3134 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
3135 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
3136 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3138 // ...but still use 8 for larger payments as 6 has a variable feerate
3139 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 2000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3140 assert_eq!(route.paths[0].len(), 5);
3142 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3143 assert_eq!(route.paths[0][0].short_channel_id, 2);
3144 assert_eq!(route.paths[0][0].fee_msat, 3000);
3145 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
3146 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3147 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3149 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3150 assert_eq!(route.paths[0][1].short_channel_id, 4);
3151 assert_eq!(route.paths[0][1].fee_msat, 0);
3152 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
3153 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3154 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3156 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
3157 assert_eq!(route.paths[0][2].short_channel_id, 6);
3158 assert_eq!(route.paths[0][2].fee_msat, 0);
3159 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
3160 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
3161 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
3163 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
3164 assert_eq!(route.paths[0][3].short_channel_id, 11);
3165 assert_eq!(route.paths[0][3].fee_msat, 1000);
3166 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
3167 // If we have a peer in the node map, we'll use their features here since we don't have
3168 // a way of figuring out their features from the invoice:
3169 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
3170 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
3172 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
3173 assert_eq!(route.paths[0][4].short_channel_id, 8);
3174 assert_eq!(route.paths[0][4].fee_msat, 2000);
3175 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
3176 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
3177 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3180 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> {
3181 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
3182 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3183 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3185 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
3186 let last_hops = RouteHint(vec![RouteHintHop {
3187 src_node_id: middle_node_id,
3188 short_channel_id: 8,
3191 proportional_millionths: last_hop_fee_prop,
3193 cltv_expiry_delta: (8 << 4) | 1,
3194 htlc_minimum_msat: None,
3195 htlc_maximum_msat: last_hop_htlc_max,
3197 let payment_params = PaymentParameters::from_node_id(target_node_id).with_route_hints(vec![last_hops]);
3198 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
3199 let scorer = test_utils::TestScorer::with_penalty(0);
3200 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3201 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3202 get_route(&source_node_id, &payment_params, &NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash()).read_only(),
3203 Some(&our_chans.iter().collect::<Vec<_>>()), route_val, 42, &test_utils::TestLogger::new(), &scorer, &random_seed_bytes)
3207 fn unannounced_path_test() {
3208 // We should be able to send a payment to a destination without any help of a routing graph
3209 // if we have a channel with a common counterparty that appears in the first and last hop
3211 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
3213 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3214 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3215 assert_eq!(route.paths[0].len(), 2);
3217 assert_eq!(route.paths[0][0].pubkey, middle_node_id);
3218 assert_eq!(route.paths[0][0].short_channel_id, 42);
3219 assert_eq!(route.paths[0][0].fee_msat, 1001);
3220 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 4) | 1);
3221 assert_eq!(route.paths[0][0].node_features.le_flags(), &[0b11]);
3222 assert_eq!(route.paths[0][0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3224 assert_eq!(route.paths[0][1].pubkey, target_node_id);
3225 assert_eq!(route.paths[0][1].short_channel_id, 8);
3226 assert_eq!(route.paths[0][1].fee_msat, 1000000);
3227 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
3228 assert_eq!(route.paths[0][1].node_features.le_flags(), &[0; 0]); // We dont pass flags in from invoices yet
3229 assert_eq!(route.paths[0][1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3233 fn overflow_unannounced_path_test_liquidity_underflow() {
3234 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
3235 // the last-hop had a fee which overflowed a u64, we'd panic.
3236 // This was due to us adding the first-hop from us unconditionally, causing us to think
3237 // we'd built a path (as our node is in the "best candidate" set), when we had not.
3238 // In this test, we previously hit a subtraction underflow due to having less available
3239 // liquidity at the last hop than 0.
3240 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());
3244 fn overflow_unannounced_path_test_feerate_overflow() {
3245 // This tests for the same case as above, except instead of hitting a subtraction
3246 // underflow, we hit a case where the fee charged at a hop overflowed.
3247 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());
3251 fn available_amount_while_routing_test() {
3252 // Tests whether we choose the correct available channel amount while routing.
3254 let (secp_ctx, network_graph, mut net_graph_msg_handler, chain_monitor, logger) = build_graph();
3255 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3256 let scorer = test_utils::TestScorer::with_penalty(0);
3257 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3258 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3259 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
3261 // We will use a simple single-path route from
3262 // our node to node2 via node0: channels {1, 3}.
3264 // First disable all other paths.
3265 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3266 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3267 short_channel_id: 2,
3270 cltv_expiry_delta: 0,
3271 htlc_minimum_msat: 0,
3272 htlc_maximum_msat: OptionalField::Present(100_000),
3274 fee_proportional_millionths: 0,
3275 excess_data: Vec::new()
3277 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3278 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3279 short_channel_id: 12,
3282 cltv_expiry_delta: 0,
3283 htlc_minimum_msat: 0,
3284 htlc_maximum_msat: OptionalField::Present(100_000),
3286 fee_proportional_millionths: 0,
3287 excess_data: Vec::new()
3290 // Make the first channel (#1) very permissive,
3291 // and we will be testing all limits on the second channel.
3292 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3293 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3294 short_channel_id: 1,
3297 cltv_expiry_delta: 0,
3298 htlc_minimum_msat: 0,
3299 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3301 fee_proportional_millionths: 0,
3302 excess_data: Vec::new()
3305 // First, let's see if routing works if we have absolutely no idea about the available amount.
3306 // In this case, it should be set to 250_000 sats.
3307 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3308 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3309 short_channel_id: 3,
3312 cltv_expiry_delta: 0,
3313 htlc_minimum_msat: 0,
3314 htlc_maximum_msat: OptionalField::Absent,
3316 fee_proportional_millionths: 0,
3317 excess_data: Vec::new()
3321 // Attempt to route more than available results in a failure.
3322 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3323 &our_id, &payment_params, &network_graph.read_only(), None, 250_000_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3324 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3325 } else { panic!(); }
3329 // Now, attempt to route an exact amount we have should be fine.
3330 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();
3331 assert_eq!(route.paths.len(), 1);
3332 let path = route.paths.last().unwrap();
3333 assert_eq!(path.len(), 2);
3334 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3335 assert_eq!(path.last().unwrap().fee_msat, 250_000_000);
3338 // Check that setting outbound_capacity_msat in first_hops limits the channels.
3339 // Disable channel #1 and use another first hop.
3340 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3341 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3342 short_channel_id: 1,
3345 cltv_expiry_delta: 0,
3346 htlc_minimum_msat: 0,
3347 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3349 fee_proportional_millionths: 0,
3350 excess_data: Vec::new()
3353 // Now, limit the first_hop by the outbound_capacity_msat of 200_000 sats.
3354 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
3357 // Attempt to route more than available results in a failure.
3358 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3359 &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) {
3360 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3361 } else { panic!(); }
3365 // Now, attempt to route an exact amount we have should be fine.
3366 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();
3367 assert_eq!(route.paths.len(), 1);
3368 let path = route.paths.last().unwrap();
3369 assert_eq!(path.len(), 2);
3370 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3371 assert_eq!(path.last().unwrap().fee_msat, 200_000_000);
3374 // Enable channel #1 back.
3375 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3376 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3377 short_channel_id: 1,
3380 cltv_expiry_delta: 0,
3381 htlc_minimum_msat: 0,
3382 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3384 fee_proportional_millionths: 0,
3385 excess_data: Vec::new()
3389 // Now let's see if routing works if we know only htlc_maximum_msat.
3390 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3391 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3392 short_channel_id: 3,
3395 cltv_expiry_delta: 0,
3396 htlc_minimum_msat: 0,
3397 htlc_maximum_msat: OptionalField::Present(15_000),
3399 fee_proportional_millionths: 0,
3400 excess_data: Vec::new()
3404 // Attempt to route more than available results in a failure.
3405 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3406 &our_id, &payment_params, &network_graph.read_only(), None, 15_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3407 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3408 } else { panic!(); }
3412 // Now, attempt to route an exact amount we have should be fine.
3413 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 15_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3414 assert_eq!(route.paths.len(), 1);
3415 let path = route.paths.last().unwrap();
3416 assert_eq!(path.len(), 2);
3417 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3418 assert_eq!(path.last().unwrap().fee_msat, 15_000);
3421 // Now let's see if routing works if we know only capacity from the UTXO.
3423 // We can't change UTXO capacity on the fly, so we'll disable
3424 // the existing channel and add another one with the capacity we need.
3425 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3426 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3427 short_channel_id: 3,
3430 cltv_expiry_delta: 0,
3431 htlc_minimum_msat: 0,
3432 htlc_maximum_msat: OptionalField::Absent,
3434 fee_proportional_millionths: 0,
3435 excess_data: Vec::new()
3438 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
3439 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
3440 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
3441 .push_opcode(opcodes::all::OP_PUSHNUM_2)
3442 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
3444 *chain_monitor.utxo_ret.lock().unwrap() = Ok(TxOut { value: 15, script_pubkey: good_script.clone() });
3445 net_graph_msg_handler.add_chain_access(Some(chain_monitor));
3447 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
3448 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3449 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3450 short_channel_id: 333,
3453 cltv_expiry_delta: (3 << 4) | 1,
3454 htlc_minimum_msat: 0,
3455 htlc_maximum_msat: OptionalField::Absent,
3457 fee_proportional_millionths: 0,
3458 excess_data: Vec::new()
3460 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3461 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3462 short_channel_id: 333,
3465 cltv_expiry_delta: (3 << 4) | 2,
3466 htlc_minimum_msat: 0,
3467 htlc_maximum_msat: OptionalField::Absent,
3469 fee_proportional_millionths: 0,
3470 excess_data: Vec::new()
3474 // Attempt to route more than available results in a failure.
3475 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3476 &our_id, &payment_params, &network_graph.read_only(), None, 15_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3477 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3478 } else { panic!(); }
3482 // Now, attempt to route an exact amount we have should be fine.
3483 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 15_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3484 assert_eq!(route.paths.len(), 1);
3485 let path = route.paths.last().unwrap();
3486 assert_eq!(path.len(), 2);
3487 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3488 assert_eq!(path.last().unwrap().fee_msat, 15_000);
3491 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
3492 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3493 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3494 short_channel_id: 333,
3497 cltv_expiry_delta: 0,
3498 htlc_minimum_msat: 0,
3499 htlc_maximum_msat: OptionalField::Present(10_000),
3501 fee_proportional_millionths: 0,
3502 excess_data: Vec::new()
3506 // Attempt to route more than available results in a failure.
3507 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3508 &our_id, &payment_params, &network_graph.read_only(), None, 10_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3509 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3510 } else { panic!(); }
3514 // Now, attempt to route an exact amount we have should be fine.
3515 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 10_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3516 assert_eq!(route.paths.len(), 1);
3517 let path = route.paths.last().unwrap();
3518 assert_eq!(path.len(), 2);
3519 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3520 assert_eq!(path.last().unwrap().fee_msat, 10_000);
3525 fn available_liquidity_last_hop_test() {
3526 // Check that available liquidity properly limits the path even when only
3527 // one of the latter hops is limited.
3528 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3529 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3530 let scorer = test_utils::TestScorer::with_penalty(0);
3531 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3532 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3533 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
3535 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3536 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
3537 // Total capacity: 50 sats.
3539 // Disable other potential paths.
3540 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3541 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3542 short_channel_id: 2,
3545 cltv_expiry_delta: 0,
3546 htlc_minimum_msat: 0,
3547 htlc_maximum_msat: OptionalField::Present(100_000),
3549 fee_proportional_millionths: 0,
3550 excess_data: Vec::new()
3552 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3553 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3554 short_channel_id: 7,
3557 cltv_expiry_delta: 0,
3558 htlc_minimum_msat: 0,
3559 htlc_maximum_msat: OptionalField::Present(100_000),
3561 fee_proportional_millionths: 0,
3562 excess_data: Vec::new()
3567 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3568 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3569 short_channel_id: 12,
3572 cltv_expiry_delta: 0,
3573 htlc_minimum_msat: 0,
3574 htlc_maximum_msat: OptionalField::Present(100_000),
3576 fee_proportional_millionths: 0,
3577 excess_data: Vec::new()
3579 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3580 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3581 short_channel_id: 13,
3584 cltv_expiry_delta: 0,
3585 htlc_minimum_msat: 0,
3586 htlc_maximum_msat: OptionalField::Present(100_000),
3588 fee_proportional_millionths: 0,
3589 excess_data: Vec::new()
3592 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3593 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3594 short_channel_id: 6,
3597 cltv_expiry_delta: 0,
3598 htlc_minimum_msat: 0,
3599 htlc_maximum_msat: OptionalField::Present(50_000),
3601 fee_proportional_millionths: 0,
3602 excess_data: Vec::new()
3604 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3605 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3606 short_channel_id: 11,
3609 cltv_expiry_delta: 0,
3610 htlc_minimum_msat: 0,
3611 htlc_maximum_msat: OptionalField::Present(100_000),
3613 fee_proportional_millionths: 0,
3614 excess_data: Vec::new()
3617 // Attempt to route more than available results in a failure.
3618 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3619 &our_id, &payment_params, &network_graph.read_only(), None, 60_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3620 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3621 } else { panic!(); }
3625 // Now, attempt to route 49 sats (just a bit below the capacity).
3626 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 49_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3627 assert_eq!(route.paths.len(), 1);
3628 let mut total_amount_paid_msat = 0;
3629 for path in &route.paths {
3630 assert_eq!(path.len(), 4);
3631 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3632 total_amount_paid_msat += path.last().unwrap().fee_msat;
3634 assert_eq!(total_amount_paid_msat, 49_000);
3638 // Attempt to route an exact amount is also fine
3639 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3640 assert_eq!(route.paths.len(), 1);
3641 let mut total_amount_paid_msat = 0;
3642 for path in &route.paths {
3643 assert_eq!(path.len(), 4);
3644 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3645 total_amount_paid_msat += path.last().unwrap().fee_msat;
3647 assert_eq!(total_amount_paid_msat, 50_000);
3652 fn ignore_fee_first_hop_test() {
3653 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3654 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3655 let scorer = test_utils::TestScorer::with_penalty(0);
3656 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3657 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3658 let payment_params = PaymentParameters::from_node_id(nodes[2]);
3660 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3661 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3662 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3663 short_channel_id: 1,
3666 cltv_expiry_delta: 0,
3667 htlc_minimum_msat: 0,
3668 htlc_maximum_msat: OptionalField::Present(100_000),
3669 fee_base_msat: 1_000_000,
3670 fee_proportional_millionths: 0,
3671 excess_data: Vec::new()
3673 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3674 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3675 short_channel_id: 3,
3678 cltv_expiry_delta: 0,
3679 htlc_minimum_msat: 0,
3680 htlc_maximum_msat: OptionalField::Present(50_000),
3682 fee_proportional_millionths: 0,
3683 excess_data: Vec::new()
3687 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3688 assert_eq!(route.paths.len(), 1);
3689 let mut total_amount_paid_msat = 0;
3690 for path in &route.paths {
3691 assert_eq!(path.len(), 2);
3692 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3693 total_amount_paid_msat += path.last().unwrap().fee_msat;
3695 assert_eq!(total_amount_paid_msat, 50_000);
3700 fn simple_mpp_route_test() {
3701 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3702 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3703 let scorer = test_utils::TestScorer::with_penalty(0);
3704 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3705 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3706 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
3708 // We need a route consisting of 3 paths:
3709 // From our node to node2 via node0, node7, node1 (three paths one hop each).
3710 // To achieve this, the amount being transferred should be around
3711 // the total capacity of these 3 paths.
3713 // First, we set limits on these (previously unlimited) channels.
3714 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
3716 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3717 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3718 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3719 short_channel_id: 1,
3722 cltv_expiry_delta: 0,
3723 htlc_minimum_msat: 0,
3724 htlc_maximum_msat: OptionalField::Present(100_000),
3726 fee_proportional_millionths: 0,
3727 excess_data: Vec::new()
3729 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3730 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3731 short_channel_id: 3,
3734 cltv_expiry_delta: 0,
3735 htlc_minimum_msat: 0,
3736 htlc_maximum_msat: OptionalField::Present(50_000),
3738 fee_proportional_millionths: 0,
3739 excess_data: Vec::new()
3742 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
3743 // (total limit 60).
3744 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3745 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3746 short_channel_id: 12,
3749 cltv_expiry_delta: 0,
3750 htlc_minimum_msat: 0,
3751 htlc_maximum_msat: OptionalField::Present(60_000),
3753 fee_proportional_millionths: 0,
3754 excess_data: Vec::new()
3756 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3757 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3758 short_channel_id: 13,
3761 cltv_expiry_delta: 0,
3762 htlc_minimum_msat: 0,
3763 htlc_maximum_msat: OptionalField::Present(60_000),
3765 fee_proportional_millionths: 0,
3766 excess_data: Vec::new()
3769 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
3770 // (total capacity 180 sats).
3771 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3772 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3773 short_channel_id: 2,
3776 cltv_expiry_delta: 0,
3777 htlc_minimum_msat: 0,
3778 htlc_maximum_msat: OptionalField::Present(200_000),
3780 fee_proportional_millionths: 0,
3781 excess_data: Vec::new()
3783 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3784 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3785 short_channel_id: 4,
3788 cltv_expiry_delta: 0,
3789 htlc_minimum_msat: 0,
3790 htlc_maximum_msat: OptionalField::Present(180_000),
3792 fee_proportional_millionths: 0,
3793 excess_data: Vec::new()
3797 // Attempt to route more than available results in a failure.
3798 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3799 &our_id, &payment_params, &network_graph.read_only(), None, 300_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3800 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3801 } else { panic!(); }
3805 // Now, attempt to route 250 sats (just a bit below the capacity).
3806 // Our algorithm should provide us with these 3 paths.
3807 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 250_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3808 assert_eq!(route.paths.len(), 3);
3809 let mut total_amount_paid_msat = 0;
3810 for path in &route.paths {
3811 assert_eq!(path.len(), 2);
3812 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3813 total_amount_paid_msat += path.last().unwrap().fee_msat;
3815 assert_eq!(total_amount_paid_msat, 250_000);
3819 // Attempt to route an exact amount is also fine
3820 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 290_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3821 assert_eq!(route.paths.len(), 3);
3822 let mut total_amount_paid_msat = 0;
3823 for path in &route.paths {
3824 assert_eq!(path.len(), 2);
3825 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3826 total_amount_paid_msat += path.last().unwrap().fee_msat;
3828 assert_eq!(total_amount_paid_msat, 290_000);
3833 fn long_mpp_route_test() {
3834 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3835 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3836 let scorer = test_utils::TestScorer::with_penalty(0);
3837 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3838 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3839 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
3841 // We need a route consisting of 3 paths:
3842 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3843 // Note that these paths overlap (channels 5, 12, 13).
3844 // We will route 300 sats.
3845 // Each path will have 100 sats capacity, those channels which
3846 // are used twice will have 200 sats capacity.
3848 // Disable other potential paths.
3849 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3850 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3851 short_channel_id: 2,
3854 cltv_expiry_delta: 0,
3855 htlc_minimum_msat: 0,
3856 htlc_maximum_msat: OptionalField::Present(100_000),
3858 fee_proportional_millionths: 0,
3859 excess_data: Vec::new()
3861 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3862 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3863 short_channel_id: 7,
3866 cltv_expiry_delta: 0,
3867 htlc_minimum_msat: 0,
3868 htlc_maximum_msat: OptionalField::Present(100_000),
3870 fee_proportional_millionths: 0,
3871 excess_data: Vec::new()
3874 // Path via {node0, node2} is channels {1, 3, 5}.
3875 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3876 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3877 short_channel_id: 1,
3880 cltv_expiry_delta: 0,
3881 htlc_minimum_msat: 0,
3882 htlc_maximum_msat: OptionalField::Present(100_000),
3884 fee_proportional_millionths: 0,
3885 excess_data: Vec::new()
3887 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3888 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3889 short_channel_id: 3,
3892 cltv_expiry_delta: 0,
3893 htlc_minimum_msat: 0,
3894 htlc_maximum_msat: OptionalField::Present(100_000),
3896 fee_proportional_millionths: 0,
3897 excess_data: Vec::new()
3900 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3901 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3902 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3903 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3904 short_channel_id: 5,
3907 cltv_expiry_delta: 0,
3908 htlc_minimum_msat: 0,
3909 htlc_maximum_msat: OptionalField::Present(200_000),
3911 fee_proportional_millionths: 0,
3912 excess_data: Vec::new()
3915 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3916 // Add 100 sats to the capacities of {12, 13}, because these channels
3917 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3918 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3919 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3920 short_channel_id: 12,
3923 cltv_expiry_delta: 0,
3924 htlc_minimum_msat: 0,
3925 htlc_maximum_msat: OptionalField::Present(200_000),
3927 fee_proportional_millionths: 0,
3928 excess_data: Vec::new()
3930 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3931 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3932 short_channel_id: 13,
3935 cltv_expiry_delta: 0,
3936 htlc_minimum_msat: 0,
3937 htlc_maximum_msat: OptionalField::Present(200_000),
3939 fee_proportional_millionths: 0,
3940 excess_data: Vec::new()
3943 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3944 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3945 short_channel_id: 6,
3948 cltv_expiry_delta: 0,
3949 htlc_minimum_msat: 0,
3950 htlc_maximum_msat: OptionalField::Present(100_000),
3952 fee_proportional_millionths: 0,
3953 excess_data: Vec::new()
3955 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3956 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3957 short_channel_id: 11,
3960 cltv_expiry_delta: 0,
3961 htlc_minimum_msat: 0,
3962 htlc_maximum_msat: OptionalField::Present(100_000),
3964 fee_proportional_millionths: 0,
3965 excess_data: Vec::new()
3968 // Path via {node7, node2} is channels {12, 13, 5}.
3969 // We already limited them to 200 sats (they are used twice for 100 sats).
3970 // Nothing to do here.
3973 // Attempt to route more than available results in a failure.
3974 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3975 &our_id, &payment_params, &network_graph.read_only(), None, 350_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3976 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3977 } else { panic!(); }
3981 // Now, attempt to route 300 sats (exact amount we can route).
3982 // Our algorithm should provide us with these 3 paths, 100 sats each.
3983 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 300_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3984 assert_eq!(route.paths.len(), 3);
3986 let mut total_amount_paid_msat = 0;
3987 for path in &route.paths {
3988 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3989 total_amount_paid_msat += path.last().unwrap().fee_msat;
3991 assert_eq!(total_amount_paid_msat, 300_000);
3997 fn mpp_cheaper_route_test() {
3998 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3999 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4000 let scorer = test_utils::TestScorer::with_penalty(0);
4001 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4002 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4003 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
4005 // This test checks that if we have two cheaper paths and one more expensive path,
4006 // so that liquidity-wise any 2 of 3 combination is sufficient,
4007 // two cheaper paths will be taken.
4008 // These paths have equal available liquidity.
4010 // We need a combination of 3 paths:
4011 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
4012 // Note that these paths overlap (channels 5, 12, 13).
4013 // Each path will have 100 sats capacity, those channels which
4014 // are used twice will have 200 sats capacity.
4016 // Disable other potential paths.
4017 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4018 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4019 short_channel_id: 2,
4022 cltv_expiry_delta: 0,
4023 htlc_minimum_msat: 0,
4024 htlc_maximum_msat: OptionalField::Present(100_000),
4026 fee_proportional_millionths: 0,
4027 excess_data: Vec::new()
4029 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4030 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4031 short_channel_id: 7,
4034 cltv_expiry_delta: 0,
4035 htlc_minimum_msat: 0,
4036 htlc_maximum_msat: OptionalField::Present(100_000),
4038 fee_proportional_millionths: 0,
4039 excess_data: Vec::new()
4042 // Path via {node0, node2} is channels {1, 3, 5}.
4043 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4044 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4045 short_channel_id: 1,
4048 cltv_expiry_delta: 0,
4049 htlc_minimum_msat: 0,
4050 htlc_maximum_msat: OptionalField::Present(100_000),
4052 fee_proportional_millionths: 0,
4053 excess_data: Vec::new()
4055 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4056 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4057 short_channel_id: 3,
4060 cltv_expiry_delta: 0,
4061 htlc_minimum_msat: 0,
4062 htlc_maximum_msat: OptionalField::Present(100_000),
4064 fee_proportional_millionths: 0,
4065 excess_data: Vec::new()
4068 // Capacity of 200 sats because this channel will be used by 3rd path as well.
4069 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4070 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4071 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4072 short_channel_id: 5,
4075 cltv_expiry_delta: 0,
4076 htlc_minimum_msat: 0,
4077 htlc_maximum_msat: OptionalField::Present(200_000),
4079 fee_proportional_millionths: 0,
4080 excess_data: Vec::new()
4083 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4084 // Add 100 sats to the capacities of {12, 13}, because these channels
4085 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
4086 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4087 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4088 short_channel_id: 12,
4091 cltv_expiry_delta: 0,
4092 htlc_minimum_msat: 0,
4093 htlc_maximum_msat: OptionalField::Present(200_000),
4095 fee_proportional_millionths: 0,
4096 excess_data: Vec::new()
4098 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4099 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4100 short_channel_id: 13,
4103 cltv_expiry_delta: 0,
4104 htlc_minimum_msat: 0,
4105 htlc_maximum_msat: OptionalField::Present(200_000),
4107 fee_proportional_millionths: 0,
4108 excess_data: Vec::new()
4111 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4112 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4113 short_channel_id: 6,
4116 cltv_expiry_delta: 0,
4117 htlc_minimum_msat: 0,
4118 htlc_maximum_msat: OptionalField::Present(100_000),
4119 fee_base_msat: 1_000,
4120 fee_proportional_millionths: 0,
4121 excess_data: Vec::new()
4123 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4124 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4125 short_channel_id: 11,
4128 cltv_expiry_delta: 0,
4129 htlc_minimum_msat: 0,
4130 htlc_maximum_msat: OptionalField::Present(100_000),
4132 fee_proportional_millionths: 0,
4133 excess_data: Vec::new()
4136 // Path via {node7, node2} is channels {12, 13, 5}.
4137 // We already limited them to 200 sats (they are used twice for 100 sats).
4138 // Nothing to do here.
4141 // Now, attempt to route 180 sats.
4142 // Our algorithm should provide us with these 2 paths.
4143 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 180_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4144 assert_eq!(route.paths.len(), 2);
4146 let mut total_value_transferred_msat = 0;
4147 let mut total_paid_msat = 0;
4148 for path in &route.paths {
4149 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
4150 total_value_transferred_msat += path.last().unwrap().fee_msat;
4152 total_paid_msat += hop.fee_msat;
4155 // If we paid fee, this would be higher.
4156 assert_eq!(total_value_transferred_msat, 180_000);
4157 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
4158 assert_eq!(total_fees_paid, 0);
4163 fn fees_on_mpp_route_test() {
4164 // This test makes sure that MPP algorithm properly takes into account
4165 // fees charged on the channels, by making the fees impactful:
4166 // if the fee is not properly accounted for, the behavior is different.
4167 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4168 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4169 let scorer = test_utils::TestScorer::with_penalty(0);
4170 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4171 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4172 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
4174 // We need a route consisting of 2 paths:
4175 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
4176 // We will route 200 sats, Each path will have 100 sats capacity.
4178 // This test is not particularly stable: e.g.,
4179 // there's a way to route via {node0, node2, node4}.
4180 // It works while pathfinding is deterministic, but can be broken otherwise.
4181 // It's fine to ignore this concern for now.
4183 // Disable other potential paths.
4184 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4185 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4186 short_channel_id: 2,
4189 cltv_expiry_delta: 0,
4190 htlc_minimum_msat: 0,
4191 htlc_maximum_msat: OptionalField::Present(100_000),
4193 fee_proportional_millionths: 0,
4194 excess_data: Vec::new()
4197 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4198 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4199 short_channel_id: 7,
4202 cltv_expiry_delta: 0,
4203 htlc_minimum_msat: 0,
4204 htlc_maximum_msat: OptionalField::Present(100_000),
4206 fee_proportional_millionths: 0,
4207 excess_data: Vec::new()
4210 // Path via {node0, node2} is channels {1, 3, 5}.
4211 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4212 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4213 short_channel_id: 1,
4216 cltv_expiry_delta: 0,
4217 htlc_minimum_msat: 0,
4218 htlc_maximum_msat: OptionalField::Present(100_000),
4220 fee_proportional_millionths: 0,
4221 excess_data: Vec::new()
4223 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4224 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4225 short_channel_id: 3,
4228 cltv_expiry_delta: 0,
4229 htlc_minimum_msat: 0,
4230 htlc_maximum_msat: OptionalField::Present(100_000),
4232 fee_proportional_millionths: 0,
4233 excess_data: Vec::new()
4236 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4237 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4238 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4239 short_channel_id: 5,
4242 cltv_expiry_delta: 0,
4243 htlc_minimum_msat: 0,
4244 htlc_maximum_msat: OptionalField::Present(100_000),
4246 fee_proportional_millionths: 0,
4247 excess_data: Vec::new()
4250 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4251 // All channels should be 100 sats capacity. But for the fee experiment,
4252 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
4253 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
4254 // 100 sats (and pay 150 sats in fees for the use of channel 6),
4255 // so no matter how large are other channels,
4256 // the whole path will be limited by 100 sats with just these 2 conditions:
4257 // - channel 12 capacity is 250 sats
4258 // - fee for channel 6 is 150 sats
4259 // Let's test this by enforcing these 2 conditions and removing other limits.
4260 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4261 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4262 short_channel_id: 12,
4265 cltv_expiry_delta: 0,
4266 htlc_minimum_msat: 0,
4267 htlc_maximum_msat: OptionalField::Present(250_000),
4269 fee_proportional_millionths: 0,
4270 excess_data: Vec::new()
4272 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4273 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4274 short_channel_id: 13,
4277 cltv_expiry_delta: 0,
4278 htlc_minimum_msat: 0,
4279 htlc_maximum_msat: OptionalField::Absent,
4281 fee_proportional_millionths: 0,
4282 excess_data: Vec::new()
4285 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4286 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4287 short_channel_id: 6,
4290 cltv_expiry_delta: 0,
4291 htlc_minimum_msat: 0,
4292 htlc_maximum_msat: OptionalField::Absent,
4293 fee_base_msat: 150_000,
4294 fee_proportional_millionths: 0,
4295 excess_data: Vec::new()
4297 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4298 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4299 short_channel_id: 11,
4302 cltv_expiry_delta: 0,
4303 htlc_minimum_msat: 0,
4304 htlc_maximum_msat: OptionalField::Absent,
4306 fee_proportional_millionths: 0,
4307 excess_data: Vec::new()
4311 // Attempt to route more than available results in a failure.
4312 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4313 &our_id, &payment_params, &network_graph.read_only(), None, 210_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
4314 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4315 } else { panic!(); }
4319 // Now, attempt to route 200 sats (exact amount we can route).
4320 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 200_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4321 assert_eq!(route.paths.len(), 2);
4323 let mut total_amount_paid_msat = 0;
4324 for path in &route.paths {
4325 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
4326 total_amount_paid_msat += path.last().unwrap().fee_msat;
4328 assert_eq!(total_amount_paid_msat, 200_000);
4329 assert_eq!(route.get_total_fees(), 150_000);
4334 fn mpp_with_last_hops() {
4335 // Previously, if we tried to send an MPP payment to a destination which was only reachable
4336 // via a single last-hop route hint, we'd fail to route if we first collected routes
4337 // totaling close but not quite enough to fund the full payment.
4339 // This was because we considered last-hop hints to have exactly the sought payment amount
4340 // instead of the amount we were trying to collect, needlessly limiting our path searching
4341 // at the very first hop.
4343 // Specifically, this interacted with our "all paths must fund at least 5% of total target"
4344 // criterion to cause us to refuse all routes at the last hop hint which would be considered
4345 // to only have the remaining to-collect amount in available liquidity.
4347 // This bug appeared in production in some specific channel configurations.
4348 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4349 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4350 let scorer = test_utils::TestScorer::with_penalty(0);
4351 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4352 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4353 let payment_params = PaymentParameters::from_node_id(PublicKey::from_slice(&[02; 33]).unwrap()).with_features(InvoiceFeatures::known())
4354 .with_route_hints(vec![RouteHint(vec![RouteHintHop {
4355 src_node_id: nodes[2],
4356 short_channel_id: 42,
4357 fees: RoutingFees { base_msat: 0, proportional_millionths: 0 },
4358 cltv_expiry_delta: 42,
4359 htlc_minimum_msat: None,
4360 htlc_maximum_msat: None,
4363 // Keep only two paths from us to nodes[2], both with a 99sat HTLC maximum, with one with
4364 // no fee and one with a 1msat fee. Previously, trying to route 100 sats to nodes[2] here
4365 // would first use the no-fee route and then fail to find a path along the second route as
4366 // we think we can only send up to 1 additional sat over the last-hop but refuse to as its
4367 // under 5% of our payment amount.
4368 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4369 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4370 short_channel_id: 1,
4373 cltv_expiry_delta: (5 << 4) | 5,
4374 htlc_minimum_msat: 0,
4375 htlc_maximum_msat: OptionalField::Present(99_000),
4376 fee_base_msat: u32::max_value(),
4377 fee_proportional_millionths: u32::max_value(),
4378 excess_data: Vec::new()
4380 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4381 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4382 short_channel_id: 2,
4385 cltv_expiry_delta: (5 << 4) | 3,
4386 htlc_minimum_msat: 0,
4387 htlc_maximum_msat: OptionalField::Present(99_000),
4388 fee_base_msat: u32::max_value(),
4389 fee_proportional_millionths: u32::max_value(),
4390 excess_data: Vec::new()
4392 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4393 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4394 short_channel_id: 4,
4397 cltv_expiry_delta: (4 << 4) | 1,
4398 htlc_minimum_msat: 0,
4399 htlc_maximum_msat: OptionalField::Absent,
4401 fee_proportional_millionths: 0,
4402 excess_data: Vec::new()
4404 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4405 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4406 short_channel_id: 13,
4408 flags: 0|2, // Channel disabled
4409 cltv_expiry_delta: (13 << 4) | 1,
4410 htlc_minimum_msat: 0,
4411 htlc_maximum_msat: OptionalField::Absent,
4413 fee_proportional_millionths: 2000000,
4414 excess_data: Vec::new()
4417 // Get a route for 100 sats and check that we found the MPP route no problem and didn't
4419 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4420 assert_eq!(route.paths.len(), 2);
4421 // Paths are somewhat randomly ordered, but:
4422 // * the first is channel 2 (1 msat fee) -> channel 4 -> channel 42
4423 // * the second is channel 1 (0 fee, but 99 sat maximum) -> channel 3 -> channel 42
4424 assert_eq!(route.paths[0][0].short_channel_id, 2);
4425 assert_eq!(route.paths[0][0].fee_msat, 1);
4426 assert_eq!(route.paths[0][2].fee_msat, 1_000);
4427 assert_eq!(route.paths[1][0].short_channel_id, 1);
4428 assert_eq!(route.paths[1][0].fee_msat, 0);
4429 assert_eq!(route.paths[1][2].fee_msat, 99_000);
4430 assert_eq!(route.get_total_fees(), 1);
4431 assert_eq!(route.get_total_amount(), 100_000);
4435 fn drop_lowest_channel_mpp_route_test() {
4436 // This test checks that low-capacity channel is dropped when after
4437 // path finding we realize that we found more capacity than we need.
4438 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4439 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4440 let scorer = test_utils::TestScorer::with_penalty(0);
4441 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4442 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4443 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
4445 // We need a route consisting of 3 paths:
4446 // From our node to node2 via node0, node7, node1 (three paths one hop each).
4448 // The first and the second paths should be sufficient, but the third should be
4449 // cheaper, so that we select it but drop later.
4451 // First, we set limits on these (previously unlimited) channels.
4452 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
4454 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
4455 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4456 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4457 short_channel_id: 1,
4460 cltv_expiry_delta: 0,
4461 htlc_minimum_msat: 0,
4462 htlc_maximum_msat: OptionalField::Present(100_000),
4464 fee_proportional_millionths: 0,
4465 excess_data: Vec::new()
4467 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4468 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4469 short_channel_id: 3,
4472 cltv_expiry_delta: 0,
4473 htlc_minimum_msat: 0,
4474 htlc_maximum_msat: OptionalField::Present(50_000),
4476 fee_proportional_millionths: 0,
4477 excess_data: Vec::new()
4480 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
4481 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4482 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4483 short_channel_id: 12,
4486 cltv_expiry_delta: 0,
4487 htlc_minimum_msat: 0,
4488 htlc_maximum_msat: OptionalField::Present(60_000),
4490 fee_proportional_millionths: 0,
4491 excess_data: Vec::new()
4493 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4494 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4495 short_channel_id: 13,
4498 cltv_expiry_delta: 0,
4499 htlc_minimum_msat: 0,
4500 htlc_maximum_msat: OptionalField::Present(60_000),
4502 fee_proportional_millionths: 0,
4503 excess_data: Vec::new()
4506 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
4507 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4508 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4509 short_channel_id: 2,
4512 cltv_expiry_delta: 0,
4513 htlc_minimum_msat: 0,
4514 htlc_maximum_msat: OptionalField::Present(20_000),
4516 fee_proportional_millionths: 0,
4517 excess_data: Vec::new()
4519 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4520 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4521 short_channel_id: 4,
4524 cltv_expiry_delta: 0,
4525 htlc_minimum_msat: 0,
4526 htlc_maximum_msat: OptionalField::Present(20_000),
4528 fee_proportional_millionths: 0,
4529 excess_data: Vec::new()
4533 // Attempt to route more than available results in a failure.
4534 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4535 &our_id, &payment_params, &network_graph.read_only(), None, 150_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
4536 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4537 } else { panic!(); }
4541 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
4542 // Our algorithm should provide us with these 3 paths.
4543 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 125_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4544 assert_eq!(route.paths.len(), 3);
4545 let mut total_amount_paid_msat = 0;
4546 for path in &route.paths {
4547 assert_eq!(path.len(), 2);
4548 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4549 total_amount_paid_msat += path.last().unwrap().fee_msat;
4551 assert_eq!(total_amount_paid_msat, 125_000);
4555 // Attempt to route without the last small cheap channel
4556 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4557 assert_eq!(route.paths.len(), 2);
4558 let mut total_amount_paid_msat = 0;
4559 for path in &route.paths {
4560 assert_eq!(path.len(), 2);
4561 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4562 total_amount_paid_msat += path.last().unwrap().fee_msat;
4564 assert_eq!(total_amount_paid_msat, 90_000);
4569 fn min_criteria_consistency() {
4570 // Test that we don't use an inconsistent metric between updating and walking nodes during
4571 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
4572 // was updated with a different criterion from the heap sorting, resulting in loops in
4573 // calculated paths. We test for that specific case here.
4575 // We construct a network that looks like this:
4577 // node2 -1(3)2- node3
4581 // node1 -1(5)2- node4 -1(1)2- node6
4587 // We create a loop on the side of our real path - our destination is node 6, with a
4588 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
4589 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
4590 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
4591 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
4592 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
4593 // "previous hop" being set to node 3, creating a loop in the path.
4594 let secp_ctx = Secp256k1::new();
4595 let logger = Arc::new(test_utils::TestLogger::new());
4596 let network = Arc::new(NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash()));
4597 let net_graph_msg_handler = NetGraphMsgHandler::new(Arc::clone(&network), None, Arc::clone(&logger));
4598 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4599 let scorer = test_utils::TestScorer::with_penalty(0);
4600 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4601 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4602 let payment_params = PaymentParameters::from_node_id(nodes[6]);
4604 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
4605 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4606 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4607 short_channel_id: 6,
4610 cltv_expiry_delta: (6 << 4) | 0,
4611 htlc_minimum_msat: 0,
4612 htlc_maximum_msat: OptionalField::Absent,
4614 fee_proportional_millionths: 0,
4615 excess_data: Vec::new()
4617 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
4619 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4620 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4621 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4622 short_channel_id: 5,
4625 cltv_expiry_delta: (5 << 4) | 0,
4626 htlc_minimum_msat: 0,
4627 htlc_maximum_msat: OptionalField::Absent,
4629 fee_proportional_millionths: 0,
4630 excess_data: Vec::new()
4632 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
4634 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
4635 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4636 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4637 short_channel_id: 4,
4640 cltv_expiry_delta: (4 << 4) | 0,
4641 htlc_minimum_msat: 0,
4642 htlc_maximum_msat: OptionalField::Absent,
4644 fee_proportional_millionths: 0,
4645 excess_data: Vec::new()
4647 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
4649 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
4650 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
4651 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4652 short_channel_id: 3,
4655 cltv_expiry_delta: (3 << 4) | 0,
4656 htlc_minimum_msat: 0,
4657 htlc_maximum_msat: OptionalField::Absent,
4659 fee_proportional_millionths: 0,
4660 excess_data: Vec::new()
4662 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
4664 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
4665 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4666 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4667 short_channel_id: 2,
4670 cltv_expiry_delta: (2 << 4) | 0,
4671 htlc_minimum_msat: 0,
4672 htlc_maximum_msat: OptionalField::Absent,
4674 fee_proportional_millionths: 0,
4675 excess_data: Vec::new()
4678 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
4679 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4680 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4681 short_channel_id: 1,
4684 cltv_expiry_delta: (1 << 4) | 0,
4685 htlc_minimum_msat: 100,
4686 htlc_maximum_msat: OptionalField::Absent,
4688 fee_proportional_millionths: 0,
4689 excess_data: Vec::new()
4691 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
4694 // Now ensure the route flows simply over nodes 1 and 4 to 6.
4695 let route = get_route(&our_id, &payment_params, &network.read_only(), None, 10_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4696 assert_eq!(route.paths.len(), 1);
4697 assert_eq!(route.paths[0].len(), 3);
4699 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
4700 assert_eq!(route.paths[0][0].short_channel_id, 6);
4701 assert_eq!(route.paths[0][0].fee_msat, 100);
4702 assert_eq!(route.paths[0][0].cltv_expiry_delta, (5 << 4) | 0);
4703 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(1));
4704 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(6));
4706 assert_eq!(route.paths[0][1].pubkey, nodes[4]);
4707 assert_eq!(route.paths[0][1].short_channel_id, 5);
4708 assert_eq!(route.paths[0][1].fee_msat, 0);
4709 assert_eq!(route.paths[0][1].cltv_expiry_delta, (1 << 4) | 0);
4710 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(4));
4711 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(5));
4713 assert_eq!(route.paths[0][2].pubkey, nodes[6]);
4714 assert_eq!(route.paths[0][2].short_channel_id, 1);
4715 assert_eq!(route.paths[0][2].fee_msat, 10_000);
4716 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
4717 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
4718 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(1));
4724 fn exact_fee_liquidity_limit() {
4725 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
4726 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
4727 // we calculated fees on a higher value, resulting in us ignoring such paths.
4728 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4729 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
4730 let scorer = test_utils::TestScorer::with_penalty(0);
4731 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4732 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4733 let payment_params = PaymentParameters::from_node_id(nodes[2]);
4735 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
4737 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4738 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4739 short_channel_id: 2,
4742 cltv_expiry_delta: 0,
4743 htlc_minimum_msat: 0,
4744 htlc_maximum_msat: OptionalField::Present(85_000),
4746 fee_proportional_millionths: 0,
4747 excess_data: Vec::new()
4750 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4751 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4752 short_channel_id: 12,
4755 cltv_expiry_delta: (4 << 4) | 1,
4756 htlc_minimum_msat: 0,
4757 htlc_maximum_msat: OptionalField::Present(270_000),
4759 fee_proportional_millionths: 1000000,
4760 excess_data: Vec::new()
4764 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
4765 // 200% fee charged channel 13 in the 1-to-2 direction.
4766 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4767 assert_eq!(route.paths.len(), 1);
4768 assert_eq!(route.paths[0].len(), 2);
4770 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
4771 assert_eq!(route.paths[0][0].short_channel_id, 12);
4772 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
4773 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
4774 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
4775 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
4777 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
4778 assert_eq!(route.paths[0][1].short_channel_id, 13);
4779 assert_eq!(route.paths[0][1].fee_msat, 90_000);
4780 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
4781 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
4782 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
4787 fn htlc_max_reduction_below_min() {
4788 // Test that if, while walking the graph, we reduce the value being sent to meet an
4789 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
4790 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
4791 // resulting in us thinking there is no possible path, even if other paths exist.
4792 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4793 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4794 let scorer = test_utils::TestScorer::with_penalty(0);
4795 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4796 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4797 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
4799 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
4800 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
4801 // then try to send 90_000.
4802 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4803 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4804 short_channel_id: 2,
4807 cltv_expiry_delta: 0,
4808 htlc_minimum_msat: 0,
4809 htlc_maximum_msat: OptionalField::Present(80_000),
4811 fee_proportional_millionths: 0,
4812 excess_data: Vec::new()
4814 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4815 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4816 short_channel_id: 4,
4819 cltv_expiry_delta: (4 << 4) | 1,
4820 htlc_minimum_msat: 90_000,
4821 htlc_maximum_msat: OptionalField::Absent,
4823 fee_proportional_millionths: 0,
4824 excess_data: Vec::new()
4828 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
4829 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
4830 // expensive) channels 12-13 path.
4831 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4832 assert_eq!(route.paths.len(), 1);
4833 assert_eq!(route.paths[0].len(), 2);
4835 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
4836 assert_eq!(route.paths[0][0].short_channel_id, 12);
4837 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
4838 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
4839 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
4840 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
4842 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
4843 assert_eq!(route.paths[0][1].short_channel_id, 13);
4844 assert_eq!(route.paths[0][1].fee_msat, 90_000);
4845 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
4846 assert_eq!(route.paths[0][1].node_features.le_flags(), InvoiceFeatures::known().le_flags());
4847 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
4852 fn multiple_direct_first_hops() {
4853 // Previously we'd only ever considered one first hop path per counterparty.
4854 // However, as we don't restrict users to one channel per peer, we really need to support
4855 // looking at all first hop paths.
4856 // Here we test that we do not ignore all-but-the-last first hop paths per counterparty (as
4857 // we used to do by overwriting the `first_hop_targets` hashmap entry) and that we can MPP
4858 // route over multiple channels with the same first hop.
4859 let secp_ctx = Secp256k1::new();
4860 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4861 let logger = Arc::new(test_utils::TestLogger::new());
4862 let network_graph = NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash());
4863 let scorer = test_utils::TestScorer::with_penalty(0);
4864 let payment_params = PaymentParameters::from_node_id(nodes[0]).with_features(InvoiceFeatures::known());
4865 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4866 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4869 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
4870 &get_channel_details(Some(3), nodes[0], InitFeatures::known(), 200_000),
4871 &get_channel_details(Some(2), nodes[0], InitFeatures::known(), 10_000),
4872 ]), 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4873 assert_eq!(route.paths.len(), 1);
4874 assert_eq!(route.paths[0].len(), 1);
4876 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
4877 assert_eq!(route.paths[0][0].short_channel_id, 3);
4878 assert_eq!(route.paths[0][0].fee_msat, 100_000);
4881 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
4882 &get_channel_details(Some(3), nodes[0], InitFeatures::known(), 50_000),
4883 &get_channel_details(Some(2), nodes[0], InitFeatures::known(), 50_000),
4884 ]), 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4885 assert_eq!(route.paths.len(), 2);
4886 assert_eq!(route.paths[0].len(), 1);
4887 assert_eq!(route.paths[1].len(), 1);
4889 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
4890 assert_eq!(route.paths[0][0].short_channel_id, 3);
4891 assert_eq!(route.paths[0][0].fee_msat, 50_000);
4893 assert_eq!(route.paths[1][0].pubkey, nodes[0]);
4894 assert_eq!(route.paths[1][0].short_channel_id, 2);
4895 assert_eq!(route.paths[1][0].fee_msat, 50_000);
4900 fn prefers_shorter_route_with_higher_fees() {
4901 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4902 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4903 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
4905 // Without penalizing each hop 100 msats, a longer path with lower fees is chosen.
4906 let scorer = test_utils::TestScorer::with_penalty(0);
4907 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4908 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4909 let route = get_route(
4910 &our_id, &payment_params, &network_graph.read_only(), None, 100, 42,
4911 Arc::clone(&logger), &scorer, &random_seed_bytes
4913 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4915 assert_eq!(route.get_total_fees(), 100);
4916 assert_eq!(route.get_total_amount(), 100);
4917 assert_eq!(path, vec![2, 4, 6, 11, 8]);
4919 // Applying a 100 msat penalty to each hop results in taking channels 7 and 10 to nodes[6]
4920 // from nodes[2] rather than channel 6, 11, and 8, even though the longer path is cheaper.
4921 let scorer = test_utils::TestScorer::with_penalty(100);
4922 let route = get_route(
4923 &our_id, &payment_params, &network_graph.read_only(), None, 100, 42,
4924 Arc::clone(&logger), &scorer, &random_seed_bytes
4926 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4928 assert_eq!(route.get_total_fees(), 300);
4929 assert_eq!(route.get_total_amount(), 100);
4930 assert_eq!(path, vec![2, 4, 7, 10]);
4933 struct BadChannelScorer {
4934 short_channel_id: u64,
4938 impl Writeable for BadChannelScorer {
4939 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), ::io::Error> { unimplemented!() }
4941 impl Score for BadChannelScorer {
4942 fn channel_penalty_msat(&self, short_channel_id: u64, _send_amt: u64, _capacity_msat: u64, _source: &NodeId, _target: &NodeId) -> u64 {
4943 if short_channel_id == self.short_channel_id { u64::max_value() } else { 0 }
4946 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
4947 fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
4950 struct BadNodeScorer {
4955 impl Writeable for BadNodeScorer {
4956 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), ::io::Error> { unimplemented!() }
4959 impl Score for BadNodeScorer {
4960 fn channel_penalty_msat(&self, _short_channel_id: u64, _send_amt: u64, _capacity_msat: u64, _source: &NodeId, target: &NodeId) -> u64 {
4961 if *target == self.node_id { u64::max_value() } else { 0 }
4964 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
4965 fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
4969 fn avoids_routing_through_bad_channels_and_nodes() {
4970 let (secp_ctx, network, _, _, logger) = build_graph();
4971 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4972 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
4973 let network_graph = network.read_only();
4975 // A path to nodes[6] exists when no penalties are applied to any channel.
4976 let scorer = test_utils::TestScorer::with_penalty(0);
4977 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4978 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4979 let route = get_route(
4980 &our_id, &payment_params, &network_graph, None, 100, 42,
4981 Arc::clone(&logger), &scorer, &random_seed_bytes
4983 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4985 assert_eq!(route.get_total_fees(), 100);
4986 assert_eq!(route.get_total_amount(), 100);
4987 assert_eq!(path, vec![2, 4, 6, 11, 8]);
4989 // A different path to nodes[6] exists if channel 6 cannot be routed over.
4990 let scorer = BadChannelScorer { short_channel_id: 6 };
4991 let route = get_route(
4992 &our_id, &payment_params, &network_graph, None, 100, 42,
4993 Arc::clone(&logger), &scorer, &random_seed_bytes
4995 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4997 assert_eq!(route.get_total_fees(), 300);
4998 assert_eq!(route.get_total_amount(), 100);
4999 assert_eq!(path, vec![2, 4, 7, 10]);
5001 // A path to nodes[6] does not exist if nodes[2] cannot be routed through.
5002 let scorer = BadNodeScorer { node_id: NodeId::from_pubkey(&nodes[2]) };
5004 &our_id, &payment_params, &network_graph, None, 100, 42,
5005 Arc::clone(&logger), &scorer, &random_seed_bytes
5007 Err(LightningError { err, .. } ) => {
5008 assert_eq!(err, "Failed to find a path to the given destination");
5010 Ok(_) => panic!("Expected error"),
5015 fn total_fees_single_path() {
5019 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5020 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5021 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5024 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5025 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5026 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5029 pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
5030 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5031 short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0
5034 payment_params: None,
5037 assert_eq!(route.get_total_fees(), 250);
5038 assert_eq!(route.get_total_amount(), 225);
5042 fn total_fees_multi_path() {
5046 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5047 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5048 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5051 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5052 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5053 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5057 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5058 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5059 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5062 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5063 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5064 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5067 payment_params: None,
5070 assert_eq!(route.get_total_fees(), 200);
5071 assert_eq!(route.get_total_amount(), 300);
5075 fn total_empty_route_no_panic() {
5076 // In an earlier version of `Route::get_total_fees` and `Route::get_total_amount`, they
5077 // would both panic if the route was completely empty. We test to ensure they return 0
5078 // here, even though its somewhat nonsensical as a route.
5079 let route = Route { paths: Vec::new(), payment_params: None };
5081 assert_eq!(route.get_total_fees(), 0);
5082 assert_eq!(route.get_total_amount(), 0);
5086 fn limits_total_cltv_delta() {
5087 let (secp_ctx, network, _, _, logger) = build_graph();
5088 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5089 let network_graph = network.read_only();
5091 let scorer = test_utils::TestScorer::with_penalty(0);
5093 // Make sure that generally there is at least one route available
5094 let feasible_max_total_cltv_delta = 1008;
5095 let feasible_payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes))
5096 .with_max_total_cltv_expiry_delta(feasible_max_total_cltv_delta);
5097 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5098 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5099 let route = get_route(&our_id, &feasible_payment_params, &network_graph, None, 100, 0, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5100 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5101 assert_ne!(path.len(), 0);
5103 // But not if we exclude all paths on the basis of their accumulated CLTV delta
5104 let fail_max_total_cltv_delta = 23;
5105 let fail_payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes))
5106 .with_max_total_cltv_expiry_delta(fail_max_total_cltv_delta);
5107 match get_route(&our_id, &fail_payment_params, &network_graph, None, 100, 0, Arc::clone(&logger), &scorer, &random_seed_bytes)
5109 Err(LightningError { err, .. } ) => {
5110 assert_eq!(err, "Failed to find a path to the given destination");
5112 Ok(_) => panic!("Expected error"),
5117 fn adds_and_limits_cltv_offset() {
5118 let (secp_ctx, network_graph, _, _, logger) = build_graph();
5119 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5121 let scorer = test_utils::TestScorer::with_penalty(0);
5123 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
5124 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5125 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5126 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5127 assert_eq!(route.paths.len(), 1);
5129 let cltv_expiry_deltas_before = route.paths[0].iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5131 // Check whether the offset added to the last hop by default is in [1 .. DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA]
5132 let mut route_default = route.clone();
5133 add_random_cltv_offset(&mut route_default, &payment_params, &network_graph.read_only(), &random_seed_bytes);
5134 let cltv_expiry_deltas_default = route_default.paths[0].iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5135 assert_eq!(cltv_expiry_deltas_before.split_last().unwrap().1, cltv_expiry_deltas_default.split_last().unwrap().1);
5136 assert!(cltv_expiry_deltas_default.last() > cltv_expiry_deltas_before.last());
5137 assert!(cltv_expiry_deltas_default.last().unwrap() <= &DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA);
5139 // Check that no offset is added when we restrict the max_total_cltv_expiry_delta
5140 let mut route_limited = route.clone();
5141 let limited_max_total_cltv_expiry_delta = cltv_expiry_deltas_before.iter().sum();
5142 let limited_payment_params = payment_params.with_max_total_cltv_expiry_delta(limited_max_total_cltv_expiry_delta);
5143 add_random_cltv_offset(&mut route_limited, &limited_payment_params, &network_graph.read_only(), &random_seed_bytes);
5144 let cltv_expiry_deltas_limited = route_limited.paths[0].iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5145 assert_eq!(cltv_expiry_deltas_before, cltv_expiry_deltas_limited);
5149 fn adds_plausible_cltv_offset() {
5150 let (secp_ctx, network, _, _, logger) = build_graph();
5151 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5152 let network_graph = network.read_only();
5153 let network_nodes = network_graph.nodes();
5154 let network_channels = network_graph.channels();
5155 let scorer = test_utils::TestScorer::with_penalty(0);
5156 let payment_params = PaymentParameters::from_node_id(nodes[3]);
5157 let keys_manager = test_utils::TestKeysInterface::new(&[4u8; 32], Network::Testnet);
5158 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5160 let mut route = get_route(&our_id, &payment_params, &network_graph, None, 100, 0,
5161 Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5162 add_random_cltv_offset(&mut route, &payment_params, &network_graph, &random_seed_bytes);
5164 let mut path_plausibility = vec![];
5166 for p in route.paths {
5167 // 1. Select random observation point
5168 let mut prng = ChaCha20::new(&random_seed_bytes, &[0u8; 12]);
5169 let mut random_bytes = [0u8; ::core::mem::size_of::<usize>()];
5171 prng.process_in_place(&mut random_bytes);
5172 let random_path_index = usize::from_be_bytes(random_bytes).wrapping_rem(p.len());
5173 let observation_point = NodeId::from_pubkey(&p.get(random_path_index).unwrap().pubkey);
5175 // 2. Calculate what CLTV expiry delta we would observe there
5176 let observed_cltv_expiry_delta: u32 = p[random_path_index..].iter().map(|h| h.cltv_expiry_delta).sum();
5178 // 3. Starting from the observation point, find candidate paths
5179 let mut candidates: VecDeque<(NodeId, Vec<u32>)> = VecDeque::new();
5180 candidates.push_back((observation_point, vec![]));
5182 let mut found_plausible_candidate = false;
5184 'candidate_loop: while let Some((cur_node_id, cur_path_cltv_deltas)) = candidates.pop_front() {
5185 if let Some(remaining) = observed_cltv_expiry_delta.checked_sub(cur_path_cltv_deltas.iter().sum::<u32>()) {
5186 if remaining == 0 || remaining.wrapping_rem(40) == 0 || remaining.wrapping_rem(144) == 0 {
5187 found_plausible_candidate = true;
5188 break 'candidate_loop;
5192 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
5193 for channel_id in &cur_node.channels {
5194 if let Some(channel_info) = network_channels.get(&channel_id) {
5195 if let Some((dir_info, next_id)) = channel_info.as_directed_from(&cur_node_id) {
5196 if let Some(channel_update_info) = dir_info.direction() {
5197 let next_cltv_expiry_delta = channel_update_info.cltv_expiry_delta as u32;
5198 if cur_path_cltv_deltas.iter().sum::<u32>()
5199 .saturating_add(next_cltv_expiry_delta) <= observed_cltv_expiry_delta {
5200 let mut new_path_cltv_deltas = cur_path_cltv_deltas.clone();
5201 new_path_cltv_deltas.push(next_cltv_expiry_delta);
5202 candidates.push_back((*next_id, new_path_cltv_deltas));
5211 path_plausibility.push(found_plausible_candidate);
5213 assert!(path_plausibility.iter().all(|x| *x));
5216 #[cfg(not(feature = "no-std"))]
5217 pub(super) fn random_init_seed() -> u64 {
5218 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
5219 use core::hash::{BuildHasher, Hasher};
5220 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
5221 println!("Using seed of {}", seed);
5224 #[cfg(not(feature = "no-std"))]
5225 use util::ser::Readable;
5228 #[cfg(not(feature = "no-std"))]
5229 fn generate_routes() {
5230 use routing::scoring::{ProbabilisticScorer, ProbabilisticScoringParameters};
5232 let mut d = match super::test_utils::get_route_file() {
5239 let graph = NetworkGraph::read(&mut d).unwrap();
5240 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5241 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5243 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
5244 let mut seed = random_init_seed() as usize;
5245 let nodes = graph.read_only().nodes().clone();
5246 'load_endpoints: for _ in 0..10 {
5248 seed = seed.overflowing_mul(0xdeadbeef).0;
5249 let src = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5250 seed = seed.overflowing_mul(0xdeadbeef).0;
5251 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5252 let payment_params = PaymentParameters::from_node_id(dst);
5253 let amt = seed as u64 % 200_000_000;
5254 let params = ProbabilisticScoringParameters::default();
5255 let scorer = ProbabilisticScorer::new(params, &graph);
5256 if get_route(src, &payment_params, &graph.read_only(), None, amt, 42, &test_utils::TestLogger::new(), &scorer, &random_seed_bytes).is_ok() {
5257 continue 'load_endpoints;
5264 #[cfg(not(feature = "no-std"))]
5265 fn generate_routes_mpp() {
5266 use routing::scoring::{ProbabilisticScorer, ProbabilisticScoringParameters};
5268 let mut d = match super::test_utils::get_route_file() {
5275 let graph = NetworkGraph::read(&mut d).unwrap();
5276 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5277 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5279 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
5280 let mut seed = random_init_seed() as usize;
5281 let nodes = graph.read_only().nodes().clone();
5282 'load_endpoints: for _ in 0..10 {
5284 seed = seed.overflowing_mul(0xdeadbeef).0;
5285 let src = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5286 seed = seed.overflowing_mul(0xdeadbeef).0;
5287 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5288 let payment_params = PaymentParameters::from_node_id(dst).with_features(InvoiceFeatures::known());
5289 let amt = seed as u64 % 200_000_000;
5290 let params = ProbabilisticScoringParameters::default();
5291 let scorer = ProbabilisticScorer::new(params, &graph);
5292 if get_route(src, &payment_params, &graph.read_only(), None, amt, 42, &test_utils::TestLogger::new(), &scorer, &random_seed_bytes).is_ok() {
5293 continue 'load_endpoints;
5300 #[cfg(all(test, not(feature = "no-std")))]
5301 pub(crate) mod test_utils {
5303 /// Tries to open a network graph file, or panics with a URL to fetch it.
5304 pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
5305 let res = File::open("net_graph-2021-05-31.bin") // By default we're run in RL/lightning
5306 .or_else(|_| File::open("lightning/net_graph-2021-05-31.bin")) // We may be run manually in RL/
5307 .or_else(|_| { // Fall back to guessing based on the binary location
5308 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
5309 let mut path = std::env::current_exe().unwrap();
5310 path.pop(); // lightning-...
5312 path.pop(); // debug
5313 path.pop(); // target
5314 path.push("lightning");
5315 path.push("net_graph-2021-05-31.bin");
5316 eprintln!("{}", path.to_str().unwrap());
5319 .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");
5320 #[cfg(require_route_graph_test)]
5321 return Ok(res.unwrap());
5322 #[cfg(not(require_route_graph_test))]
5327 #[cfg(all(test, feature = "_bench_unstable", not(feature = "no-std")))]
5330 use bitcoin::hashes::Hash;
5331 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
5332 use chain::transaction::OutPoint;
5333 use chain::keysinterface::{KeysManager,KeysInterface};
5334 use ln::channelmanager::{ChannelCounterparty, ChannelDetails};
5335 use ln::features::{InitFeatures, InvoiceFeatures};
5336 use routing::scoring::{FixedPenaltyScorer, ProbabilisticScorer, ProbabilisticScoringParameters, Scorer};
5337 use util::logger::{Logger, Record};
5341 struct DummyLogger {}
5342 impl Logger for DummyLogger {
5343 fn log(&self, _record: &Record) {}
5346 fn read_network_graph() -> NetworkGraph {
5347 let mut d = test_utils::get_route_file().unwrap();
5348 NetworkGraph::read(&mut d).unwrap()
5351 fn payer_pubkey() -> PublicKey {
5352 let secp_ctx = Secp256k1::new();
5353 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
5357 fn first_hop(node_id: PublicKey) -> ChannelDetails {
5359 channel_id: [0; 32],
5360 counterparty: ChannelCounterparty {
5361 features: InitFeatures::known(),
5363 unspendable_punishment_reserve: 0,
5364 forwarding_info: None,
5366 funding_txo: Some(OutPoint {
5367 txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0
5369 short_channel_id: Some(1),
5370 inbound_scid_alias: None,
5371 channel_value_satoshis: 10_000_000,
5373 balance_msat: 10_000_000,
5374 outbound_capacity_msat: 10_000_000,
5375 inbound_capacity_msat: 0,
5376 unspendable_punishment_reserve: None,
5377 confirmations_required: None,
5378 force_close_spend_delay: None,
5380 is_funding_locked: true,
5387 fn generate_routes_with_zero_penalty_scorer(bench: &mut Bencher) {
5388 let network_graph = read_network_graph();
5389 let scorer = FixedPenaltyScorer::with_penalty(0);
5390 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::empty());
5394 fn generate_mpp_routes_with_zero_penalty_scorer(bench: &mut Bencher) {
5395 let network_graph = read_network_graph();
5396 let scorer = FixedPenaltyScorer::with_penalty(0);
5397 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::known());
5401 fn generate_routes_with_default_scorer(bench: &mut Bencher) {
5402 let network_graph = read_network_graph();
5403 let scorer = Scorer::default();
5404 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::empty());
5408 fn generate_mpp_routes_with_default_scorer(bench: &mut Bencher) {
5409 let network_graph = read_network_graph();
5410 let scorer = Scorer::default();
5411 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::known());
5415 fn generate_routes_with_probabilistic_scorer(bench: &mut Bencher) {
5416 let network_graph = read_network_graph();
5417 let params = ProbabilisticScoringParameters::default();
5418 let scorer = ProbabilisticScorer::new(params, &network_graph);
5419 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::empty());
5423 fn generate_mpp_routes_with_probabilistic_scorer(bench: &mut Bencher) {
5424 let network_graph = read_network_graph();
5425 let params = ProbabilisticScoringParameters::default();
5426 let scorer = ProbabilisticScorer::new(params, &network_graph);
5427 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::known());
5430 fn generate_routes<S: Score>(
5431 bench: &mut Bencher, graph: &NetworkGraph, mut scorer: S, features: InvoiceFeatures
5433 let nodes = graph.read_only().nodes().clone();
5434 let payer = payer_pubkey();
5435 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
5436 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5438 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
5439 let mut routes = Vec::new();
5440 let mut route_endpoints = Vec::new();
5441 let mut seed: usize = 0xdeadbeef;
5442 'load_endpoints: for _ in 0..150 {
5445 let src = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5447 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5448 let params = PaymentParameters::from_node_id(dst).with_features(features.clone());
5449 let first_hop = first_hop(src);
5450 let amt = seed as u64 % 1_000_000;
5451 if let Ok(route) = get_route(&payer, ¶ms, &graph.read_only(), Some(&[&first_hop]), amt, 42, &DummyLogger{}, &scorer, &random_seed_bytes) {
5453 route_endpoints.push((first_hop, params, amt));
5454 continue 'load_endpoints;
5459 // ...and seed the scorer with success and failure data...
5460 for route in routes {
5461 let amount = route.get_total_amount();
5462 if amount < 250_000 {
5463 for path in route.paths {
5464 scorer.payment_path_successful(&path.iter().collect::<Vec<_>>());
5466 } else if amount > 750_000 {
5467 for path in route.paths {
5468 let short_channel_id = path[path.len() / 2].short_channel_id;
5469 scorer.payment_path_failed(&path.iter().collect::<Vec<_>>(), short_channel_id);
5474 // Because we've changed channel scores, its possible we'll take different routes to the
5475 // selected destinations, possibly causing us to fail because, eg, the newly-selected path
5476 // requires a too-high CLTV delta.
5477 route_endpoints.retain(|(first_hop, params, amt)| {
5478 get_route(&payer, params, &graph.read_only(), Some(&[first_hop]), *amt, 42, &DummyLogger{}, &scorer, &random_seed_bytes).is_ok()
5480 route_endpoints.truncate(100);
5481 assert_eq!(route_endpoints.len(), 100);
5483 // ...then benchmark finding paths between the nodes we learned.
5486 let (first_hop, params, amt) = &route_endpoints[idx % route_endpoints.len()];
5487 assert!(get_route(&payer, params, &graph.read_only(), Some(&[first_hop]), *amt, 42, &DummyLogger{}, &scorer, &random_seed_bytes).is_ok());