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 .saturating_add(other.path_penalty_msat);
336 let self_score = cmp::max(self.lowest_fee_to_peer_through_node, self.path_htlc_minimum_msat)
337 .saturating_add(self.path_penalty_msat);
338 other_score.cmp(&self_score).then_with(|| other.node_id.cmp(&self.node_id))
342 impl cmp::PartialOrd for RouteGraphNode {
343 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
344 Some(self.cmp(other))
348 /// A wrapper around the various hop representations.
350 /// Used to construct a [`PathBuildingHop`] and to estimate [`EffectiveCapacity`].
351 #[derive(Clone, Debug)]
352 enum CandidateRouteHop<'a> {
353 /// A hop from the payer, where the outbound liquidity is known.
355 details: &'a ChannelDetails,
357 /// A hop found in the [`NetworkGraph`], where the channel capacity may or may not be known.
359 info: DirectedChannelInfoWithUpdate<'a>,
360 short_channel_id: u64,
362 /// A hop to the payee found in the payment invoice, though not necessarily a direct channel.
364 hint: &'a RouteHintHop,
368 impl<'a> CandidateRouteHop<'a> {
369 fn short_channel_id(&self) -> u64 {
371 CandidateRouteHop::FirstHop { details } => details.short_channel_id.unwrap(),
372 CandidateRouteHop::PublicHop { short_channel_id, .. } => *short_channel_id,
373 CandidateRouteHop::PrivateHop { hint } => hint.short_channel_id,
377 // NOTE: This may alloc memory so avoid calling it in a hot code path.
378 fn features(&self) -> ChannelFeatures {
380 CandidateRouteHop::FirstHop { details } => details.counterparty.features.to_context(),
381 CandidateRouteHop::PublicHop { info, .. } => info.channel().features.clone(),
382 CandidateRouteHop::PrivateHop { .. } => ChannelFeatures::empty(),
386 fn cltv_expiry_delta(&self) -> u32 {
388 CandidateRouteHop::FirstHop { .. } => 0,
389 CandidateRouteHop::PublicHop { info, .. } => info.direction().cltv_expiry_delta as u32,
390 CandidateRouteHop::PrivateHop { hint } => hint.cltv_expiry_delta as u32,
394 fn htlc_minimum_msat(&self) -> u64 {
396 CandidateRouteHop::FirstHop { .. } => 0,
397 CandidateRouteHop::PublicHop { info, .. } => info.direction().htlc_minimum_msat,
398 CandidateRouteHop::PrivateHop { hint } => hint.htlc_minimum_msat.unwrap_or(0),
402 fn fees(&self) -> RoutingFees {
404 CandidateRouteHop::FirstHop { .. } => RoutingFees {
405 base_msat: 0, proportional_millionths: 0,
407 CandidateRouteHop::PublicHop { info, .. } => info.direction().fees,
408 CandidateRouteHop::PrivateHop { hint } => hint.fees,
412 fn effective_capacity(&self) -> EffectiveCapacity {
414 CandidateRouteHop::FirstHop { details } => EffectiveCapacity::ExactLiquidity {
415 liquidity_msat: details.outbound_capacity_msat,
417 CandidateRouteHop::PublicHop { info, .. } => info.effective_capacity(),
418 CandidateRouteHop::PrivateHop { .. } => EffectiveCapacity::Infinite,
423 /// It's useful to keep track of the hops associated with the fees required to use them,
424 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
425 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
426 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
428 struct PathBuildingHop<'a> {
429 // Note that this should be dropped in favor of loading it from CandidateRouteHop, but doing so
430 // is a larger refactor and will require careful performance analysis.
432 candidate: CandidateRouteHop<'a>,
435 /// Minimal fees required to route to the source node of the current hop via any of its inbound channels.
436 src_lowest_inbound_fees: RoutingFees,
437 /// All the fees paid *after* this channel on the way to the destination
438 next_hops_fee_msat: u64,
439 /// Fee paid for the use of the current channel (see candidate.fees()).
440 /// The value will be actually deducted from the counterparty balance on the previous link.
441 hop_use_fee_msat: u64,
442 /// Used to compare channels when choosing the for routing.
443 /// Includes paying for the use of a hop and the following hops, as well as
444 /// an estimated cost of reaching this hop.
445 /// Might get stale when fees are recomputed. Primarily for internal use.
447 /// A mirror of the same field in RouteGraphNode. Note that this is only used during the graph
448 /// walk and may be invalid thereafter.
449 path_htlc_minimum_msat: u64,
450 /// All penalties incurred from this channel on the way to the destination, as calculated using
452 path_penalty_msat: u64,
453 /// If we've already processed a node as the best node, we shouldn't process it again. Normally
454 /// we'd just ignore it if we did as all channels would have a higher new fee, but because we
455 /// may decrease the amounts in use as we walk the graph, the actual calculated fee may
456 /// decrease as well. Thus, we have to explicitly track which nodes have been processed and
457 /// avoid processing them again.
459 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
460 // In tests, we apply further sanity checks on cases where we skip nodes we already processed
461 // to ensure it is specifically in cases where the fee has gone down because of a decrease in
462 // value_contribution_msat, which requires tracking it here. See comments below where it is
463 // used for more info.
464 value_contribution_msat: u64,
467 impl<'a> core::fmt::Debug for PathBuildingHop<'a> {
468 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
469 f.debug_struct("PathBuildingHop")
470 .field("node_id", &self.node_id)
471 .field("short_channel_id", &self.candidate.short_channel_id())
472 .field("total_fee_msat", &self.total_fee_msat)
473 .field("next_hops_fee_msat", &self.next_hops_fee_msat)
474 .field("hop_use_fee_msat", &self.hop_use_fee_msat)
475 .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)))
476 .field("path_penalty_msat", &self.path_penalty_msat)
477 .field("path_htlc_minimum_msat", &self.path_htlc_minimum_msat)
478 .field("cltv_expiry_delta", &self.candidate.cltv_expiry_delta())
483 // Instantiated with a list of hops with correct data in them collected during path finding,
484 // an instance of this struct should be further modified only via given methods.
486 struct PaymentPath<'a> {
487 hops: Vec<(PathBuildingHop<'a>, NodeFeatures)>,
490 impl<'a> PaymentPath<'a> {
491 // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
492 fn get_value_msat(&self) -> u64 {
493 self.hops.last().unwrap().0.fee_msat
496 fn get_path_penalty_msat(&self) -> u64 {
497 self.hops.first().map(|h| h.0.path_penalty_msat).unwrap_or(u64::max_value())
500 fn get_total_fee_paid_msat(&self) -> u64 {
501 if self.hops.len() < 1 {
505 // Can't use next_hops_fee_msat because it gets outdated.
506 for (i, (hop, _)) in self.hops.iter().enumerate() {
507 if i != self.hops.len() - 1 {
508 result += hop.fee_msat;
514 fn get_cost_msat(&self) -> u64 {
515 self.get_total_fee_paid_msat().saturating_add(self.get_path_penalty_msat())
518 // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
519 // to change fees may result in an inconsistency.
521 // Sometimes we call this function right after constructing a path which is inconsistent in
522 // that it the value being transferred has decreased while we were doing path finding, leading
523 // to the fees being paid not lining up with the actual limits.
525 // Note that this function is not aware of the available_liquidity limit, and thus does not
526 // support increasing the value being transferred.
527 fn update_value_and_recompute_fees(&mut self, value_msat: u64) {
528 assert!(value_msat <= self.hops.last().unwrap().0.fee_msat);
530 let mut total_fee_paid_msat = 0 as u64;
531 for i in (0..self.hops.len()).rev() {
532 let last_hop = i == self.hops.len() - 1;
534 // For non-last-hop, this value will represent the fees paid on the current hop. It
535 // will consist of the fees for the use of the next hop, and extra fees to match
536 // htlc_minimum_msat of the current channel. Last hop is handled separately.
537 let mut cur_hop_fees_msat = 0;
539 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().0.hop_use_fee_msat;
542 let mut cur_hop = &mut self.hops.get_mut(i).unwrap().0;
543 cur_hop.next_hops_fee_msat = total_fee_paid_msat;
544 // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
545 // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
546 // set it too high just to maliciously take more fees by exploiting this
547 // match htlc_minimum_msat logic.
548 let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
549 if let Some(extra_fees_msat) = cur_hop.candidate.htlc_minimum_msat().checked_sub(cur_hop_transferred_amount_msat) {
550 // Note that there is a risk that *previous hops* (those closer to us, as we go
551 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
553 // This might make us end up with a broken route, although this should be super-rare
554 // in practice, both because of how healthy channels look like, and how we pick
555 // channels in add_entry.
556 // Also, this can't be exploited more heavily than *announce a free path and fail
558 cur_hop_transferred_amount_msat += extra_fees_msat;
559 total_fee_paid_msat += extra_fees_msat;
560 cur_hop_fees_msat += extra_fees_msat;
564 // Final hop is a special case: it usually has just value_msat (by design), but also
565 // it still could overpay for the htlc_minimum_msat.
566 cur_hop.fee_msat = cur_hop_transferred_amount_msat;
568 // Propagate updated fees for the use of the channels to one hop back, where they
569 // will be actually paid (fee_msat). The last hop is handled above separately.
570 cur_hop.fee_msat = cur_hop_fees_msat;
573 // Fee for the use of the current hop which will be deducted on the previous hop.
574 // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
575 // this channel is free for us.
577 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.candidate.fees()) {
578 cur_hop.hop_use_fee_msat = new_fee;
579 total_fee_paid_msat += new_fee;
581 // It should not be possible because this function is called only to reduce the
582 // value. In that case, compute_fee was already called with the same fees for
583 // larger amount and there was no overflow.
591 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
592 let proportional_fee_millions =
593 amount_msat.checked_mul(channel_fees.proportional_millionths as u64);
594 if let Some(new_fee) = proportional_fee_millions.and_then(|part| {
595 (channel_fees.base_msat as u64).checked_add(part / 1_000_000) }) {
599 // This function may be (indirectly) called without any verification,
600 // with channel_fees provided by a caller. We should handle it gracefully.
605 /// Finds a route from us (payer) to the given target node (payee).
607 /// If the payee provided features in their invoice, they should be provided via `params.payee`.
608 /// Without this, MPP will only be used if the payee's features are available in the network graph.
610 /// Private routing paths between a public node and the target may be included in `params.payee`.
612 /// If some channels aren't announced, it may be useful to fill in `first_hops` with the results
613 /// from [`ChannelManager::list_usable_channels`]. If it is filled in, the view of our local
614 /// channels from [`NetworkGraph`] will be ignored, and only those in `first_hops` will be used.
616 /// The fees on channels from us to the next hop are ignored as they are assumed to all be equal.
617 /// However, the enabled/disabled bit on such channels as well as the `htlc_minimum_msat` /
618 /// `htlc_maximum_msat` *are* checked as they may change based on the receiving node.
622 /// May be used to re-compute a [`Route`] when handling a [`Event::PaymentPathFailed`]. Any
623 /// adjustments to the [`NetworkGraph`] and channel scores should be made prior to calling this
628 /// Panics if first_hops contains channels without short_channel_ids;
629 /// [`ChannelManager::list_usable_channels`] will never include such channels.
631 /// [`ChannelManager::list_usable_channels`]: crate::ln::channelmanager::ChannelManager::list_usable_channels
632 /// [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed
633 pub fn find_route<L: Deref, S: Score>(
634 our_node_pubkey: &PublicKey, route_params: &RouteParameters, network: &NetworkGraph,
635 first_hops: Option<&[&ChannelDetails]>, logger: L, scorer: &S, random_seed_bytes: &[u8; 32]
636 ) -> Result<Route, LightningError>
637 where L::Target: Logger {
638 let network_graph = network.read_only();
640 our_node_pubkey, &route_params.payment_params, &network_graph, first_hops, route_params.final_value_msat,
641 route_params.final_cltv_expiry_delta, logger, scorer, random_seed_bytes
644 add_random_cltv_offset(&mut route, &route_params.payment_params, &network_graph, random_seed_bytes);
647 Err(err) => Err(err),
651 pub(crate) fn get_route<L: Deref, S: Score>(
652 our_node_pubkey: &PublicKey, payment_params: &PaymentParameters, network_graph: &ReadOnlyNetworkGraph,
653 first_hops: Option<&[&ChannelDetails]>, final_value_msat: u64, final_cltv_expiry_delta: u32,
654 logger: L, scorer: &S, random_seed_bytes: &[u8; 32]
655 ) -> Result<Route, LightningError>
656 where L::Target: Logger {
657 let payee_node_id = NodeId::from_pubkey(&payment_params.payee_pubkey);
658 let our_node_id = NodeId::from_pubkey(&our_node_pubkey);
660 if payee_node_id == our_node_id {
661 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
664 if final_value_msat > MAX_VALUE_MSAT {
665 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
668 if final_value_msat == 0 {
669 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
672 for route in payment_params.route_hints.iter() {
673 for hop in &route.0 {
674 if hop.src_node_id == payment_params.payee_pubkey {
675 return Err(LightningError{err: "Route hint cannot have the payee as the source.".to_owned(), action: ErrorAction::IgnoreError});
679 if payment_params.max_total_cltv_expiry_delta <= final_cltv_expiry_delta {
680 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});
683 // The general routing idea is the following:
684 // 1. Fill first/last hops communicated by the caller.
685 // 2. Attempt to construct a path from payer to payee for transferring
686 // any ~sufficient (described later) value.
687 // If succeed, remember which channels were used and how much liquidity they have available,
688 // so that future paths don't rely on the same liquidity.
689 // 3. Proceed to the next step if:
690 // - we hit the recommended target value;
691 // - OR if we could not construct a new path. Any next attempt will fail too.
692 // Otherwise, repeat step 2.
693 // 4. See if we managed to collect paths which aggregately are able to transfer target value
694 // (not recommended value).
695 // 5. If yes, proceed. If not, fail routing.
696 // 6. Randomly combine paths into routes having enough to fulfill the payment. (TODO: knapsack)
697 // 7. Of all the found paths, select only those with the lowest total fee.
698 // 8. The last path in every selected route is likely to be more than we need.
699 // Reduce its value-to-transfer and recompute fees.
700 // 9. Choose the best route by the lowest total fee.
702 // As for the actual search algorithm,
703 // we do a payee-to-payer pseudo-Dijkstra's sorting by each node's distance from the payee
704 // plus the minimum per-HTLC fee to get from it to another node (aka "shitty pseudo-A*").
706 // We are not a faithful Dijkstra's implementation because we can change values which impact
707 // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
708 // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) than
709 // the value we are currently attempting to send over a path, we simply reduce the value being
710 // sent along the path for any hops after that channel. This may imply that later fees (which
711 // we've already tabulated) are lower because a smaller value is passing through the channels
712 // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
713 // channels which were selected earlier (and which may still be used for other paths without a
714 // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
717 // One potentially problematic case for this algorithm would be if there are many
718 // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
719 // graph walking), we may never find a path which is not liquidity-limited and has lower
720 // proportional fee (and only lower absolute fee when considering the ultimate value sent).
721 // Because we only consider paths with at least 5% of the total value being sent, the damage
722 // from such a case should be limited, however this could be further reduced in the future by
723 // calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
724 // limits for the purposes of fee calculation.
726 // Alternatively, we could store more detailed path information in the heap (targets, below)
727 // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
728 // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
729 // and practically (as we would need to store dynamically-allocated path information in heap
730 // objects, increasing malloc traffic and indirect memory access significantly). Further, the
731 // results of such an algorithm would likely be biased towards lower-value paths.
733 // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
734 // outside of our current search value, running a path search more times to gather candidate
735 // paths at different values. While this may be acceptable, further path searches may increase
736 // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
737 // graph for candidate paths, calculating the maximum value which can realistically be sent at
738 // the same time, remaining generic across different payment values.
740 // TODO: There are a few tweaks we could do, including possibly pre-calculating more stuff
741 // to use as the A* heuristic beyond just the cost to get one node further than the current
744 let network_channels = network_graph.channels();
745 let network_nodes = network_graph.nodes();
747 // Allow MPP only if we have a features set from somewhere that indicates the payee supports
748 // it. If the payee supports it they're supposed to include it in the invoice, so that should
750 let allow_mpp = if let Some(features) = &payment_params.features {
751 features.supports_basic_mpp()
752 } else if let Some(node) = network_nodes.get(&payee_node_id) {
753 if let Some(node_info) = node.announcement_info.as_ref() {
754 node_info.features.supports_basic_mpp()
757 log_trace!(logger, "Searching for a route from payer {} to payee {} {} MPP and {} first hops {}overriding the network graph", our_node_pubkey,
758 payment_params.payee_pubkey, if allow_mpp { "with" } else { "without" },
759 first_hops.map(|hops| hops.len()).unwrap_or(0), if first_hops.is_some() { "" } else { "not " });
762 // Prepare the data we'll use for payee-to-payer search by
763 // inserting first hops suggested by the caller as targets.
764 // Our search will then attempt to reach them while traversing from the payee node.
765 let mut first_hop_targets: HashMap<_, Vec<&ChannelDetails>> =
766 HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
767 if let Some(hops) = first_hops {
769 if chan.short_channel_id.is_none() {
770 panic!("first_hops should be filled in with usable channels, not pending ones");
772 if chan.counterparty.node_id == *our_node_pubkey {
773 return Err(LightningError{err: "First hop cannot have our_node_pubkey as a destination.".to_owned(), action: ErrorAction::IgnoreError});
776 .entry(NodeId::from_pubkey(&chan.counterparty.node_id))
777 .or_insert(Vec::new())
780 if first_hop_targets.is_empty() {
781 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
785 // The main heap containing all candidate next-hops sorted by their score (max(A* fee,
786 // htlc_minimum)). Ideally this would be a heap which allowed cheap score reduction instead of
787 // adding duplicate entries when we find a better path to a given node.
788 let mut targets = BinaryHeap::new();
790 // Map from node_id to information about the best current path to that node, including feerate
792 let mut dist = HashMap::with_capacity(network_nodes.len());
794 // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
795 // indicating that we may wish to try again with a higher value, potentially paying to meet an
796 // htlc_minimum with extra fees while still finding a cheaper path.
797 let mut hit_minimum_limit;
799 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
800 // We start with a path_value of the exact amount we want, and if that generates a route we may
801 // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
802 // amount we want in total across paths, selecting the best subset at the end.
803 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
804 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
805 let mut path_value_msat = final_value_msat;
807 // We don't want multiple paths (as per MPP) share liquidity of the same channels.
808 // This map allows paths to be aware of the channel use by other paths in the same call.
809 // This would help to make a better path finding decisions and not "overbook" channels.
810 // It is unaware of the directions (except for `outbound_capacity_msat` in `first_hops`).
811 let mut bookkept_channels_liquidity_available_msat = HashMap::with_capacity(network_nodes.len());
813 // Keeping track of how much value we already collected across other paths. Helps to decide:
814 // - how much a new path should be transferring (upper bound);
815 // - whether a channel should be disregarded because
816 // it's available liquidity is too small comparing to how much more we need to collect;
817 // - when we want to stop looking for new paths.
818 let mut already_collected_value_msat = 0;
820 for (_, channels) in first_hop_targets.iter_mut() {
821 // Sort the first_hops channels to the same node(s) in priority order of which channel we'd
824 // First, if channels are below `recommended_value_msat`, sort them in descending order,
825 // preferring larger channels to avoid splitting the payment into more MPP parts than is
828 // Second, because simply always sorting in descending order would always use our largest
829 // available outbound capacity, needlessly fragmenting our available channel capacities,
830 // sort channels above `recommended_value_msat` in ascending order, preferring channels
831 // which have enough, but not too much, capacity for the payment.
832 channels.sort_unstable_by(|chan_a, chan_b| {
833 if chan_b.outbound_capacity_msat < recommended_value_msat || chan_a.outbound_capacity_msat < recommended_value_msat {
834 // Sort in descending order
835 chan_b.outbound_capacity_msat.cmp(&chan_a.outbound_capacity_msat)
837 // Sort in ascending order
838 chan_a.outbound_capacity_msat.cmp(&chan_b.outbound_capacity_msat)
843 log_trace!(logger, "Building path from {} (payee) to {} (us/payer) for value {} msat.", payment_params.payee_pubkey, our_node_pubkey, final_value_msat);
845 macro_rules! add_entry {
846 // Adds entry which goes from $src_node_id to $dest_node_id over the $candidate hop.
847 // $next_hops_fee_msat represents the fees paid for using all the channels *after* this one,
848 // since that value has to be transferred over this channel.
849 // Returns whether this channel caused an update to `targets`.
850 ( $candidate: expr, $src_node_id: expr, $dest_node_id: expr, $next_hops_fee_msat: expr,
851 $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr,
852 $next_hops_path_penalty_msat: expr, $next_hops_cltv_delta: expr ) => { {
853 // We "return" whether we updated the path at the end, via this:
854 let mut did_add_update_path_to_src_node = false;
855 // Channels to self should not be used. This is more of belt-and-suspenders, because in
856 // practice these cases should be caught earlier:
857 // - for regular channels at channel announcement (TODO)
858 // - for first and last hops early in get_route
859 if $src_node_id != $dest_node_id {
860 let short_channel_id = $candidate.short_channel_id();
861 let available_liquidity_msat = bookkept_channels_liquidity_available_msat
862 .entry(short_channel_id)
863 .or_insert_with(|| $candidate.effective_capacity().as_msat());
865 // It is tricky to subtract $next_hops_fee_msat from available liquidity here.
866 // It may be misleading because we might later choose to reduce the value transferred
867 // over these channels, and the channel which was insufficient might become sufficient.
868 // Worst case: we drop a good channel here because it can't cover the high following
869 // fees caused by one expensive channel, but then this channel could have been used
870 // if the amount being transferred over this path is lower.
871 // We do this for now, but this is a subject for removal.
872 if let Some(available_value_contribution_msat) = available_liquidity_msat.checked_sub($next_hops_fee_msat) {
874 // Routing Fragmentation Mitigation heuristic:
876 // Routing fragmentation across many payment paths increases the overall routing
877 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
878 // Taking too many smaller paths also increases the chance of payment failure.
879 // Thus to avoid this effect, we require from our collected links to provide
880 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
882 // This requirement is currently 5% of the remaining-to-be-collected value.
883 // This means as we successfully advance in our collection,
884 // the absolute liquidity contribution is lowered,
885 // thus increasing the number of potential channels to be selected.
887 // Derive the minimal liquidity contribution with a ratio of 20 (5%, rounded up)
888 // or 100% if we're not allowed to do multipath payments.
889 let minimal_value_contribution_msat: u64 = if allow_mpp {
890 (recommended_value_msat - already_collected_value_msat + 19) / 20
894 // Verify the liquidity offered by this channel complies to the minimal contribution.
895 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
897 // Do not consider candidates that exceed the maximum total cltv expiry limit.
898 // In order to already account for some of the privacy enhancing random CLTV
899 // expiry delta offset we add on top later, we subtract a rough estimate
900 // (2*MEDIAN_HOP_CLTV_EXPIRY_DELTA) here.
901 let max_total_cltv_expiry_delta = (payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta)
902 .checked_sub(2*MEDIAN_HOP_CLTV_EXPIRY_DELTA)
903 .unwrap_or(payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta);
904 let hop_total_cltv_delta = ($next_hops_cltv_delta as u32)
905 .saturating_add($candidate.cltv_expiry_delta());
906 let doesnt_exceed_cltv_delta_limit = hop_total_cltv_delta <= max_total_cltv_expiry_delta;
908 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
909 // Includes paying fees for the use of the following channels.
910 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
911 Some(result) => result,
912 // Can't overflow due to how the values were computed right above.
913 None => unreachable!(),
915 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
916 let over_path_minimum_msat = amount_to_transfer_over_msat >= $candidate.htlc_minimum_msat() &&
917 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
919 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
920 // bother considering this channel.
921 // Since we're choosing amount_to_transfer_over_msat as maximum possible, it can
922 // be only reduced later (not increased), so this channel should just be skipped
923 // as not sufficient.
924 if !over_path_minimum_msat && doesnt_exceed_cltv_delta_limit {
925 hit_minimum_limit = true;
926 } else if contributes_sufficient_value && doesnt_exceed_cltv_delta_limit {
927 // Note that low contribution here (limited by available_liquidity_msat)
928 // might violate htlc_minimum_msat on the hops which are next along the
929 // payment path (upstream to the payee). To avoid that, we recompute
930 // path fees knowing the final path contribution after constructing it.
931 let path_htlc_minimum_msat = compute_fees($next_hops_path_htlc_minimum_msat, $candidate.fees())
932 .and_then(|fee_msat| fee_msat.checked_add($next_hops_path_htlc_minimum_msat))
933 .map(|fee_msat| cmp::max(fee_msat, $candidate.htlc_minimum_msat()))
934 .unwrap_or_else(|| u64::max_value());
935 let hm_entry = dist.entry($src_node_id);
936 let old_entry = hm_entry.or_insert_with(|| {
937 // If there was previously no known way to access the source node
938 // (recall it goes payee-to-payer) of short_channel_id, first add a
939 // semi-dummy record just to compute the fees to reach the source node.
940 // This will affect our decision on selecting short_channel_id
941 // as a way to reach the $dest_node_id.
942 let mut fee_base_msat = 0;
943 let mut fee_proportional_millionths = 0;
944 if let Some(Some(fees)) = network_nodes.get(&$src_node_id).map(|node| node.lowest_inbound_channel_fees) {
945 fee_base_msat = fees.base_msat;
946 fee_proportional_millionths = fees.proportional_millionths;
949 node_id: $dest_node_id.clone(),
950 candidate: $candidate.clone(),
952 src_lowest_inbound_fees: RoutingFees {
953 base_msat: fee_base_msat,
954 proportional_millionths: fee_proportional_millionths,
956 next_hops_fee_msat: u64::max_value(),
957 hop_use_fee_msat: u64::max_value(),
958 total_fee_msat: u64::max_value(),
959 path_htlc_minimum_msat,
960 path_penalty_msat: u64::max_value(),
961 was_processed: false,
962 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
963 value_contribution_msat,
967 #[allow(unused_mut)] // We only use the mut in cfg(test)
968 let mut should_process = !old_entry.was_processed;
969 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
971 // In test/fuzzing builds, we do extra checks to make sure the skipping
972 // of already-seen nodes only happens in cases we expect (see below).
973 if !should_process { should_process = true; }
977 let mut hop_use_fee_msat = 0;
978 let mut total_fee_msat = $next_hops_fee_msat;
980 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
981 // will have the same effective-fee
982 if $src_node_id != our_node_id {
983 match compute_fees(amount_to_transfer_over_msat, $candidate.fees()) {
984 // max_value means we'll always fail
985 // the old_entry.total_fee_msat > total_fee_msat check
986 None => total_fee_msat = u64::max_value(),
988 hop_use_fee_msat = fee_msat;
989 total_fee_msat += hop_use_fee_msat;
990 // When calculating the lowest inbound fees to a node, we
991 // calculate fees here not based on the actual value we think
992 // will flow over this channel, but on the minimum value that
993 // we'll accept flowing over it. The minimum accepted value
994 // is a constant through each path collection run, ensuring
995 // consistent basis. Otherwise we may later find a
996 // different path to the source node that is more expensive,
997 // but which we consider to be cheaper because we are capacity
998 // constrained and the relative fee becomes lower.
999 match compute_fees(minimal_value_contribution_msat, old_entry.src_lowest_inbound_fees)
1000 .map(|a| a.checked_add(total_fee_msat)) {
1005 total_fee_msat = u64::max_value();
1012 let path_penalty_msat = $next_hops_path_penalty_msat.saturating_add(
1013 scorer.channel_penalty_msat(short_channel_id, amount_to_transfer_over_msat,
1014 *available_liquidity_msat, &$src_node_id, &$dest_node_id));
1015 let new_graph_node = RouteGraphNode {
1016 node_id: $src_node_id,
1017 lowest_fee_to_peer_through_node: total_fee_msat,
1018 lowest_fee_to_node: $next_hops_fee_msat as u64 + hop_use_fee_msat,
1019 total_cltv_delta: hop_total_cltv_delta,
1020 value_contribution_msat: value_contribution_msat,
1021 path_htlc_minimum_msat,
1025 // Update the way of reaching $src_node_id with the given short_channel_id (from $dest_node_id),
1026 // if this way is cheaper than the already known
1027 // (considering the cost to "reach" this channel from the route destination,
1028 // the cost of using this channel,
1029 // and the cost of routing to the source node of this channel).
1030 // Also, consider that htlc_minimum_msat_difference, because we might end up
1031 // paying it. Consider the following exploit:
1032 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
1033 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
1034 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
1035 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
1037 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
1038 // but it may require additional tracking - we don't want to double-count
1039 // the fees included in $next_hops_path_htlc_minimum_msat, but also
1040 // can't use something that may decrease on future hops.
1041 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat)
1042 .saturating_add(old_entry.path_penalty_msat);
1043 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat)
1044 .saturating_add(path_penalty_msat);
1046 if !old_entry.was_processed && new_cost < old_cost {
1047 targets.push(new_graph_node);
1048 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
1049 old_entry.hop_use_fee_msat = hop_use_fee_msat;
1050 old_entry.total_fee_msat = total_fee_msat;
1051 old_entry.node_id = $dest_node_id.clone();
1052 old_entry.candidate = $candidate.clone();
1053 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
1054 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
1055 old_entry.path_penalty_msat = path_penalty_msat;
1056 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
1058 old_entry.value_contribution_msat = value_contribution_msat;
1060 did_add_update_path_to_src_node = true;
1061 } else if old_entry.was_processed && new_cost < old_cost {
1062 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
1064 // If we're skipping processing a node which was previously
1065 // processed even though we found another path to it with a
1066 // cheaper fee, check that it was because the second path we
1067 // found (which we are processing now) has a lower value
1068 // contribution due to an HTLC minimum limit.
1070 // e.g. take a graph with two paths from node 1 to node 2, one
1071 // through channel A, and one through channel B. Channel A and
1072 // B are both in the to-process heap, with their scores set by
1073 // a higher htlc_minimum than fee.
1074 // Channel A is processed first, and the channels onwards from
1075 // node 1 are added to the to-process heap. Thereafter, we pop
1076 // Channel B off of the heap, note that it has a much more
1077 // restrictive htlc_maximum_msat, and recalculate the fees for
1078 // all of node 1's channels using the new, reduced, amount.
1080 // This would be bogus - we'd be selecting a higher-fee path
1081 // with a lower htlc_maximum_msat instead of the one we'd
1082 // already decided to use.
1083 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
1085 value_contribution_msat + path_penalty_msat <
1086 old_entry.value_contribution_msat + old_entry.path_penalty_msat
1094 did_add_update_path_to_src_node
1098 let empty_node_features = NodeFeatures::empty();
1099 // Find ways (channels with destination) to reach a given node and store them
1100 // in the corresponding data structures (routing graph etc).
1101 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
1102 // meaning how much will be paid in fees after this node (to the best of our knowledge).
1103 // This data can later be helpful to optimize routing (pay lower fees).
1104 macro_rules! add_entries_to_cheapest_to_target_node {
1105 ( $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 ) => {
1106 let skip_node = if let Some(elem) = dist.get_mut(&$node_id) {
1107 let was_processed = elem.was_processed;
1108 elem.was_processed = true;
1111 // Entries are added to dist in add_entry!() when there is a channel from a node.
1112 // Because there are no channels from payee, it will not have a dist entry at this point.
1113 // If we're processing any other node, it is always be the result of a channel from it.
1114 assert_eq!($node_id, payee_node_id);
1119 if let Some(first_channels) = first_hop_targets.get(&$node_id) {
1120 for details in first_channels {
1121 let candidate = CandidateRouteHop::FirstHop { details };
1122 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);
1126 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
1129 &empty_node_features
1132 if !features.requires_unknown_bits() {
1133 for chan_id in $node.channels.iter() {
1134 let chan = network_channels.get(chan_id).unwrap();
1135 if !chan.features.requires_unknown_bits() {
1136 let (directed_channel, source) =
1137 chan.as_directed_to(&$node_id).expect("inconsistent NetworkGraph");
1138 if first_hops.is_none() || *source != our_node_id {
1139 if let Some(direction) = directed_channel.direction() {
1140 if direction.enabled {
1141 let candidate = CandidateRouteHop::PublicHop {
1142 info: directed_channel.with_update().unwrap(),
1143 short_channel_id: *chan_id,
1145 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);
1156 let mut payment_paths = Vec::<PaymentPath>::new();
1158 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
1159 'paths_collection: loop {
1160 // For every new path, start from scratch, except
1161 // bookkept_channels_liquidity_available_msat, which will improve
1162 // the further iterations of path finding. Also don't erase first_hop_targets.
1165 hit_minimum_limit = false;
1167 // If first hop is a private channel and the only way to reach the payee, this is the only
1168 // place where it could be added.
1169 if let Some(first_channels) = first_hop_targets.get(&payee_node_id) {
1170 for details in first_channels {
1171 let candidate = CandidateRouteHop::FirstHop { details };
1172 let added = add_entry!(candidate, our_node_id, payee_node_id, 0, path_value_msat, 0, 0u64, 0);
1173 log_trace!(logger, "{} direct route to payee via SCID {}", if added { "Added" } else { "Skipped" }, candidate.short_channel_id());
1177 // Add the payee as a target, so that the payee-to-payer
1178 // search algorithm knows what to start with.
1179 match network_nodes.get(&payee_node_id) {
1180 // The payee is not in our network graph, so nothing to add here.
1181 // There is still a chance of reaching them via last_hops though,
1182 // so don't yet fail the payment here.
1183 // If not, targets.pop() will not even let us enter the loop in step 2.
1186 add_entries_to_cheapest_to_target_node!(node, payee_node_id, 0, path_value_msat, 0, 0u64, 0);
1191 // If a caller provided us with last hops, add them to routing targets. Since this happens
1192 // earlier than general path finding, they will be somewhat prioritized, although currently
1193 // it matters only if the fees are exactly the same.
1194 for route in payment_params.route_hints.iter().filter(|route| !route.0.is_empty()) {
1195 let first_hop_in_route = &(route.0)[0];
1196 let have_hop_src_in_graph =
1197 // Only add the hops in this route to our candidate set if either
1198 // we have a direct channel to the first hop or the first hop is
1199 // in the regular network graph.
1200 first_hop_targets.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some() ||
1201 network_nodes.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some();
1202 if have_hop_src_in_graph {
1203 // We start building the path from reverse, i.e., from payee
1204 // to the first RouteHintHop in the path.
1205 let hop_iter = route.0.iter().rev();
1206 let prev_hop_iter = core::iter::once(&payment_params.payee_pubkey).chain(
1207 route.0.iter().skip(1).rev().map(|hop| &hop.src_node_id));
1208 let mut hop_used = true;
1209 let mut aggregate_next_hops_fee_msat: u64 = 0;
1210 let mut aggregate_next_hops_path_htlc_minimum_msat: u64 = 0;
1211 let mut aggregate_next_hops_path_penalty_msat: u64 = 0;
1212 let mut aggregate_next_hops_cltv_delta: u32 = 0;
1214 for (idx, (hop, prev_hop_id)) in hop_iter.zip(prev_hop_iter).enumerate() {
1215 let source = NodeId::from_pubkey(&hop.src_node_id);
1216 let target = NodeId::from_pubkey(&prev_hop_id);
1217 let candidate = network_channels
1218 .get(&hop.short_channel_id)
1219 .and_then(|channel| channel.as_directed_to(&target))
1220 .and_then(|(channel, _)| channel.with_update())
1221 .map(|info| CandidateRouteHop::PublicHop {
1223 short_channel_id: hop.short_channel_id,
1225 .unwrap_or_else(|| CandidateRouteHop::PrivateHop { hint: hop });
1226 let capacity_msat = candidate.effective_capacity().as_msat();
1227 aggregate_next_hops_path_penalty_msat = aggregate_next_hops_path_penalty_msat
1228 .saturating_add(scorer.channel_penalty_msat(hop.short_channel_id, final_value_msat, capacity_msat, &source, &target));
1230 aggregate_next_hops_cltv_delta = aggregate_next_hops_cltv_delta
1231 .saturating_add(hop.cltv_expiry_delta as u32);
1233 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) {
1234 // If this hop was not used then there is no use checking the preceding hops
1235 // in the RouteHint. We can break by just searching for a direct channel between
1236 // last checked hop and first_hop_targets
1240 // Searching for a direct channel between last checked hop and first_hop_targets
1241 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&prev_hop_id)) {
1242 for details in first_channels {
1243 let candidate = CandidateRouteHop::FirstHop { details };
1244 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);
1252 // In the next values of the iterator, the aggregate fees already reflects
1253 // the sum of value sent from payer (final_value_msat) and routing fees
1254 // for the last node in the RouteHint. We need to just add the fees to
1255 // route through the current node so that the preceeding node (next iteration)
1257 let hops_fee = compute_fees(aggregate_next_hops_fee_msat + final_value_msat, hop.fees)
1258 .map_or(None, |inc| inc.checked_add(aggregate_next_hops_fee_msat));
1259 aggregate_next_hops_fee_msat = if let Some(val) = hops_fee { val } else { break; };
1261 let hop_htlc_minimum_msat = candidate.htlc_minimum_msat();
1262 let hop_htlc_minimum_msat_inc = if let Some(val) = compute_fees(aggregate_next_hops_path_htlc_minimum_msat, hop.fees) { val } else { break; };
1263 let hops_path_htlc_minimum = aggregate_next_hops_path_htlc_minimum_msat
1264 .checked_add(hop_htlc_minimum_msat_inc);
1265 aggregate_next_hops_path_htlc_minimum_msat = if let Some(val) = hops_path_htlc_minimum { cmp::max(hop_htlc_minimum_msat, val) } else { break; };
1267 if idx == route.0.len() - 1 {
1268 // The last hop in this iterator is the first hop in
1269 // overall RouteHint.
1270 // If this hop connects to a node with which we have a direct channel,
1271 // ignore the network graph and, if the last hop was added, add our
1272 // direct channel to the candidate set.
1274 // Note that we *must* check if the last hop was added as `add_entry`
1275 // always assumes that the third argument is a node to which we have a
1277 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&hop.src_node_id)) {
1278 for details in first_channels {
1279 let candidate = CandidateRouteHop::FirstHop { details };
1280 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);
1288 log_trace!(logger, "Starting main path collection loop with {} nodes pre-filled from first/last hops.", targets.len());
1290 // At this point, targets are filled with the data from first and
1291 // last hops communicated by the caller, and the payment receiver.
1292 let mut found_new_path = false;
1295 // If this loop terminates due the exhaustion of targets, two situations are possible:
1296 // - not enough outgoing liquidity:
1297 // 0 < already_collected_value_msat < final_value_msat
1298 // - enough outgoing liquidity:
1299 // final_value_msat <= already_collected_value_msat < recommended_value_msat
1300 // Both these cases (and other cases except reaching recommended_value_msat) mean that
1301 // paths_collection will be stopped because found_new_path==false.
1302 // This is not necessarily a routing failure.
1303 '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() {
1305 // Since we're going payee-to-payer, hitting our node as a target means we should stop
1306 // traversing the graph and arrange the path out of what we found.
1307 if node_id == our_node_id {
1308 let mut new_entry = dist.remove(&our_node_id).unwrap();
1309 let mut ordered_hops = vec!((new_entry.clone(), NodeFeatures::empty()));
1312 let mut features_set = false;
1313 if let Some(first_channels) = first_hop_targets.get(&ordered_hops.last().unwrap().0.node_id) {
1314 for details in first_channels {
1315 if details.short_channel_id.unwrap() == ordered_hops.last().unwrap().0.candidate.short_channel_id() {
1316 ordered_hops.last_mut().unwrap().1 = details.counterparty.features.to_context();
1317 features_set = true;
1323 if let Some(node) = network_nodes.get(&ordered_hops.last().unwrap().0.node_id) {
1324 if let Some(node_info) = node.announcement_info.as_ref() {
1325 ordered_hops.last_mut().unwrap().1 = node_info.features.clone();
1327 ordered_hops.last_mut().unwrap().1 = NodeFeatures::empty();
1330 // We can fill in features for everything except hops which were
1331 // provided via the invoice we're paying. We could guess based on the
1332 // recipient's features but for now we simply avoid guessing at all.
1336 // Means we succesfully traversed from the payer to the payee, now
1337 // save this path for the payment route. Also, update the liquidity
1338 // remaining on the used hops, so that we take them into account
1339 // while looking for more paths.
1340 if ordered_hops.last().unwrap().0.node_id == payee_node_id {
1344 new_entry = match dist.remove(&ordered_hops.last().unwrap().0.node_id) {
1345 Some(payment_hop) => payment_hop,
1346 // We can't arrive at None because, if we ever add an entry to targets,
1347 // we also fill in the entry in dist (see add_entry!).
1348 None => unreachable!(),
1350 // We "propagate" the fees one hop backward (topologically) here,
1351 // so that fees paid for a HTLC forwarding on the current channel are
1352 // associated with the previous channel (where they will be subtracted).
1353 ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
1354 ordered_hops.push((new_entry.clone(), NodeFeatures::empty()));
1356 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
1357 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
1359 log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: \n {:#?}",
1360 ordered_hops.len(), value_contribution_msat, ordered_hops.iter().map(|h| &(h.0)).collect::<Vec<&PathBuildingHop>>());
1362 let mut payment_path = PaymentPath {hops: ordered_hops};
1364 // We could have possibly constructed a slightly inconsistent path: since we reduce
1365 // value being transferred along the way, we could have violated htlc_minimum_msat
1366 // on some channels we already passed (assuming dest->source direction). Here, we
1367 // recompute the fees again, so that if that's the case, we match the currently
1368 // underpaid htlc_minimum_msat with fees.
1369 payment_path.update_value_and_recompute_fees(cmp::min(value_contribution_msat, final_value_msat));
1371 // Since a path allows to transfer as much value as
1372 // the smallest channel it has ("bottleneck"), we should recompute
1373 // the fees so sender HTLC don't overpay fees when traversing
1374 // larger channels than the bottleneck. This may happen because
1375 // when we were selecting those channels we were not aware how much value
1376 // this path will transfer, and the relative fee for them
1377 // might have been computed considering a larger value.
1378 // Remember that we used these channels so that we don't rely
1379 // on the same liquidity in future paths.
1380 let mut prevented_redundant_path_selection = false;
1381 for (payment_hop, _) in payment_path.hops.iter() {
1382 let channel_liquidity_available_msat = bookkept_channels_liquidity_available_msat.get_mut(&payment_hop.candidate.short_channel_id()).unwrap();
1383 let mut spent_on_hop_msat = value_contribution_msat;
1384 let next_hops_fee_msat = payment_hop.next_hops_fee_msat;
1385 spent_on_hop_msat += next_hops_fee_msat;
1386 if spent_on_hop_msat == *channel_liquidity_available_msat {
1387 // If this path used all of this channel's available liquidity, we know
1388 // this path will not be selected again in the next loop iteration.
1389 prevented_redundant_path_selection = true;
1391 *channel_liquidity_available_msat -= spent_on_hop_msat;
1393 if !prevented_redundant_path_selection {
1394 // If we weren't capped by hitting a liquidity limit on a channel in the path,
1395 // we'll probably end up picking the same path again on the next iteration.
1396 // Decrease the available liquidity of a hop in the middle of the path.
1397 let victim_scid = payment_path.hops[(payment_path.hops.len()) / 2].0.candidate.short_channel_id();
1398 log_trace!(logger, "Disabling channel {} for future path building iterations to avoid duplicates.", victim_scid);
1399 let victim_liquidity = bookkept_channels_liquidity_available_msat.get_mut(&victim_scid).unwrap();
1400 *victim_liquidity = 0;
1403 // Track the total amount all our collected paths allow to send so that we:
1404 // - know when to stop looking for more paths
1405 // - know which of the hops are useless considering how much more sats we need
1406 // (contributes_sufficient_value)
1407 already_collected_value_msat += value_contribution_msat;
1409 payment_paths.push(payment_path);
1410 found_new_path = true;
1411 break 'path_construction;
1414 // If we found a path back to the payee, we shouldn't try to process it again. This is
1415 // the equivalent of the `elem.was_processed` check in
1416 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
1417 if node_id == payee_node_id { continue 'path_construction; }
1419 // Otherwise, since the current target node is not us,
1420 // keep "unrolling" the payment graph from payee to payer by
1421 // finding a way to reach the current target from the payer side.
1422 match network_nodes.get(&node_id) {
1425 add_entries_to_cheapest_to_target_node!(node, node_id, lowest_fee_to_node, value_contribution_msat, path_htlc_minimum_msat, path_penalty_msat, total_cltv_delta);
1431 // If we don't support MPP, no use trying to gather more value ever.
1432 break 'paths_collection;
1436 // Stop either when the recommended value is reached or if no new path was found in this
1438 // In the latter case, making another path finding attempt won't help,
1439 // because we deterministically terminated the search due to low liquidity.
1440 if already_collected_value_msat >= recommended_value_msat || !found_new_path {
1441 log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
1442 already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
1443 break 'paths_collection;
1444 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
1445 // Further, if this was our first walk of the graph, and we weren't limited by an
1446 // htlc_minimum_msat, return immediately because this path should suffice. If we were
1447 // limited by an htlc_minimum_msat value, find another path with a higher value,
1448 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
1449 // still keeping a lower total fee than this path.
1450 if !hit_minimum_limit {
1451 log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
1452 break 'paths_collection;
1454 log_trace!(logger, "Collected our payment amount on the first pass, but running again to collect extra paths with a potentially higher limit.");
1455 path_value_msat = recommended_value_msat;
1460 if payment_paths.len() == 0 {
1461 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1464 if already_collected_value_msat < final_value_msat {
1465 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1468 // Sort by total fees and take the best paths.
1469 payment_paths.sort_unstable_by_key(|path| path.get_total_fee_paid_msat());
1470 if payment_paths.len() > 50 {
1471 payment_paths.truncate(50);
1474 // Draw multiple sufficient routes by randomly combining the selected paths.
1475 let mut drawn_routes = Vec::new();
1476 let mut prng = ChaCha20::new(random_seed_bytes, &[0u8; 12]);
1477 let mut random_index_bytes = [0u8; ::core::mem::size_of::<usize>()];
1479 let num_permutations = payment_paths.len();
1480 for _ in 0..num_permutations {
1481 let mut cur_route = Vec::<PaymentPath>::new();
1482 let mut aggregate_route_value_msat = 0;
1485 // Do a Fisher-Yates shuffle to create a random permutation of the payment paths
1486 for cur_index in (1..payment_paths.len()).rev() {
1487 prng.process_in_place(&mut random_index_bytes);
1488 let random_index = usize::from_be_bytes(random_index_bytes).wrapping_rem(cur_index+1);
1489 payment_paths.swap(cur_index, random_index);
1493 for payment_path in &payment_paths {
1494 cur_route.push(payment_path.clone());
1495 aggregate_route_value_msat += payment_path.get_value_msat();
1496 if aggregate_route_value_msat > final_value_msat {
1497 // Last path likely overpaid. Substract it from the most expensive
1498 // (in terms of proportional fee) path in this route and recompute fees.
1499 // This might be not the most economically efficient way, but fewer paths
1500 // also makes routing more reliable.
1501 let mut overpaid_value_msat = aggregate_route_value_msat - final_value_msat;
1503 // First, we drop some expensive low-value paths entirely if possible, since fewer
1504 // paths is better: the payment is less likely to fail. In order to do so, we sort
1505 // by value and fall back to total fees paid, i.e., in case of equal values we
1506 // prefer lower cost paths.
1507 cur_route.sort_unstable_by(|a, b| {
1508 a.get_value_msat().cmp(&b.get_value_msat())
1509 // Reverse ordering for cost, so we drop higher-cost paths first
1510 .then_with(|| b.get_cost_msat().cmp(&a.get_cost_msat()))
1513 // We should make sure that at least 1 path left.
1514 let mut paths_left = cur_route.len();
1515 cur_route.retain(|path| {
1516 if paths_left == 1 {
1519 let mut keep = true;
1520 let path_value_msat = path.get_value_msat();
1521 if path_value_msat <= overpaid_value_msat {
1523 overpaid_value_msat -= path_value_msat;
1529 if overpaid_value_msat == 0 {
1533 assert!(cur_route.len() > 0);
1536 // Now, subtract the overpaid value from the most-expensive path.
1537 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1538 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1539 cur_route.sort_unstable_by_key(|path| { path.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>() });
1540 let expensive_payment_path = cur_route.first_mut().unwrap();
1542 // We already dropped all the small value paths above, meaning all the
1543 // remaining paths are larger than remaining overpaid_value_msat.
1544 // Thus, this can't be negative.
1545 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
1546 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
1550 drawn_routes.push(cur_route);
1554 // Select the best route by lowest total cost.
1555 drawn_routes.sort_unstable_by_key(|paths| paths.iter().map(|path| path.get_cost_msat()).sum::<u64>());
1556 let mut selected_paths = Vec::<Vec<Result<RouteHop, LightningError>>>::new();
1557 for payment_path in drawn_routes.first().unwrap() {
1558 let mut path = payment_path.hops.iter().map(|(payment_hop, node_features)| {
1560 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)})?,
1561 node_features: node_features.clone(),
1562 short_channel_id: payment_hop.candidate.short_channel_id(),
1563 channel_features: payment_hop.candidate.features(),
1564 fee_msat: payment_hop.fee_msat,
1565 cltv_expiry_delta: payment_hop.candidate.cltv_expiry_delta(),
1567 }).collect::<Vec<_>>();
1568 // Propagate the cltv_expiry_delta one hop backwards since the delta from the current hop is
1569 // applicable for the previous hop.
1570 path.iter_mut().rev().fold(final_cltv_expiry_delta, |prev_cltv_expiry_delta, hop| {
1571 core::mem::replace(&mut hop.as_mut().unwrap().cltv_expiry_delta, prev_cltv_expiry_delta)
1573 selected_paths.push(path);
1576 if let Some(features) = &payment_params.features {
1577 for path in selected_paths.iter_mut() {
1578 if let Ok(route_hop) = path.last_mut().unwrap() {
1579 route_hop.node_features = features.to_context();
1585 paths: selected_paths.into_iter().map(|path| path.into_iter().collect()).collect::<Result<Vec<_>, _>>()?,
1586 payment_params: Some(payment_params.clone()),
1588 log_info!(logger, "Got route to {}: {}", payment_params.payee_pubkey, log_route!(route));
1592 // When an adversarial intermediary node observes a payment, it may be able to infer its
1593 // destination, if the remaining CLTV expiry delta exactly matches a feasible path in the network
1594 // graph. In order to improve privacy, this method obfuscates the CLTV expiry deltas along the
1595 // payment path by adding a randomized 'shadow route' offset to the final hop.
1596 fn add_random_cltv_offset(route: &mut Route, payment_params: &PaymentParameters, network_graph: &ReadOnlyNetworkGraph, random_seed_bytes: &[u8; 32]) {
1597 let network_channels = network_graph.channels();
1598 let network_nodes = network_graph.nodes();
1600 for path in route.paths.iter_mut() {
1601 let mut shadow_ctlv_expiry_delta_offset: u32 = 0;
1603 // Remember the last three nodes of the random walk and avoid looping back on them.
1604 // Init with the last three nodes from the actual path, if possible.
1605 let mut nodes_to_avoid: [NodeId; 3] = [NodeId::from_pubkey(&path.last().unwrap().pubkey),
1606 NodeId::from_pubkey(&path.get(path.len().saturating_sub(2)).unwrap().pubkey),
1607 NodeId::from_pubkey(&path.get(path.len().saturating_sub(3)).unwrap().pubkey)];
1609 // Choose the last publicly known node as the starting point for the random walk.
1610 let mut cur_hop: Option<NodeId> = None;
1611 let mut path_nonce = [0u8; 12];
1612 if let Some(starting_hop) = path.iter().rev()
1613 .find(|h| network_nodes.contains_key(&NodeId::from_pubkey(&h.pubkey))) {
1614 cur_hop = Some(NodeId::from_pubkey(&starting_hop.pubkey));
1615 path_nonce.copy_from_slice(&cur_hop.unwrap().as_slice()[..12]);
1618 // Init PRNG with the path-dependant nonce, which is static for private paths.
1619 let mut prng = ChaCha20::new(random_seed_bytes, &path_nonce);
1620 let mut random_path_bytes = [0u8; ::core::mem::size_of::<usize>()];
1622 // Pick a random path length in [1 .. 3]
1623 prng.process_in_place(&mut random_path_bytes);
1624 let random_walk_length = usize::from_be_bytes(random_path_bytes).wrapping_rem(3).wrapping_add(1);
1626 for random_hop in 0..random_walk_length {
1627 // If we don't find a suitable offset in the public network graph, we default to
1628 // MEDIAN_HOP_CLTV_EXPIRY_DELTA.
1629 let mut random_hop_offset = MEDIAN_HOP_CLTV_EXPIRY_DELTA;
1631 if let Some(cur_node_id) = cur_hop {
1632 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
1633 // Randomly choose the next unvisited hop.
1634 prng.process_in_place(&mut random_path_bytes);
1635 if let Some(random_channel) = usize::from_be_bytes(random_path_bytes)
1636 .checked_rem(cur_node.channels.len())
1637 .and_then(|index| cur_node.channels.get(index))
1638 .and_then(|id| network_channels.get(id)) {
1639 random_channel.as_directed_from(&cur_node_id).map(|(dir_info, next_id)| {
1640 if !nodes_to_avoid.iter().any(|x| x == next_id) {
1641 nodes_to_avoid[random_hop] = *next_id;
1642 dir_info.direction().map(|channel_update_info| {
1643 random_hop_offset = channel_update_info.cltv_expiry_delta.into();
1644 cur_hop = Some(*next_id);
1652 shadow_ctlv_expiry_delta_offset = shadow_ctlv_expiry_delta_offset
1653 .checked_add(random_hop_offset)
1654 .unwrap_or(shadow_ctlv_expiry_delta_offset);
1657 // Limit the total offset to reduce the worst-case locked liquidity timevalue
1658 const MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET: u32 = 3*144;
1659 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET);
1661 // Limit the offset so we never exceed the max_total_cltv_expiry_delta. To improve plausibility,
1662 // we choose the limit to be the largest possible multiple of MEDIAN_HOP_CLTV_EXPIRY_DELTA.
1663 let path_total_cltv_expiry_delta: u32 = path.iter().map(|h| h.cltv_expiry_delta).sum();
1664 let mut max_path_offset = payment_params.max_total_cltv_expiry_delta - path_total_cltv_expiry_delta;
1665 max_path_offset = cmp::max(
1666 max_path_offset - (max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA),
1667 max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA);
1668 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, max_path_offset);
1670 // Add 'shadow' CLTV offset to the final hop
1671 if let Some(last_hop) = path.last_mut() {
1672 last_hop.cltv_expiry_delta = last_hop.cltv_expiry_delta
1673 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(last_hop.cltv_expiry_delta);
1680 use routing::network_graph::{NetworkGraph, NetGraphMsgHandler, NodeId};
1681 use routing::router::{get_route, add_random_cltv_offset, PaymentParameters, Route, RouteHint, RouteHintHop, RouteHop, RoutingFees, DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA};
1682 use routing::scoring::Score;
1683 use chain::transaction::OutPoint;
1684 use chain::keysinterface::KeysInterface;
1685 use ln::features::{ChannelFeatures, InitFeatures, InvoiceFeatures, NodeFeatures};
1686 use ln::msgs::{ErrorAction, LightningError, OptionalField, UnsignedChannelAnnouncement, ChannelAnnouncement, RoutingMessageHandler,
1687 NodeAnnouncement, UnsignedNodeAnnouncement, ChannelUpdate, UnsignedChannelUpdate};
1688 use ln::channelmanager;
1689 use util::test_utils;
1690 use util::chacha20::ChaCha20;
1691 use util::ser::Writeable;
1693 use util::ser::Writer;
1695 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
1696 use bitcoin::hashes::Hash;
1697 use bitcoin::network::constants::Network;
1698 use bitcoin::blockdata::constants::genesis_block;
1699 use bitcoin::blockdata::script::Builder;
1700 use bitcoin::blockdata::opcodes;
1701 use bitcoin::blockdata::transaction::TxOut;
1705 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
1706 use bitcoin::secp256k1::{Secp256k1, All};
1709 use sync::{self, Arc};
1711 fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
1712 features: InitFeatures, outbound_capacity_msat: u64) -> channelmanager::ChannelDetails {
1713 channelmanager::ChannelDetails {
1714 channel_id: [0; 32],
1715 counterparty: channelmanager::ChannelCounterparty {
1718 unspendable_punishment_reserve: 0,
1719 forwarding_info: None,
1721 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
1724 inbound_scid_alias: None,
1725 channel_value_satoshis: 0,
1728 outbound_capacity_msat,
1729 inbound_capacity_msat: 42,
1730 unspendable_punishment_reserve: None,
1731 confirmations_required: None,
1732 force_close_spend_delay: None,
1733 is_outbound: true, is_funding_locked: true,
1734 is_usable: true, is_public: true,
1738 // Using the same keys for LN and BTC ids
1740 net_graph_msg_handler: &NetGraphMsgHandler<Arc<NetworkGraph>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1741 secp_ctx: &Secp256k1<All>, node_1_privkey: &SecretKey, node_2_privkey: &SecretKey, features: ChannelFeatures, short_channel_id: u64
1743 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1744 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1746 let unsigned_announcement = UnsignedChannelAnnouncement {
1748 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1752 bitcoin_key_1: node_id_1,
1753 bitcoin_key_2: node_id_2,
1754 excess_data: Vec::new(),
1757 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1758 let valid_announcement = ChannelAnnouncement {
1759 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1760 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1761 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1762 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1763 contents: unsigned_announcement.clone(),
1765 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1766 Ok(res) => assert!(res),
1772 net_graph_msg_handler: &NetGraphMsgHandler<Arc<NetworkGraph>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1773 secp_ctx: &Secp256k1<All>, node_privkey: &SecretKey, update: UnsignedChannelUpdate
1775 let msghash = hash_to_message!(&Sha256dHash::hash(&update.encode()[..])[..]);
1776 let valid_channel_update = ChannelUpdate {
1777 signature: secp_ctx.sign(&msghash, node_privkey),
1778 contents: update.clone()
1781 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1782 Ok(res) => assert!(res),
1787 fn add_or_update_node(
1788 net_graph_msg_handler: &NetGraphMsgHandler<Arc<NetworkGraph>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1789 secp_ctx: &Secp256k1<All>, node_privkey: &SecretKey, features: NodeFeatures, timestamp: u32
1791 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
1792 let unsigned_announcement = UnsignedNodeAnnouncement {
1798 addresses: Vec::new(),
1799 excess_address_data: Vec::new(),
1800 excess_data: Vec::new(),
1802 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1803 let valid_announcement = NodeAnnouncement {
1804 signature: secp_ctx.sign(&msghash, node_privkey),
1805 contents: unsigned_announcement.clone()
1808 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1814 fn get_nodes(secp_ctx: &Secp256k1<All>) -> (SecretKey, PublicKey, Vec<SecretKey>, Vec<PublicKey>) {
1815 let privkeys: Vec<SecretKey> = (2..10).map(|i| {
1816 SecretKey::from_slice(&hex::decode(format!("{:02x}", i).repeat(32)).unwrap()[..]).unwrap()
1819 let pubkeys = privkeys.iter().map(|secret| PublicKey::from_secret_key(&secp_ctx, secret)).collect();
1821 let our_privkey = SecretKey::from_slice(&hex::decode("01".repeat(32)).unwrap()[..]).unwrap();
1822 let our_id = PublicKey::from_secret_key(&secp_ctx, &our_privkey);
1824 (our_privkey, our_id, privkeys, pubkeys)
1827 fn id_to_feature_flags(id: u8) -> Vec<u8> {
1828 // Set the feature flags to the id'th odd (ie non-required) feature bit so that we can
1829 // test for it later.
1830 let idx = (id - 1) * 2 + 1;
1832 vec![1 << (idx - 8*3), 0, 0, 0]
1833 } else if idx > 8*2 {
1834 vec![1 << (idx - 8*2), 0, 0]
1835 } else if idx > 8*1 {
1836 vec![1 << (idx - 8*1), 0]
1842 fn build_graph() -> (
1844 sync::Arc<NetworkGraph>,
1845 NetGraphMsgHandler<sync::Arc<NetworkGraph>, sync::Arc<test_utils::TestChainSource>, sync::Arc<crate::util::test_utils::TestLogger>>,
1846 sync::Arc<test_utils::TestChainSource>,
1847 sync::Arc<test_utils::TestLogger>,
1849 let secp_ctx = Secp256k1::new();
1850 let logger = Arc::new(test_utils::TestLogger::new());
1851 let chain_monitor = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1852 let network_graph = Arc::new(NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash()));
1853 let net_graph_msg_handler = NetGraphMsgHandler::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
1854 // Build network from our_id to node6:
1856 // -1(1)2- node0 -1(3)2-
1858 // our_id -1(12)2- node7 -1(13)2--- node2
1860 // -1(2)2- node1 -1(4)2-
1863 // chan1 1-to-2: disabled
1864 // chan1 2-to-1: enabled, 0 fee
1866 // chan2 1-to-2: enabled, ignored fee
1867 // chan2 2-to-1: enabled, 0 fee
1869 // chan3 1-to-2: enabled, 0 fee
1870 // chan3 2-to-1: enabled, 100 msat fee
1872 // chan4 1-to-2: enabled, 100% fee
1873 // chan4 2-to-1: enabled, 0 fee
1875 // chan12 1-to-2: enabled, ignored fee
1876 // chan12 2-to-1: enabled, 0 fee
1878 // chan13 1-to-2: enabled, 200% fee
1879 // chan13 2-to-1: enabled, 0 fee
1882 // -1(5)2- node3 -1(8)2--
1886 // node2--1(6)2- node4 -1(9)2--- node6 (not in global route map)
1888 // -1(7)2- node5 -1(10)2-
1890 // Channels 5, 8, 9 and 10 are private channels.
1892 // chan5 1-to-2: enabled, 100 msat fee
1893 // chan5 2-to-1: enabled, 0 fee
1895 // chan6 1-to-2: enabled, 0 fee
1896 // chan6 2-to-1: enabled, 0 fee
1898 // chan7 1-to-2: enabled, 100% fee
1899 // chan7 2-to-1: enabled, 0 fee
1901 // chan8 1-to-2: enabled, variable fee (0 then 1000 msat)
1902 // chan8 2-to-1: enabled, 0 fee
1904 // chan9 1-to-2: enabled, 1001 msat fee
1905 // chan9 2-to-1: enabled, 0 fee
1907 // chan10 1-to-2: enabled, 0 fee
1908 // chan10 2-to-1: enabled, 0 fee
1910 // chan11 1-to-2: enabled, 0 fee
1911 // chan11 2-to-1: enabled, 0 fee
1913 let (our_privkey, _, privkeys, _) = get_nodes(&secp_ctx);
1915 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[0], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
1916 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1917 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1918 short_channel_id: 1,
1921 cltv_expiry_delta: 0,
1922 htlc_minimum_msat: 0,
1923 htlc_maximum_msat: OptionalField::Absent,
1925 fee_proportional_millionths: 0,
1926 excess_data: Vec::new()
1929 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
1931 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
1932 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1933 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1934 short_channel_id: 2,
1937 cltv_expiry_delta: (5 << 4) | 3,
1938 htlc_minimum_msat: 0,
1939 htlc_maximum_msat: OptionalField::Absent,
1940 fee_base_msat: u32::max_value(),
1941 fee_proportional_millionths: u32::max_value(),
1942 excess_data: Vec::new()
1944 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1945 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1946 short_channel_id: 2,
1949 cltv_expiry_delta: 0,
1950 htlc_minimum_msat: 0,
1951 htlc_maximum_msat: OptionalField::Absent,
1953 fee_proportional_millionths: 0,
1954 excess_data: Vec::new()
1957 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
1959 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[7], ChannelFeatures::from_le_bytes(id_to_feature_flags(12)), 12);
1960 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1961 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1962 short_channel_id: 12,
1965 cltv_expiry_delta: (5 << 4) | 3,
1966 htlc_minimum_msat: 0,
1967 htlc_maximum_msat: OptionalField::Absent,
1968 fee_base_msat: u32::max_value(),
1969 fee_proportional_millionths: u32::max_value(),
1970 excess_data: Vec::new()
1972 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1973 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1974 short_channel_id: 12,
1977 cltv_expiry_delta: 0,
1978 htlc_minimum_msat: 0,
1979 htlc_maximum_msat: OptionalField::Absent,
1981 fee_proportional_millionths: 0,
1982 excess_data: Vec::new()
1985 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], NodeFeatures::from_le_bytes(id_to_feature_flags(8)), 0);
1987 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
1988 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1989 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1990 short_channel_id: 3,
1993 cltv_expiry_delta: (3 << 4) | 1,
1994 htlc_minimum_msat: 0,
1995 htlc_maximum_msat: OptionalField::Absent,
1997 fee_proportional_millionths: 0,
1998 excess_data: Vec::new()
2000 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2001 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2002 short_channel_id: 3,
2005 cltv_expiry_delta: (3 << 4) | 2,
2006 htlc_minimum_msat: 0,
2007 htlc_maximum_msat: OptionalField::Absent,
2009 fee_proportional_millionths: 0,
2010 excess_data: Vec::new()
2013 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
2014 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2015 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2016 short_channel_id: 4,
2019 cltv_expiry_delta: (4 << 4) | 1,
2020 htlc_minimum_msat: 0,
2021 htlc_maximum_msat: OptionalField::Absent,
2023 fee_proportional_millionths: 1000000,
2024 excess_data: Vec::new()
2026 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2027 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2028 short_channel_id: 4,
2031 cltv_expiry_delta: (4 << 4) | 2,
2032 htlc_minimum_msat: 0,
2033 htlc_maximum_msat: OptionalField::Absent,
2035 fee_proportional_millionths: 0,
2036 excess_data: Vec::new()
2039 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(13)), 13);
2040 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2041 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2042 short_channel_id: 13,
2045 cltv_expiry_delta: (13 << 4) | 1,
2046 htlc_minimum_msat: 0,
2047 htlc_maximum_msat: OptionalField::Absent,
2049 fee_proportional_millionths: 2000000,
2050 excess_data: Vec::new()
2052 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2053 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2054 short_channel_id: 13,
2057 cltv_expiry_delta: (13 << 4) | 2,
2058 htlc_minimum_msat: 0,
2059 htlc_maximum_msat: OptionalField::Absent,
2061 fee_proportional_millionths: 0,
2062 excess_data: Vec::new()
2065 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
2067 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
2068 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2069 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2070 short_channel_id: 6,
2073 cltv_expiry_delta: (6 << 4) | 1,
2074 htlc_minimum_msat: 0,
2075 htlc_maximum_msat: OptionalField::Absent,
2077 fee_proportional_millionths: 0,
2078 excess_data: Vec::new()
2080 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
2081 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2082 short_channel_id: 6,
2085 cltv_expiry_delta: (6 << 4) | 2,
2086 htlc_minimum_msat: 0,
2087 htlc_maximum_msat: OptionalField::Absent,
2089 fee_proportional_millionths: 0,
2090 excess_data: Vec::new(),
2093 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(11)), 11);
2094 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
2095 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2096 short_channel_id: 11,
2099 cltv_expiry_delta: (11 << 4) | 1,
2100 htlc_minimum_msat: 0,
2101 htlc_maximum_msat: OptionalField::Absent,
2103 fee_proportional_millionths: 0,
2104 excess_data: Vec::new()
2106 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
2107 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2108 short_channel_id: 11,
2111 cltv_expiry_delta: (11 << 4) | 2,
2112 htlc_minimum_msat: 0,
2113 htlc_maximum_msat: OptionalField::Absent,
2115 fee_proportional_millionths: 0,
2116 excess_data: Vec::new()
2119 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(5)), 0);
2121 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
2123 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[5], ChannelFeatures::from_le_bytes(id_to_feature_flags(7)), 7);
2124 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2125 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2126 short_channel_id: 7,
2129 cltv_expiry_delta: (7 << 4) | 1,
2130 htlc_minimum_msat: 0,
2131 htlc_maximum_msat: OptionalField::Absent,
2133 fee_proportional_millionths: 1000000,
2134 excess_data: Vec::new()
2136 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[5], UnsignedChannelUpdate {
2137 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2138 short_channel_id: 7,
2141 cltv_expiry_delta: (7 << 4) | 2,
2142 htlc_minimum_msat: 0,
2143 htlc_maximum_msat: OptionalField::Absent,
2145 fee_proportional_millionths: 0,
2146 excess_data: Vec::new()
2149 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[5], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
2151 (secp_ctx, network_graph, net_graph_msg_handler, chain_monitor, logger)
2155 fn simple_route_test() {
2156 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2157 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2158 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2159 let scorer = test_utils::TestScorer::with_penalty(0);
2160 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2161 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2163 // Simple route to 2 via 1
2165 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) {
2166 assert_eq!(err, "Cannot send a payment of 0 msat");
2167 } else { panic!(); }
2169 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2170 assert_eq!(route.paths[0].len(), 2);
2172 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2173 assert_eq!(route.paths[0][0].short_channel_id, 2);
2174 assert_eq!(route.paths[0][0].fee_msat, 100);
2175 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2176 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2177 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2179 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2180 assert_eq!(route.paths[0][1].short_channel_id, 4);
2181 assert_eq!(route.paths[0][1].fee_msat, 100);
2182 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2183 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2184 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2188 fn invalid_first_hop_test() {
2189 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2190 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2191 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2192 let scorer = test_utils::TestScorer::with_penalty(0);
2193 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2194 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2196 // Simple route to 2 via 1
2198 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
2200 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) =
2201 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) {
2202 assert_eq!(err, "First hop cannot have our_node_pubkey as a destination.");
2203 } else { panic!(); }
2205 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2206 assert_eq!(route.paths[0].len(), 2);
2210 fn htlc_minimum_test() {
2211 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2212 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2213 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2214 let scorer = test_utils::TestScorer::with_penalty(0);
2215 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2216 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2218 // Simple route to 2 via 1
2220 // Disable other paths
2221 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2222 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2223 short_channel_id: 12,
2225 flags: 2, // to disable
2226 cltv_expiry_delta: 0,
2227 htlc_minimum_msat: 0,
2228 htlc_maximum_msat: OptionalField::Absent,
2230 fee_proportional_millionths: 0,
2231 excess_data: Vec::new()
2233 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2234 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2235 short_channel_id: 3,
2237 flags: 2, // to disable
2238 cltv_expiry_delta: 0,
2239 htlc_minimum_msat: 0,
2240 htlc_maximum_msat: OptionalField::Absent,
2242 fee_proportional_millionths: 0,
2243 excess_data: Vec::new()
2245 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2246 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2247 short_channel_id: 13,
2249 flags: 2, // to disable
2250 cltv_expiry_delta: 0,
2251 htlc_minimum_msat: 0,
2252 htlc_maximum_msat: OptionalField::Absent,
2254 fee_proportional_millionths: 0,
2255 excess_data: Vec::new()
2257 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2258 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2259 short_channel_id: 6,
2261 flags: 2, // to disable
2262 cltv_expiry_delta: 0,
2263 htlc_minimum_msat: 0,
2264 htlc_maximum_msat: OptionalField::Absent,
2266 fee_proportional_millionths: 0,
2267 excess_data: Vec::new()
2269 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2270 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2271 short_channel_id: 7,
2273 flags: 2, // to disable
2274 cltv_expiry_delta: 0,
2275 htlc_minimum_msat: 0,
2276 htlc_maximum_msat: OptionalField::Absent,
2278 fee_proportional_millionths: 0,
2279 excess_data: Vec::new()
2282 // Check against amount_to_transfer_over_msat.
2283 // Set minimal HTLC of 200_000_000 msat.
2284 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2285 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2286 short_channel_id: 2,
2289 cltv_expiry_delta: 0,
2290 htlc_minimum_msat: 200_000_000,
2291 htlc_maximum_msat: OptionalField::Absent,
2293 fee_proportional_millionths: 0,
2294 excess_data: Vec::new()
2297 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
2299 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2300 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2301 short_channel_id: 4,
2304 cltv_expiry_delta: 0,
2305 htlc_minimum_msat: 0,
2306 htlc_maximum_msat: OptionalField::Present(199_999_999),
2308 fee_proportional_millionths: 0,
2309 excess_data: Vec::new()
2312 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
2313 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) {
2314 assert_eq!(err, "Failed to find a path to the given destination");
2315 } else { panic!(); }
2317 // Lift the restriction on the first hop.
2318 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2319 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2320 short_channel_id: 2,
2323 cltv_expiry_delta: 0,
2324 htlc_minimum_msat: 0,
2325 htlc_maximum_msat: OptionalField::Absent,
2327 fee_proportional_millionths: 0,
2328 excess_data: Vec::new()
2331 // A payment above the minimum should pass
2332 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();
2333 assert_eq!(route.paths[0].len(), 2);
2337 fn htlc_minimum_overpay_test() {
2338 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2339 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2340 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
2341 let scorer = test_utils::TestScorer::with_penalty(0);
2342 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2343 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2345 // A route to node#2 via two paths.
2346 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
2347 // Thus, they can't send 60 without overpaying.
2348 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2349 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2350 short_channel_id: 2,
2353 cltv_expiry_delta: 0,
2354 htlc_minimum_msat: 35_000,
2355 htlc_maximum_msat: OptionalField::Present(40_000),
2357 fee_proportional_millionths: 0,
2358 excess_data: Vec::new()
2360 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2361 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2362 short_channel_id: 12,
2365 cltv_expiry_delta: 0,
2366 htlc_minimum_msat: 35_000,
2367 htlc_maximum_msat: OptionalField::Present(40_000),
2369 fee_proportional_millionths: 0,
2370 excess_data: Vec::new()
2374 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2375 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2376 short_channel_id: 13,
2379 cltv_expiry_delta: 0,
2380 htlc_minimum_msat: 0,
2381 htlc_maximum_msat: OptionalField::Absent,
2383 fee_proportional_millionths: 0,
2384 excess_data: Vec::new()
2386 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2387 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2388 short_channel_id: 4,
2391 cltv_expiry_delta: 0,
2392 htlc_minimum_msat: 0,
2393 htlc_maximum_msat: OptionalField::Absent,
2395 fee_proportional_millionths: 0,
2396 excess_data: Vec::new()
2399 // Disable other paths
2400 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2401 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2402 short_channel_id: 1,
2404 flags: 2, // to disable
2405 cltv_expiry_delta: 0,
2406 htlc_minimum_msat: 0,
2407 htlc_maximum_msat: OptionalField::Absent,
2409 fee_proportional_millionths: 0,
2410 excess_data: Vec::new()
2413 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 60_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2414 // Overpay fees to hit htlc_minimum_msat.
2415 let overpaid_fees = route.paths[0][0].fee_msat + route.paths[1][0].fee_msat;
2416 // TODO: this could be better balanced to overpay 10k and not 15k.
2417 assert_eq!(overpaid_fees, 15_000);
2419 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
2420 // while taking even more fee to match htlc_minimum_msat.
2421 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2422 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2423 short_channel_id: 12,
2426 cltv_expiry_delta: 0,
2427 htlc_minimum_msat: 65_000,
2428 htlc_maximum_msat: OptionalField::Present(80_000),
2430 fee_proportional_millionths: 0,
2431 excess_data: Vec::new()
2433 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2434 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2435 short_channel_id: 2,
2438 cltv_expiry_delta: 0,
2439 htlc_minimum_msat: 0,
2440 htlc_maximum_msat: OptionalField::Absent,
2442 fee_proportional_millionths: 0,
2443 excess_data: Vec::new()
2445 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2446 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2447 short_channel_id: 4,
2450 cltv_expiry_delta: 0,
2451 htlc_minimum_msat: 0,
2452 htlc_maximum_msat: OptionalField::Absent,
2454 fee_proportional_millionths: 100_000,
2455 excess_data: Vec::new()
2458 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 60_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2459 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
2460 assert_eq!(route.paths.len(), 1);
2461 assert_eq!(route.paths[0][0].short_channel_id, 12);
2462 let fees = route.paths[0][0].fee_msat;
2463 assert_eq!(fees, 5_000);
2465 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2466 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
2467 // the other channel.
2468 assert_eq!(route.paths.len(), 1);
2469 assert_eq!(route.paths[0][0].short_channel_id, 2);
2470 let fees = route.paths[0][0].fee_msat;
2471 assert_eq!(fees, 5_000);
2475 fn disable_channels_test() {
2476 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2477 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2478 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2479 let scorer = test_utils::TestScorer::with_penalty(0);
2480 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2481 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2483 // // Disable channels 4 and 12 by flags=2
2484 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2485 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2486 short_channel_id: 4,
2488 flags: 2, // to disable
2489 cltv_expiry_delta: 0,
2490 htlc_minimum_msat: 0,
2491 htlc_maximum_msat: OptionalField::Absent,
2493 fee_proportional_millionths: 0,
2494 excess_data: Vec::new()
2496 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2497 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2498 short_channel_id: 12,
2500 flags: 2, // to disable
2501 cltv_expiry_delta: 0,
2502 htlc_minimum_msat: 0,
2503 htlc_maximum_msat: OptionalField::Absent,
2505 fee_proportional_millionths: 0,
2506 excess_data: Vec::new()
2509 // If all the channels require some features we don't understand, route should fail
2510 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) {
2511 assert_eq!(err, "Failed to find a path to the given destination");
2512 } else { panic!(); }
2514 // If we specify a channel to node7, that overrides our local channel view and that gets used
2515 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2516 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();
2517 assert_eq!(route.paths[0].len(), 2);
2519 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2520 assert_eq!(route.paths[0][0].short_channel_id, 42);
2521 assert_eq!(route.paths[0][0].fee_msat, 200);
2522 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2523 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2524 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2526 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2527 assert_eq!(route.paths[0][1].short_channel_id, 13);
2528 assert_eq!(route.paths[0][1].fee_msat, 100);
2529 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2530 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2531 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2535 fn disable_node_test() {
2536 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2537 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2538 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2539 let scorer = test_utils::TestScorer::with_penalty(0);
2540 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2541 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2543 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
2544 let mut unknown_features = NodeFeatures::known();
2545 unknown_features.set_unknown_feature_required();
2546 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
2547 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
2548 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
2550 // If all nodes require some features we don't understand, route should fail
2551 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) {
2552 assert_eq!(err, "Failed to find a path to the given destination");
2553 } else { panic!(); }
2555 // If we specify a channel to node7, that overrides our local channel view and that gets used
2556 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2557 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();
2558 assert_eq!(route.paths[0].len(), 2);
2560 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2561 assert_eq!(route.paths[0][0].short_channel_id, 42);
2562 assert_eq!(route.paths[0][0].fee_msat, 200);
2563 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2564 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2565 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2567 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2568 assert_eq!(route.paths[0][1].short_channel_id, 13);
2569 assert_eq!(route.paths[0][1].fee_msat, 100);
2570 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2571 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2572 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2574 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
2575 // naively) assume that the user checked the feature bits on the invoice, which override
2576 // the node_announcement.
2580 fn our_chans_test() {
2581 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2582 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2583 let scorer = test_utils::TestScorer::with_penalty(0);
2584 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2585 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2587 // Route to 1 via 2 and 3 because our channel to 1 is disabled
2588 let payment_params = PaymentParameters::from_node_id(nodes[0]);
2589 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2590 assert_eq!(route.paths[0].len(), 3);
2592 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2593 assert_eq!(route.paths[0][0].short_channel_id, 2);
2594 assert_eq!(route.paths[0][0].fee_msat, 200);
2595 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2596 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2597 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2599 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2600 assert_eq!(route.paths[0][1].short_channel_id, 4);
2601 assert_eq!(route.paths[0][1].fee_msat, 100);
2602 assert_eq!(route.paths[0][1].cltv_expiry_delta, (3 << 4) | 2);
2603 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2604 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2606 assert_eq!(route.paths[0][2].pubkey, nodes[0]);
2607 assert_eq!(route.paths[0][2].short_channel_id, 3);
2608 assert_eq!(route.paths[0][2].fee_msat, 100);
2609 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
2610 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(1));
2611 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(3));
2613 // If we specify a channel to node7, that overrides our local channel view and that gets used
2614 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2615 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2616 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();
2617 assert_eq!(route.paths[0].len(), 2);
2619 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2620 assert_eq!(route.paths[0][0].short_channel_id, 42);
2621 assert_eq!(route.paths[0][0].fee_msat, 200);
2622 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2623 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2624 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2626 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2627 assert_eq!(route.paths[0][1].short_channel_id, 13);
2628 assert_eq!(route.paths[0][1].fee_msat, 100);
2629 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2630 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2631 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2634 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2635 let zero_fees = RoutingFees {
2637 proportional_millionths: 0,
2639 vec![RouteHint(vec![RouteHintHop {
2640 src_node_id: nodes[3],
2641 short_channel_id: 8,
2643 cltv_expiry_delta: (8 << 4) | 1,
2644 htlc_minimum_msat: None,
2645 htlc_maximum_msat: None,
2647 ]), RouteHint(vec![RouteHintHop {
2648 src_node_id: nodes[4],
2649 short_channel_id: 9,
2652 proportional_millionths: 0,
2654 cltv_expiry_delta: (9 << 4) | 1,
2655 htlc_minimum_msat: None,
2656 htlc_maximum_msat: None,
2657 }]), RouteHint(vec![RouteHintHop {
2658 src_node_id: nodes[5],
2659 short_channel_id: 10,
2661 cltv_expiry_delta: (10 << 4) | 1,
2662 htlc_minimum_msat: None,
2663 htlc_maximum_msat: None,
2667 fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2668 let zero_fees = RoutingFees {
2670 proportional_millionths: 0,
2672 vec![RouteHint(vec![RouteHintHop {
2673 src_node_id: nodes[2],
2674 short_channel_id: 5,
2677 proportional_millionths: 0,
2679 cltv_expiry_delta: (5 << 4) | 1,
2680 htlc_minimum_msat: None,
2681 htlc_maximum_msat: None,
2683 src_node_id: nodes[3],
2684 short_channel_id: 8,
2686 cltv_expiry_delta: (8 << 4) | 1,
2687 htlc_minimum_msat: None,
2688 htlc_maximum_msat: None,
2690 ]), RouteHint(vec![RouteHintHop {
2691 src_node_id: nodes[4],
2692 short_channel_id: 9,
2695 proportional_millionths: 0,
2697 cltv_expiry_delta: (9 << 4) | 1,
2698 htlc_minimum_msat: None,
2699 htlc_maximum_msat: None,
2700 }]), RouteHint(vec![RouteHintHop {
2701 src_node_id: nodes[5],
2702 short_channel_id: 10,
2704 cltv_expiry_delta: (10 << 4) | 1,
2705 htlc_minimum_msat: None,
2706 htlc_maximum_msat: None,
2711 fn partial_route_hint_test() {
2712 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2713 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2714 let scorer = test_utils::TestScorer::with_penalty(0);
2715 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2716 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2718 // Simple test across 2, 3, 5, and 4 via a last_hop channel
2719 // Tests the behaviour when the RouteHint contains a suboptimal hop.
2720 // RouteHint may be partially used by the algo to build the best path.
2722 // First check that last hop can't have its source as the payee.
2723 let invalid_last_hop = RouteHint(vec![RouteHintHop {
2724 src_node_id: nodes[6],
2725 short_channel_id: 8,
2728 proportional_millionths: 0,
2730 cltv_expiry_delta: (8 << 4) | 1,
2731 htlc_minimum_msat: None,
2732 htlc_maximum_msat: None,
2735 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
2736 invalid_last_hops.push(invalid_last_hop);
2738 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(invalid_last_hops);
2739 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) {
2740 assert_eq!(err, "Route hint cannot have the payee as the source.");
2741 } else { panic!(); }
2744 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops_multi_private_channels(&nodes));
2745 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2746 assert_eq!(route.paths[0].len(), 5);
2748 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2749 assert_eq!(route.paths[0][0].short_channel_id, 2);
2750 assert_eq!(route.paths[0][0].fee_msat, 100);
2751 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2752 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2753 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2755 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2756 assert_eq!(route.paths[0][1].short_channel_id, 4);
2757 assert_eq!(route.paths[0][1].fee_msat, 0);
2758 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
2759 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2760 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2762 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2763 assert_eq!(route.paths[0][2].short_channel_id, 6);
2764 assert_eq!(route.paths[0][2].fee_msat, 0);
2765 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
2766 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2767 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2769 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2770 assert_eq!(route.paths[0][3].short_channel_id, 11);
2771 assert_eq!(route.paths[0][3].fee_msat, 0);
2772 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
2773 // If we have a peer in the node map, we'll use their features here since we don't have
2774 // a way of figuring out their features from the invoice:
2775 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2776 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2778 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2779 assert_eq!(route.paths[0][4].short_channel_id, 8);
2780 assert_eq!(route.paths[0][4].fee_msat, 100);
2781 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2782 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2783 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2786 fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2787 let zero_fees = RoutingFees {
2789 proportional_millionths: 0,
2791 vec![RouteHint(vec![RouteHintHop {
2792 src_node_id: nodes[3],
2793 short_channel_id: 8,
2795 cltv_expiry_delta: (8 << 4) | 1,
2796 htlc_minimum_msat: None,
2797 htlc_maximum_msat: None,
2798 }]), RouteHint(vec![
2800 ]), RouteHint(vec![RouteHintHop {
2801 src_node_id: nodes[5],
2802 short_channel_id: 10,
2804 cltv_expiry_delta: (10 << 4) | 1,
2805 htlc_minimum_msat: None,
2806 htlc_maximum_msat: None,
2811 fn ignores_empty_last_hops_test() {
2812 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2813 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2814 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(empty_last_hop(&nodes));
2815 let scorer = test_utils::TestScorer::with_penalty(0);
2816 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2817 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2819 // Test handling of an empty RouteHint passed in Invoice.
2821 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2822 assert_eq!(route.paths[0].len(), 5);
2824 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2825 assert_eq!(route.paths[0][0].short_channel_id, 2);
2826 assert_eq!(route.paths[0][0].fee_msat, 100);
2827 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2828 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2829 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2831 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2832 assert_eq!(route.paths[0][1].short_channel_id, 4);
2833 assert_eq!(route.paths[0][1].fee_msat, 0);
2834 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
2835 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2836 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2838 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2839 assert_eq!(route.paths[0][2].short_channel_id, 6);
2840 assert_eq!(route.paths[0][2].fee_msat, 0);
2841 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
2842 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2843 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2845 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2846 assert_eq!(route.paths[0][3].short_channel_id, 11);
2847 assert_eq!(route.paths[0][3].fee_msat, 0);
2848 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
2849 // If we have a peer in the node map, we'll use their features here since we don't have
2850 // a way of figuring out their features from the invoice:
2851 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2852 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2854 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2855 assert_eq!(route.paths[0][4].short_channel_id, 8);
2856 assert_eq!(route.paths[0][4].fee_msat, 100);
2857 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2858 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2859 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2862 /// Builds a trivial last-hop hint that passes through the two nodes given, with channel 0xff00
2864 fn multi_hop_last_hops_hint(hint_hops: [PublicKey; 2]) -> Vec<RouteHint> {
2865 let zero_fees = RoutingFees {
2867 proportional_millionths: 0,
2869 vec![RouteHint(vec![RouteHintHop {
2870 src_node_id: hint_hops[0],
2871 short_channel_id: 0xff00,
2874 proportional_millionths: 0,
2876 cltv_expiry_delta: (5 << 4) | 1,
2877 htlc_minimum_msat: None,
2878 htlc_maximum_msat: None,
2880 src_node_id: hint_hops[1],
2881 short_channel_id: 0xff01,
2883 cltv_expiry_delta: (8 << 4) | 1,
2884 htlc_minimum_msat: None,
2885 htlc_maximum_msat: None,
2890 fn multi_hint_last_hops_test() {
2891 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2892 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2893 let last_hops = multi_hop_last_hops_hint([nodes[2], nodes[3]]);
2894 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops.clone());
2895 let scorer = test_utils::TestScorer::with_penalty(0);
2896 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2897 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2898 // Test through channels 2, 3, 0xff00, 0xff01.
2899 // Test shows that multiple hop hints are considered.
2901 // Disabling channels 6 & 7 by flags=2
2902 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2903 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2904 short_channel_id: 6,
2906 flags: 2, // to disable
2907 cltv_expiry_delta: 0,
2908 htlc_minimum_msat: 0,
2909 htlc_maximum_msat: OptionalField::Absent,
2911 fee_proportional_millionths: 0,
2912 excess_data: Vec::new()
2914 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2915 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2916 short_channel_id: 7,
2918 flags: 2, // to disable
2919 cltv_expiry_delta: 0,
2920 htlc_minimum_msat: 0,
2921 htlc_maximum_msat: OptionalField::Absent,
2923 fee_proportional_millionths: 0,
2924 excess_data: Vec::new()
2927 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2928 assert_eq!(route.paths[0].len(), 4);
2930 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2931 assert_eq!(route.paths[0][0].short_channel_id, 2);
2932 assert_eq!(route.paths[0][0].fee_msat, 200);
2933 assert_eq!(route.paths[0][0].cltv_expiry_delta, 65);
2934 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2935 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2937 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2938 assert_eq!(route.paths[0][1].short_channel_id, 4);
2939 assert_eq!(route.paths[0][1].fee_msat, 100);
2940 assert_eq!(route.paths[0][1].cltv_expiry_delta, 81);
2941 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2942 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2944 assert_eq!(route.paths[0][2].pubkey, nodes[3]);
2945 assert_eq!(route.paths[0][2].short_channel_id, last_hops[0].0[0].short_channel_id);
2946 assert_eq!(route.paths[0][2].fee_msat, 0);
2947 assert_eq!(route.paths[0][2].cltv_expiry_delta, 129);
2948 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(4));
2949 assert_eq!(route.paths[0][2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2951 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2952 assert_eq!(route.paths[0][3].short_channel_id, last_hops[0].0[1].short_channel_id);
2953 assert_eq!(route.paths[0][3].fee_msat, 100);
2954 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2955 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2956 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2960 fn private_multi_hint_last_hops_test() {
2961 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2962 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2964 let non_announced_privkey = SecretKey::from_slice(&hex::decode(format!("{:02x}", 0xf0).repeat(32)).unwrap()[..]).unwrap();
2965 let non_announced_pubkey = PublicKey::from_secret_key(&secp_ctx, &non_announced_privkey);
2967 let last_hops = multi_hop_last_hops_hint([nodes[2], non_announced_pubkey]);
2968 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops.clone());
2969 let scorer = test_utils::TestScorer::with_penalty(0);
2970 // Test through channels 2, 3, 0xff00, 0xff01.
2971 // Test shows that multiple hop hints are considered.
2973 // Disabling channels 6 & 7 by flags=2
2974 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2975 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2976 short_channel_id: 6,
2978 flags: 2, // to disable
2979 cltv_expiry_delta: 0,
2980 htlc_minimum_msat: 0,
2981 htlc_maximum_msat: OptionalField::Absent,
2983 fee_proportional_millionths: 0,
2984 excess_data: Vec::new()
2986 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2987 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2988 short_channel_id: 7,
2990 flags: 2, // to disable
2991 cltv_expiry_delta: 0,
2992 htlc_minimum_msat: 0,
2993 htlc_maximum_msat: OptionalField::Absent,
2995 fee_proportional_millionths: 0,
2996 excess_data: Vec::new()
2999 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &[42u8; 32]).unwrap();
3000 assert_eq!(route.paths[0].len(), 4);
3002 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3003 assert_eq!(route.paths[0][0].short_channel_id, 2);
3004 assert_eq!(route.paths[0][0].fee_msat, 200);
3005 assert_eq!(route.paths[0][0].cltv_expiry_delta, 65);
3006 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3007 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3009 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3010 assert_eq!(route.paths[0][1].short_channel_id, 4);
3011 assert_eq!(route.paths[0][1].fee_msat, 100);
3012 assert_eq!(route.paths[0][1].cltv_expiry_delta, 81);
3013 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3014 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3016 assert_eq!(route.paths[0][2].pubkey, non_announced_pubkey);
3017 assert_eq!(route.paths[0][2].short_channel_id, last_hops[0].0[0].short_channel_id);
3018 assert_eq!(route.paths[0][2].fee_msat, 0);
3019 assert_eq!(route.paths[0][2].cltv_expiry_delta, 129);
3020 assert_eq!(route.paths[0][2].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
3021 assert_eq!(route.paths[0][2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3023 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
3024 assert_eq!(route.paths[0][3].short_channel_id, last_hops[0].0[1].short_channel_id);
3025 assert_eq!(route.paths[0][3].fee_msat, 100);
3026 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
3027 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
3028 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3031 fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3032 let zero_fees = RoutingFees {
3034 proportional_millionths: 0,
3036 vec![RouteHint(vec![RouteHintHop {
3037 src_node_id: nodes[4],
3038 short_channel_id: 11,
3040 cltv_expiry_delta: (11 << 4) | 1,
3041 htlc_minimum_msat: None,
3042 htlc_maximum_msat: None,
3044 src_node_id: nodes[3],
3045 short_channel_id: 8,
3047 cltv_expiry_delta: (8 << 4) | 1,
3048 htlc_minimum_msat: None,
3049 htlc_maximum_msat: None,
3050 }]), RouteHint(vec![RouteHintHop {
3051 src_node_id: nodes[4],
3052 short_channel_id: 9,
3055 proportional_millionths: 0,
3057 cltv_expiry_delta: (9 << 4) | 1,
3058 htlc_minimum_msat: None,
3059 htlc_maximum_msat: None,
3060 }]), RouteHint(vec![RouteHintHop {
3061 src_node_id: nodes[5],
3062 short_channel_id: 10,
3064 cltv_expiry_delta: (10 << 4) | 1,
3065 htlc_minimum_msat: None,
3066 htlc_maximum_msat: None,
3071 fn last_hops_with_public_channel_test() {
3072 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3073 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3074 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops_with_public_channel(&nodes));
3075 let scorer = test_utils::TestScorer::with_penalty(0);
3076 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3077 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3078 // This test shows that public routes can be present in the invoice
3079 // which would be handled in the same manner.
3081 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3082 assert_eq!(route.paths[0].len(), 5);
3084 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3085 assert_eq!(route.paths[0][0].short_channel_id, 2);
3086 assert_eq!(route.paths[0][0].fee_msat, 100);
3087 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
3088 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3089 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3091 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3092 assert_eq!(route.paths[0][1].short_channel_id, 4);
3093 assert_eq!(route.paths[0][1].fee_msat, 0);
3094 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
3095 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3096 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3098 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
3099 assert_eq!(route.paths[0][2].short_channel_id, 6);
3100 assert_eq!(route.paths[0][2].fee_msat, 0);
3101 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
3102 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
3103 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
3105 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
3106 assert_eq!(route.paths[0][3].short_channel_id, 11);
3107 assert_eq!(route.paths[0][3].fee_msat, 0);
3108 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
3109 // If we have a peer in the node map, we'll use their features here since we don't have
3110 // a way of figuring out their features from the invoice:
3111 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
3112 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
3114 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
3115 assert_eq!(route.paths[0][4].short_channel_id, 8);
3116 assert_eq!(route.paths[0][4].fee_msat, 100);
3117 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
3118 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
3119 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3123 fn our_chans_last_hop_connect_test() {
3124 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3125 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3126 let scorer = test_utils::TestScorer::with_penalty(0);
3127 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3128 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3130 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
3131 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3132 let mut last_hops = last_hops(&nodes);
3133 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops.clone());
3134 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();
3135 assert_eq!(route.paths[0].len(), 2);
3137 assert_eq!(route.paths[0][0].pubkey, nodes[3]);
3138 assert_eq!(route.paths[0][0].short_channel_id, 42);
3139 assert_eq!(route.paths[0][0].fee_msat, 0);
3140 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 4) | 1);
3141 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
3142 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3144 assert_eq!(route.paths[0][1].pubkey, nodes[6]);
3145 assert_eq!(route.paths[0][1].short_channel_id, 8);
3146 assert_eq!(route.paths[0][1].fee_msat, 100);
3147 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
3148 assert_eq!(route.paths[0][1].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
3149 assert_eq!(route.paths[0][1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3151 last_hops[0].0[0].fees.base_msat = 1000;
3153 // Revert to via 6 as the fee on 8 goes up
3154 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops);
3155 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3156 assert_eq!(route.paths[0].len(), 4);
3158 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3159 assert_eq!(route.paths[0][0].short_channel_id, 2);
3160 assert_eq!(route.paths[0][0].fee_msat, 200); // fee increased as its % of value transferred across node
3161 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
3162 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3163 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3165 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3166 assert_eq!(route.paths[0][1].short_channel_id, 4);
3167 assert_eq!(route.paths[0][1].fee_msat, 100);
3168 assert_eq!(route.paths[0][1].cltv_expiry_delta, (7 << 4) | 1);
3169 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3170 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3172 assert_eq!(route.paths[0][2].pubkey, nodes[5]);
3173 assert_eq!(route.paths[0][2].short_channel_id, 7);
3174 assert_eq!(route.paths[0][2].fee_msat, 0);
3175 assert_eq!(route.paths[0][2].cltv_expiry_delta, (10 << 4) | 1);
3176 // If we have a peer in the node map, we'll use their features here since we don't have
3177 // a way of figuring out their features from the invoice:
3178 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
3179 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(7));
3181 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
3182 assert_eq!(route.paths[0][3].short_channel_id, 10);
3183 assert_eq!(route.paths[0][3].fee_msat, 100);
3184 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
3185 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
3186 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3188 // ...but still use 8 for larger payments as 6 has a variable feerate
3189 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 2000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3190 assert_eq!(route.paths[0].len(), 5);
3192 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3193 assert_eq!(route.paths[0][0].short_channel_id, 2);
3194 assert_eq!(route.paths[0][0].fee_msat, 3000);
3195 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
3196 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3197 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3199 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3200 assert_eq!(route.paths[0][1].short_channel_id, 4);
3201 assert_eq!(route.paths[0][1].fee_msat, 0);
3202 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
3203 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3204 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3206 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
3207 assert_eq!(route.paths[0][2].short_channel_id, 6);
3208 assert_eq!(route.paths[0][2].fee_msat, 0);
3209 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
3210 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
3211 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
3213 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
3214 assert_eq!(route.paths[0][3].short_channel_id, 11);
3215 assert_eq!(route.paths[0][3].fee_msat, 1000);
3216 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
3217 // If we have a peer in the node map, we'll use their features here since we don't have
3218 // a way of figuring out their features from the invoice:
3219 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
3220 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
3222 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
3223 assert_eq!(route.paths[0][4].short_channel_id, 8);
3224 assert_eq!(route.paths[0][4].fee_msat, 2000);
3225 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
3226 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
3227 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3230 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> {
3231 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
3232 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3233 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3235 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
3236 let last_hops = RouteHint(vec![RouteHintHop {
3237 src_node_id: middle_node_id,
3238 short_channel_id: 8,
3241 proportional_millionths: last_hop_fee_prop,
3243 cltv_expiry_delta: (8 << 4) | 1,
3244 htlc_minimum_msat: None,
3245 htlc_maximum_msat: last_hop_htlc_max,
3247 let payment_params = PaymentParameters::from_node_id(target_node_id).with_route_hints(vec![last_hops]);
3248 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
3249 let scorer = test_utils::TestScorer::with_penalty(0);
3250 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3251 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3252 get_route(&source_node_id, &payment_params, &NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash()).read_only(),
3253 Some(&our_chans.iter().collect::<Vec<_>>()), route_val, 42, &test_utils::TestLogger::new(), &scorer, &random_seed_bytes)
3257 fn unannounced_path_test() {
3258 // We should be able to send a payment to a destination without any help of a routing graph
3259 // if we have a channel with a common counterparty that appears in the first and last hop
3261 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
3263 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3264 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3265 assert_eq!(route.paths[0].len(), 2);
3267 assert_eq!(route.paths[0][0].pubkey, middle_node_id);
3268 assert_eq!(route.paths[0][0].short_channel_id, 42);
3269 assert_eq!(route.paths[0][0].fee_msat, 1001);
3270 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 4) | 1);
3271 assert_eq!(route.paths[0][0].node_features.le_flags(), &[0b11]);
3272 assert_eq!(route.paths[0][0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3274 assert_eq!(route.paths[0][1].pubkey, target_node_id);
3275 assert_eq!(route.paths[0][1].short_channel_id, 8);
3276 assert_eq!(route.paths[0][1].fee_msat, 1000000);
3277 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
3278 assert_eq!(route.paths[0][1].node_features.le_flags(), &[0; 0]); // We dont pass flags in from invoices yet
3279 assert_eq!(route.paths[0][1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3283 fn overflow_unannounced_path_test_liquidity_underflow() {
3284 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
3285 // the last-hop had a fee which overflowed a u64, we'd panic.
3286 // This was due to us adding the first-hop from us unconditionally, causing us to think
3287 // we'd built a path (as our node is in the "best candidate" set), when we had not.
3288 // In this test, we previously hit a subtraction underflow due to having less available
3289 // liquidity at the last hop than 0.
3290 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());
3294 fn overflow_unannounced_path_test_feerate_overflow() {
3295 // This tests for the same case as above, except instead of hitting a subtraction
3296 // underflow, we hit a case where the fee charged at a hop overflowed.
3297 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());
3301 fn available_amount_while_routing_test() {
3302 // Tests whether we choose the correct available channel amount while routing.
3304 let (secp_ctx, network_graph, mut net_graph_msg_handler, chain_monitor, logger) = build_graph();
3305 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3306 let scorer = test_utils::TestScorer::with_penalty(0);
3307 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3308 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3309 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
3311 // We will use a simple single-path route from
3312 // our node to node2 via node0: channels {1, 3}.
3314 // First disable all other paths.
3315 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3316 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3317 short_channel_id: 2,
3320 cltv_expiry_delta: 0,
3321 htlc_minimum_msat: 0,
3322 htlc_maximum_msat: OptionalField::Present(100_000),
3324 fee_proportional_millionths: 0,
3325 excess_data: Vec::new()
3327 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3328 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3329 short_channel_id: 12,
3332 cltv_expiry_delta: 0,
3333 htlc_minimum_msat: 0,
3334 htlc_maximum_msat: OptionalField::Present(100_000),
3336 fee_proportional_millionths: 0,
3337 excess_data: Vec::new()
3340 // Make the first channel (#1) very permissive,
3341 // and we will be testing all limits on the second channel.
3342 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3343 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3344 short_channel_id: 1,
3347 cltv_expiry_delta: 0,
3348 htlc_minimum_msat: 0,
3349 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3351 fee_proportional_millionths: 0,
3352 excess_data: Vec::new()
3355 // First, let's see if routing works if we have absolutely no idea about the available amount.
3356 // In this case, it should be set to 250_000 sats.
3357 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3358 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3359 short_channel_id: 3,
3362 cltv_expiry_delta: 0,
3363 htlc_minimum_msat: 0,
3364 htlc_maximum_msat: OptionalField::Absent,
3366 fee_proportional_millionths: 0,
3367 excess_data: Vec::new()
3371 // Attempt to route more than available results in a failure.
3372 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3373 &our_id, &payment_params, &network_graph.read_only(), None, 250_000_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3374 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3375 } else { panic!(); }
3379 // Now, attempt to route an exact amount we have should be fine.
3380 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();
3381 assert_eq!(route.paths.len(), 1);
3382 let path = route.paths.last().unwrap();
3383 assert_eq!(path.len(), 2);
3384 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3385 assert_eq!(path.last().unwrap().fee_msat, 250_000_000);
3388 // Check that setting outbound_capacity_msat in first_hops limits the channels.
3389 // Disable channel #1 and use another first hop.
3390 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3391 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3392 short_channel_id: 1,
3395 cltv_expiry_delta: 0,
3396 htlc_minimum_msat: 0,
3397 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3399 fee_proportional_millionths: 0,
3400 excess_data: Vec::new()
3403 // Now, limit the first_hop by the outbound_capacity_msat of 200_000 sats.
3404 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
3407 // Attempt to route more than available results in a failure.
3408 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3409 &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) {
3410 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3411 } else { panic!(); }
3415 // Now, attempt to route an exact amount we have should be fine.
3416 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();
3417 assert_eq!(route.paths.len(), 1);
3418 let path = route.paths.last().unwrap();
3419 assert_eq!(path.len(), 2);
3420 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3421 assert_eq!(path.last().unwrap().fee_msat, 200_000_000);
3424 // Enable channel #1 back.
3425 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3426 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3427 short_channel_id: 1,
3430 cltv_expiry_delta: 0,
3431 htlc_minimum_msat: 0,
3432 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3434 fee_proportional_millionths: 0,
3435 excess_data: Vec::new()
3439 // Now let's see if routing works if we know only htlc_maximum_msat.
3440 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3441 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3442 short_channel_id: 3,
3445 cltv_expiry_delta: 0,
3446 htlc_minimum_msat: 0,
3447 htlc_maximum_msat: OptionalField::Present(15_000),
3449 fee_proportional_millionths: 0,
3450 excess_data: Vec::new()
3454 // Attempt to route more than available results in a failure.
3455 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3456 &our_id, &payment_params, &network_graph.read_only(), None, 15_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3457 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3458 } else { panic!(); }
3462 // Now, attempt to route an exact amount we have should be fine.
3463 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 15_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3464 assert_eq!(route.paths.len(), 1);
3465 let path = route.paths.last().unwrap();
3466 assert_eq!(path.len(), 2);
3467 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3468 assert_eq!(path.last().unwrap().fee_msat, 15_000);
3471 // Now let's see if routing works if we know only capacity from the UTXO.
3473 // We can't change UTXO capacity on the fly, so we'll disable
3474 // the existing channel and add another one with the capacity we need.
3475 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3476 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3477 short_channel_id: 3,
3480 cltv_expiry_delta: 0,
3481 htlc_minimum_msat: 0,
3482 htlc_maximum_msat: OptionalField::Absent,
3484 fee_proportional_millionths: 0,
3485 excess_data: Vec::new()
3488 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
3489 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
3490 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
3491 .push_opcode(opcodes::all::OP_PUSHNUM_2)
3492 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
3494 *chain_monitor.utxo_ret.lock().unwrap() = Ok(TxOut { value: 15, script_pubkey: good_script.clone() });
3495 net_graph_msg_handler.add_chain_access(Some(chain_monitor));
3497 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
3498 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3499 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3500 short_channel_id: 333,
3503 cltv_expiry_delta: (3 << 4) | 1,
3504 htlc_minimum_msat: 0,
3505 htlc_maximum_msat: OptionalField::Absent,
3507 fee_proportional_millionths: 0,
3508 excess_data: Vec::new()
3510 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3511 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3512 short_channel_id: 333,
3515 cltv_expiry_delta: (3 << 4) | 2,
3516 htlc_minimum_msat: 0,
3517 htlc_maximum_msat: OptionalField::Absent,
3519 fee_proportional_millionths: 0,
3520 excess_data: Vec::new()
3524 // Attempt to route more than available results in a failure.
3525 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3526 &our_id, &payment_params, &network_graph.read_only(), None, 15_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3527 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3528 } else { panic!(); }
3532 // Now, attempt to route an exact amount we have should be fine.
3533 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 15_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3534 assert_eq!(route.paths.len(), 1);
3535 let path = route.paths.last().unwrap();
3536 assert_eq!(path.len(), 2);
3537 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3538 assert_eq!(path.last().unwrap().fee_msat, 15_000);
3541 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
3542 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3543 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3544 short_channel_id: 333,
3547 cltv_expiry_delta: 0,
3548 htlc_minimum_msat: 0,
3549 htlc_maximum_msat: OptionalField::Present(10_000),
3551 fee_proportional_millionths: 0,
3552 excess_data: Vec::new()
3556 // Attempt to route more than available results in a failure.
3557 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3558 &our_id, &payment_params, &network_graph.read_only(), None, 10_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3559 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3560 } else { panic!(); }
3564 // Now, attempt to route an exact amount we have should be fine.
3565 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 10_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3566 assert_eq!(route.paths.len(), 1);
3567 let path = route.paths.last().unwrap();
3568 assert_eq!(path.len(), 2);
3569 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3570 assert_eq!(path.last().unwrap().fee_msat, 10_000);
3575 fn available_liquidity_last_hop_test() {
3576 // Check that available liquidity properly limits the path even when only
3577 // one of the latter hops is limited.
3578 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3579 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3580 let scorer = test_utils::TestScorer::with_penalty(0);
3581 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3582 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3583 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
3585 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3586 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
3587 // Total capacity: 50 sats.
3589 // Disable other potential paths.
3590 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3591 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3592 short_channel_id: 2,
3595 cltv_expiry_delta: 0,
3596 htlc_minimum_msat: 0,
3597 htlc_maximum_msat: OptionalField::Present(100_000),
3599 fee_proportional_millionths: 0,
3600 excess_data: Vec::new()
3602 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3603 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3604 short_channel_id: 7,
3607 cltv_expiry_delta: 0,
3608 htlc_minimum_msat: 0,
3609 htlc_maximum_msat: OptionalField::Present(100_000),
3611 fee_proportional_millionths: 0,
3612 excess_data: Vec::new()
3617 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3618 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3619 short_channel_id: 12,
3622 cltv_expiry_delta: 0,
3623 htlc_minimum_msat: 0,
3624 htlc_maximum_msat: OptionalField::Present(100_000),
3626 fee_proportional_millionths: 0,
3627 excess_data: Vec::new()
3629 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3630 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3631 short_channel_id: 13,
3634 cltv_expiry_delta: 0,
3635 htlc_minimum_msat: 0,
3636 htlc_maximum_msat: OptionalField::Present(100_000),
3638 fee_proportional_millionths: 0,
3639 excess_data: Vec::new()
3642 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3643 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3644 short_channel_id: 6,
3647 cltv_expiry_delta: 0,
3648 htlc_minimum_msat: 0,
3649 htlc_maximum_msat: OptionalField::Present(50_000),
3651 fee_proportional_millionths: 0,
3652 excess_data: Vec::new()
3654 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3655 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3656 short_channel_id: 11,
3659 cltv_expiry_delta: 0,
3660 htlc_minimum_msat: 0,
3661 htlc_maximum_msat: OptionalField::Present(100_000),
3663 fee_proportional_millionths: 0,
3664 excess_data: Vec::new()
3667 // Attempt to route more than available results in a failure.
3668 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3669 &our_id, &payment_params, &network_graph.read_only(), None, 60_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3670 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3671 } else { panic!(); }
3675 // Now, attempt to route 49 sats (just a bit below the capacity).
3676 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 49_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3677 assert_eq!(route.paths.len(), 1);
3678 let mut total_amount_paid_msat = 0;
3679 for path in &route.paths {
3680 assert_eq!(path.len(), 4);
3681 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3682 total_amount_paid_msat += path.last().unwrap().fee_msat;
3684 assert_eq!(total_amount_paid_msat, 49_000);
3688 // Attempt to route an exact amount is also fine
3689 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3690 assert_eq!(route.paths.len(), 1);
3691 let mut total_amount_paid_msat = 0;
3692 for path in &route.paths {
3693 assert_eq!(path.len(), 4);
3694 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3695 total_amount_paid_msat += path.last().unwrap().fee_msat;
3697 assert_eq!(total_amount_paid_msat, 50_000);
3702 fn ignore_fee_first_hop_test() {
3703 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3704 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3705 let scorer = test_utils::TestScorer::with_penalty(0);
3706 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3707 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3708 let payment_params = PaymentParameters::from_node_id(nodes[2]);
3710 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3711 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3712 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3713 short_channel_id: 1,
3716 cltv_expiry_delta: 0,
3717 htlc_minimum_msat: 0,
3718 htlc_maximum_msat: OptionalField::Present(100_000),
3719 fee_base_msat: 1_000_000,
3720 fee_proportional_millionths: 0,
3721 excess_data: Vec::new()
3723 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3724 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3725 short_channel_id: 3,
3728 cltv_expiry_delta: 0,
3729 htlc_minimum_msat: 0,
3730 htlc_maximum_msat: OptionalField::Present(50_000),
3732 fee_proportional_millionths: 0,
3733 excess_data: Vec::new()
3737 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3738 assert_eq!(route.paths.len(), 1);
3739 let mut total_amount_paid_msat = 0;
3740 for path in &route.paths {
3741 assert_eq!(path.len(), 2);
3742 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3743 total_amount_paid_msat += path.last().unwrap().fee_msat;
3745 assert_eq!(total_amount_paid_msat, 50_000);
3750 fn simple_mpp_route_test() {
3751 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3752 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3753 let scorer = test_utils::TestScorer::with_penalty(0);
3754 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3755 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3756 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
3758 // We need a route consisting of 3 paths:
3759 // From our node to node2 via node0, node7, node1 (three paths one hop each).
3760 // To achieve this, the amount being transferred should be around
3761 // the total capacity of these 3 paths.
3763 // First, we set limits on these (previously unlimited) channels.
3764 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
3766 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3767 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3768 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3769 short_channel_id: 1,
3772 cltv_expiry_delta: 0,
3773 htlc_minimum_msat: 0,
3774 htlc_maximum_msat: OptionalField::Present(100_000),
3776 fee_proportional_millionths: 0,
3777 excess_data: Vec::new()
3779 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3780 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3781 short_channel_id: 3,
3784 cltv_expiry_delta: 0,
3785 htlc_minimum_msat: 0,
3786 htlc_maximum_msat: OptionalField::Present(50_000),
3788 fee_proportional_millionths: 0,
3789 excess_data: Vec::new()
3792 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
3793 // (total limit 60).
3794 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3795 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3796 short_channel_id: 12,
3799 cltv_expiry_delta: 0,
3800 htlc_minimum_msat: 0,
3801 htlc_maximum_msat: OptionalField::Present(60_000),
3803 fee_proportional_millionths: 0,
3804 excess_data: Vec::new()
3806 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3807 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3808 short_channel_id: 13,
3811 cltv_expiry_delta: 0,
3812 htlc_minimum_msat: 0,
3813 htlc_maximum_msat: OptionalField::Present(60_000),
3815 fee_proportional_millionths: 0,
3816 excess_data: Vec::new()
3819 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
3820 // (total capacity 180 sats).
3821 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3822 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3823 short_channel_id: 2,
3826 cltv_expiry_delta: 0,
3827 htlc_minimum_msat: 0,
3828 htlc_maximum_msat: OptionalField::Present(200_000),
3830 fee_proportional_millionths: 0,
3831 excess_data: Vec::new()
3833 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3834 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3835 short_channel_id: 4,
3838 cltv_expiry_delta: 0,
3839 htlc_minimum_msat: 0,
3840 htlc_maximum_msat: OptionalField::Present(180_000),
3842 fee_proportional_millionths: 0,
3843 excess_data: Vec::new()
3847 // Attempt to route more than available results in a failure.
3848 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3849 &our_id, &payment_params, &network_graph.read_only(), None, 300_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3850 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3851 } else { panic!(); }
3855 // Now, attempt to route 250 sats (just a bit below the capacity).
3856 // Our algorithm should provide us with these 3 paths.
3857 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 250_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3858 assert_eq!(route.paths.len(), 3);
3859 let mut total_amount_paid_msat = 0;
3860 for path in &route.paths {
3861 assert_eq!(path.len(), 2);
3862 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3863 total_amount_paid_msat += path.last().unwrap().fee_msat;
3865 assert_eq!(total_amount_paid_msat, 250_000);
3869 // Attempt to route an exact amount is also fine
3870 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 290_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3871 assert_eq!(route.paths.len(), 3);
3872 let mut total_amount_paid_msat = 0;
3873 for path in &route.paths {
3874 assert_eq!(path.len(), 2);
3875 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3876 total_amount_paid_msat += path.last().unwrap().fee_msat;
3878 assert_eq!(total_amount_paid_msat, 290_000);
3883 fn long_mpp_route_test() {
3884 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3885 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3886 let scorer = test_utils::TestScorer::with_penalty(0);
3887 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3888 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3889 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
3891 // We need a route consisting of 3 paths:
3892 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3893 // Note that these paths overlap (channels 5, 12, 13).
3894 // We will route 300 sats.
3895 // Each path will have 100 sats capacity, those channels which
3896 // are used twice will have 200 sats capacity.
3898 // Disable other potential paths.
3899 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3900 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3901 short_channel_id: 2,
3904 cltv_expiry_delta: 0,
3905 htlc_minimum_msat: 0,
3906 htlc_maximum_msat: OptionalField::Present(100_000),
3908 fee_proportional_millionths: 0,
3909 excess_data: Vec::new()
3911 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3912 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3913 short_channel_id: 7,
3916 cltv_expiry_delta: 0,
3917 htlc_minimum_msat: 0,
3918 htlc_maximum_msat: OptionalField::Present(100_000),
3920 fee_proportional_millionths: 0,
3921 excess_data: Vec::new()
3924 // Path via {node0, node2} is channels {1, 3, 5}.
3925 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3926 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3927 short_channel_id: 1,
3930 cltv_expiry_delta: 0,
3931 htlc_minimum_msat: 0,
3932 htlc_maximum_msat: OptionalField::Present(100_000),
3934 fee_proportional_millionths: 0,
3935 excess_data: Vec::new()
3937 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3938 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3939 short_channel_id: 3,
3942 cltv_expiry_delta: 0,
3943 htlc_minimum_msat: 0,
3944 htlc_maximum_msat: OptionalField::Present(100_000),
3946 fee_proportional_millionths: 0,
3947 excess_data: Vec::new()
3950 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3951 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3952 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3953 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3954 short_channel_id: 5,
3957 cltv_expiry_delta: 0,
3958 htlc_minimum_msat: 0,
3959 htlc_maximum_msat: OptionalField::Present(200_000),
3961 fee_proportional_millionths: 0,
3962 excess_data: Vec::new()
3965 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3966 // Add 100 sats to the capacities of {12, 13}, because these channels
3967 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3968 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3969 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3970 short_channel_id: 12,
3973 cltv_expiry_delta: 0,
3974 htlc_minimum_msat: 0,
3975 htlc_maximum_msat: OptionalField::Present(200_000),
3977 fee_proportional_millionths: 0,
3978 excess_data: Vec::new()
3980 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3981 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3982 short_channel_id: 13,
3985 cltv_expiry_delta: 0,
3986 htlc_minimum_msat: 0,
3987 htlc_maximum_msat: OptionalField::Present(200_000),
3989 fee_proportional_millionths: 0,
3990 excess_data: Vec::new()
3993 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3994 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3995 short_channel_id: 6,
3998 cltv_expiry_delta: 0,
3999 htlc_minimum_msat: 0,
4000 htlc_maximum_msat: OptionalField::Present(100_000),
4002 fee_proportional_millionths: 0,
4003 excess_data: Vec::new()
4005 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4006 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4007 short_channel_id: 11,
4010 cltv_expiry_delta: 0,
4011 htlc_minimum_msat: 0,
4012 htlc_maximum_msat: OptionalField::Present(100_000),
4014 fee_proportional_millionths: 0,
4015 excess_data: Vec::new()
4018 // Path via {node7, node2} is channels {12, 13, 5}.
4019 // We already limited them to 200 sats (they are used twice for 100 sats).
4020 // Nothing to do here.
4023 // Attempt to route more than available results in a failure.
4024 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4025 &our_id, &payment_params, &network_graph.read_only(), None, 350_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
4026 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4027 } else { panic!(); }
4031 // Now, attempt to route 300 sats (exact amount we can route).
4032 // Our algorithm should provide us with these 3 paths, 100 sats each.
4033 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 300_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4034 assert_eq!(route.paths.len(), 3);
4036 let mut total_amount_paid_msat = 0;
4037 for path in &route.paths {
4038 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
4039 total_amount_paid_msat += path.last().unwrap().fee_msat;
4041 assert_eq!(total_amount_paid_msat, 300_000);
4047 fn mpp_cheaper_route_test() {
4048 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4049 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4050 let scorer = test_utils::TestScorer::with_penalty(0);
4051 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4052 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4053 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
4055 // This test checks that if we have two cheaper paths and one more expensive path,
4056 // so that liquidity-wise any 2 of 3 combination is sufficient,
4057 // two cheaper paths will be taken.
4058 // These paths have equal available liquidity.
4060 // We need a combination of 3 paths:
4061 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
4062 // Note that these paths overlap (channels 5, 12, 13).
4063 // Each path will have 100 sats capacity, those channels which
4064 // are used twice will have 200 sats capacity.
4066 // Disable other potential paths.
4067 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4068 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4069 short_channel_id: 2,
4072 cltv_expiry_delta: 0,
4073 htlc_minimum_msat: 0,
4074 htlc_maximum_msat: OptionalField::Present(100_000),
4076 fee_proportional_millionths: 0,
4077 excess_data: Vec::new()
4079 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4080 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4081 short_channel_id: 7,
4084 cltv_expiry_delta: 0,
4085 htlc_minimum_msat: 0,
4086 htlc_maximum_msat: OptionalField::Present(100_000),
4088 fee_proportional_millionths: 0,
4089 excess_data: Vec::new()
4092 // Path via {node0, node2} is channels {1, 3, 5}.
4093 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4094 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4095 short_channel_id: 1,
4098 cltv_expiry_delta: 0,
4099 htlc_minimum_msat: 0,
4100 htlc_maximum_msat: OptionalField::Present(100_000),
4102 fee_proportional_millionths: 0,
4103 excess_data: Vec::new()
4105 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4106 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4107 short_channel_id: 3,
4110 cltv_expiry_delta: 0,
4111 htlc_minimum_msat: 0,
4112 htlc_maximum_msat: OptionalField::Present(100_000),
4114 fee_proportional_millionths: 0,
4115 excess_data: Vec::new()
4118 // Capacity of 200 sats because this channel will be used by 3rd path as well.
4119 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4120 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4121 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4122 short_channel_id: 5,
4125 cltv_expiry_delta: 0,
4126 htlc_minimum_msat: 0,
4127 htlc_maximum_msat: OptionalField::Present(200_000),
4129 fee_proportional_millionths: 0,
4130 excess_data: Vec::new()
4133 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4134 // Add 100 sats to the capacities of {12, 13}, because these channels
4135 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
4136 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4137 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4138 short_channel_id: 12,
4141 cltv_expiry_delta: 0,
4142 htlc_minimum_msat: 0,
4143 htlc_maximum_msat: OptionalField::Present(200_000),
4145 fee_proportional_millionths: 0,
4146 excess_data: Vec::new()
4148 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4149 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4150 short_channel_id: 13,
4153 cltv_expiry_delta: 0,
4154 htlc_minimum_msat: 0,
4155 htlc_maximum_msat: OptionalField::Present(200_000),
4157 fee_proportional_millionths: 0,
4158 excess_data: Vec::new()
4161 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4162 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4163 short_channel_id: 6,
4166 cltv_expiry_delta: 0,
4167 htlc_minimum_msat: 0,
4168 htlc_maximum_msat: OptionalField::Present(100_000),
4169 fee_base_msat: 1_000,
4170 fee_proportional_millionths: 0,
4171 excess_data: Vec::new()
4173 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4174 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4175 short_channel_id: 11,
4178 cltv_expiry_delta: 0,
4179 htlc_minimum_msat: 0,
4180 htlc_maximum_msat: OptionalField::Present(100_000),
4182 fee_proportional_millionths: 0,
4183 excess_data: Vec::new()
4186 // Path via {node7, node2} is channels {12, 13, 5}.
4187 // We already limited them to 200 sats (they are used twice for 100 sats).
4188 // Nothing to do here.
4191 // Now, attempt to route 180 sats.
4192 // Our algorithm should provide us with these 2 paths.
4193 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 180_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4194 assert_eq!(route.paths.len(), 2);
4196 let mut total_value_transferred_msat = 0;
4197 let mut total_paid_msat = 0;
4198 for path in &route.paths {
4199 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
4200 total_value_transferred_msat += path.last().unwrap().fee_msat;
4202 total_paid_msat += hop.fee_msat;
4205 // If we paid fee, this would be higher.
4206 assert_eq!(total_value_transferred_msat, 180_000);
4207 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
4208 assert_eq!(total_fees_paid, 0);
4213 fn fees_on_mpp_route_test() {
4214 // This test makes sure that MPP algorithm properly takes into account
4215 // fees charged on the channels, by making the fees impactful:
4216 // if the fee is not properly accounted for, the behavior is different.
4217 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4218 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4219 let scorer = test_utils::TestScorer::with_penalty(0);
4220 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4221 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4222 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
4224 // We need a route consisting of 2 paths:
4225 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
4226 // We will route 200 sats, Each path will have 100 sats capacity.
4228 // This test is not particularly stable: e.g.,
4229 // there's a way to route via {node0, node2, node4}.
4230 // It works while pathfinding is deterministic, but can be broken otherwise.
4231 // It's fine to ignore this concern for now.
4233 // Disable other potential paths.
4234 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4235 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4236 short_channel_id: 2,
4239 cltv_expiry_delta: 0,
4240 htlc_minimum_msat: 0,
4241 htlc_maximum_msat: OptionalField::Present(100_000),
4243 fee_proportional_millionths: 0,
4244 excess_data: Vec::new()
4247 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4248 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4249 short_channel_id: 7,
4252 cltv_expiry_delta: 0,
4253 htlc_minimum_msat: 0,
4254 htlc_maximum_msat: OptionalField::Present(100_000),
4256 fee_proportional_millionths: 0,
4257 excess_data: Vec::new()
4260 // Path via {node0, node2} is channels {1, 3, 5}.
4261 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4262 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4263 short_channel_id: 1,
4266 cltv_expiry_delta: 0,
4267 htlc_minimum_msat: 0,
4268 htlc_maximum_msat: OptionalField::Present(100_000),
4270 fee_proportional_millionths: 0,
4271 excess_data: Vec::new()
4273 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4274 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4275 short_channel_id: 3,
4278 cltv_expiry_delta: 0,
4279 htlc_minimum_msat: 0,
4280 htlc_maximum_msat: OptionalField::Present(100_000),
4282 fee_proportional_millionths: 0,
4283 excess_data: Vec::new()
4286 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4287 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4288 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4289 short_channel_id: 5,
4292 cltv_expiry_delta: 0,
4293 htlc_minimum_msat: 0,
4294 htlc_maximum_msat: OptionalField::Present(100_000),
4296 fee_proportional_millionths: 0,
4297 excess_data: Vec::new()
4300 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4301 // All channels should be 100 sats capacity. But for the fee experiment,
4302 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
4303 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
4304 // 100 sats (and pay 150 sats in fees for the use of channel 6),
4305 // so no matter how large are other channels,
4306 // the whole path will be limited by 100 sats with just these 2 conditions:
4307 // - channel 12 capacity is 250 sats
4308 // - fee for channel 6 is 150 sats
4309 // Let's test this by enforcing these 2 conditions and removing other limits.
4310 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4311 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4312 short_channel_id: 12,
4315 cltv_expiry_delta: 0,
4316 htlc_minimum_msat: 0,
4317 htlc_maximum_msat: OptionalField::Present(250_000),
4319 fee_proportional_millionths: 0,
4320 excess_data: Vec::new()
4322 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4323 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4324 short_channel_id: 13,
4327 cltv_expiry_delta: 0,
4328 htlc_minimum_msat: 0,
4329 htlc_maximum_msat: OptionalField::Absent,
4331 fee_proportional_millionths: 0,
4332 excess_data: Vec::new()
4335 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4336 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4337 short_channel_id: 6,
4340 cltv_expiry_delta: 0,
4341 htlc_minimum_msat: 0,
4342 htlc_maximum_msat: OptionalField::Absent,
4343 fee_base_msat: 150_000,
4344 fee_proportional_millionths: 0,
4345 excess_data: Vec::new()
4347 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4348 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4349 short_channel_id: 11,
4352 cltv_expiry_delta: 0,
4353 htlc_minimum_msat: 0,
4354 htlc_maximum_msat: OptionalField::Absent,
4356 fee_proportional_millionths: 0,
4357 excess_data: Vec::new()
4361 // Attempt to route more than available results in a failure.
4362 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4363 &our_id, &payment_params, &network_graph.read_only(), None, 210_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
4364 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4365 } else { panic!(); }
4369 // Now, attempt to route 200 sats (exact amount we can route).
4370 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 200_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4371 assert_eq!(route.paths.len(), 2);
4373 let mut total_amount_paid_msat = 0;
4374 for path in &route.paths {
4375 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
4376 total_amount_paid_msat += path.last().unwrap().fee_msat;
4378 assert_eq!(total_amount_paid_msat, 200_000);
4379 assert_eq!(route.get_total_fees(), 150_000);
4384 fn mpp_with_last_hops() {
4385 // Previously, if we tried to send an MPP payment to a destination which was only reachable
4386 // via a single last-hop route hint, we'd fail to route if we first collected routes
4387 // totaling close but not quite enough to fund the full payment.
4389 // This was because we considered last-hop hints to have exactly the sought payment amount
4390 // instead of the amount we were trying to collect, needlessly limiting our path searching
4391 // at the very first hop.
4393 // Specifically, this interacted with our "all paths must fund at least 5% of total target"
4394 // criterion to cause us to refuse all routes at the last hop hint which would be considered
4395 // to only have the remaining to-collect amount in available liquidity.
4397 // This bug appeared in production in some specific channel configurations.
4398 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4399 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4400 let scorer = test_utils::TestScorer::with_penalty(0);
4401 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4402 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4403 let payment_params = PaymentParameters::from_node_id(PublicKey::from_slice(&[02; 33]).unwrap()).with_features(InvoiceFeatures::known())
4404 .with_route_hints(vec![RouteHint(vec![RouteHintHop {
4405 src_node_id: nodes[2],
4406 short_channel_id: 42,
4407 fees: RoutingFees { base_msat: 0, proportional_millionths: 0 },
4408 cltv_expiry_delta: 42,
4409 htlc_minimum_msat: None,
4410 htlc_maximum_msat: None,
4413 // Keep only two paths from us to nodes[2], both with a 99sat HTLC maximum, with one with
4414 // no fee and one with a 1msat fee. Previously, trying to route 100 sats to nodes[2] here
4415 // would first use the no-fee route and then fail to find a path along the second route as
4416 // we think we can only send up to 1 additional sat over the last-hop but refuse to as its
4417 // under 5% of our payment amount.
4418 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4419 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4420 short_channel_id: 1,
4423 cltv_expiry_delta: (5 << 4) | 5,
4424 htlc_minimum_msat: 0,
4425 htlc_maximum_msat: OptionalField::Present(99_000),
4426 fee_base_msat: u32::max_value(),
4427 fee_proportional_millionths: u32::max_value(),
4428 excess_data: Vec::new()
4430 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4431 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4432 short_channel_id: 2,
4435 cltv_expiry_delta: (5 << 4) | 3,
4436 htlc_minimum_msat: 0,
4437 htlc_maximum_msat: OptionalField::Present(99_000),
4438 fee_base_msat: u32::max_value(),
4439 fee_proportional_millionths: u32::max_value(),
4440 excess_data: Vec::new()
4442 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4443 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4444 short_channel_id: 4,
4447 cltv_expiry_delta: (4 << 4) | 1,
4448 htlc_minimum_msat: 0,
4449 htlc_maximum_msat: OptionalField::Absent,
4451 fee_proportional_millionths: 0,
4452 excess_data: Vec::new()
4454 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4455 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4456 short_channel_id: 13,
4458 flags: 0|2, // Channel disabled
4459 cltv_expiry_delta: (13 << 4) | 1,
4460 htlc_minimum_msat: 0,
4461 htlc_maximum_msat: OptionalField::Absent,
4463 fee_proportional_millionths: 2000000,
4464 excess_data: Vec::new()
4467 // Get a route for 100 sats and check that we found the MPP route no problem and didn't
4469 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4470 assert_eq!(route.paths.len(), 2);
4471 // Paths are somewhat randomly ordered, but:
4472 // * the first is channel 2 (1 msat fee) -> channel 4 -> channel 42
4473 // * the second is channel 1 (0 fee, but 99 sat maximum) -> channel 3 -> channel 42
4474 assert_eq!(route.paths[0][0].short_channel_id, 2);
4475 assert_eq!(route.paths[0][0].fee_msat, 1);
4476 assert_eq!(route.paths[0][2].fee_msat, 1_000);
4477 assert_eq!(route.paths[1][0].short_channel_id, 1);
4478 assert_eq!(route.paths[1][0].fee_msat, 0);
4479 assert_eq!(route.paths[1][2].fee_msat, 99_000);
4480 assert_eq!(route.get_total_fees(), 1);
4481 assert_eq!(route.get_total_amount(), 100_000);
4485 fn drop_lowest_channel_mpp_route_test() {
4486 // This test checks that low-capacity channel is dropped when after
4487 // path finding we realize that we found more capacity than we need.
4488 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4489 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4490 let scorer = test_utils::TestScorer::with_penalty(0);
4491 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4492 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4493 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
4495 // We need a route consisting of 3 paths:
4496 // From our node to node2 via node0, node7, node1 (three paths one hop each).
4498 // The first and the second paths should be sufficient, but the third should be
4499 // cheaper, so that we select it but drop later.
4501 // First, we set limits on these (previously unlimited) channels.
4502 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
4504 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
4505 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4506 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4507 short_channel_id: 1,
4510 cltv_expiry_delta: 0,
4511 htlc_minimum_msat: 0,
4512 htlc_maximum_msat: OptionalField::Present(100_000),
4514 fee_proportional_millionths: 0,
4515 excess_data: Vec::new()
4517 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4518 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4519 short_channel_id: 3,
4522 cltv_expiry_delta: 0,
4523 htlc_minimum_msat: 0,
4524 htlc_maximum_msat: OptionalField::Present(50_000),
4526 fee_proportional_millionths: 0,
4527 excess_data: Vec::new()
4530 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
4531 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4532 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4533 short_channel_id: 12,
4536 cltv_expiry_delta: 0,
4537 htlc_minimum_msat: 0,
4538 htlc_maximum_msat: OptionalField::Present(60_000),
4540 fee_proportional_millionths: 0,
4541 excess_data: Vec::new()
4543 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4544 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4545 short_channel_id: 13,
4548 cltv_expiry_delta: 0,
4549 htlc_minimum_msat: 0,
4550 htlc_maximum_msat: OptionalField::Present(60_000),
4552 fee_proportional_millionths: 0,
4553 excess_data: Vec::new()
4556 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
4557 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4558 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4559 short_channel_id: 2,
4562 cltv_expiry_delta: 0,
4563 htlc_minimum_msat: 0,
4564 htlc_maximum_msat: OptionalField::Present(20_000),
4566 fee_proportional_millionths: 0,
4567 excess_data: Vec::new()
4569 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4570 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4571 short_channel_id: 4,
4574 cltv_expiry_delta: 0,
4575 htlc_minimum_msat: 0,
4576 htlc_maximum_msat: OptionalField::Present(20_000),
4578 fee_proportional_millionths: 0,
4579 excess_data: Vec::new()
4583 // Attempt to route more than available results in a failure.
4584 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4585 &our_id, &payment_params, &network_graph.read_only(), None, 150_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
4586 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4587 } else { panic!(); }
4591 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
4592 // Our algorithm should provide us with these 3 paths.
4593 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 125_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4594 assert_eq!(route.paths.len(), 3);
4595 let mut total_amount_paid_msat = 0;
4596 for path in &route.paths {
4597 assert_eq!(path.len(), 2);
4598 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4599 total_amount_paid_msat += path.last().unwrap().fee_msat;
4601 assert_eq!(total_amount_paid_msat, 125_000);
4605 // Attempt to route without the last small cheap channel
4606 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4607 assert_eq!(route.paths.len(), 2);
4608 let mut total_amount_paid_msat = 0;
4609 for path in &route.paths {
4610 assert_eq!(path.len(), 2);
4611 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4612 total_amount_paid_msat += path.last().unwrap().fee_msat;
4614 assert_eq!(total_amount_paid_msat, 90_000);
4619 fn min_criteria_consistency() {
4620 // Test that we don't use an inconsistent metric between updating and walking nodes during
4621 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
4622 // was updated with a different criterion from the heap sorting, resulting in loops in
4623 // calculated paths. We test for that specific case here.
4625 // We construct a network that looks like this:
4627 // node2 -1(3)2- node3
4631 // node1 -1(5)2- node4 -1(1)2- node6
4637 // We create a loop on the side of our real path - our destination is node 6, with a
4638 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
4639 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
4640 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
4641 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
4642 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
4643 // "previous hop" being set to node 3, creating a loop in the path.
4644 let secp_ctx = Secp256k1::new();
4645 let logger = Arc::new(test_utils::TestLogger::new());
4646 let network = Arc::new(NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash()));
4647 let net_graph_msg_handler = NetGraphMsgHandler::new(Arc::clone(&network), None, Arc::clone(&logger));
4648 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4649 let scorer = test_utils::TestScorer::with_penalty(0);
4650 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4651 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4652 let payment_params = PaymentParameters::from_node_id(nodes[6]);
4654 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
4655 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4656 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4657 short_channel_id: 6,
4660 cltv_expiry_delta: (6 << 4) | 0,
4661 htlc_minimum_msat: 0,
4662 htlc_maximum_msat: OptionalField::Absent,
4664 fee_proportional_millionths: 0,
4665 excess_data: Vec::new()
4667 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
4669 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4670 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4671 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4672 short_channel_id: 5,
4675 cltv_expiry_delta: (5 << 4) | 0,
4676 htlc_minimum_msat: 0,
4677 htlc_maximum_msat: OptionalField::Absent,
4679 fee_proportional_millionths: 0,
4680 excess_data: Vec::new()
4682 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
4684 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
4685 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4686 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4687 short_channel_id: 4,
4690 cltv_expiry_delta: (4 << 4) | 0,
4691 htlc_minimum_msat: 0,
4692 htlc_maximum_msat: OptionalField::Absent,
4694 fee_proportional_millionths: 0,
4695 excess_data: Vec::new()
4697 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
4699 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
4700 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
4701 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4702 short_channel_id: 3,
4705 cltv_expiry_delta: (3 << 4) | 0,
4706 htlc_minimum_msat: 0,
4707 htlc_maximum_msat: OptionalField::Absent,
4709 fee_proportional_millionths: 0,
4710 excess_data: Vec::new()
4712 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
4714 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
4715 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4716 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4717 short_channel_id: 2,
4720 cltv_expiry_delta: (2 << 4) | 0,
4721 htlc_minimum_msat: 0,
4722 htlc_maximum_msat: OptionalField::Absent,
4724 fee_proportional_millionths: 0,
4725 excess_data: Vec::new()
4728 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
4729 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4730 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4731 short_channel_id: 1,
4734 cltv_expiry_delta: (1 << 4) | 0,
4735 htlc_minimum_msat: 100,
4736 htlc_maximum_msat: OptionalField::Absent,
4738 fee_proportional_millionths: 0,
4739 excess_data: Vec::new()
4741 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
4744 // Now ensure the route flows simply over nodes 1 and 4 to 6.
4745 let route = get_route(&our_id, &payment_params, &network.read_only(), None, 10_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4746 assert_eq!(route.paths.len(), 1);
4747 assert_eq!(route.paths[0].len(), 3);
4749 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
4750 assert_eq!(route.paths[0][0].short_channel_id, 6);
4751 assert_eq!(route.paths[0][0].fee_msat, 100);
4752 assert_eq!(route.paths[0][0].cltv_expiry_delta, (5 << 4) | 0);
4753 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(1));
4754 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(6));
4756 assert_eq!(route.paths[0][1].pubkey, nodes[4]);
4757 assert_eq!(route.paths[0][1].short_channel_id, 5);
4758 assert_eq!(route.paths[0][1].fee_msat, 0);
4759 assert_eq!(route.paths[0][1].cltv_expiry_delta, (1 << 4) | 0);
4760 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(4));
4761 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(5));
4763 assert_eq!(route.paths[0][2].pubkey, nodes[6]);
4764 assert_eq!(route.paths[0][2].short_channel_id, 1);
4765 assert_eq!(route.paths[0][2].fee_msat, 10_000);
4766 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
4767 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
4768 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(1));
4774 fn exact_fee_liquidity_limit() {
4775 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
4776 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
4777 // we calculated fees on a higher value, resulting in us ignoring such paths.
4778 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4779 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
4780 let scorer = test_utils::TestScorer::with_penalty(0);
4781 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4782 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4783 let payment_params = PaymentParameters::from_node_id(nodes[2]);
4785 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
4787 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4788 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4789 short_channel_id: 2,
4792 cltv_expiry_delta: 0,
4793 htlc_minimum_msat: 0,
4794 htlc_maximum_msat: OptionalField::Present(85_000),
4796 fee_proportional_millionths: 0,
4797 excess_data: Vec::new()
4800 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4801 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4802 short_channel_id: 12,
4805 cltv_expiry_delta: (4 << 4) | 1,
4806 htlc_minimum_msat: 0,
4807 htlc_maximum_msat: OptionalField::Present(270_000),
4809 fee_proportional_millionths: 1000000,
4810 excess_data: Vec::new()
4814 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
4815 // 200% fee charged channel 13 in the 1-to-2 direction.
4816 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4817 assert_eq!(route.paths.len(), 1);
4818 assert_eq!(route.paths[0].len(), 2);
4820 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
4821 assert_eq!(route.paths[0][0].short_channel_id, 12);
4822 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
4823 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
4824 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
4825 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
4827 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
4828 assert_eq!(route.paths[0][1].short_channel_id, 13);
4829 assert_eq!(route.paths[0][1].fee_msat, 90_000);
4830 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
4831 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
4832 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
4837 fn htlc_max_reduction_below_min() {
4838 // Test that if, while walking the graph, we reduce the value being sent to meet an
4839 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
4840 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
4841 // resulting in us thinking there is no possible path, even if other paths exist.
4842 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4843 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4844 let scorer = test_utils::TestScorer::with_penalty(0);
4845 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4846 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4847 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
4849 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
4850 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
4851 // then try to send 90_000.
4852 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4853 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4854 short_channel_id: 2,
4857 cltv_expiry_delta: 0,
4858 htlc_minimum_msat: 0,
4859 htlc_maximum_msat: OptionalField::Present(80_000),
4861 fee_proportional_millionths: 0,
4862 excess_data: Vec::new()
4864 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4865 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4866 short_channel_id: 4,
4869 cltv_expiry_delta: (4 << 4) | 1,
4870 htlc_minimum_msat: 90_000,
4871 htlc_maximum_msat: OptionalField::Absent,
4873 fee_proportional_millionths: 0,
4874 excess_data: Vec::new()
4878 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
4879 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
4880 // expensive) channels 12-13 path.
4881 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4882 assert_eq!(route.paths.len(), 1);
4883 assert_eq!(route.paths[0].len(), 2);
4885 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
4886 assert_eq!(route.paths[0][0].short_channel_id, 12);
4887 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
4888 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
4889 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
4890 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
4892 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
4893 assert_eq!(route.paths[0][1].short_channel_id, 13);
4894 assert_eq!(route.paths[0][1].fee_msat, 90_000);
4895 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
4896 assert_eq!(route.paths[0][1].node_features.le_flags(), InvoiceFeatures::known().le_flags());
4897 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
4902 fn multiple_direct_first_hops() {
4903 // Previously we'd only ever considered one first hop path per counterparty.
4904 // However, as we don't restrict users to one channel per peer, we really need to support
4905 // looking at all first hop paths.
4906 // Here we test that we do not ignore all-but-the-last first hop paths per counterparty (as
4907 // we used to do by overwriting the `first_hop_targets` hashmap entry) and that we can MPP
4908 // route over multiple channels with the same first hop.
4909 let secp_ctx = Secp256k1::new();
4910 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4911 let logger = Arc::new(test_utils::TestLogger::new());
4912 let network_graph = NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash());
4913 let scorer = test_utils::TestScorer::with_penalty(0);
4914 let payment_params = PaymentParameters::from_node_id(nodes[0]).with_features(InvoiceFeatures::known());
4915 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4916 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4919 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
4920 &get_channel_details(Some(3), nodes[0], InitFeatures::known(), 200_000),
4921 &get_channel_details(Some(2), nodes[0], InitFeatures::known(), 10_000),
4922 ]), 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4923 assert_eq!(route.paths.len(), 1);
4924 assert_eq!(route.paths[0].len(), 1);
4926 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
4927 assert_eq!(route.paths[0][0].short_channel_id, 3);
4928 assert_eq!(route.paths[0][0].fee_msat, 100_000);
4931 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
4932 &get_channel_details(Some(3), nodes[0], InitFeatures::known(), 50_000),
4933 &get_channel_details(Some(2), nodes[0], InitFeatures::known(), 50_000),
4934 ]), 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4935 assert_eq!(route.paths.len(), 2);
4936 assert_eq!(route.paths[0].len(), 1);
4937 assert_eq!(route.paths[1].len(), 1);
4939 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
4940 assert_eq!(route.paths[0][0].short_channel_id, 3);
4941 assert_eq!(route.paths[0][0].fee_msat, 50_000);
4943 assert_eq!(route.paths[1][0].pubkey, nodes[0]);
4944 assert_eq!(route.paths[1][0].short_channel_id, 2);
4945 assert_eq!(route.paths[1][0].fee_msat, 50_000);
4949 // If we have a bunch of outbound channels to the same node, where most are not
4950 // sufficient to pay the full payment, but one is, we should default to just using the
4951 // one single channel that has sufficient balance, avoiding MPP.
4953 // If we have several options above the 3xpayment value threshold, we should pick the
4954 // smallest of them, avoiding further fragmenting our available outbound balance to
4956 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
4957 &get_channel_details(Some(2), nodes[0], InitFeatures::known(), 50_000),
4958 &get_channel_details(Some(3), nodes[0], InitFeatures::known(), 50_000),
4959 &get_channel_details(Some(5), nodes[0], InitFeatures::known(), 50_000),
4960 &get_channel_details(Some(6), nodes[0], InitFeatures::known(), 300_000),
4961 &get_channel_details(Some(7), nodes[0], InitFeatures::known(), 50_000),
4962 &get_channel_details(Some(8), nodes[0], InitFeatures::known(), 50_000),
4963 &get_channel_details(Some(9), nodes[0], InitFeatures::known(), 50_000),
4964 &get_channel_details(Some(4), nodes[0], InitFeatures::known(), 1_000_000),
4965 ]), 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4966 assert_eq!(route.paths.len(), 1);
4967 assert_eq!(route.paths[0].len(), 1);
4969 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
4970 assert_eq!(route.paths[0][0].short_channel_id, 6);
4971 assert_eq!(route.paths[0][0].fee_msat, 100_000);
4976 fn prefers_shorter_route_with_higher_fees() {
4977 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4978 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4979 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
4981 // Without penalizing each hop 100 msats, a longer path with lower fees is chosen.
4982 let scorer = test_utils::TestScorer::with_penalty(0);
4983 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4984 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4985 let route = get_route(
4986 &our_id, &payment_params, &network_graph.read_only(), None, 100, 42,
4987 Arc::clone(&logger), &scorer, &random_seed_bytes
4989 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4991 assert_eq!(route.get_total_fees(), 100);
4992 assert_eq!(route.get_total_amount(), 100);
4993 assert_eq!(path, vec![2, 4, 6, 11, 8]);
4995 // Applying a 100 msat penalty to each hop results in taking channels 7 and 10 to nodes[6]
4996 // from nodes[2] rather than channel 6, 11, and 8, even though the longer path is cheaper.
4997 let scorer = test_utils::TestScorer::with_penalty(100);
4998 let route = get_route(
4999 &our_id, &payment_params, &network_graph.read_only(), None, 100, 42,
5000 Arc::clone(&logger), &scorer, &random_seed_bytes
5002 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5004 assert_eq!(route.get_total_fees(), 300);
5005 assert_eq!(route.get_total_amount(), 100);
5006 assert_eq!(path, vec![2, 4, 7, 10]);
5009 struct BadChannelScorer {
5010 short_channel_id: u64,
5014 impl Writeable for BadChannelScorer {
5015 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), ::io::Error> { unimplemented!() }
5017 impl Score for BadChannelScorer {
5018 fn channel_penalty_msat(&self, short_channel_id: u64, _send_amt: u64, _capacity_msat: u64, _source: &NodeId, _target: &NodeId) -> u64 {
5019 if short_channel_id == self.short_channel_id { u64::max_value() } else { 0 }
5022 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
5023 fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
5026 struct BadNodeScorer {
5031 impl Writeable for BadNodeScorer {
5032 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), ::io::Error> { unimplemented!() }
5035 impl Score for BadNodeScorer {
5036 fn channel_penalty_msat(&self, _short_channel_id: u64, _send_amt: u64, _capacity_msat: u64, _source: &NodeId, target: &NodeId) -> u64 {
5037 if *target == self.node_id { u64::max_value() } else { 0 }
5040 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
5041 fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
5045 fn avoids_routing_through_bad_channels_and_nodes() {
5046 let (secp_ctx, network, _, _, logger) = build_graph();
5047 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5048 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
5049 let network_graph = network.read_only();
5051 // A path to nodes[6] exists when no penalties are applied to any channel.
5052 let scorer = test_utils::TestScorer::with_penalty(0);
5053 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5054 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5055 let route = get_route(
5056 &our_id, &payment_params, &network_graph, None, 100, 42,
5057 Arc::clone(&logger), &scorer, &random_seed_bytes
5059 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5061 assert_eq!(route.get_total_fees(), 100);
5062 assert_eq!(route.get_total_amount(), 100);
5063 assert_eq!(path, vec![2, 4, 6, 11, 8]);
5065 // A different path to nodes[6] exists if channel 6 cannot be routed over.
5066 let scorer = BadChannelScorer { short_channel_id: 6 };
5067 let route = get_route(
5068 &our_id, &payment_params, &network_graph, None, 100, 42,
5069 Arc::clone(&logger), &scorer, &random_seed_bytes
5071 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5073 assert_eq!(route.get_total_fees(), 300);
5074 assert_eq!(route.get_total_amount(), 100);
5075 assert_eq!(path, vec![2, 4, 7, 10]);
5077 // A path to nodes[6] does not exist if nodes[2] cannot be routed through.
5078 let scorer = BadNodeScorer { node_id: NodeId::from_pubkey(&nodes[2]) };
5080 &our_id, &payment_params, &network_graph, None, 100, 42,
5081 Arc::clone(&logger), &scorer, &random_seed_bytes
5083 Err(LightningError { err, .. } ) => {
5084 assert_eq!(err, "Failed to find a path to the given destination");
5086 Ok(_) => panic!("Expected error"),
5091 fn total_fees_single_path() {
5095 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5096 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5097 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5100 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5101 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5102 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5105 pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
5106 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5107 short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0
5110 payment_params: None,
5113 assert_eq!(route.get_total_fees(), 250);
5114 assert_eq!(route.get_total_amount(), 225);
5118 fn total_fees_multi_path() {
5122 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5123 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5124 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5127 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5128 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5129 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5133 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5134 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5135 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5138 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5139 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5140 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5143 payment_params: None,
5146 assert_eq!(route.get_total_fees(), 200);
5147 assert_eq!(route.get_total_amount(), 300);
5151 fn total_empty_route_no_panic() {
5152 // In an earlier version of `Route::get_total_fees` and `Route::get_total_amount`, they
5153 // would both panic if the route was completely empty. We test to ensure they return 0
5154 // here, even though its somewhat nonsensical as a route.
5155 let route = Route { paths: Vec::new(), payment_params: None };
5157 assert_eq!(route.get_total_fees(), 0);
5158 assert_eq!(route.get_total_amount(), 0);
5162 fn limits_total_cltv_delta() {
5163 let (secp_ctx, network, _, _, logger) = build_graph();
5164 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5165 let network_graph = network.read_only();
5167 let scorer = test_utils::TestScorer::with_penalty(0);
5169 // Make sure that generally there is at least one route available
5170 let feasible_max_total_cltv_delta = 1008;
5171 let feasible_payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes))
5172 .with_max_total_cltv_expiry_delta(feasible_max_total_cltv_delta);
5173 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5174 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5175 let route = get_route(&our_id, &feasible_payment_params, &network_graph, None, 100, 0, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5176 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5177 assert_ne!(path.len(), 0);
5179 // But not if we exclude all paths on the basis of their accumulated CLTV delta
5180 let fail_max_total_cltv_delta = 23;
5181 let fail_payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes))
5182 .with_max_total_cltv_expiry_delta(fail_max_total_cltv_delta);
5183 match get_route(&our_id, &fail_payment_params, &network_graph, None, 100, 0, Arc::clone(&logger), &scorer, &random_seed_bytes)
5185 Err(LightningError { err, .. } ) => {
5186 assert_eq!(err, "Failed to find a path to the given destination");
5188 Ok(_) => panic!("Expected error"),
5193 fn adds_and_limits_cltv_offset() {
5194 let (secp_ctx, network_graph, _, _, logger) = build_graph();
5195 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5197 let scorer = test_utils::TestScorer::with_penalty(0);
5199 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
5200 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5201 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5202 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5203 assert_eq!(route.paths.len(), 1);
5205 let cltv_expiry_deltas_before = route.paths[0].iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5207 // Check whether the offset added to the last hop by default is in [1 .. DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA]
5208 let mut route_default = route.clone();
5209 add_random_cltv_offset(&mut route_default, &payment_params, &network_graph.read_only(), &random_seed_bytes);
5210 let cltv_expiry_deltas_default = route_default.paths[0].iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5211 assert_eq!(cltv_expiry_deltas_before.split_last().unwrap().1, cltv_expiry_deltas_default.split_last().unwrap().1);
5212 assert!(cltv_expiry_deltas_default.last() > cltv_expiry_deltas_before.last());
5213 assert!(cltv_expiry_deltas_default.last().unwrap() <= &DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA);
5215 // Check that no offset is added when we restrict the max_total_cltv_expiry_delta
5216 let mut route_limited = route.clone();
5217 let limited_max_total_cltv_expiry_delta = cltv_expiry_deltas_before.iter().sum();
5218 let limited_payment_params = payment_params.with_max_total_cltv_expiry_delta(limited_max_total_cltv_expiry_delta);
5219 add_random_cltv_offset(&mut route_limited, &limited_payment_params, &network_graph.read_only(), &random_seed_bytes);
5220 let cltv_expiry_deltas_limited = route_limited.paths[0].iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5221 assert_eq!(cltv_expiry_deltas_before, cltv_expiry_deltas_limited);
5225 fn adds_plausible_cltv_offset() {
5226 let (secp_ctx, network, _, _, logger) = build_graph();
5227 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5228 let network_graph = network.read_only();
5229 let network_nodes = network_graph.nodes();
5230 let network_channels = network_graph.channels();
5231 let scorer = test_utils::TestScorer::with_penalty(0);
5232 let payment_params = PaymentParameters::from_node_id(nodes[3]);
5233 let keys_manager = test_utils::TestKeysInterface::new(&[4u8; 32], Network::Testnet);
5234 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5236 let mut route = get_route(&our_id, &payment_params, &network_graph, None, 100, 0,
5237 Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5238 add_random_cltv_offset(&mut route, &payment_params, &network_graph, &random_seed_bytes);
5240 let mut path_plausibility = vec![];
5242 for p in route.paths {
5243 // 1. Select random observation point
5244 let mut prng = ChaCha20::new(&random_seed_bytes, &[0u8; 12]);
5245 let mut random_bytes = [0u8; ::core::mem::size_of::<usize>()];
5247 prng.process_in_place(&mut random_bytes);
5248 let random_path_index = usize::from_be_bytes(random_bytes).wrapping_rem(p.len());
5249 let observation_point = NodeId::from_pubkey(&p.get(random_path_index).unwrap().pubkey);
5251 // 2. Calculate what CLTV expiry delta we would observe there
5252 let observed_cltv_expiry_delta: u32 = p[random_path_index..].iter().map(|h| h.cltv_expiry_delta).sum();
5254 // 3. Starting from the observation point, find candidate paths
5255 let mut candidates: VecDeque<(NodeId, Vec<u32>)> = VecDeque::new();
5256 candidates.push_back((observation_point, vec![]));
5258 let mut found_plausible_candidate = false;
5260 'candidate_loop: while let Some((cur_node_id, cur_path_cltv_deltas)) = candidates.pop_front() {
5261 if let Some(remaining) = observed_cltv_expiry_delta.checked_sub(cur_path_cltv_deltas.iter().sum::<u32>()) {
5262 if remaining == 0 || remaining.wrapping_rem(40) == 0 || remaining.wrapping_rem(144) == 0 {
5263 found_plausible_candidate = true;
5264 break 'candidate_loop;
5268 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
5269 for channel_id in &cur_node.channels {
5270 if let Some(channel_info) = network_channels.get(&channel_id) {
5271 if let Some((dir_info, next_id)) = channel_info.as_directed_from(&cur_node_id) {
5272 if let Some(channel_update_info) = dir_info.direction() {
5273 let next_cltv_expiry_delta = channel_update_info.cltv_expiry_delta as u32;
5274 if cur_path_cltv_deltas.iter().sum::<u32>()
5275 .saturating_add(next_cltv_expiry_delta) <= observed_cltv_expiry_delta {
5276 let mut new_path_cltv_deltas = cur_path_cltv_deltas.clone();
5277 new_path_cltv_deltas.push(next_cltv_expiry_delta);
5278 candidates.push_back((*next_id, new_path_cltv_deltas));
5287 path_plausibility.push(found_plausible_candidate);
5289 assert!(path_plausibility.iter().all(|x| *x));
5292 #[cfg(not(feature = "no-std"))]
5293 pub(super) fn random_init_seed() -> u64 {
5294 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
5295 use core::hash::{BuildHasher, Hasher};
5296 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
5297 println!("Using seed of {}", seed);
5300 #[cfg(not(feature = "no-std"))]
5301 use util::ser::Readable;
5304 #[cfg(not(feature = "no-std"))]
5305 fn generate_routes() {
5306 use routing::scoring::{ProbabilisticScorer, ProbabilisticScoringParameters};
5308 let mut d = match super::test_utils::get_route_file() {
5315 let graph = NetworkGraph::read(&mut d).unwrap();
5316 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5317 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5319 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
5320 let mut seed = random_init_seed() as usize;
5321 let nodes = graph.read_only().nodes().clone();
5322 'load_endpoints: for _ in 0..10 {
5324 seed = seed.overflowing_mul(0xdeadbeef).0;
5325 let src = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5326 seed = seed.overflowing_mul(0xdeadbeef).0;
5327 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5328 let payment_params = PaymentParameters::from_node_id(dst);
5329 let amt = seed as u64 % 200_000_000;
5330 let params = ProbabilisticScoringParameters::default();
5331 let scorer = ProbabilisticScorer::new(params, &graph);
5332 if get_route(src, &payment_params, &graph.read_only(), None, amt, 42, &test_utils::TestLogger::new(), &scorer, &random_seed_bytes).is_ok() {
5333 continue 'load_endpoints;
5340 #[cfg(not(feature = "no-std"))]
5341 fn generate_routes_mpp() {
5342 use routing::scoring::{ProbabilisticScorer, ProbabilisticScoringParameters};
5344 let mut d = match super::test_utils::get_route_file() {
5351 let graph = NetworkGraph::read(&mut d).unwrap();
5352 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5353 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5355 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
5356 let mut seed = random_init_seed() as usize;
5357 let nodes = graph.read_only().nodes().clone();
5358 'load_endpoints: for _ in 0..10 {
5360 seed = seed.overflowing_mul(0xdeadbeef).0;
5361 let src = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5362 seed = seed.overflowing_mul(0xdeadbeef).0;
5363 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5364 let payment_params = PaymentParameters::from_node_id(dst).with_features(InvoiceFeatures::known());
5365 let amt = seed as u64 % 200_000_000;
5366 let params = ProbabilisticScoringParameters::default();
5367 let scorer = ProbabilisticScorer::new(params, &graph);
5368 if get_route(src, &payment_params, &graph.read_only(), None, amt, 42, &test_utils::TestLogger::new(), &scorer, &random_seed_bytes).is_ok() {
5369 continue 'load_endpoints;
5376 #[cfg(all(test, not(feature = "no-std")))]
5377 pub(crate) mod test_utils {
5379 /// Tries to open a network graph file, or panics with a URL to fetch it.
5380 pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
5381 let res = File::open("net_graph-2021-05-31.bin") // By default we're run in RL/lightning
5382 .or_else(|_| File::open("lightning/net_graph-2021-05-31.bin")) // We may be run manually in RL/
5383 .or_else(|_| { // Fall back to guessing based on the binary location
5384 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
5385 let mut path = std::env::current_exe().unwrap();
5386 path.pop(); // lightning-...
5388 path.pop(); // debug
5389 path.pop(); // target
5390 path.push("lightning");
5391 path.push("net_graph-2021-05-31.bin");
5392 eprintln!("{}", path.to_str().unwrap());
5395 .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");
5396 #[cfg(require_route_graph_test)]
5397 return Ok(res.unwrap());
5398 #[cfg(not(require_route_graph_test))]
5403 #[cfg(all(test, feature = "_bench_unstable", not(feature = "no-std")))]
5406 use bitcoin::hashes::Hash;
5407 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
5408 use chain::transaction::OutPoint;
5409 use chain::keysinterface::{KeysManager,KeysInterface};
5410 use ln::channelmanager::{ChannelCounterparty, ChannelDetails};
5411 use ln::features::{InitFeatures, InvoiceFeatures};
5412 use routing::scoring::{FixedPenaltyScorer, ProbabilisticScorer, ProbabilisticScoringParameters, Scorer};
5413 use util::logger::{Logger, Record};
5417 struct DummyLogger {}
5418 impl Logger for DummyLogger {
5419 fn log(&self, _record: &Record) {}
5422 fn read_network_graph() -> NetworkGraph {
5423 let mut d = test_utils::get_route_file().unwrap();
5424 NetworkGraph::read(&mut d).unwrap()
5427 fn payer_pubkey() -> PublicKey {
5428 let secp_ctx = Secp256k1::new();
5429 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
5433 fn first_hop(node_id: PublicKey) -> ChannelDetails {
5435 channel_id: [0; 32],
5436 counterparty: ChannelCounterparty {
5437 features: InitFeatures::known(),
5439 unspendable_punishment_reserve: 0,
5440 forwarding_info: None,
5442 funding_txo: Some(OutPoint {
5443 txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0
5446 short_channel_id: Some(1),
5447 inbound_scid_alias: None,
5448 channel_value_satoshis: 10_000_000,
5450 balance_msat: 10_000_000,
5451 outbound_capacity_msat: 10_000_000,
5452 inbound_capacity_msat: 0,
5453 unspendable_punishment_reserve: None,
5454 confirmations_required: None,
5455 force_close_spend_delay: None,
5457 is_funding_locked: true,
5464 fn generate_routes_with_zero_penalty_scorer(bench: &mut Bencher) {
5465 let network_graph = read_network_graph();
5466 let scorer = FixedPenaltyScorer::with_penalty(0);
5467 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::empty());
5471 fn generate_mpp_routes_with_zero_penalty_scorer(bench: &mut Bencher) {
5472 let network_graph = read_network_graph();
5473 let scorer = FixedPenaltyScorer::with_penalty(0);
5474 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::known());
5478 fn generate_routes_with_default_scorer(bench: &mut Bencher) {
5479 let network_graph = read_network_graph();
5480 let scorer = Scorer::default();
5481 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::empty());
5485 fn generate_mpp_routes_with_default_scorer(bench: &mut Bencher) {
5486 let network_graph = read_network_graph();
5487 let scorer = Scorer::default();
5488 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::known());
5492 fn generate_routes_with_probabilistic_scorer(bench: &mut Bencher) {
5493 let network_graph = read_network_graph();
5494 let params = ProbabilisticScoringParameters::default();
5495 let scorer = ProbabilisticScorer::new(params, &network_graph);
5496 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::empty());
5500 fn generate_mpp_routes_with_probabilistic_scorer(bench: &mut Bencher) {
5501 let network_graph = read_network_graph();
5502 let params = ProbabilisticScoringParameters::default();
5503 let scorer = ProbabilisticScorer::new(params, &network_graph);
5504 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::known());
5507 fn generate_routes<S: Score>(
5508 bench: &mut Bencher, graph: &NetworkGraph, mut scorer: S, features: InvoiceFeatures
5510 let nodes = graph.read_only().nodes().clone();
5511 let payer = payer_pubkey();
5512 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
5513 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5515 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
5516 let mut routes = Vec::new();
5517 let mut route_endpoints = Vec::new();
5518 let mut seed: usize = 0xdeadbeef;
5519 'load_endpoints: for _ in 0..150 {
5522 let src = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5524 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5525 let params = PaymentParameters::from_node_id(dst).with_features(features.clone());
5526 let first_hop = first_hop(src);
5527 let amt = seed as u64 % 1_000_000;
5528 if let Ok(route) = get_route(&payer, ¶ms, &graph.read_only(), Some(&[&first_hop]), amt, 42, &DummyLogger{}, &scorer, &random_seed_bytes) {
5530 route_endpoints.push((first_hop, params, amt));
5531 continue 'load_endpoints;
5536 // ...and seed the scorer with success and failure data...
5537 for route in routes {
5538 let amount = route.get_total_amount();
5539 if amount < 250_000 {
5540 for path in route.paths {
5541 scorer.payment_path_successful(&path.iter().collect::<Vec<_>>());
5543 } else if amount > 750_000 {
5544 for path in route.paths {
5545 let short_channel_id = path[path.len() / 2].short_channel_id;
5546 scorer.payment_path_failed(&path.iter().collect::<Vec<_>>(), short_channel_id);
5551 // Because we've changed channel scores, its possible we'll take different routes to the
5552 // selected destinations, possibly causing us to fail because, eg, the newly-selected path
5553 // requires a too-high CLTV delta.
5554 route_endpoints.retain(|(first_hop, params, amt)| {
5555 get_route(&payer, params, &graph.read_only(), Some(&[first_hop]), *amt, 42, &DummyLogger{}, &scorer, &random_seed_bytes).is_ok()
5557 route_endpoints.truncate(100);
5558 assert_eq!(route_endpoints.len(), 100);
5560 // ...then benchmark finding paths between the nodes we learned.
5563 let (first_hop, params, amt) = &route_endpoints[idx % route_endpoints.len()];
5564 assert!(get_route(&payer, params, &graph.read_only(), Some(&[first_hop]), *amt, 42, &DummyLogger{}, &scorer, &random_seed_bytes).is_ok());