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 // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
515 // to change fees may result in an inconsistency.
517 // Sometimes we call this function right after constructing a path which is inconsistent in
518 // that it the value being transferred has decreased while we were doing path finding, leading
519 // to the fees being paid not lining up with the actual limits.
521 // Note that this function is not aware of the available_liquidity limit, and thus does not
522 // support increasing the value being transferred.
523 fn update_value_and_recompute_fees(&mut self, value_msat: u64) {
524 assert!(value_msat <= self.hops.last().unwrap().0.fee_msat);
526 let mut total_fee_paid_msat = 0 as u64;
527 for i in (0..self.hops.len()).rev() {
528 let last_hop = i == self.hops.len() - 1;
530 // For non-last-hop, this value will represent the fees paid on the current hop. It
531 // will consist of the fees for the use of the next hop, and extra fees to match
532 // htlc_minimum_msat of the current channel. Last hop is handled separately.
533 let mut cur_hop_fees_msat = 0;
535 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().0.hop_use_fee_msat;
538 let mut cur_hop = &mut self.hops.get_mut(i).unwrap().0;
539 cur_hop.next_hops_fee_msat = total_fee_paid_msat;
540 // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
541 // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
542 // set it too high just to maliciously take more fees by exploiting this
543 // match htlc_minimum_msat logic.
544 let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
545 if let Some(extra_fees_msat) = cur_hop.candidate.htlc_minimum_msat().checked_sub(cur_hop_transferred_amount_msat) {
546 // Note that there is a risk that *previous hops* (those closer to us, as we go
547 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
549 // This might make us end up with a broken route, although this should be super-rare
550 // in practice, both because of how healthy channels look like, and how we pick
551 // channels in add_entry.
552 // Also, this can't be exploited more heavily than *announce a free path and fail
554 cur_hop_transferred_amount_msat += extra_fees_msat;
555 total_fee_paid_msat += extra_fees_msat;
556 cur_hop_fees_msat += extra_fees_msat;
560 // Final hop is a special case: it usually has just value_msat (by design), but also
561 // it still could overpay for the htlc_minimum_msat.
562 cur_hop.fee_msat = cur_hop_transferred_amount_msat;
564 // Propagate updated fees for the use of the channels to one hop back, where they
565 // will be actually paid (fee_msat). The last hop is handled above separately.
566 cur_hop.fee_msat = cur_hop_fees_msat;
569 // Fee for the use of the current hop which will be deducted on the previous hop.
570 // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
571 // this channel is free for us.
573 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.candidate.fees()) {
574 cur_hop.hop_use_fee_msat = new_fee;
575 total_fee_paid_msat += new_fee;
577 // It should not be possible because this function is called only to reduce the
578 // value. In that case, compute_fee was already called with the same fees for
579 // larger amount and there was no overflow.
587 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
588 let proportional_fee_millions =
589 amount_msat.checked_mul(channel_fees.proportional_millionths as u64);
590 if let Some(new_fee) = proportional_fee_millions.and_then(|part| {
591 (channel_fees.base_msat as u64).checked_add(part / 1_000_000) }) {
595 // This function may be (indirectly) called without any verification,
596 // with channel_fees provided by a caller. We should handle it gracefully.
601 /// Finds a route from us (payer) to the given target node (payee).
603 /// If the payee provided features in their invoice, they should be provided via `params.payee`.
604 /// Without this, MPP will only be used if the payee's features are available in the network graph.
606 /// Private routing paths between a public node and the target may be included in `params.payee`.
608 /// If some channels aren't announced, it may be useful to fill in `first_hops` with the results
609 /// from [`ChannelManager::list_usable_channels`]. If it is filled in, the view of our local
610 /// channels from [`NetworkGraph`] will be ignored, and only those in `first_hops` will be used.
612 /// The fees on channels from us to the next hop are ignored as they are assumed to all be equal.
613 /// However, the enabled/disabled bit on such channels as well as the `htlc_minimum_msat` /
614 /// `htlc_maximum_msat` *are* checked as they may change based on the receiving node.
618 /// May be used to re-compute a [`Route`] when handling a [`Event::PaymentPathFailed`]. Any
619 /// adjustments to the [`NetworkGraph`] and channel scores should be made prior to calling this
624 /// Panics if first_hops contains channels without short_channel_ids;
625 /// [`ChannelManager::list_usable_channels`] will never include such channels.
627 /// [`ChannelManager::list_usable_channels`]: crate::ln::channelmanager::ChannelManager::list_usable_channels
628 /// [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed
629 pub fn find_route<L: Deref, S: Score>(
630 our_node_pubkey: &PublicKey, route_params: &RouteParameters, network: &NetworkGraph,
631 first_hops: Option<&[&ChannelDetails]>, logger: L, scorer: &S, random_seed_bytes: &[u8; 32]
632 ) -> Result<Route, LightningError>
633 where L::Target: Logger {
634 let network_graph = network.read_only();
636 our_node_pubkey, &route_params.payment_params, &network_graph, first_hops, route_params.final_value_msat,
637 route_params.final_cltv_expiry_delta, logger, scorer, random_seed_bytes
640 add_random_cltv_offset(&mut route, &route_params.payment_params, &network_graph, random_seed_bytes);
643 Err(err) => Err(err),
647 pub(crate) fn get_route<L: Deref, S: Score>(
648 our_node_pubkey: &PublicKey, payment_params: &PaymentParameters, network_graph: &ReadOnlyNetworkGraph,
649 first_hops: Option<&[&ChannelDetails]>, final_value_msat: u64, final_cltv_expiry_delta: u32,
650 logger: L, scorer: &S, random_seed_bytes: &[u8; 32]
651 ) -> Result<Route, LightningError>
652 where L::Target: Logger {
653 let payee_node_id = NodeId::from_pubkey(&payment_params.payee_pubkey);
654 let our_node_id = NodeId::from_pubkey(&our_node_pubkey);
656 if payee_node_id == our_node_id {
657 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
660 if final_value_msat > MAX_VALUE_MSAT {
661 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
664 if final_value_msat == 0 {
665 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
668 for route in payment_params.route_hints.iter() {
669 for hop in &route.0 {
670 if hop.src_node_id == payment_params.payee_pubkey {
671 return Err(LightningError{err: "Route hint cannot have the payee as the source.".to_owned(), action: ErrorAction::IgnoreError});
675 if payment_params.max_total_cltv_expiry_delta <= final_cltv_expiry_delta {
676 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});
679 // The general routing idea is the following:
680 // 1. Fill first/last hops communicated by the caller.
681 // 2. Attempt to construct a path from payer to payee for transferring
682 // any ~sufficient (described later) value.
683 // If succeed, remember which channels were used and how much liquidity they have available,
684 // so that future paths don't rely on the same liquidity.
685 // 3. Proceed to the next step if:
686 // - we hit the recommended target value;
687 // - OR if we could not construct a new path. Any next attempt will fail too.
688 // Otherwise, repeat step 2.
689 // 4. See if we managed to collect paths which aggregately are able to transfer target value
690 // (not recommended value).
691 // 5. If yes, proceed. If not, fail routing.
692 // 6. Randomly combine paths into routes having enough to fulfill the payment. (TODO: knapsack)
693 // 7. Of all the found paths, select only those with the lowest total fee.
694 // 8. The last path in every selected route is likely to be more than we need.
695 // Reduce its value-to-transfer and recompute fees.
696 // 9. Choose the best route by the lowest total fee.
698 // As for the actual search algorithm,
699 // we do a payee-to-payer pseudo-Dijkstra's sorting by each node's distance from the payee
700 // plus the minimum per-HTLC fee to get from it to another node (aka "shitty pseudo-A*").
702 // We are not a faithful Dijkstra's implementation because we can change values which impact
703 // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
704 // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) than
705 // the value we are currently attempting to send over a path, we simply reduce the value being
706 // sent along the path for any hops after that channel. This may imply that later fees (which
707 // we've already tabulated) are lower because a smaller value is passing through the channels
708 // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
709 // channels which were selected earlier (and which may still be used for other paths without a
710 // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
713 // One potentially problematic case for this algorithm would be if there are many
714 // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
715 // graph walking), we may never find a path which is not liquidity-limited and has lower
716 // proportional fee (and only lower absolute fee when considering the ultimate value sent).
717 // Because we only consider paths with at least 5% of the total value being sent, the damage
718 // from such a case should be limited, however this could be further reduced in the future by
719 // calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
720 // limits for the purposes of fee calculation.
722 // Alternatively, we could store more detailed path information in the heap (targets, below)
723 // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
724 // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
725 // and practically (as we would need to store dynamically-allocated path information in heap
726 // objects, increasing malloc traffic and indirect memory access significantly). Further, the
727 // results of such an algorithm would likely be biased towards lower-value paths.
729 // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
730 // outside of our current search value, running a path search more times to gather candidate
731 // paths at different values. While this may be acceptable, further path searches may increase
732 // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
733 // graph for candidate paths, calculating the maximum value which can realistically be sent at
734 // the same time, remaining generic across different payment values.
736 // TODO: There are a few tweaks we could do, including possibly pre-calculating more stuff
737 // to use as the A* heuristic beyond just the cost to get one node further than the current
740 let network_channels = network_graph.channels();
741 let network_nodes = network_graph.nodes();
743 // Allow MPP only if we have a features set from somewhere that indicates the payee supports
744 // it. If the payee supports it they're supposed to include it in the invoice, so that should
746 let allow_mpp = if let Some(features) = &payment_params.features {
747 features.supports_basic_mpp()
748 } else if let Some(node) = network_nodes.get(&payee_node_id) {
749 if let Some(node_info) = node.announcement_info.as_ref() {
750 node_info.features.supports_basic_mpp()
753 log_trace!(logger, "Searching for a route from payer {} to payee {} {} MPP and {} first hops {}overriding the network graph", our_node_pubkey,
754 payment_params.payee_pubkey, if allow_mpp { "with" } else { "without" },
755 first_hops.map(|hops| hops.len()).unwrap_or(0), if first_hops.is_some() { "" } else { "not " });
758 // Prepare the data we'll use for payee-to-payer search by
759 // inserting first hops suggested by the caller as targets.
760 // Our search will then attempt to reach them while traversing from the payee node.
761 let mut first_hop_targets: HashMap<_, Vec<&ChannelDetails>> =
762 HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
763 if let Some(hops) = first_hops {
765 if chan.short_channel_id.is_none() {
766 panic!("first_hops should be filled in with usable channels, not pending ones");
768 if chan.counterparty.node_id == *our_node_pubkey {
769 return Err(LightningError{err: "First hop cannot have our_node_pubkey as a destination.".to_owned(), action: ErrorAction::IgnoreError});
772 .entry(NodeId::from_pubkey(&chan.counterparty.node_id))
773 .or_insert(Vec::new())
776 if first_hop_targets.is_empty() {
777 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
781 // The main heap containing all candidate next-hops sorted by their score (max(A* fee,
782 // htlc_minimum)). Ideally this would be a heap which allowed cheap score reduction instead of
783 // adding duplicate entries when we find a better path to a given node.
784 let mut targets = BinaryHeap::new();
786 // Map from node_id to information about the best current path to that node, including feerate
788 let mut dist = HashMap::with_capacity(network_nodes.len());
790 // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
791 // indicating that we may wish to try again with a higher value, potentially paying to meet an
792 // htlc_minimum with extra fees while still finding a cheaper path.
793 let mut hit_minimum_limit;
795 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
796 // We start with a path_value of the exact amount we want, and if that generates a route we may
797 // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
798 // amount we want in total across paths, selecting the best subset at the end.
799 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
800 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
801 let mut path_value_msat = final_value_msat;
803 // We don't want multiple paths (as per MPP) share liquidity of the same channels.
804 // This map allows paths to be aware of the channel use by other paths in the same call.
805 // This would help to make a better path finding decisions and not "overbook" channels.
806 // It is unaware of the directions (except for `outbound_capacity_msat` in `first_hops`).
807 let mut bookkept_channels_liquidity_available_msat = HashMap::with_capacity(network_nodes.len());
809 // Keeping track of how much value we already collected across other paths. Helps to decide:
810 // - how much a new path should be transferring (upper bound);
811 // - whether a channel should be disregarded because
812 // it's available liquidity is too small comparing to how much more we need to collect;
813 // - when we want to stop looking for new paths.
814 let mut already_collected_value_msat = 0;
816 for (_, channels) in first_hop_targets.iter_mut() {
817 // Sort the first_hops channels to the same node(s) in priority order of which channel we'd
820 // First, if channels are below `recommended_value_msat`, sort them in descending order,
821 // preferring larger channels to avoid splitting the payment into more MPP parts than is
824 // Second, because simply always sorting in descending order would always use our largest
825 // available outbound capacity, needlessly fragmenting our available channel capacities,
826 // sort channels above `recommended_value_msat` in ascending order, preferring channels
827 // which have enough, but not too much, capacity for the payment.
828 channels.sort_unstable_by(|chan_a, chan_b| {
829 if chan_b.outbound_capacity_msat < recommended_value_msat || chan_a.outbound_capacity_msat < recommended_value_msat {
830 // Sort in descending order
831 chan_b.outbound_capacity_msat.cmp(&chan_a.outbound_capacity_msat)
833 // Sort in ascending order
834 chan_a.outbound_capacity_msat.cmp(&chan_b.outbound_capacity_msat)
839 log_trace!(logger, "Building path from {} (payee) to {} (us/payer) for value {} msat.", payment_params.payee_pubkey, our_node_pubkey, final_value_msat);
841 macro_rules! add_entry {
842 // Adds entry which goes from $src_node_id to $dest_node_id over the $candidate hop.
843 // $next_hops_fee_msat represents the fees paid for using all the channels *after* this one,
844 // since that value has to be transferred over this channel.
845 // Returns whether this channel caused an update to `targets`.
846 ( $candidate: expr, $src_node_id: expr, $dest_node_id: expr, $next_hops_fee_msat: expr,
847 $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr,
848 $next_hops_path_penalty_msat: expr, $next_hops_cltv_delta: expr ) => { {
849 // We "return" whether we updated the path at the end, via this:
850 let mut did_add_update_path_to_src_node = false;
851 // Channels to self should not be used. This is more of belt-and-suspenders, because in
852 // practice these cases should be caught earlier:
853 // - for regular channels at channel announcement (TODO)
854 // - for first and last hops early in get_route
855 if $src_node_id != $dest_node_id {
856 let short_channel_id = $candidate.short_channel_id();
857 let available_liquidity_msat = bookkept_channels_liquidity_available_msat
858 .entry(short_channel_id)
859 .or_insert_with(|| $candidate.effective_capacity().as_msat());
861 // It is tricky to subtract $next_hops_fee_msat from available liquidity here.
862 // It may be misleading because we might later choose to reduce the value transferred
863 // over these channels, and the channel which was insufficient might become sufficient.
864 // Worst case: we drop a good channel here because it can't cover the high following
865 // fees caused by one expensive channel, but then this channel could have been used
866 // if the amount being transferred over this path is lower.
867 // We do this for now, but this is a subject for removal.
868 if let Some(available_value_contribution_msat) = available_liquidity_msat.checked_sub($next_hops_fee_msat) {
870 // Routing Fragmentation Mitigation heuristic:
872 // Routing fragmentation across many payment paths increases the overall routing
873 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
874 // Taking too many smaller paths also increases the chance of payment failure.
875 // Thus to avoid this effect, we require from our collected links to provide
876 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
878 // This requirement is currently 5% of the remaining-to-be-collected value.
879 // This means as we successfully advance in our collection,
880 // the absolute liquidity contribution is lowered,
881 // thus increasing the number of potential channels to be selected.
883 // Derive the minimal liquidity contribution with a ratio of 20 (5%, rounded up)
884 // or 100% if we're not allowed to do multipath payments.
885 let minimal_value_contribution_msat: u64 = if allow_mpp {
886 (recommended_value_msat - already_collected_value_msat + 19) / 20
890 // Verify the liquidity offered by this channel complies to the minimal contribution.
891 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
893 // Do not consider candidates that exceed the maximum total cltv expiry limit.
894 // In order to already account for some of the privacy enhancing random CLTV
895 // expiry delta offset we add on top later, we subtract a rough estimate
896 // (2*MEDIAN_HOP_CLTV_EXPIRY_DELTA) here.
897 let max_total_cltv_expiry_delta = (payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta)
898 .checked_sub(2*MEDIAN_HOP_CLTV_EXPIRY_DELTA)
899 .unwrap_or(payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta);
900 let hop_total_cltv_delta = ($next_hops_cltv_delta as u32)
901 .saturating_add($candidate.cltv_expiry_delta());
902 let doesnt_exceed_cltv_delta_limit = hop_total_cltv_delta <= max_total_cltv_expiry_delta;
904 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
905 // Includes paying fees for the use of the following channels.
906 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
907 Some(result) => result,
908 // Can't overflow due to how the values were computed right above.
909 None => unreachable!(),
911 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
912 let over_path_minimum_msat = amount_to_transfer_over_msat >= $candidate.htlc_minimum_msat() &&
913 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
915 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
916 // bother considering this channel.
917 // Since we're choosing amount_to_transfer_over_msat as maximum possible, it can
918 // be only reduced later (not increased), so this channel should just be skipped
919 // as not sufficient.
920 if !over_path_minimum_msat && doesnt_exceed_cltv_delta_limit {
921 hit_minimum_limit = true;
922 } else if contributes_sufficient_value && doesnt_exceed_cltv_delta_limit {
923 // Note that low contribution here (limited by available_liquidity_msat)
924 // might violate htlc_minimum_msat on the hops which are next along the
925 // payment path (upstream to the payee). To avoid that, we recompute
926 // path fees knowing the final path contribution after constructing it.
927 let path_htlc_minimum_msat = compute_fees($next_hops_path_htlc_minimum_msat, $candidate.fees())
928 .and_then(|fee_msat| fee_msat.checked_add($next_hops_path_htlc_minimum_msat))
929 .map(|fee_msat| cmp::max(fee_msat, $candidate.htlc_minimum_msat()))
930 .unwrap_or_else(|| u64::max_value());
931 let hm_entry = dist.entry($src_node_id);
932 let old_entry = hm_entry.or_insert_with(|| {
933 // If there was previously no known way to access the source node
934 // (recall it goes payee-to-payer) of short_channel_id, first add a
935 // semi-dummy record just to compute the fees to reach the source node.
936 // This will affect our decision on selecting short_channel_id
937 // as a way to reach the $dest_node_id.
938 let mut fee_base_msat = 0;
939 let mut fee_proportional_millionths = 0;
940 if let Some(Some(fees)) = network_nodes.get(&$src_node_id).map(|node| node.lowest_inbound_channel_fees) {
941 fee_base_msat = fees.base_msat;
942 fee_proportional_millionths = fees.proportional_millionths;
945 node_id: $dest_node_id.clone(),
946 candidate: $candidate.clone(),
948 src_lowest_inbound_fees: RoutingFees {
949 base_msat: fee_base_msat,
950 proportional_millionths: fee_proportional_millionths,
952 next_hops_fee_msat: u64::max_value(),
953 hop_use_fee_msat: u64::max_value(),
954 total_fee_msat: u64::max_value(),
955 path_htlc_minimum_msat,
956 path_penalty_msat: u64::max_value(),
957 was_processed: false,
958 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
959 value_contribution_msat,
963 #[allow(unused_mut)] // We only use the mut in cfg(test)
964 let mut should_process = !old_entry.was_processed;
965 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
967 // In test/fuzzing builds, we do extra checks to make sure the skipping
968 // of already-seen nodes only happens in cases we expect (see below).
969 if !should_process { should_process = true; }
973 let mut hop_use_fee_msat = 0;
974 let mut total_fee_msat = $next_hops_fee_msat;
976 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
977 // will have the same effective-fee
978 if $src_node_id != our_node_id {
979 match compute_fees(amount_to_transfer_over_msat, $candidate.fees()) {
980 // max_value means we'll always fail
981 // the old_entry.total_fee_msat > total_fee_msat check
982 None => total_fee_msat = u64::max_value(),
984 hop_use_fee_msat = fee_msat;
985 total_fee_msat += hop_use_fee_msat;
986 // When calculating the lowest inbound fees to a node, we
987 // calculate fees here not based on the actual value we think
988 // will flow over this channel, but on the minimum value that
989 // we'll accept flowing over it. The minimum accepted value
990 // is a constant through each path collection run, ensuring
991 // consistent basis. Otherwise we may later find a
992 // different path to the source node that is more expensive,
993 // but which we consider to be cheaper because we are capacity
994 // constrained and the relative fee becomes lower.
995 match compute_fees(minimal_value_contribution_msat, old_entry.src_lowest_inbound_fees)
996 .map(|a| a.checked_add(total_fee_msat)) {
1001 total_fee_msat = u64::max_value();
1008 let path_penalty_msat = $next_hops_path_penalty_msat.saturating_add(
1009 scorer.channel_penalty_msat(short_channel_id, amount_to_transfer_over_msat,
1010 *available_liquidity_msat, &$src_node_id, &$dest_node_id));
1011 let new_graph_node = RouteGraphNode {
1012 node_id: $src_node_id,
1013 lowest_fee_to_peer_through_node: total_fee_msat,
1014 lowest_fee_to_node: $next_hops_fee_msat as u64 + hop_use_fee_msat,
1015 total_cltv_delta: hop_total_cltv_delta,
1016 value_contribution_msat: value_contribution_msat,
1017 path_htlc_minimum_msat,
1021 // Update the way of reaching $src_node_id with the given short_channel_id (from $dest_node_id),
1022 // if this way is cheaper than the already known
1023 // (considering the cost to "reach" this channel from the route destination,
1024 // the cost of using this channel,
1025 // and the cost of routing to the source node of this channel).
1026 // Also, consider that htlc_minimum_msat_difference, because we might end up
1027 // paying it. Consider the following exploit:
1028 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
1029 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
1030 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
1031 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
1033 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
1034 // but it may require additional tracking - we don't want to double-count
1035 // the fees included in $next_hops_path_htlc_minimum_msat, but also
1036 // can't use something that may decrease on future hops.
1037 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat)
1038 .saturating_add(old_entry.path_penalty_msat);
1039 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat)
1040 .saturating_add(path_penalty_msat);
1042 if !old_entry.was_processed && new_cost < old_cost {
1043 targets.push(new_graph_node);
1044 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
1045 old_entry.hop_use_fee_msat = hop_use_fee_msat;
1046 old_entry.total_fee_msat = total_fee_msat;
1047 old_entry.node_id = $dest_node_id.clone();
1048 old_entry.candidate = $candidate.clone();
1049 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
1050 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
1051 old_entry.path_penalty_msat = path_penalty_msat;
1052 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
1054 old_entry.value_contribution_msat = value_contribution_msat;
1056 did_add_update_path_to_src_node = true;
1057 } else if old_entry.was_processed && new_cost < old_cost {
1058 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
1060 // If we're skipping processing a node which was previously
1061 // processed even though we found another path to it with a
1062 // cheaper fee, check that it was because the second path we
1063 // found (which we are processing now) has a lower value
1064 // contribution due to an HTLC minimum limit.
1066 // e.g. take a graph with two paths from node 1 to node 2, one
1067 // through channel A, and one through channel B. Channel A and
1068 // B are both in the to-process heap, with their scores set by
1069 // a higher htlc_minimum than fee.
1070 // Channel A is processed first, and the channels onwards from
1071 // node 1 are added to the to-process heap. Thereafter, we pop
1072 // Channel B off of the heap, note that it has a much more
1073 // restrictive htlc_maximum_msat, and recalculate the fees for
1074 // all of node 1's channels using the new, reduced, amount.
1076 // This would be bogus - we'd be selecting a higher-fee path
1077 // with a lower htlc_maximum_msat instead of the one we'd
1078 // already decided to use.
1079 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
1081 value_contribution_msat + path_penalty_msat <
1082 old_entry.value_contribution_msat + old_entry.path_penalty_msat
1090 did_add_update_path_to_src_node
1094 let empty_node_features = NodeFeatures::empty();
1095 // Find ways (channels with destination) to reach a given node and store them
1096 // in the corresponding data structures (routing graph etc).
1097 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
1098 // meaning how much will be paid in fees after this node (to the best of our knowledge).
1099 // This data can later be helpful to optimize routing (pay lower fees).
1100 macro_rules! add_entries_to_cheapest_to_target_node {
1101 ( $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 ) => {
1102 let skip_node = if let Some(elem) = dist.get_mut(&$node_id) {
1103 let was_processed = elem.was_processed;
1104 elem.was_processed = true;
1107 // Entries are added to dist in add_entry!() when there is a channel from a node.
1108 // Because there are no channels from payee, it will not have a dist entry at this point.
1109 // If we're processing any other node, it is always be the result of a channel from it.
1110 assert_eq!($node_id, payee_node_id);
1115 if let Some(first_channels) = first_hop_targets.get(&$node_id) {
1116 for details in first_channels {
1117 let candidate = CandidateRouteHop::FirstHop { details };
1118 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);
1122 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
1125 &empty_node_features
1128 if !features.requires_unknown_bits() {
1129 for chan_id in $node.channels.iter() {
1130 let chan = network_channels.get(chan_id).unwrap();
1131 if !chan.features.requires_unknown_bits() {
1132 let (directed_channel, source) =
1133 chan.as_directed_to(&$node_id).expect("inconsistent NetworkGraph");
1134 if first_hops.is_none() || *source != our_node_id {
1135 if let Some(direction) = directed_channel.direction() {
1136 if direction.enabled {
1137 let candidate = CandidateRouteHop::PublicHop {
1138 info: directed_channel.with_update().unwrap(),
1139 short_channel_id: *chan_id,
1141 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);
1152 let mut payment_paths = Vec::<PaymentPath>::new();
1154 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
1155 'paths_collection: loop {
1156 // For every new path, start from scratch, except
1157 // bookkept_channels_liquidity_available_msat, which will improve
1158 // the further iterations of path finding. Also don't erase first_hop_targets.
1161 hit_minimum_limit = false;
1163 // If first hop is a private channel and the only way to reach the payee, this is the only
1164 // place where it could be added.
1165 if let Some(first_channels) = first_hop_targets.get(&payee_node_id) {
1166 for details in first_channels {
1167 let candidate = CandidateRouteHop::FirstHop { details };
1168 let added = add_entry!(candidate, our_node_id, payee_node_id, 0, path_value_msat, 0, 0u64, 0);
1169 log_trace!(logger, "{} direct route to payee via SCID {}", if added { "Added" } else { "Skipped" }, candidate.short_channel_id());
1173 // Add the payee as a target, so that the payee-to-payer
1174 // search algorithm knows what to start with.
1175 match network_nodes.get(&payee_node_id) {
1176 // The payee is not in our network graph, so nothing to add here.
1177 // There is still a chance of reaching them via last_hops though,
1178 // so don't yet fail the payment here.
1179 // If not, targets.pop() will not even let us enter the loop in step 2.
1182 add_entries_to_cheapest_to_target_node!(node, payee_node_id, 0, path_value_msat, 0, 0u64, 0);
1187 // If a caller provided us with last hops, add them to routing targets. Since this happens
1188 // earlier than general path finding, they will be somewhat prioritized, although currently
1189 // it matters only if the fees are exactly the same.
1190 for route in payment_params.route_hints.iter().filter(|route| !route.0.is_empty()) {
1191 let first_hop_in_route = &(route.0)[0];
1192 let have_hop_src_in_graph =
1193 // Only add the hops in this route to our candidate set if either
1194 // we have a direct channel to the first hop or the first hop is
1195 // in the regular network graph.
1196 first_hop_targets.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some() ||
1197 network_nodes.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some();
1198 if have_hop_src_in_graph {
1199 // We start building the path from reverse, i.e., from payee
1200 // to the first RouteHintHop in the path.
1201 let hop_iter = route.0.iter().rev();
1202 let prev_hop_iter = core::iter::once(&payment_params.payee_pubkey).chain(
1203 route.0.iter().skip(1).rev().map(|hop| &hop.src_node_id));
1204 let mut hop_used = true;
1205 let mut aggregate_next_hops_fee_msat: u64 = 0;
1206 let mut aggregate_next_hops_path_htlc_minimum_msat: u64 = 0;
1207 let mut aggregate_next_hops_path_penalty_msat: u64 = 0;
1208 let mut aggregate_next_hops_cltv_delta: u32 = 0;
1210 for (idx, (hop, prev_hop_id)) in hop_iter.zip(prev_hop_iter).enumerate() {
1211 let source = NodeId::from_pubkey(&hop.src_node_id);
1212 let target = NodeId::from_pubkey(&prev_hop_id);
1213 let candidate = network_channels
1214 .get(&hop.short_channel_id)
1215 .and_then(|channel| channel.as_directed_to(&target))
1216 .and_then(|(channel, _)| channel.with_update())
1217 .map(|info| CandidateRouteHop::PublicHop {
1219 short_channel_id: hop.short_channel_id,
1221 .unwrap_or_else(|| CandidateRouteHop::PrivateHop { hint: hop });
1222 let capacity_msat = candidate.effective_capacity().as_msat();
1223 aggregate_next_hops_path_penalty_msat = aggregate_next_hops_path_penalty_msat
1224 .saturating_add(scorer.channel_penalty_msat(hop.short_channel_id, final_value_msat, capacity_msat, &source, &target));
1226 aggregate_next_hops_cltv_delta = aggregate_next_hops_cltv_delta
1227 .saturating_add(hop.cltv_expiry_delta as u32);
1229 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) {
1230 // If this hop was not used then there is no use checking the preceding hops
1231 // in the RouteHint. We can break by just searching for a direct channel between
1232 // last checked hop and first_hop_targets
1236 // Searching for a direct channel between last checked hop and first_hop_targets
1237 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&prev_hop_id)) {
1238 for details in first_channels {
1239 let candidate = CandidateRouteHop::FirstHop { details };
1240 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);
1248 // In the next values of the iterator, the aggregate fees already reflects
1249 // the sum of value sent from payer (final_value_msat) and routing fees
1250 // for the last node in the RouteHint. We need to just add the fees to
1251 // route through the current node so that the preceeding node (next iteration)
1253 let hops_fee = compute_fees(aggregate_next_hops_fee_msat + final_value_msat, hop.fees)
1254 .map_or(None, |inc| inc.checked_add(aggregate_next_hops_fee_msat));
1255 aggregate_next_hops_fee_msat = if let Some(val) = hops_fee { val } else { break; };
1257 let hop_htlc_minimum_msat = candidate.htlc_minimum_msat();
1258 let hop_htlc_minimum_msat_inc = if let Some(val) = compute_fees(aggregate_next_hops_path_htlc_minimum_msat, hop.fees) { val } else { break; };
1259 let hops_path_htlc_minimum = aggregate_next_hops_path_htlc_minimum_msat
1260 .checked_add(hop_htlc_minimum_msat_inc);
1261 aggregate_next_hops_path_htlc_minimum_msat = if let Some(val) = hops_path_htlc_minimum { cmp::max(hop_htlc_minimum_msat, val) } else { break; };
1263 if idx == route.0.len() - 1 {
1264 // The last hop in this iterator is the first hop in
1265 // overall RouteHint.
1266 // If this hop connects to a node with which we have a direct channel,
1267 // ignore the network graph and, if the last hop was added, add our
1268 // direct channel to the candidate set.
1270 // Note that we *must* check if the last hop was added as `add_entry`
1271 // always assumes that the third argument is a node to which we have a
1273 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&hop.src_node_id)) {
1274 for details in first_channels {
1275 let candidate = CandidateRouteHop::FirstHop { details };
1276 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);
1284 log_trace!(logger, "Starting main path collection loop with {} nodes pre-filled from first/last hops.", targets.len());
1286 // At this point, targets are filled with the data from first and
1287 // last hops communicated by the caller, and the payment receiver.
1288 let mut found_new_path = false;
1291 // If this loop terminates due the exhaustion of targets, two situations are possible:
1292 // - not enough outgoing liquidity:
1293 // 0 < already_collected_value_msat < final_value_msat
1294 // - enough outgoing liquidity:
1295 // final_value_msat <= already_collected_value_msat < recommended_value_msat
1296 // Both these cases (and other cases except reaching recommended_value_msat) mean that
1297 // paths_collection will be stopped because found_new_path==false.
1298 // This is not necessarily a routing failure.
1299 '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() {
1301 // Since we're going payee-to-payer, hitting our node as a target means we should stop
1302 // traversing the graph and arrange the path out of what we found.
1303 if node_id == our_node_id {
1304 let mut new_entry = dist.remove(&our_node_id).unwrap();
1305 let mut ordered_hops = vec!((new_entry.clone(), NodeFeatures::empty()));
1308 let mut features_set = false;
1309 if let Some(first_channels) = first_hop_targets.get(&ordered_hops.last().unwrap().0.node_id) {
1310 for details in first_channels {
1311 if details.short_channel_id.unwrap() == ordered_hops.last().unwrap().0.candidate.short_channel_id() {
1312 ordered_hops.last_mut().unwrap().1 = details.counterparty.features.to_context();
1313 features_set = true;
1319 if let Some(node) = network_nodes.get(&ordered_hops.last().unwrap().0.node_id) {
1320 if let Some(node_info) = node.announcement_info.as_ref() {
1321 ordered_hops.last_mut().unwrap().1 = node_info.features.clone();
1323 ordered_hops.last_mut().unwrap().1 = NodeFeatures::empty();
1326 // We can fill in features for everything except hops which were
1327 // provided via the invoice we're paying. We could guess based on the
1328 // recipient's features but for now we simply avoid guessing at all.
1332 // Means we succesfully traversed from the payer to the payee, now
1333 // save this path for the payment route. Also, update the liquidity
1334 // remaining on the used hops, so that we take them into account
1335 // while looking for more paths.
1336 if ordered_hops.last().unwrap().0.node_id == payee_node_id {
1340 new_entry = match dist.remove(&ordered_hops.last().unwrap().0.node_id) {
1341 Some(payment_hop) => payment_hop,
1342 // We can't arrive at None because, if we ever add an entry to targets,
1343 // we also fill in the entry in dist (see add_entry!).
1344 None => unreachable!(),
1346 // We "propagate" the fees one hop backward (topologically) here,
1347 // so that fees paid for a HTLC forwarding on the current channel are
1348 // associated with the previous channel (where they will be subtracted).
1349 ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
1350 ordered_hops.push((new_entry.clone(), NodeFeatures::empty()));
1352 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
1353 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
1355 log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: \n {:#?}",
1356 ordered_hops.len(), value_contribution_msat, ordered_hops.iter().map(|h| &(h.0)).collect::<Vec<&PathBuildingHop>>());
1358 let mut payment_path = PaymentPath {hops: ordered_hops};
1360 // We could have possibly constructed a slightly inconsistent path: since we reduce
1361 // value being transferred along the way, we could have violated htlc_minimum_msat
1362 // on some channels we already passed (assuming dest->source direction). Here, we
1363 // recompute the fees again, so that if that's the case, we match the currently
1364 // underpaid htlc_minimum_msat with fees.
1365 payment_path.update_value_and_recompute_fees(cmp::min(value_contribution_msat, final_value_msat));
1367 // Since a path allows to transfer as much value as
1368 // the smallest channel it has ("bottleneck"), we should recompute
1369 // the fees so sender HTLC don't overpay fees when traversing
1370 // larger channels than the bottleneck. This may happen because
1371 // when we were selecting those channels we were not aware how much value
1372 // this path will transfer, and the relative fee for them
1373 // might have been computed considering a larger value.
1374 // Remember that we used these channels so that we don't rely
1375 // on the same liquidity in future paths.
1376 let mut prevented_redundant_path_selection = false;
1377 for (payment_hop, _) in payment_path.hops.iter() {
1378 let channel_liquidity_available_msat = bookkept_channels_liquidity_available_msat.get_mut(&payment_hop.candidate.short_channel_id()).unwrap();
1379 let mut spent_on_hop_msat = value_contribution_msat;
1380 let next_hops_fee_msat = payment_hop.next_hops_fee_msat;
1381 spent_on_hop_msat += next_hops_fee_msat;
1382 if spent_on_hop_msat == *channel_liquidity_available_msat {
1383 // If this path used all of this channel's available liquidity, we know
1384 // this path will not be selected again in the next loop iteration.
1385 prevented_redundant_path_selection = true;
1387 *channel_liquidity_available_msat -= spent_on_hop_msat;
1389 if !prevented_redundant_path_selection {
1390 // If we weren't capped by hitting a liquidity limit on a channel in the path,
1391 // we'll probably end up picking the same path again on the next iteration.
1392 // Decrease the available liquidity of a hop in the middle of the path.
1393 let victim_scid = payment_path.hops[(payment_path.hops.len()) / 2].0.candidate.short_channel_id();
1394 log_trace!(logger, "Disabling channel {} for future path building iterations to avoid duplicates.", victim_scid);
1395 let victim_liquidity = bookkept_channels_liquidity_available_msat.get_mut(&victim_scid).unwrap();
1396 *victim_liquidity = 0;
1399 // Track the total amount all our collected paths allow to send so that we:
1400 // - know when to stop looking for more paths
1401 // - know which of the hops are useless considering how much more sats we need
1402 // (contributes_sufficient_value)
1403 already_collected_value_msat += value_contribution_msat;
1405 payment_paths.push(payment_path);
1406 found_new_path = true;
1407 break 'path_construction;
1410 // If we found a path back to the payee, we shouldn't try to process it again. This is
1411 // the equivalent of the `elem.was_processed` check in
1412 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
1413 if node_id == payee_node_id { continue 'path_construction; }
1415 // Otherwise, since the current target node is not us,
1416 // keep "unrolling" the payment graph from payee to payer by
1417 // finding a way to reach the current target from the payer side.
1418 match network_nodes.get(&node_id) {
1421 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);
1427 // If we don't support MPP, no use trying to gather more value ever.
1428 break 'paths_collection;
1432 // Stop either when the recommended value is reached or if no new path was found in this
1434 // In the latter case, making another path finding attempt won't help,
1435 // because we deterministically terminated the search due to low liquidity.
1436 if already_collected_value_msat >= recommended_value_msat || !found_new_path {
1437 log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
1438 already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
1439 break 'paths_collection;
1440 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
1441 // Further, if this was our first walk of the graph, and we weren't limited by an
1442 // htlc_minimum_msat, return immediately because this path should suffice. If we were
1443 // limited by an htlc_minimum_msat value, find another path with a higher value,
1444 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
1445 // still keeping a lower total fee than this path.
1446 if !hit_minimum_limit {
1447 log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
1448 break 'paths_collection;
1450 log_trace!(logger, "Collected our payment amount on the first pass, but running again to collect extra paths with a potentially higher limit.");
1451 path_value_msat = recommended_value_msat;
1456 if payment_paths.len() == 0 {
1457 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1460 if already_collected_value_msat < final_value_msat {
1461 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1464 // Sort by total fees and take the best paths.
1465 payment_paths.sort_unstable_by_key(|path| path.get_total_fee_paid_msat());
1466 if payment_paths.len() > 50 {
1467 payment_paths.truncate(50);
1470 // Draw multiple sufficient routes by randomly combining the selected paths.
1471 let mut drawn_routes = Vec::new();
1472 let mut prng = ChaCha20::new(random_seed_bytes, &[0u8; 12]);
1473 let mut random_index_bytes = [0u8; ::core::mem::size_of::<usize>()];
1475 let num_permutations = payment_paths.len();
1476 for _ in 0..num_permutations {
1477 let mut cur_route = Vec::<PaymentPath>::new();
1478 let mut aggregate_route_value_msat = 0;
1481 // Do a Fisher-Yates shuffle to create a random permutation of the payment paths
1482 for cur_index in (1..payment_paths.len()).rev() {
1483 prng.process_in_place(&mut random_index_bytes);
1484 let random_index = usize::from_be_bytes(random_index_bytes).wrapping_rem(cur_index+1);
1485 payment_paths.swap(cur_index, random_index);
1489 for payment_path in &payment_paths {
1490 cur_route.push(payment_path.clone());
1491 aggregate_route_value_msat += payment_path.get_value_msat();
1492 if aggregate_route_value_msat > final_value_msat {
1493 // Last path likely overpaid. Substract it from the most expensive
1494 // (in terms of proportional fee) path in this route and recompute fees.
1495 // This might be not the most economically efficient way, but fewer paths
1496 // also makes routing more reliable.
1497 let mut overpaid_value_msat = aggregate_route_value_msat - final_value_msat;
1499 // First, we drop some expensive low-value paths entirely if possible, since fewer
1500 // paths is better: the payment is less likely to fail. In order to do so, we sort
1501 // by value and fall back to total fees paid, i.e., in case of equal values we
1502 // prefer lower cost paths.
1503 cur_route.sort_unstable_by(|a, b| {
1504 a.get_value_msat().cmp(&b.get_value_msat())
1505 // Reverse ordering for fees, so we drop higher-fee paths first
1506 .then_with(|| b.get_total_fee_paid_msat().saturating_add(b.get_path_penalty_msat())
1507 .cmp(&a.get_total_fee_paid_msat().saturating_add(a.get_path_penalty_msat())))
1510 // We should make sure that at least 1 path left.
1511 let mut paths_left = cur_route.len();
1512 cur_route.retain(|path| {
1513 if paths_left == 1 {
1516 let mut keep = true;
1517 let path_value_msat = path.get_value_msat();
1518 if path_value_msat <= overpaid_value_msat {
1520 overpaid_value_msat -= path_value_msat;
1526 if overpaid_value_msat == 0 {
1530 assert!(cur_route.len() > 0);
1533 // Now, subtract the overpaid value from the most-expensive path.
1534 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1535 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1536 cur_route.sort_unstable_by_key(|path| { path.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>() });
1537 let expensive_payment_path = cur_route.first_mut().unwrap();
1539 // We already dropped all the small value paths above, meaning all the
1540 // remaining paths are larger than remaining overpaid_value_msat.
1541 // Thus, this can't be negative.
1542 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
1543 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
1547 drawn_routes.push(cur_route);
1551 // Select the best route by lowest total fee.
1552 drawn_routes.sort_unstable_by_key(|paths| paths.iter().map(|path| path.get_total_fee_paid_msat()).sum::<u64>());
1553 let mut selected_paths = Vec::<Vec<Result<RouteHop, LightningError>>>::new();
1554 for payment_path in drawn_routes.first().unwrap() {
1555 let mut path = payment_path.hops.iter().map(|(payment_hop, node_features)| {
1557 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)})?,
1558 node_features: node_features.clone(),
1559 short_channel_id: payment_hop.candidate.short_channel_id(),
1560 channel_features: payment_hop.candidate.features(),
1561 fee_msat: payment_hop.fee_msat,
1562 cltv_expiry_delta: payment_hop.candidate.cltv_expiry_delta(),
1564 }).collect::<Vec<_>>();
1565 // Propagate the cltv_expiry_delta one hop backwards since the delta from the current hop is
1566 // applicable for the previous hop.
1567 path.iter_mut().rev().fold(final_cltv_expiry_delta, |prev_cltv_expiry_delta, hop| {
1568 core::mem::replace(&mut hop.as_mut().unwrap().cltv_expiry_delta, prev_cltv_expiry_delta)
1570 selected_paths.push(path);
1573 if let Some(features) = &payment_params.features {
1574 for path in selected_paths.iter_mut() {
1575 if let Ok(route_hop) = path.last_mut().unwrap() {
1576 route_hop.node_features = features.to_context();
1582 paths: selected_paths.into_iter().map(|path| path.into_iter().collect()).collect::<Result<Vec<_>, _>>()?,
1583 payment_params: Some(payment_params.clone()),
1585 log_info!(logger, "Got route to {}: {}", payment_params.payee_pubkey, log_route!(route));
1589 // When an adversarial intermediary node observes a payment, it may be able to infer its
1590 // destination, if the remaining CLTV expiry delta exactly matches a feasible path in the network
1591 // graph. In order to improve privacy, this method obfuscates the CLTV expiry deltas along the
1592 // payment path by adding a randomized 'shadow route' offset to the final hop.
1593 fn add_random_cltv_offset(route: &mut Route, payment_params: &PaymentParameters, network_graph: &ReadOnlyNetworkGraph, random_seed_bytes: &[u8; 32]) {
1594 let network_channels = network_graph.channels();
1595 let network_nodes = network_graph.nodes();
1597 for path in route.paths.iter_mut() {
1598 let mut shadow_ctlv_expiry_delta_offset: u32 = 0;
1600 // Remember the last three nodes of the random walk and avoid looping back on them.
1601 // Init with the last three nodes from the actual path, if possible.
1602 let mut nodes_to_avoid: [NodeId; 3] = [NodeId::from_pubkey(&path.last().unwrap().pubkey),
1603 NodeId::from_pubkey(&path.get(path.len().saturating_sub(2)).unwrap().pubkey),
1604 NodeId::from_pubkey(&path.get(path.len().saturating_sub(3)).unwrap().pubkey)];
1606 // Choose the last publicly known node as the starting point for the random walk.
1607 let mut cur_hop: Option<NodeId> = None;
1608 let mut path_nonce = [0u8; 12];
1609 if let Some(starting_hop) = path.iter().rev()
1610 .find(|h| network_nodes.contains_key(&NodeId::from_pubkey(&h.pubkey))) {
1611 cur_hop = Some(NodeId::from_pubkey(&starting_hop.pubkey));
1612 path_nonce.copy_from_slice(&cur_hop.unwrap().as_slice()[..12]);
1615 // Init PRNG with the path-dependant nonce, which is static for private paths.
1616 let mut prng = ChaCha20::new(random_seed_bytes, &path_nonce);
1617 let mut random_path_bytes = [0u8; ::core::mem::size_of::<usize>()];
1619 // Pick a random path length in [1 .. 3]
1620 prng.process_in_place(&mut random_path_bytes);
1621 let random_walk_length = usize::from_be_bytes(random_path_bytes).wrapping_rem(3).wrapping_add(1);
1623 for random_hop in 0..random_walk_length {
1624 // If we don't find a suitable offset in the public network graph, we default to
1625 // MEDIAN_HOP_CLTV_EXPIRY_DELTA.
1626 let mut random_hop_offset = MEDIAN_HOP_CLTV_EXPIRY_DELTA;
1628 if let Some(cur_node_id) = cur_hop {
1629 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
1630 // Randomly choose the next unvisited hop.
1631 prng.process_in_place(&mut random_path_bytes);
1632 if let Some(random_channel) = usize::from_be_bytes(random_path_bytes)
1633 .checked_rem(cur_node.channels.len())
1634 .and_then(|index| cur_node.channels.get(index))
1635 .and_then(|id| network_channels.get(id)) {
1636 random_channel.as_directed_from(&cur_node_id).map(|(dir_info, next_id)| {
1637 if !nodes_to_avoid.iter().any(|x| x == next_id) {
1638 nodes_to_avoid[random_hop] = *next_id;
1639 dir_info.direction().map(|channel_update_info| {
1640 random_hop_offset = channel_update_info.cltv_expiry_delta.into();
1641 cur_hop = Some(*next_id);
1649 shadow_ctlv_expiry_delta_offset = shadow_ctlv_expiry_delta_offset
1650 .checked_add(random_hop_offset)
1651 .unwrap_or(shadow_ctlv_expiry_delta_offset);
1654 // Limit the total offset to reduce the worst-case locked liquidity timevalue
1655 const MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET: u32 = 3*144;
1656 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET);
1658 // Limit the offset so we never exceed the max_total_cltv_expiry_delta. To improve plausibility,
1659 // we choose the limit to be the largest possible multiple of MEDIAN_HOP_CLTV_EXPIRY_DELTA.
1660 let path_total_cltv_expiry_delta: u32 = path.iter().map(|h| h.cltv_expiry_delta).sum();
1661 let mut max_path_offset = payment_params.max_total_cltv_expiry_delta - path_total_cltv_expiry_delta;
1662 max_path_offset = cmp::max(
1663 max_path_offset - (max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA),
1664 max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA);
1665 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, max_path_offset);
1667 // Add 'shadow' CLTV offset to the final hop
1668 if let Some(last_hop) = path.last_mut() {
1669 last_hop.cltv_expiry_delta = last_hop.cltv_expiry_delta
1670 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(last_hop.cltv_expiry_delta);
1677 use routing::network_graph::{NetworkGraph, NetGraphMsgHandler, NodeId};
1678 use routing::router::{get_route, add_random_cltv_offset, PaymentParameters, Route, RouteHint, RouteHintHop, RouteHop, RoutingFees, DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA};
1679 use routing::scoring::Score;
1680 use chain::transaction::OutPoint;
1681 use chain::keysinterface::KeysInterface;
1682 use ln::features::{ChannelFeatures, InitFeatures, InvoiceFeatures, NodeFeatures};
1683 use ln::msgs::{ErrorAction, LightningError, OptionalField, UnsignedChannelAnnouncement, ChannelAnnouncement, RoutingMessageHandler,
1684 NodeAnnouncement, UnsignedNodeAnnouncement, ChannelUpdate, UnsignedChannelUpdate};
1685 use ln::channelmanager;
1686 use util::test_utils;
1687 use util::chacha20::ChaCha20;
1688 use util::ser::Writeable;
1690 use util::ser::Writer;
1692 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
1693 use bitcoin::hashes::Hash;
1694 use bitcoin::network::constants::Network;
1695 use bitcoin::blockdata::constants::genesis_block;
1696 use bitcoin::blockdata::script::Builder;
1697 use bitcoin::blockdata::opcodes;
1698 use bitcoin::blockdata::transaction::TxOut;
1702 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
1703 use bitcoin::secp256k1::{Secp256k1, All};
1706 use sync::{self, Arc};
1708 fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
1709 features: InitFeatures, outbound_capacity_msat: u64) -> channelmanager::ChannelDetails {
1710 channelmanager::ChannelDetails {
1711 channel_id: [0; 32],
1712 counterparty: channelmanager::ChannelCounterparty {
1715 unspendable_punishment_reserve: 0,
1716 forwarding_info: None,
1718 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
1721 inbound_scid_alias: None,
1722 channel_value_satoshis: 0,
1725 outbound_capacity_msat,
1726 inbound_capacity_msat: 42,
1727 unspendable_punishment_reserve: None,
1728 confirmations_required: None,
1729 force_close_spend_delay: None,
1730 is_outbound: true, is_funding_locked: true,
1731 is_usable: true, is_public: true,
1735 // Using the same keys for LN and BTC ids
1737 net_graph_msg_handler: &NetGraphMsgHandler<Arc<NetworkGraph>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1738 secp_ctx: &Secp256k1<All>, node_1_privkey: &SecretKey, node_2_privkey: &SecretKey, features: ChannelFeatures, short_channel_id: u64
1740 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1741 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1743 let unsigned_announcement = UnsignedChannelAnnouncement {
1745 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1749 bitcoin_key_1: node_id_1,
1750 bitcoin_key_2: node_id_2,
1751 excess_data: Vec::new(),
1754 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1755 let valid_announcement = ChannelAnnouncement {
1756 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1757 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1758 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1759 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1760 contents: unsigned_announcement.clone(),
1762 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1763 Ok(res) => assert!(res),
1769 net_graph_msg_handler: &NetGraphMsgHandler<Arc<NetworkGraph>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1770 secp_ctx: &Secp256k1<All>, node_privkey: &SecretKey, update: UnsignedChannelUpdate
1772 let msghash = hash_to_message!(&Sha256dHash::hash(&update.encode()[..])[..]);
1773 let valid_channel_update = ChannelUpdate {
1774 signature: secp_ctx.sign(&msghash, node_privkey),
1775 contents: update.clone()
1778 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1779 Ok(res) => assert!(res),
1784 fn add_or_update_node(
1785 net_graph_msg_handler: &NetGraphMsgHandler<Arc<NetworkGraph>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1786 secp_ctx: &Secp256k1<All>, node_privkey: &SecretKey, features: NodeFeatures, timestamp: u32
1788 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
1789 let unsigned_announcement = UnsignedNodeAnnouncement {
1795 addresses: Vec::new(),
1796 excess_address_data: Vec::new(),
1797 excess_data: Vec::new(),
1799 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1800 let valid_announcement = NodeAnnouncement {
1801 signature: secp_ctx.sign(&msghash, node_privkey),
1802 contents: unsigned_announcement.clone()
1805 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1811 fn get_nodes(secp_ctx: &Secp256k1<All>) -> (SecretKey, PublicKey, Vec<SecretKey>, Vec<PublicKey>) {
1812 let privkeys: Vec<SecretKey> = (2..10).map(|i| {
1813 SecretKey::from_slice(&hex::decode(format!("{:02x}", i).repeat(32)).unwrap()[..]).unwrap()
1816 let pubkeys = privkeys.iter().map(|secret| PublicKey::from_secret_key(&secp_ctx, secret)).collect();
1818 let our_privkey = SecretKey::from_slice(&hex::decode("01".repeat(32)).unwrap()[..]).unwrap();
1819 let our_id = PublicKey::from_secret_key(&secp_ctx, &our_privkey);
1821 (our_privkey, our_id, privkeys, pubkeys)
1824 fn id_to_feature_flags(id: u8) -> Vec<u8> {
1825 // Set the feature flags to the id'th odd (ie non-required) feature bit so that we can
1826 // test for it later.
1827 let idx = (id - 1) * 2 + 1;
1829 vec![1 << (idx - 8*3), 0, 0, 0]
1830 } else if idx > 8*2 {
1831 vec![1 << (idx - 8*2), 0, 0]
1832 } else if idx > 8*1 {
1833 vec![1 << (idx - 8*1), 0]
1839 fn build_graph() -> (
1841 sync::Arc<NetworkGraph>,
1842 NetGraphMsgHandler<sync::Arc<NetworkGraph>, sync::Arc<test_utils::TestChainSource>, sync::Arc<crate::util::test_utils::TestLogger>>,
1843 sync::Arc<test_utils::TestChainSource>,
1844 sync::Arc<test_utils::TestLogger>,
1846 let secp_ctx = Secp256k1::new();
1847 let logger = Arc::new(test_utils::TestLogger::new());
1848 let chain_monitor = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1849 let network_graph = Arc::new(NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash()));
1850 let net_graph_msg_handler = NetGraphMsgHandler::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
1851 // Build network from our_id to node6:
1853 // -1(1)2- node0 -1(3)2-
1855 // our_id -1(12)2- node7 -1(13)2--- node2
1857 // -1(2)2- node1 -1(4)2-
1860 // chan1 1-to-2: disabled
1861 // chan1 2-to-1: enabled, 0 fee
1863 // chan2 1-to-2: enabled, ignored fee
1864 // chan2 2-to-1: enabled, 0 fee
1866 // chan3 1-to-2: enabled, 0 fee
1867 // chan3 2-to-1: enabled, 100 msat fee
1869 // chan4 1-to-2: enabled, 100% fee
1870 // chan4 2-to-1: enabled, 0 fee
1872 // chan12 1-to-2: enabled, ignored fee
1873 // chan12 2-to-1: enabled, 0 fee
1875 // chan13 1-to-2: enabled, 200% fee
1876 // chan13 2-to-1: enabled, 0 fee
1879 // -1(5)2- node3 -1(8)2--
1883 // node2--1(6)2- node4 -1(9)2--- node6 (not in global route map)
1885 // -1(7)2- node5 -1(10)2-
1887 // Channels 5, 8, 9 and 10 are private channels.
1889 // chan5 1-to-2: enabled, 100 msat fee
1890 // chan5 2-to-1: enabled, 0 fee
1892 // chan6 1-to-2: enabled, 0 fee
1893 // chan6 2-to-1: enabled, 0 fee
1895 // chan7 1-to-2: enabled, 100% fee
1896 // chan7 2-to-1: enabled, 0 fee
1898 // chan8 1-to-2: enabled, variable fee (0 then 1000 msat)
1899 // chan8 2-to-1: enabled, 0 fee
1901 // chan9 1-to-2: enabled, 1001 msat fee
1902 // chan9 2-to-1: enabled, 0 fee
1904 // chan10 1-to-2: enabled, 0 fee
1905 // chan10 2-to-1: enabled, 0 fee
1907 // chan11 1-to-2: enabled, 0 fee
1908 // chan11 2-to-1: enabled, 0 fee
1910 let (our_privkey, _, privkeys, _) = get_nodes(&secp_ctx);
1912 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[0], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
1913 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1914 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1915 short_channel_id: 1,
1918 cltv_expiry_delta: 0,
1919 htlc_minimum_msat: 0,
1920 htlc_maximum_msat: OptionalField::Absent,
1922 fee_proportional_millionths: 0,
1923 excess_data: Vec::new()
1926 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
1928 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
1929 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1930 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1931 short_channel_id: 2,
1934 cltv_expiry_delta: (5 << 4) | 3,
1935 htlc_minimum_msat: 0,
1936 htlc_maximum_msat: OptionalField::Absent,
1937 fee_base_msat: u32::max_value(),
1938 fee_proportional_millionths: u32::max_value(),
1939 excess_data: Vec::new()
1941 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1942 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1943 short_channel_id: 2,
1946 cltv_expiry_delta: 0,
1947 htlc_minimum_msat: 0,
1948 htlc_maximum_msat: OptionalField::Absent,
1950 fee_proportional_millionths: 0,
1951 excess_data: Vec::new()
1954 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
1956 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[7], ChannelFeatures::from_le_bytes(id_to_feature_flags(12)), 12);
1957 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1958 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1959 short_channel_id: 12,
1962 cltv_expiry_delta: (5 << 4) | 3,
1963 htlc_minimum_msat: 0,
1964 htlc_maximum_msat: OptionalField::Absent,
1965 fee_base_msat: u32::max_value(),
1966 fee_proportional_millionths: u32::max_value(),
1967 excess_data: Vec::new()
1969 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1970 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1971 short_channel_id: 12,
1974 cltv_expiry_delta: 0,
1975 htlc_minimum_msat: 0,
1976 htlc_maximum_msat: OptionalField::Absent,
1978 fee_proportional_millionths: 0,
1979 excess_data: Vec::new()
1982 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], NodeFeatures::from_le_bytes(id_to_feature_flags(8)), 0);
1984 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
1985 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1986 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1987 short_channel_id: 3,
1990 cltv_expiry_delta: (3 << 4) | 1,
1991 htlc_minimum_msat: 0,
1992 htlc_maximum_msat: OptionalField::Absent,
1994 fee_proportional_millionths: 0,
1995 excess_data: Vec::new()
1997 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1998 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1999 short_channel_id: 3,
2002 cltv_expiry_delta: (3 << 4) | 2,
2003 htlc_minimum_msat: 0,
2004 htlc_maximum_msat: OptionalField::Absent,
2006 fee_proportional_millionths: 0,
2007 excess_data: Vec::new()
2010 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
2011 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2012 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2013 short_channel_id: 4,
2016 cltv_expiry_delta: (4 << 4) | 1,
2017 htlc_minimum_msat: 0,
2018 htlc_maximum_msat: OptionalField::Absent,
2020 fee_proportional_millionths: 1000000,
2021 excess_data: Vec::new()
2023 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2024 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2025 short_channel_id: 4,
2028 cltv_expiry_delta: (4 << 4) | 2,
2029 htlc_minimum_msat: 0,
2030 htlc_maximum_msat: OptionalField::Absent,
2032 fee_proportional_millionths: 0,
2033 excess_data: Vec::new()
2036 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(13)), 13);
2037 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2038 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2039 short_channel_id: 13,
2042 cltv_expiry_delta: (13 << 4) | 1,
2043 htlc_minimum_msat: 0,
2044 htlc_maximum_msat: OptionalField::Absent,
2046 fee_proportional_millionths: 2000000,
2047 excess_data: Vec::new()
2049 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2050 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2051 short_channel_id: 13,
2054 cltv_expiry_delta: (13 << 4) | 2,
2055 htlc_minimum_msat: 0,
2056 htlc_maximum_msat: OptionalField::Absent,
2058 fee_proportional_millionths: 0,
2059 excess_data: Vec::new()
2062 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
2064 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
2065 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2066 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2067 short_channel_id: 6,
2070 cltv_expiry_delta: (6 << 4) | 1,
2071 htlc_minimum_msat: 0,
2072 htlc_maximum_msat: OptionalField::Absent,
2074 fee_proportional_millionths: 0,
2075 excess_data: Vec::new()
2077 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
2078 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2079 short_channel_id: 6,
2082 cltv_expiry_delta: (6 << 4) | 2,
2083 htlc_minimum_msat: 0,
2084 htlc_maximum_msat: OptionalField::Absent,
2086 fee_proportional_millionths: 0,
2087 excess_data: Vec::new(),
2090 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(11)), 11);
2091 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
2092 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2093 short_channel_id: 11,
2096 cltv_expiry_delta: (11 << 4) | 1,
2097 htlc_minimum_msat: 0,
2098 htlc_maximum_msat: OptionalField::Absent,
2100 fee_proportional_millionths: 0,
2101 excess_data: Vec::new()
2103 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
2104 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2105 short_channel_id: 11,
2108 cltv_expiry_delta: (11 << 4) | 2,
2109 htlc_minimum_msat: 0,
2110 htlc_maximum_msat: OptionalField::Absent,
2112 fee_proportional_millionths: 0,
2113 excess_data: Vec::new()
2116 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(5)), 0);
2118 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
2120 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[5], ChannelFeatures::from_le_bytes(id_to_feature_flags(7)), 7);
2121 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2122 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2123 short_channel_id: 7,
2126 cltv_expiry_delta: (7 << 4) | 1,
2127 htlc_minimum_msat: 0,
2128 htlc_maximum_msat: OptionalField::Absent,
2130 fee_proportional_millionths: 1000000,
2131 excess_data: Vec::new()
2133 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[5], UnsignedChannelUpdate {
2134 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2135 short_channel_id: 7,
2138 cltv_expiry_delta: (7 << 4) | 2,
2139 htlc_minimum_msat: 0,
2140 htlc_maximum_msat: OptionalField::Absent,
2142 fee_proportional_millionths: 0,
2143 excess_data: Vec::new()
2146 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[5], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
2148 (secp_ctx, network_graph, net_graph_msg_handler, chain_monitor, logger)
2152 fn simple_route_test() {
2153 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2154 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2155 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2156 let scorer = test_utils::TestScorer::with_penalty(0);
2157 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2158 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2160 // Simple route to 2 via 1
2162 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) {
2163 assert_eq!(err, "Cannot send a payment of 0 msat");
2164 } else { panic!(); }
2166 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2167 assert_eq!(route.paths[0].len(), 2);
2169 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2170 assert_eq!(route.paths[0][0].short_channel_id, 2);
2171 assert_eq!(route.paths[0][0].fee_msat, 100);
2172 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2173 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2174 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2176 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2177 assert_eq!(route.paths[0][1].short_channel_id, 4);
2178 assert_eq!(route.paths[0][1].fee_msat, 100);
2179 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2180 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2181 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2185 fn invalid_first_hop_test() {
2186 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2187 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2188 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2189 let scorer = test_utils::TestScorer::with_penalty(0);
2190 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2191 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2193 // Simple route to 2 via 1
2195 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
2197 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) =
2198 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) {
2199 assert_eq!(err, "First hop cannot have our_node_pubkey as a destination.");
2200 } else { panic!(); }
2202 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2203 assert_eq!(route.paths[0].len(), 2);
2207 fn htlc_minimum_test() {
2208 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2209 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2210 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2211 let scorer = test_utils::TestScorer::with_penalty(0);
2212 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2213 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2215 // Simple route to 2 via 1
2217 // Disable other paths
2218 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2219 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2220 short_channel_id: 12,
2222 flags: 2, // to disable
2223 cltv_expiry_delta: 0,
2224 htlc_minimum_msat: 0,
2225 htlc_maximum_msat: OptionalField::Absent,
2227 fee_proportional_millionths: 0,
2228 excess_data: Vec::new()
2230 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2231 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2232 short_channel_id: 3,
2234 flags: 2, // to disable
2235 cltv_expiry_delta: 0,
2236 htlc_minimum_msat: 0,
2237 htlc_maximum_msat: OptionalField::Absent,
2239 fee_proportional_millionths: 0,
2240 excess_data: Vec::new()
2242 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2243 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2244 short_channel_id: 13,
2246 flags: 2, // to disable
2247 cltv_expiry_delta: 0,
2248 htlc_minimum_msat: 0,
2249 htlc_maximum_msat: OptionalField::Absent,
2251 fee_proportional_millionths: 0,
2252 excess_data: Vec::new()
2254 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2255 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2256 short_channel_id: 6,
2258 flags: 2, // to disable
2259 cltv_expiry_delta: 0,
2260 htlc_minimum_msat: 0,
2261 htlc_maximum_msat: OptionalField::Absent,
2263 fee_proportional_millionths: 0,
2264 excess_data: Vec::new()
2266 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2267 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2268 short_channel_id: 7,
2270 flags: 2, // to disable
2271 cltv_expiry_delta: 0,
2272 htlc_minimum_msat: 0,
2273 htlc_maximum_msat: OptionalField::Absent,
2275 fee_proportional_millionths: 0,
2276 excess_data: Vec::new()
2279 // Check against amount_to_transfer_over_msat.
2280 // Set minimal HTLC of 200_000_000 msat.
2281 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2282 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2283 short_channel_id: 2,
2286 cltv_expiry_delta: 0,
2287 htlc_minimum_msat: 200_000_000,
2288 htlc_maximum_msat: OptionalField::Absent,
2290 fee_proportional_millionths: 0,
2291 excess_data: Vec::new()
2294 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
2296 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2297 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2298 short_channel_id: 4,
2301 cltv_expiry_delta: 0,
2302 htlc_minimum_msat: 0,
2303 htlc_maximum_msat: OptionalField::Present(199_999_999),
2305 fee_proportional_millionths: 0,
2306 excess_data: Vec::new()
2309 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
2310 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) {
2311 assert_eq!(err, "Failed to find a path to the given destination");
2312 } else { panic!(); }
2314 // Lift the restriction on the first hop.
2315 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2316 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2317 short_channel_id: 2,
2320 cltv_expiry_delta: 0,
2321 htlc_minimum_msat: 0,
2322 htlc_maximum_msat: OptionalField::Absent,
2324 fee_proportional_millionths: 0,
2325 excess_data: Vec::new()
2328 // A payment above the minimum should pass
2329 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();
2330 assert_eq!(route.paths[0].len(), 2);
2334 fn htlc_minimum_overpay_test() {
2335 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2336 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2337 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
2338 let scorer = test_utils::TestScorer::with_penalty(0);
2339 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2340 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2342 // A route to node#2 via two paths.
2343 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
2344 // Thus, they can't send 60 without overpaying.
2345 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2346 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2347 short_channel_id: 2,
2350 cltv_expiry_delta: 0,
2351 htlc_minimum_msat: 35_000,
2352 htlc_maximum_msat: OptionalField::Present(40_000),
2354 fee_proportional_millionths: 0,
2355 excess_data: Vec::new()
2357 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2358 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2359 short_channel_id: 12,
2362 cltv_expiry_delta: 0,
2363 htlc_minimum_msat: 35_000,
2364 htlc_maximum_msat: OptionalField::Present(40_000),
2366 fee_proportional_millionths: 0,
2367 excess_data: Vec::new()
2371 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2372 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2373 short_channel_id: 13,
2376 cltv_expiry_delta: 0,
2377 htlc_minimum_msat: 0,
2378 htlc_maximum_msat: OptionalField::Absent,
2380 fee_proportional_millionths: 0,
2381 excess_data: Vec::new()
2383 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2384 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2385 short_channel_id: 4,
2388 cltv_expiry_delta: 0,
2389 htlc_minimum_msat: 0,
2390 htlc_maximum_msat: OptionalField::Absent,
2392 fee_proportional_millionths: 0,
2393 excess_data: Vec::new()
2396 // Disable other paths
2397 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2398 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2399 short_channel_id: 1,
2401 flags: 2, // to disable
2402 cltv_expiry_delta: 0,
2403 htlc_minimum_msat: 0,
2404 htlc_maximum_msat: OptionalField::Absent,
2406 fee_proportional_millionths: 0,
2407 excess_data: Vec::new()
2410 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 60_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2411 // Overpay fees to hit htlc_minimum_msat.
2412 let overpaid_fees = route.paths[0][0].fee_msat + route.paths[1][0].fee_msat;
2413 // TODO: this could be better balanced to overpay 10k and not 15k.
2414 assert_eq!(overpaid_fees, 15_000);
2416 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
2417 // while taking even more fee to match htlc_minimum_msat.
2418 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2419 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2420 short_channel_id: 12,
2423 cltv_expiry_delta: 0,
2424 htlc_minimum_msat: 65_000,
2425 htlc_maximum_msat: OptionalField::Present(80_000),
2427 fee_proportional_millionths: 0,
2428 excess_data: Vec::new()
2430 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2431 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2432 short_channel_id: 2,
2435 cltv_expiry_delta: 0,
2436 htlc_minimum_msat: 0,
2437 htlc_maximum_msat: OptionalField::Absent,
2439 fee_proportional_millionths: 0,
2440 excess_data: Vec::new()
2442 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2443 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2444 short_channel_id: 4,
2447 cltv_expiry_delta: 0,
2448 htlc_minimum_msat: 0,
2449 htlc_maximum_msat: OptionalField::Absent,
2451 fee_proportional_millionths: 100_000,
2452 excess_data: Vec::new()
2455 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 60_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2456 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
2457 assert_eq!(route.paths.len(), 1);
2458 assert_eq!(route.paths[0][0].short_channel_id, 12);
2459 let fees = route.paths[0][0].fee_msat;
2460 assert_eq!(fees, 5_000);
2462 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2463 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
2464 // the other channel.
2465 assert_eq!(route.paths.len(), 1);
2466 assert_eq!(route.paths[0][0].short_channel_id, 2);
2467 let fees = route.paths[0][0].fee_msat;
2468 assert_eq!(fees, 5_000);
2472 fn disable_channels_test() {
2473 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2474 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2475 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2476 let scorer = test_utils::TestScorer::with_penalty(0);
2477 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2478 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2480 // // Disable channels 4 and 12 by flags=2
2481 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2482 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2483 short_channel_id: 4,
2485 flags: 2, // to disable
2486 cltv_expiry_delta: 0,
2487 htlc_minimum_msat: 0,
2488 htlc_maximum_msat: OptionalField::Absent,
2490 fee_proportional_millionths: 0,
2491 excess_data: Vec::new()
2493 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2494 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2495 short_channel_id: 12,
2497 flags: 2, // to disable
2498 cltv_expiry_delta: 0,
2499 htlc_minimum_msat: 0,
2500 htlc_maximum_msat: OptionalField::Absent,
2502 fee_proportional_millionths: 0,
2503 excess_data: Vec::new()
2506 // If all the channels require some features we don't understand, route should fail
2507 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) {
2508 assert_eq!(err, "Failed to find a path to the given destination");
2509 } else { panic!(); }
2511 // If we specify a channel to node7, that overrides our local channel view and that gets used
2512 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2513 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();
2514 assert_eq!(route.paths[0].len(), 2);
2516 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2517 assert_eq!(route.paths[0][0].short_channel_id, 42);
2518 assert_eq!(route.paths[0][0].fee_msat, 200);
2519 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2520 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2521 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2523 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2524 assert_eq!(route.paths[0][1].short_channel_id, 13);
2525 assert_eq!(route.paths[0][1].fee_msat, 100);
2526 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2527 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2528 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2532 fn disable_node_test() {
2533 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2534 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2535 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2536 let scorer = test_utils::TestScorer::with_penalty(0);
2537 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2538 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2540 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
2541 let mut unknown_features = NodeFeatures::known();
2542 unknown_features.set_unknown_feature_required();
2543 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
2544 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
2545 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
2547 // If all nodes require some features we don't understand, route should fail
2548 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) {
2549 assert_eq!(err, "Failed to find a path to the given destination");
2550 } else { panic!(); }
2552 // If we specify a channel to node7, that overrides our local channel view and that gets used
2553 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2554 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();
2555 assert_eq!(route.paths[0].len(), 2);
2557 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2558 assert_eq!(route.paths[0][0].short_channel_id, 42);
2559 assert_eq!(route.paths[0][0].fee_msat, 200);
2560 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2561 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2562 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2564 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2565 assert_eq!(route.paths[0][1].short_channel_id, 13);
2566 assert_eq!(route.paths[0][1].fee_msat, 100);
2567 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2568 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2569 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2571 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
2572 // naively) assume that the user checked the feature bits on the invoice, which override
2573 // the node_announcement.
2577 fn our_chans_test() {
2578 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2579 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2580 let scorer = test_utils::TestScorer::with_penalty(0);
2581 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2582 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2584 // Route to 1 via 2 and 3 because our channel to 1 is disabled
2585 let payment_params = PaymentParameters::from_node_id(nodes[0]);
2586 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2587 assert_eq!(route.paths[0].len(), 3);
2589 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2590 assert_eq!(route.paths[0][0].short_channel_id, 2);
2591 assert_eq!(route.paths[0][0].fee_msat, 200);
2592 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2593 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2594 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2596 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2597 assert_eq!(route.paths[0][1].short_channel_id, 4);
2598 assert_eq!(route.paths[0][1].fee_msat, 100);
2599 assert_eq!(route.paths[0][1].cltv_expiry_delta, (3 << 4) | 2);
2600 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2601 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2603 assert_eq!(route.paths[0][2].pubkey, nodes[0]);
2604 assert_eq!(route.paths[0][2].short_channel_id, 3);
2605 assert_eq!(route.paths[0][2].fee_msat, 100);
2606 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
2607 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(1));
2608 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(3));
2610 // If we specify a channel to node7, that overrides our local channel view and that gets used
2611 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2612 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2613 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();
2614 assert_eq!(route.paths[0].len(), 2);
2616 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2617 assert_eq!(route.paths[0][0].short_channel_id, 42);
2618 assert_eq!(route.paths[0][0].fee_msat, 200);
2619 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2620 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2621 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2623 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2624 assert_eq!(route.paths[0][1].short_channel_id, 13);
2625 assert_eq!(route.paths[0][1].fee_msat, 100);
2626 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2627 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2628 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2631 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2632 let zero_fees = RoutingFees {
2634 proportional_millionths: 0,
2636 vec![RouteHint(vec![RouteHintHop {
2637 src_node_id: nodes[3],
2638 short_channel_id: 8,
2640 cltv_expiry_delta: (8 << 4) | 1,
2641 htlc_minimum_msat: None,
2642 htlc_maximum_msat: None,
2644 ]), RouteHint(vec![RouteHintHop {
2645 src_node_id: nodes[4],
2646 short_channel_id: 9,
2649 proportional_millionths: 0,
2651 cltv_expiry_delta: (9 << 4) | 1,
2652 htlc_minimum_msat: None,
2653 htlc_maximum_msat: None,
2654 }]), RouteHint(vec![RouteHintHop {
2655 src_node_id: nodes[5],
2656 short_channel_id: 10,
2658 cltv_expiry_delta: (10 << 4) | 1,
2659 htlc_minimum_msat: None,
2660 htlc_maximum_msat: None,
2664 fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2665 let zero_fees = RoutingFees {
2667 proportional_millionths: 0,
2669 vec![RouteHint(vec![RouteHintHop {
2670 src_node_id: nodes[2],
2671 short_channel_id: 5,
2674 proportional_millionths: 0,
2676 cltv_expiry_delta: (5 << 4) | 1,
2677 htlc_minimum_msat: None,
2678 htlc_maximum_msat: None,
2680 src_node_id: nodes[3],
2681 short_channel_id: 8,
2683 cltv_expiry_delta: (8 << 4) | 1,
2684 htlc_minimum_msat: None,
2685 htlc_maximum_msat: None,
2687 ]), RouteHint(vec![RouteHintHop {
2688 src_node_id: nodes[4],
2689 short_channel_id: 9,
2692 proportional_millionths: 0,
2694 cltv_expiry_delta: (9 << 4) | 1,
2695 htlc_minimum_msat: None,
2696 htlc_maximum_msat: None,
2697 }]), RouteHint(vec![RouteHintHop {
2698 src_node_id: nodes[5],
2699 short_channel_id: 10,
2701 cltv_expiry_delta: (10 << 4) | 1,
2702 htlc_minimum_msat: None,
2703 htlc_maximum_msat: None,
2708 fn partial_route_hint_test() {
2709 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2710 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2711 let scorer = test_utils::TestScorer::with_penalty(0);
2712 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2713 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2715 // Simple test across 2, 3, 5, and 4 via a last_hop channel
2716 // Tests the behaviour when the RouteHint contains a suboptimal hop.
2717 // RouteHint may be partially used by the algo to build the best path.
2719 // First check that last hop can't have its source as the payee.
2720 let invalid_last_hop = RouteHint(vec![RouteHintHop {
2721 src_node_id: nodes[6],
2722 short_channel_id: 8,
2725 proportional_millionths: 0,
2727 cltv_expiry_delta: (8 << 4) | 1,
2728 htlc_minimum_msat: None,
2729 htlc_maximum_msat: None,
2732 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
2733 invalid_last_hops.push(invalid_last_hop);
2735 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(invalid_last_hops);
2736 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) {
2737 assert_eq!(err, "Route hint cannot have the payee as the source.");
2738 } else { panic!(); }
2741 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops_multi_private_channels(&nodes));
2742 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2743 assert_eq!(route.paths[0].len(), 5);
2745 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2746 assert_eq!(route.paths[0][0].short_channel_id, 2);
2747 assert_eq!(route.paths[0][0].fee_msat, 100);
2748 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2749 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2750 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2752 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2753 assert_eq!(route.paths[0][1].short_channel_id, 4);
2754 assert_eq!(route.paths[0][1].fee_msat, 0);
2755 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
2756 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2757 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2759 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2760 assert_eq!(route.paths[0][2].short_channel_id, 6);
2761 assert_eq!(route.paths[0][2].fee_msat, 0);
2762 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
2763 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2764 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2766 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2767 assert_eq!(route.paths[0][3].short_channel_id, 11);
2768 assert_eq!(route.paths[0][3].fee_msat, 0);
2769 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
2770 // If we have a peer in the node map, we'll use their features here since we don't have
2771 // a way of figuring out their features from the invoice:
2772 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2773 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2775 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2776 assert_eq!(route.paths[0][4].short_channel_id, 8);
2777 assert_eq!(route.paths[0][4].fee_msat, 100);
2778 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2779 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2780 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2783 fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2784 let zero_fees = RoutingFees {
2786 proportional_millionths: 0,
2788 vec![RouteHint(vec![RouteHintHop {
2789 src_node_id: nodes[3],
2790 short_channel_id: 8,
2792 cltv_expiry_delta: (8 << 4) | 1,
2793 htlc_minimum_msat: None,
2794 htlc_maximum_msat: None,
2795 }]), RouteHint(vec![
2797 ]), RouteHint(vec![RouteHintHop {
2798 src_node_id: nodes[5],
2799 short_channel_id: 10,
2801 cltv_expiry_delta: (10 << 4) | 1,
2802 htlc_minimum_msat: None,
2803 htlc_maximum_msat: None,
2808 fn ignores_empty_last_hops_test() {
2809 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2810 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2811 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(empty_last_hop(&nodes));
2812 let scorer = test_utils::TestScorer::with_penalty(0);
2813 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2814 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2816 // Test handling of an empty RouteHint passed in Invoice.
2818 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2819 assert_eq!(route.paths[0].len(), 5);
2821 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2822 assert_eq!(route.paths[0][0].short_channel_id, 2);
2823 assert_eq!(route.paths[0][0].fee_msat, 100);
2824 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2825 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2826 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2828 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2829 assert_eq!(route.paths[0][1].short_channel_id, 4);
2830 assert_eq!(route.paths[0][1].fee_msat, 0);
2831 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
2832 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2833 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2835 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2836 assert_eq!(route.paths[0][2].short_channel_id, 6);
2837 assert_eq!(route.paths[0][2].fee_msat, 0);
2838 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
2839 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2840 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2842 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2843 assert_eq!(route.paths[0][3].short_channel_id, 11);
2844 assert_eq!(route.paths[0][3].fee_msat, 0);
2845 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
2846 // If we have a peer in the node map, we'll use their features here since we don't have
2847 // a way of figuring out their features from the invoice:
2848 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2849 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2851 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2852 assert_eq!(route.paths[0][4].short_channel_id, 8);
2853 assert_eq!(route.paths[0][4].fee_msat, 100);
2854 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2855 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2856 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2859 /// Builds a trivial last-hop hint that passes through the two nodes given, with channel 0xff00
2861 fn multi_hop_last_hops_hint(hint_hops: [PublicKey; 2]) -> Vec<RouteHint> {
2862 let zero_fees = RoutingFees {
2864 proportional_millionths: 0,
2866 vec![RouteHint(vec![RouteHintHop {
2867 src_node_id: hint_hops[0],
2868 short_channel_id: 0xff00,
2871 proportional_millionths: 0,
2873 cltv_expiry_delta: (5 << 4) | 1,
2874 htlc_minimum_msat: None,
2875 htlc_maximum_msat: None,
2877 src_node_id: hint_hops[1],
2878 short_channel_id: 0xff01,
2880 cltv_expiry_delta: (8 << 4) | 1,
2881 htlc_minimum_msat: None,
2882 htlc_maximum_msat: None,
2887 fn multi_hint_last_hops_test() {
2888 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2889 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2890 let last_hops = multi_hop_last_hops_hint([nodes[2], nodes[3]]);
2891 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops.clone());
2892 let scorer = test_utils::TestScorer::with_penalty(0);
2893 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2894 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2895 // Test through channels 2, 3, 0xff00, 0xff01.
2896 // Test shows that multiple hop hints are considered.
2898 // Disabling channels 6 & 7 by flags=2
2899 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2900 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2901 short_channel_id: 6,
2903 flags: 2, // to disable
2904 cltv_expiry_delta: 0,
2905 htlc_minimum_msat: 0,
2906 htlc_maximum_msat: OptionalField::Absent,
2908 fee_proportional_millionths: 0,
2909 excess_data: Vec::new()
2911 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2912 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2913 short_channel_id: 7,
2915 flags: 2, // to disable
2916 cltv_expiry_delta: 0,
2917 htlc_minimum_msat: 0,
2918 htlc_maximum_msat: OptionalField::Absent,
2920 fee_proportional_millionths: 0,
2921 excess_data: Vec::new()
2924 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2925 assert_eq!(route.paths[0].len(), 4);
2927 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2928 assert_eq!(route.paths[0][0].short_channel_id, 2);
2929 assert_eq!(route.paths[0][0].fee_msat, 200);
2930 assert_eq!(route.paths[0][0].cltv_expiry_delta, 65);
2931 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2932 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2934 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2935 assert_eq!(route.paths[0][1].short_channel_id, 4);
2936 assert_eq!(route.paths[0][1].fee_msat, 100);
2937 assert_eq!(route.paths[0][1].cltv_expiry_delta, 81);
2938 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2939 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2941 assert_eq!(route.paths[0][2].pubkey, nodes[3]);
2942 assert_eq!(route.paths[0][2].short_channel_id, last_hops[0].0[0].short_channel_id);
2943 assert_eq!(route.paths[0][2].fee_msat, 0);
2944 assert_eq!(route.paths[0][2].cltv_expiry_delta, 129);
2945 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(4));
2946 assert_eq!(route.paths[0][2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2948 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2949 assert_eq!(route.paths[0][3].short_channel_id, last_hops[0].0[1].short_channel_id);
2950 assert_eq!(route.paths[0][3].fee_msat, 100);
2951 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2952 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2953 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2957 fn private_multi_hint_last_hops_test() {
2958 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2959 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2961 let non_announced_privkey = SecretKey::from_slice(&hex::decode(format!("{:02x}", 0xf0).repeat(32)).unwrap()[..]).unwrap();
2962 let non_announced_pubkey = PublicKey::from_secret_key(&secp_ctx, &non_announced_privkey);
2964 let last_hops = multi_hop_last_hops_hint([nodes[2], non_announced_pubkey]);
2965 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops.clone());
2966 let scorer = test_utils::TestScorer::with_penalty(0);
2967 // Test through channels 2, 3, 0xff00, 0xff01.
2968 // Test shows that multiple hop hints are considered.
2970 // Disabling channels 6 & 7 by flags=2
2971 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2972 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2973 short_channel_id: 6,
2975 flags: 2, // to disable
2976 cltv_expiry_delta: 0,
2977 htlc_minimum_msat: 0,
2978 htlc_maximum_msat: OptionalField::Absent,
2980 fee_proportional_millionths: 0,
2981 excess_data: Vec::new()
2983 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2984 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2985 short_channel_id: 7,
2987 flags: 2, // to disable
2988 cltv_expiry_delta: 0,
2989 htlc_minimum_msat: 0,
2990 htlc_maximum_msat: OptionalField::Absent,
2992 fee_proportional_millionths: 0,
2993 excess_data: Vec::new()
2996 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &[42u8; 32]).unwrap();
2997 assert_eq!(route.paths[0].len(), 4);
2999 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3000 assert_eq!(route.paths[0][0].short_channel_id, 2);
3001 assert_eq!(route.paths[0][0].fee_msat, 200);
3002 assert_eq!(route.paths[0][0].cltv_expiry_delta, 65);
3003 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3004 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3006 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3007 assert_eq!(route.paths[0][1].short_channel_id, 4);
3008 assert_eq!(route.paths[0][1].fee_msat, 100);
3009 assert_eq!(route.paths[0][1].cltv_expiry_delta, 81);
3010 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3011 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3013 assert_eq!(route.paths[0][2].pubkey, non_announced_pubkey);
3014 assert_eq!(route.paths[0][2].short_channel_id, last_hops[0].0[0].short_channel_id);
3015 assert_eq!(route.paths[0][2].fee_msat, 0);
3016 assert_eq!(route.paths[0][2].cltv_expiry_delta, 129);
3017 assert_eq!(route.paths[0][2].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
3018 assert_eq!(route.paths[0][2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3020 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
3021 assert_eq!(route.paths[0][3].short_channel_id, last_hops[0].0[1].short_channel_id);
3022 assert_eq!(route.paths[0][3].fee_msat, 100);
3023 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
3024 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
3025 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3028 fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3029 let zero_fees = RoutingFees {
3031 proportional_millionths: 0,
3033 vec![RouteHint(vec![RouteHintHop {
3034 src_node_id: nodes[4],
3035 short_channel_id: 11,
3037 cltv_expiry_delta: (11 << 4) | 1,
3038 htlc_minimum_msat: None,
3039 htlc_maximum_msat: None,
3041 src_node_id: nodes[3],
3042 short_channel_id: 8,
3044 cltv_expiry_delta: (8 << 4) | 1,
3045 htlc_minimum_msat: None,
3046 htlc_maximum_msat: None,
3047 }]), RouteHint(vec![RouteHintHop {
3048 src_node_id: nodes[4],
3049 short_channel_id: 9,
3052 proportional_millionths: 0,
3054 cltv_expiry_delta: (9 << 4) | 1,
3055 htlc_minimum_msat: None,
3056 htlc_maximum_msat: None,
3057 }]), RouteHint(vec![RouteHintHop {
3058 src_node_id: nodes[5],
3059 short_channel_id: 10,
3061 cltv_expiry_delta: (10 << 4) | 1,
3062 htlc_minimum_msat: None,
3063 htlc_maximum_msat: None,
3068 fn last_hops_with_public_channel_test() {
3069 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3070 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3071 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops_with_public_channel(&nodes));
3072 let scorer = test_utils::TestScorer::with_penalty(0);
3073 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3074 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3075 // This test shows that public routes can be present in the invoice
3076 // which would be handled in the same manner.
3078 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3079 assert_eq!(route.paths[0].len(), 5);
3081 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3082 assert_eq!(route.paths[0][0].short_channel_id, 2);
3083 assert_eq!(route.paths[0][0].fee_msat, 100);
3084 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
3085 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3086 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3088 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3089 assert_eq!(route.paths[0][1].short_channel_id, 4);
3090 assert_eq!(route.paths[0][1].fee_msat, 0);
3091 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
3092 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3093 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3095 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
3096 assert_eq!(route.paths[0][2].short_channel_id, 6);
3097 assert_eq!(route.paths[0][2].fee_msat, 0);
3098 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
3099 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
3100 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
3102 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
3103 assert_eq!(route.paths[0][3].short_channel_id, 11);
3104 assert_eq!(route.paths[0][3].fee_msat, 0);
3105 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
3106 // If we have a peer in the node map, we'll use their features here since we don't have
3107 // a way of figuring out their features from the invoice:
3108 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
3109 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
3111 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
3112 assert_eq!(route.paths[0][4].short_channel_id, 8);
3113 assert_eq!(route.paths[0][4].fee_msat, 100);
3114 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
3115 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
3116 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3120 fn our_chans_last_hop_connect_test() {
3121 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3122 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3123 let scorer = test_utils::TestScorer::with_penalty(0);
3124 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3125 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3127 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
3128 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3129 let mut last_hops = last_hops(&nodes);
3130 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops.clone());
3131 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();
3132 assert_eq!(route.paths[0].len(), 2);
3134 assert_eq!(route.paths[0][0].pubkey, nodes[3]);
3135 assert_eq!(route.paths[0][0].short_channel_id, 42);
3136 assert_eq!(route.paths[0][0].fee_msat, 0);
3137 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 4) | 1);
3138 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
3139 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3141 assert_eq!(route.paths[0][1].pubkey, nodes[6]);
3142 assert_eq!(route.paths[0][1].short_channel_id, 8);
3143 assert_eq!(route.paths[0][1].fee_msat, 100);
3144 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
3145 assert_eq!(route.paths[0][1].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
3146 assert_eq!(route.paths[0][1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3148 last_hops[0].0[0].fees.base_msat = 1000;
3150 // Revert to via 6 as the fee on 8 goes up
3151 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops);
3152 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3153 assert_eq!(route.paths[0].len(), 4);
3155 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3156 assert_eq!(route.paths[0][0].short_channel_id, 2);
3157 assert_eq!(route.paths[0][0].fee_msat, 200); // fee increased as its % of value transferred across node
3158 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
3159 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3160 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3162 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3163 assert_eq!(route.paths[0][1].short_channel_id, 4);
3164 assert_eq!(route.paths[0][1].fee_msat, 100);
3165 assert_eq!(route.paths[0][1].cltv_expiry_delta, (7 << 4) | 1);
3166 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3167 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3169 assert_eq!(route.paths[0][2].pubkey, nodes[5]);
3170 assert_eq!(route.paths[0][2].short_channel_id, 7);
3171 assert_eq!(route.paths[0][2].fee_msat, 0);
3172 assert_eq!(route.paths[0][2].cltv_expiry_delta, (10 << 4) | 1);
3173 // If we have a peer in the node map, we'll use their features here since we don't have
3174 // a way of figuring out their features from the invoice:
3175 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
3176 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(7));
3178 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
3179 assert_eq!(route.paths[0][3].short_channel_id, 10);
3180 assert_eq!(route.paths[0][3].fee_msat, 100);
3181 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
3182 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
3183 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3185 // ...but still use 8 for larger payments as 6 has a variable feerate
3186 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 2000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3187 assert_eq!(route.paths[0].len(), 5);
3189 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3190 assert_eq!(route.paths[0][0].short_channel_id, 2);
3191 assert_eq!(route.paths[0][0].fee_msat, 3000);
3192 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
3193 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3194 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3196 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3197 assert_eq!(route.paths[0][1].short_channel_id, 4);
3198 assert_eq!(route.paths[0][1].fee_msat, 0);
3199 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
3200 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3201 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3203 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
3204 assert_eq!(route.paths[0][2].short_channel_id, 6);
3205 assert_eq!(route.paths[0][2].fee_msat, 0);
3206 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
3207 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
3208 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
3210 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
3211 assert_eq!(route.paths[0][3].short_channel_id, 11);
3212 assert_eq!(route.paths[0][3].fee_msat, 1000);
3213 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
3214 // If we have a peer in the node map, we'll use their features here since we don't have
3215 // a way of figuring out their features from the invoice:
3216 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
3217 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
3219 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
3220 assert_eq!(route.paths[0][4].short_channel_id, 8);
3221 assert_eq!(route.paths[0][4].fee_msat, 2000);
3222 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
3223 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
3224 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3227 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> {
3228 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
3229 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3230 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3232 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
3233 let last_hops = RouteHint(vec![RouteHintHop {
3234 src_node_id: middle_node_id,
3235 short_channel_id: 8,
3238 proportional_millionths: last_hop_fee_prop,
3240 cltv_expiry_delta: (8 << 4) | 1,
3241 htlc_minimum_msat: None,
3242 htlc_maximum_msat: last_hop_htlc_max,
3244 let payment_params = PaymentParameters::from_node_id(target_node_id).with_route_hints(vec![last_hops]);
3245 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
3246 let scorer = test_utils::TestScorer::with_penalty(0);
3247 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3248 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3249 get_route(&source_node_id, &payment_params, &NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash()).read_only(),
3250 Some(&our_chans.iter().collect::<Vec<_>>()), route_val, 42, &test_utils::TestLogger::new(), &scorer, &random_seed_bytes)
3254 fn unannounced_path_test() {
3255 // We should be able to send a payment to a destination without any help of a routing graph
3256 // if we have a channel with a common counterparty that appears in the first and last hop
3258 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
3260 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3261 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3262 assert_eq!(route.paths[0].len(), 2);
3264 assert_eq!(route.paths[0][0].pubkey, middle_node_id);
3265 assert_eq!(route.paths[0][0].short_channel_id, 42);
3266 assert_eq!(route.paths[0][0].fee_msat, 1001);
3267 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 4) | 1);
3268 assert_eq!(route.paths[0][0].node_features.le_flags(), &[0b11]);
3269 assert_eq!(route.paths[0][0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3271 assert_eq!(route.paths[0][1].pubkey, target_node_id);
3272 assert_eq!(route.paths[0][1].short_channel_id, 8);
3273 assert_eq!(route.paths[0][1].fee_msat, 1000000);
3274 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
3275 assert_eq!(route.paths[0][1].node_features.le_flags(), &[0; 0]); // We dont pass flags in from invoices yet
3276 assert_eq!(route.paths[0][1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3280 fn overflow_unannounced_path_test_liquidity_underflow() {
3281 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
3282 // the last-hop had a fee which overflowed a u64, we'd panic.
3283 // This was due to us adding the first-hop from us unconditionally, causing us to think
3284 // we'd built a path (as our node is in the "best candidate" set), when we had not.
3285 // In this test, we previously hit a subtraction underflow due to having less available
3286 // liquidity at the last hop than 0.
3287 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());
3291 fn overflow_unannounced_path_test_feerate_overflow() {
3292 // This tests for the same case as above, except instead of hitting a subtraction
3293 // underflow, we hit a case where the fee charged at a hop overflowed.
3294 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());
3298 fn available_amount_while_routing_test() {
3299 // Tests whether we choose the correct available channel amount while routing.
3301 let (secp_ctx, network_graph, mut net_graph_msg_handler, chain_monitor, logger) = build_graph();
3302 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3303 let scorer = test_utils::TestScorer::with_penalty(0);
3304 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3305 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3306 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
3308 // We will use a simple single-path route from
3309 // our node to node2 via node0: channels {1, 3}.
3311 // First disable all other paths.
3312 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3313 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3314 short_channel_id: 2,
3317 cltv_expiry_delta: 0,
3318 htlc_minimum_msat: 0,
3319 htlc_maximum_msat: OptionalField::Present(100_000),
3321 fee_proportional_millionths: 0,
3322 excess_data: Vec::new()
3324 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3325 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3326 short_channel_id: 12,
3329 cltv_expiry_delta: 0,
3330 htlc_minimum_msat: 0,
3331 htlc_maximum_msat: OptionalField::Present(100_000),
3333 fee_proportional_millionths: 0,
3334 excess_data: Vec::new()
3337 // Make the first channel (#1) very permissive,
3338 // and we will be testing all limits on the second channel.
3339 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3340 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3341 short_channel_id: 1,
3344 cltv_expiry_delta: 0,
3345 htlc_minimum_msat: 0,
3346 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3348 fee_proportional_millionths: 0,
3349 excess_data: Vec::new()
3352 // First, let's see if routing works if we have absolutely no idea about the available amount.
3353 // In this case, it should be set to 250_000 sats.
3354 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3355 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3356 short_channel_id: 3,
3359 cltv_expiry_delta: 0,
3360 htlc_minimum_msat: 0,
3361 htlc_maximum_msat: OptionalField::Absent,
3363 fee_proportional_millionths: 0,
3364 excess_data: Vec::new()
3368 // Attempt to route more than available results in a failure.
3369 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3370 &our_id, &payment_params, &network_graph.read_only(), None, 250_000_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3371 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3372 } else { panic!(); }
3376 // Now, attempt to route an exact amount we have should be fine.
3377 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();
3378 assert_eq!(route.paths.len(), 1);
3379 let path = route.paths.last().unwrap();
3380 assert_eq!(path.len(), 2);
3381 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3382 assert_eq!(path.last().unwrap().fee_msat, 250_000_000);
3385 // Check that setting outbound_capacity_msat in first_hops limits the channels.
3386 // Disable channel #1 and use another first hop.
3387 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3388 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3389 short_channel_id: 1,
3392 cltv_expiry_delta: 0,
3393 htlc_minimum_msat: 0,
3394 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3396 fee_proportional_millionths: 0,
3397 excess_data: Vec::new()
3400 // Now, limit the first_hop by the outbound_capacity_msat of 200_000 sats.
3401 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
3404 // Attempt to route more than available results in a failure.
3405 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3406 &our_id, &payment_params, &network_graph.read_only(), Some(&our_chans.iter().collect::<Vec<_>>()), 200_000_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3407 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3408 } else { panic!(); }
3412 // Now, attempt to route an exact amount we have should be fine.
3413 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&our_chans.iter().collect::<Vec<_>>()), 200_000_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3414 assert_eq!(route.paths.len(), 1);
3415 let path = route.paths.last().unwrap();
3416 assert_eq!(path.len(), 2);
3417 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3418 assert_eq!(path.last().unwrap().fee_msat, 200_000_000);
3421 // Enable channel #1 back.
3422 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3423 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3424 short_channel_id: 1,
3427 cltv_expiry_delta: 0,
3428 htlc_minimum_msat: 0,
3429 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3431 fee_proportional_millionths: 0,
3432 excess_data: Vec::new()
3436 // Now let's see if routing works if we know only htlc_maximum_msat.
3437 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3438 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3439 short_channel_id: 3,
3442 cltv_expiry_delta: 0,
3443 htlc_minimum_msat: 0,
3444 htlc_maximum_msat: OptionalField::Present(15_000),
3446 fee_proportional_millionths: 0,
3447 excess_data: Vec::new()
3451 // Attempt to route more than available results in a failure.
3452 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3453 &our_id, &payment_params, &network_graph.read_only(), None, 15_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3454 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3455 } else { panic!(); }
3459 // Now, attempt to route an exact amount we have should be fine.
3460 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 15_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3461 assert_eq!(route.paths.len(), 1);
3462 let path = route.paths.last().unwrap();
3463 assert_eq!(path.len(), 2);
3464 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3465 assert_eq!(path.last().unwrap().fee_msat, 15_000);
3468 // Now let's see if routing works if we know only capacity from the UTXO.
3470 // We can't change UTXO capacity on the fly, so we'll disable
3471 // the existing channel and add another one with the capacity we need.
3472 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3473 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3474 short_channel_id: 3,
3477 cltv_expiry_delta: 0,
3478 htlc_minimum_msat: 0,
3479 htlc_maximum_msat: OptionalField::Absent,
3481 fee_proportional_millionths: 0,
3482 excess_data: Vec::new()
3485 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
3486 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
3487 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
3488 .push_opcode(opcodes::all::OP_PUSHNUM_2)
3489 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
3491 *chain_monitor.utxo_ret.lock().unwrap() = Ok(TxOut { value: 15, script_pubkey: good_script.clone() });
3492 net_graph_msg_handler.add_chain_access(Some(chain_monitor));
3494 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
3495 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3496 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3497 short_channel_id: 333,
3500 cltv_expiry_delta: (3 << 4) | 1,
3501 htlc_minimum_msat: 0,
3502 htlc_maximum_msat: OptionalField::Absent,
3504 fee_proportional_millionths: 0,
3505 excess_data: Vec::new()
3507 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3508 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3509 short_channel_id: 333,
3512 cltv_expiry_delta: (3 << 4) | 2,
3513 htlc_minimum_msat: 0,
3514 htlc_maximum_msat: OptionalField::Absent,
3516 fee_proportional_millionths: 0,
3517 excess_data: Vec::new()
3521 // Attempt to route more than available results in a failure.
3522 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3523 &our_id, &payment_params, &network_graph.read_only(), None, 15_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3524 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3525 } else { panic!(); }
3529 // Now, attempt to route an exact amount we have should be fine.
3530 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 15_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3531 assert_eq!(route.paths.len(), 1);
3532 let path = route.paths.last().unwrap();
3533 assert_eq!(path.len(), 2);
3534 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3535 assert_eq!(path.last().unwrap().fee_msat, 15_000);
3538 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
3539 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3540 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3541 short_channel_id: 333,
3544 cltv_expiry_delta: 0,
3545 htlc_minimum_msat: 0,
3546 htlc_maximum_msat: OptionalField::Present(10_000),
3548 fee_proportional_millionths: 0,
3549 excess_data: Vec::new()
3553 // Attempt to route more than available results in a failure.
3554 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3555 &our_id, &payment_params, &network_graph.read_only(), None, 10_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3556 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3557 } else { panic!(); }
3561 // Now, attempt to route an exact amount we have should be fine.
3562 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 10_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3563 assert_eq!(route.paths.len(), 1);
3564 let path = route.paths.last().unwrap();
3565 assert_eq!(path.len(), 2);
3566 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3567 assert_eq!(path.last().unwrap().fee_msat, 10_000);
3572 fn available_liquidity_last_hop_test() {
3573 // Check that available liquidity properly limits the path even when only
3574 // one of the latter hops is limited.
3575 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3576 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3577 let scorer = test_utils::TestScorer::with_penalty(0);
3578 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3579 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3580 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
3582 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3583 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
3584 // Total capacity: 50 sats.
3586 // Disable other potential paths.
3587 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3588 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3589 short_channel_id: 2,
3592 cltv_expiry_delta: 0,
3593 htlc_minimum_msat: 0,
3594 htlc_maximum_msat: OptionalField::Present(100_000),
3596 fee_proportional_millionths: 0,
3597 excess_data: Vec::new()
3599 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3600 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3601 short_channel_id: 7,
3604 cltv_expiry_delta: 0,
3605 htlc_minimum_msat: 0,
3606 htlc_maximum_msat: OptionalField::Present(100_000),
3608 fee_proportional_millionths: 0,
3609 excess_data: Vec::new()
3614 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3615 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3616 short_channel_id: 12,
3619 cltv_expiry_delta: 0,
3620 htlc_minimum_msat: 0,
3621 htlc_maximum_msat: OptionalField::Present(100_000),
3623 fee_proportional_millionths: 0,
3624 excess_data: Vec::new()
3626 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3627 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3628 short_channel_id: 13,
3631 cltv_expiry_delta: 0,
3632 htlc_minimum_msat: 0,
3633 htlc_maximum_msat: OptionalField::Present(100_000),
3635 fee_proportional_millionths: 0,
3636 excess_data: Vec::new()
3639 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3640 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3641 short_channel_id: 6,
3644 cltv_expiry_delta: 0,
3645 htlc_minimum_msat: 0,
3646 htlc_maximum_msat: OptionalField::Present(50_000),
3648 fee_proportional_millionths: 0,
3649 excess_data: Vec::new()
3651 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3652 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3653 short_channel_id: 11,
3656 cltv_expiry_delta: 0,
3657 htlc_minimum_msat: 0,
3658 htlc_maximum_msat: OptionalField::Present(100_000),
3660 fee_proportional_millionths: 0,
3661 excess_data: Vec::new()
3664 // Attempt to route more than available results in a failure.
3665 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3666 &our_id, &payment_params, &network_graph.read_only(), None, 60_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3667 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3668 } else { panic!(); }
3672 // Now, attempt to route 49 sats (just a bit below the capacity).
3673 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 49_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3674 assert_eq!(route.paths.len(), 1);
3675 let mut total_amount_paid_msat = 0;
3676 for path in &route.paths {
3677 assert_eq!(path.len(), 4);
3678 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3679 total_amount_paid_msat += path.last().unwrap().fee_msat;
3681 assert_eq!(total_amount_paid_msat, 49_000);
3685 // Attempt to route an exact amount is also fine
3686 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3687 assert_eq!(route.paths.len(), 1);
3688 let mut total_amount_paid_msat = 0;
3689 for path in &route.paths {
3690 assert_eq!(path.len(), 4);
3691 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3692 total_amount_paid_msat += path.last().unwrap().fee_msat;
3694 assert_eq!(total_amount_paid_msat, 50_000);
3699 fn ignore_fee_first_hop_test() {
3700 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3701 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3702 let scorer = test_utils::TestScorer::with_penalty(0);
3703 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3704 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3705 let payment_params = PaymentParameters::from_node_id(nodes[2]);
3707 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3708 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3709 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3710 short_channel_id: 1,
3713 cltv_expiry_delta: 0,
3714 htlc_minimum_msat: 0,
3715 htlc_maximum_msat: OptionalField::Present(100_000),
3716 fee_base_msat: 1_000_000,
3717 fee_proportional_millionths: 0,
3718 excess_data: Vec::new()
3720 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3721 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3722 short_channel_id: 3,
3725 cltv_expiry_delta: 0,
3726 htlc_minimum_msat: 0,
3727 htlc_maximum_msat: OptionalField::Present(50_000),
3729 fee_proportional_millionths: 0,
3730 excess_data: Vec::new()
3734 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3735 assert_eq!(route.paths.len(), 1);
3736 let mut total_amount_paid_msat = 0;
3737 for path in &route.paths {
3738 assert_eq!(path.len(), 2);
3739 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3740 total_amount_paid_msat += path.last().unwrap().fee_msat;
3742 assert_eq!(total_amount_paid_msat, 50_000);
3747 fn simple_mpp_route_test() {
3748 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3749 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3750 let scorer = test_utils::TestScorer::with_penalty(0);
3751 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3752 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3753 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
3755 // We need a route consisting of 3 paths:
3756 // From our node to node2 via node0, node7, node1 (three paths one hop each).
3757 // To achieve this, the amount being transferred should be around
3758 // the total capacity of these 3 paths.
3760 // First, we set limits on these (previously unlimited) channels.
3761 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
3763 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3764 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3765 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3766 short_channel_id: 1,
3769 cltv_expiry_delta: 0,
3770 htlc_minimum_msat: 0,
3771 htlc_maximum_msat: OptionalField::Present(100_000),
3773 fee_proportional_millionths: 0,
3774 excess_data: Vec::new()
3776 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3777 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3778 short_channel_id: 3,
3781 cltv_expiry_delta: 0,
3782 htlc_minimum_msat: 0,
3783 htlc_maximum_msat: OptionalField::Present(50_000),
3785 fee_proportional_millionths: 0,
3786 excess_data: Vec::new()
3789 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
3790 // (total limit 60).
3791 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3792 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3793 short_channel_id: 12,
3796 cltv_expiry_delta: 0,
3797 htlc_minimum_msat: 0,
3798 htlc_maximum_msat: OptionalField::Present(60_000),
3800 fee_proportional_millionths: 0,
3801 excess_data: Vec::new()
3803 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3804 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3805 short_channel_id: 13,
3808 cltv_expiry_delta: 0,
3809 htlc_minimum_msat: 0,
3810 htlc_maximum_msat: OptionalField::Present(60_000),
3812 fee_proportional_millionths: 0,
3813 excess_data: Vec::new()
3816 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
3817 // (total capacity 180 sats).
3818 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3819 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3820 short_channel_id: 2,
3823 cltv_expiry_delta: 0,
3824 htlc_minimum_msat: 0,
3825 htlc_maximum_msat: OptionalField::Present(200_000),
3827 fee_proportional_millionths: 0,
3828 excess_data: Vec::new()
3830 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3831 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3832 short_channel_id: 4,
3835 cltv_expiry_delta: 0,
3836 htlc_minimum_msat: 0,
3837 htlc_maximum_msat: OptionalField::Present(180_000),
3839 fee_proportional_millionths: 0,
3840 excess_data: Vec::new()
3844 // Attempt to route more than available results in a failure.
3845 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3846 &our_id, &payment_params, &network_graph.read_only(), None, 300_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3847 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3848 } else { panic!(); }
3852 // Now, attempt to route 250 sats (just a bit below the capacity).
3853 // Our algorithm should provide us with these 3 paths.
3854 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 250_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3855 assert_eq!(route.paths.len(), 3);
3856 let mut total_amount_paid_msat = 0;
3857 for path in &route.paths {
3858 assert_eq!(path.len(), 2);
3859 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3860 total_amount_paid_msat += path.last().unwrap().fee_msat;
3862 assert_eq!(total_amount_paid_msat, 250_000);
3866 // Attempt to route an exact amount is also fine
3867 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 290_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3868 assert_eq!(route.paths.len(), 3);
3869 let mut total_amount_paid_msat = 0;
3870 for path in &route.paths {
3871 assert_eq!(path.len(), 2);
3872 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3873 total_amount_paid_msat += path.last().unwrap().fee_msat;
3875 assert_eq!(total_amount_paid_msat, 290_000);
3880 fn long_mpp_route_test() {
3881 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3882 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3883 let scorer = test_utils::TestScorer::with_penalty(0);
3884 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3885 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3886 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
3888 // We need a route consisting of 3 paths:
3889 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3890 // Note that these paths overlap (channels 5, 12, 13).
3891 // We will route 300 sats.
3892 // Each path will have 100 sats capacity, those channels which
3893 // are used twice will have 200 sats capacity.
3895 // Disable other potential paths.
3896 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3897 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3898 short_channel_id: 2,
3901 cltv_expiry_delta: 0,
3902 htlc_minimum_msat: 0,
3903 htlc_maximum_msat: OptionalField::Present(100_000),
3905 fee_proportional_millionths: 0,
3906 excess_data: Vec::new()
3908 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3909 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3910 short_channel_id: 7,
3913 cltv_expiry_delta: 0,
3914 htlc_minimum_msat: 0,
3915 htlc_maximum_msat: OptionalField::Present(100_000),
3917 fee_proportional_millionths: 0,
3918 excess_data: Vec::new()
3921 // Path via {node0, node2} is channels {1, 3, 5}.
3922 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3923 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3924 short_channel_id: 1,
3927 cltv_expiry_delta: 0,
3928 htlc_minimum_msat: 0,
3929 htlc_maximum_msat: OptionalField::Present(100_000),
3931 fee_proportional_millionths: 0,
3932 excess_data: Vec::new()
3934 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3935 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3936 short_channel_id: 3,
3939 cltv_expiry_delta: 0,
3940 htlc_minimum_msat: 0,
3941 htlc_maximum_msat: OptionalField::Present(100_000),
3943 fee_proportional_millionths: 0,
3944 excess_data: Vec::new()
3947 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3948 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3949 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3950 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3951 short_channel_id: 5,
3954 cltv_expiry_delta: 0,
3955 htlc_minimum_msat: 0,
3956 htlc_maximum_msat: OptionalField::Present(200_000),
3958 fee_proportional_millionths: 0,
3959 excess_data: Vec::new()
3962 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3963 // Add 100 sats to the capacities of {12, 13}, because these channels
3964 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3965 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3966 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3967 short_channel_id: 12,
3970 cltv_expiry_delta: 0,
3971 htlc_minimum_msat: 0,
3972 htlc_maximum_msat: OptionalField::Present(200_000),
3974 fee_proportional_millionths: 0,
3975 excess_data: Vec::new()
3977 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3978 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3979 short_channel_id: 13,
3982 cltv_expiry_delta: 0,
3983 htlc_minimum_msat: 0,
3984 htlc_maximum_msat: OptionalField::Present(200_000),
3986 fee_proportional_millionths: 0,
3987 excess_data: Vec::new()
3990 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3991 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3992 short_channel_id: 6,
3995 cltv_expiry_delta: 0,
3996 htlc_minimum_msat: 0,
3997 htlc_maximum_msat: OptionalField::Present(100_000),
3999 fee_proportional_millionths: 0,
4000 excess_data: Vec::new()
4002 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4003 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4004 short_channel_id: 11,
4007 cltv_expiry_delta: 0,
4008 htlc_minimum_msat: 0,
4009 htlc_maximum_msat: OptionalField::Present(100_000),
4011 fee_proportional_millionths: 0,
4012 excess_data: Vec::new()
4015 // Path via {node7, node2} is channels {12, 13, 5}.
4016 // We already limited them to 200 sats (they are used twice for 100 sats).
4017 // Nothing to do here.
4020 // Attempt to route more than available results in a failure.
4021 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4022 &our_id, &payment_params, &network_graph.read_only(), None, 350_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
4023 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4024 } else { panic!(); }
4028 // Now, attempt to route 300 sats (exact amount we can route).
4029 // Our algorithm should provide us with these 3 paths, 100 sats each.
4030 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 300_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4031 assert_eq!(route.paths.len(), 3);
4033 let mut total_amount_paid_msat = 0;
4034 for path in &route.paths {
4035 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
4036 total_amount_paid_msat += path.last().unwrap().fee_msat;
4038 assert_eq!(total_amount_paid_msat, 300_000);
4044 fn mpp_cheaper_route_test() {
4045 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4046 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4047 let scorer = test_utils::TestScorer::with_penalty(0);
4048 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4049 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4050 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
4052 // This test checks that if we have two cheaper paths and one more expensive path,
4053 // so that liquidity-wise any 2 of 3 combination is sufficient,
4054 // two cheaper paths will be taken.
4055 // These paths have equal available liquidity.
4057 // We need a combination of 3 paths:
4058 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
4059 // Note that these paths overlap (channels 5, 12, 13).
4060 // Each path will have 100 sats capacity, those channels which
4061 // are used twice will have 200 sats capacity.
4063 // Disable other potential paths.
4064 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4065 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4066 short_channel_id: 2,
4069 cltv_expiry_delta: 0,
4070 htlc_minimum_msat: 0,
4071 htlc_maximum_msat: OptionalField::Present(100_000),
4073 fee_proportional_millionths: 0,
4074 excess_data: Vec::new()
4076 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4077 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4078 short_channel_id: 7,
4081 cltv_expiry_delta: 0,
4082 htlc_minimum_msat: 0,
4083 htlc_maximum_msat: OptionalField::Present(100_000),
4085 fee_proportional_millionths: 0,
4086 excess_data: Vec::new()
4089 // Path via {node0, node2} is channels {1, 3, 5}.
4090 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4091 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4092 short_channel_id: 1,
4095 cltv_expiry_delta: 0,
4096 htlc_minimum_msat: 0,
4097 htlc_maximum_msat: OptionalField::Present(100_000),
4099 fee_proportional_millionths: 0,
4100 excess_data: Vec::new()
4102 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4103 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4104 short_channel_id: 3,
4107 cltv_expiry_delta: 0,
4108 htlc_minimum_msat: 0,
4109 htlc_maximum_msat: OptionalField::Present(100_000),
4111 fee_proportional_millionths: 0,
4112 excess_data: Vec::new()
4115 // Capacity of 200 sats because this channel will be used by 3rd path as well.
4116 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4117 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4118 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4119 short_channel_id: 5,
4122 cltv_expiry_delta: 0,
4123 htlc_minimum_msat: 0,
4124 htlc_maximum_msat: OptionalField::Present(200_000),
4126 fee_proportional_millionths: 0,
4127 excess_data: Vec::new()
4130 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4131 // Add 100 sats to the capacities of {12, 13}, because these channels
4132 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
4133 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4134 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4135 short_channel_id: 12,
4138 cltv_expiry_delta: 0,
4139 htlc_minimum_msat: 0,
4140 htlc_maximum_msat: OptionalField::Present(200_000),
4142 fee_proportional_millionths: 0,
4143 excess_data: Vec::new()
4145 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4146 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4147 short_channel_id: 13,
4150 cltv_expiry_delta: 0,
4151 htlc_minimum_msat: 0,
4152 htlc_maximum_msat: OptionalField::Present(200_000),
4154 fee_proportional_millionths: 0,
4155 excess_data: Vec::new()
4158 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4159 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4160 short_channel_id: 6,
4163 cltv_expiry_delta: 0,
4164 htlc_minimum_msat: 0,
4165 htlc_maximum_msat: OptionalField::Present(100_000),
4166 fee_base_msat: 1_000,
4167 fee_proportional_millionths: 0,
4168 excess_data: Vec::new()
4170 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4171 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4172 short_channel_id: 11,
4175 cltv_expiry_delta: 0,
4176 htlc_minimum_msat: 0,
4177 htlc_maximum_msat: OptionalField::Present(100_000),
4179 fee_proportional_millionths: 0,
4180 excess_data: Vec::new()
4183 // Path via {node7, node2} is channels {12, 13, 5}.
4184 // We already limited them to 200 sats (they are used twice for 100 sats).
4185 // Nothing to do here.
4188 // Now, attempt to route 180 sats.
4189 // Our algorithm should provide us with these 2 paths.
4190 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 180_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4191 assert_eq!(route.paths.len(), 2);
4193 let mut total_value_transferred_msat = 0;
4194 let mut total_paid_msat = 0;
4195 for path in &route.paths {
4196 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
4197 total_value_transferred_msat += path.last().unwrap().fee_msat;
4199 total_paid_msat += hop.fee_msat;
4202 // If we paid fee, this would be higher.
4203 assert_eq!(total_value_transferred_msat, 180_000);
4204 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
4205 assert_eq!(total_fees_paid, 0);
4210 fn fees_on_mpp_route_test() {
4211 // This test makes sure that MPP algorithm properly takes into account
4212 // fees charged on the channels, by making the fees impactful:
4213 // if the fee is not properly accounted for, the behavior is different.
4214 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4215 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4216 let scorer = test_utils::TestScorer::with_penalty(0);
4217 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4218 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4219 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
4221 // We need a route consisting of 2 paths:
4222 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
4223 // We will route 200 sats, Each path will have 100 sats capacity.
4225 // This test is not particularly stable: e.g.,
4226 // there's a way to route via {node0, node2, node4}.
4227 // It works while pathfinding is deterministic, but can be broken otherwise.
4228 // It's fine to ignore this concern for now.
4230 // Disable other potential paths.
4231 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4232 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4233 short_channel_id: 2,
4236 cltv_expiry_delta: 0,
4237 htlc_minimum_msat: 0,
4238 htlc_maximum_msat: OptionalField::Present(100_000),
4240 fee_proportional_millionths: 0,
4241 excess_data: Vec::new()
4244 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4245 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4246 short_channel_id: 7,
4249 cltv_expiry_delta: 0,
4250 htlc_minimum_msat: 0,
4251 htlc_maximum_msat: OptionalField::Present(100_000),
4253 fee_proportional_millionths: 0,
4254 excess_data: Vec::new()
4257 // Path via {node0, node2} is channels {1, 3, 5}.
4258 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4259 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4260 short_channel_id: 1,
4263 cltv_expiry_delta: 0,
4264 htlc_minimum_msat: 0,
4265 htlc_maximum_msat: OptionalField::Present(100_000),
4267 fee_proportional_millionths: 0,
4268 excess_data: Vec::new()
4270 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4271 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4272 short_channel_id: 3,
4275 cltv_expiry_delta: 0,
4276 htlc_minimum_msat: 0,
4277 htlc_maximum_msat: OptionalField::Present(100_000),
4279 fee_proportional_millionths: 0,
4280 excess_data: Vec::new()
4283 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4284 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4285 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4286 short_channel_id: 5,
4289 cltv_expiry_delta: 0,
4290 htlc_minimum_msat: 0,
4291 htlc_maximum_msat: OptionalField::Present(100_000),
4293 fee_proportional_millionths: 0,
4294 excess_data: Vec::new()
4297 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4298 // All channels should be 100 sats capacity. But for the fee experiment,
4299 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
4300 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
4301 // 100 sats (and pay 150 sats in fees for the use of channel 6),
4302 // so no matter how large are other channels,
4303 // the whole path will be limited by 100 sats with just these 2 conditions:
4304 // - channel 12 capacity is 250 sats
4305 // - fee for channel 6 is 150 sats
4306 // Let's test this by enforcing these 2 conditions and removing other limits.
4307 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4308 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4309 short_channel_id: 12,
4312 cltv_expiry_delta: 0,
4313 htlc_minimum_msat: 0,
4314 htlc_maximum_msat: OptionalField::Present(250_000),
4316 fee_proportional_millionths: 0,
4317 excess_data: Vec::new()
4319 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4320 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4321 short_channel_id: 13,
4324 cltv_expiry_delta: 0,
4325 htlc_minimum_msat: 0,
4326 htlc_maximum_msat: OptionalField::Absent,
4328 fee_proportional_millionths: 0,
4329 excess_data: Vec::new()
4332 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4333 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4334 short_channel_id: 6,
4337 cltv_expiry_delta: 0,
4338 htlc_minimum_msat: 0,
4339 htlc_maximum_msat: OptionalField::Absent,
4340 fee_base_msat: 150_000,
4341 fee_proportional_millionths: 0,
4342 excess_data: Vec::new()
4344 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4345 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4346 short_channel_id: 11,
4349 cltv_expiry_delta: 0,
4350 htlc_minimum_msat: 0,
4351 htlc_maximum_msat: OptionalField::Absent,
4353 fee_proportional_millionths: 0,
4354 excess_data: Vec::new()
4358 // Attempt to route more than available results in a failure.
4359 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4360 &our_id, &payment_params, &network_graph.read_only(), None, 210_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
4361 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4362 } else { panic!(); }
4366 // Now, attempt to route 200 sats (exact amount we can route).
4367 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 200_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4368 assert_eq!(route.paths.len(), 2);
4370 let mut total_amount_paid_msat = 0;
4371 for path in &route.paths {
4372 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
4373 total_amount_paid_msat += path.last().unwrap().fee_msat;
4375 assert_eq!(total_amount_paid_msat, 200_000);
4376 assert_eq!(route.get_total_fees(), 150_000);
4381 fn mpp_with_last_hops() {
4382 // Previously, if we tried to send an MPP payment to a destination which was only reachable
4383 // via a single last-hop route hint, we'd fail to route if we first collected routes
4384 // totaling close but not quite enough to fund the full payment.
4386 // This was because we considered last-hop hints to have exactly the sought payment amount
4387 // instead of the amount we were trying to collect, needlessly limiting our path searching
4388 // at the very first hop.
4390 // Specifically, this interacted with our "all paths must fund at least 5% of total target"
4391 // criterion to cause us to refuse all routes at the last hop hint which would be considered
4392 // to only have the remaining to-collect amount in available liquidity.
4394 // This bug appeared in production in some specific channel configurations.
4395 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4396 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4397 let scorer = test_utils::TestScorer::with_penalty(0);
4398 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4399 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4400 let payment_params = PaymentParameters::from_node_id(PublicKey::from_slice(&[02; 33]).unwrap()).with_features(InvoiceFeatures::known())
4401 .with_route_hints(vec![RouteHint(vec![RouteHintHop {
4402 src_node_id: nodes[2],
4403 short_channel_id: 42,
4404 fees: RoutingFees { base_msat: 0, proportional_millionths: 0 },
4405 cltv_expiry_delta: 42,
4406 htlc_minimum_msat: None,
4407 htlc_maximum_msat: None,
4410 // Keep only two paths from us to nodes[2], both with a 99sat HTLC maximum, with one with
4411 // no fee and one with a 1msat fee. Previously, trying to route 100 sats to nodes[2] here
4412 // would first use the no-fee route and then fail to find a path along the second route as
4413 // we think we can only send up to 1 additional sat over the last-hop but refuse to as its
4414 // under 5% of our payment amount.
4415 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4416 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4417 short_channel_id: 1,
4420 cltv_expiry_delta: (5 << 4) | 5,
4421 htlc_minimum_msat: 0,
4422 htlc_maximum_msat: OptionalField::Present(99_000),
4423 fee_base_msat: u32::max_value(),
4424 fee_proportional_millionths: u32::max_value(),
4425 excess_data: Vec::new()
4427 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4428 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4429 short_channel_id: 2,
4432 cltv_expiry_delta: (5 << 4) | 3,
4433 htlc_minimum_msat: 0,
4434 htlc_maximum_msat: OptionalField::Present(99_000),
4435 fee_base_msat: u32::max_value(),
4436 fee_proportional_millionths: u32::max_value(),
4437 excess_data: Vec::new()
4439 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4440 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4441 short_channel_id: 4,
4444 cltv_expiry_delta: (4 << 4) | 1,
4445 htlc_minimum_msat: 0,
4446 htlc_maximum_msat: OptionalField::Absent,
4448 fee_proportional_millionths: 0,
4449 excess_data: Vec::new()
4451 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4452 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4453 short_channel_id: 13,
4455 flags: 0|2, // Channel disabled
4456 cltv_expiry_delta: (13 << 4) | 1,
4457 htlc_minimum_msat: 0,
4458 htlc_maximum_msat: OptionalField::Absent,
4460 fee_proportional_millionths: 2000000,
4461 excess_data: Vec::new()
4464 // Get a route for 100 sats and check that we found the MPP route no problem and didn't
4466 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4467 assert_eq!(route.paths.len(), 2);
4468 // Paths are somewhat randomly ordered, but:
4469 // * the first is channel 2 (1 msat fee) -> channel 4 -> channel 42
4470 // * the second is channel 1 (0 fee, but 99 sat maximum) -> channel 3 -> channel 42
4471 assert_eq!(route.paths[0][0].short_channel_id, 2);
4472 assert_eq!(route.paths[0][0].fee_msat, 1);
4473 assert_eq!(route.paths[0][2].fee_msat, 1_000);
4474 assert_eq!(route.paths[1][0].short_channel_id, 1);
4475 assert_eq!(route.paths[1][0].fee_msat, 0);
4476 assert_eq!(route.paths[1][2].fee_msat, 99_000);
4477 assert_eq!(route.get_total_fees(), 1);
4478 assert_eq!(route.get_total_amount(), 100_000);
4482 fn drop_lowest_channel_mpp_route_test() {
4483 // This test checks that low-capacity channel is dropped when after
4484 // path finding we realize that we found more capacity than we need.
4485 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4486 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4487 let scorer = test_utils::TestScorer::with_penalty(0);
4488 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4489 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4490 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
4492 // We need a route consisting of 3 paths:
4493 // From our node to node2 via node0, node7, node1 (three paths one hop each).
4495 // The first and the second paths should be sufficient, but the third should be
4496 // cheaper, so that we select it but drop later.
4498 // First, we set limits on these (previously unlimited) channels.
4499 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
4501 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
4502 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4503 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4504 short_channel_id: 1,
4507 cltv_expiry_delta: 0,
4508 htlc_minimum_msat: 0,
4509 htlc_maximum_msat: OptionalField::Present(100_000),
4511 fee_proportional_millionths: 0,
4512 excess_data: Vec::new()
4514 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4515 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4516 short_channel_id: 3,
4519 cltv_expiry_delta: 0,
4520 htlc_minimum_msat: 0,
4521 htlc_maximum_msat: OptionalField::Present(50_000),
4523 fee_proportional_millionths: 0,
4524 excess_data: Vec::new()
4527 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
4528 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4529 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4530 short_channel_id: 12,
4533 cltv_expiry_delta: 0,
4534 htlc_minimum_msat: 0,
4535 htlc_maximum_msat: OptionalField::Present(60_000),
4537 fee_proportional_millionths: 0,
4538 excess_data: Vec::new()
4540 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4541 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4542 short_channel_id: 13,
4545 cltv_expiry_delta: 0,
4546 htlc_minimum_msat: 0,
4547 htlc_maximum_msat: OptionalField::Present(60_000),
4549 fee_proportional_millionths: 0,
4550 excess_data: Vec::new()
4553 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
4554 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4555 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4556 short_channel_id: 2,
4559 cltv_expiry_delta: 0,
4560 htlc_minimum_msat: 0,
4561 htlc_maximum_msat: OptionalField::Present(20_000),
4563 fee_proportional_millionths: 0,
4564 excess_data: Vec::new()
4566 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4567 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4568 short_channel_id: 4,
4571 cltv_expiry_delta: 0,
4572 htlc_minimum_msat: 0,
4573 htlc_maximum_msat: OptionalField::Present(20_000),
4575 fee_proportional_millionths: 0,
4576 excess_data: Vec::new()
4580 // Attempt to route more than available results in a failure.
4581 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4582 &our_id, &payment_params, &network_graph.read_only(), None, 150_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
4583 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4584 } else { panic!(); }
4588 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
4589 // Our algorithm should provide us with these 3 paths.
4590 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 125_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4591 assert_eq!(route.paths.len(), 3);
4592 let mut total_amount_paid_msat = 0;
4593 for path in &route.paths {
4594 assert_eq!(path.len(), 2);
4595 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4596 total_amount_paid_msat += path.last().unwrap().fee_msat;
4598 assert_eq!(total_amount_paid_msat, 125_000);
4602 // Attempt to route without the last small cheap channel
4603 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4604 assert_eq!(route.paths.len(), 2);
4605 let mut total_amount_paid_msat = 0;
4606 for path in &route.paths {
4607 assert_eq!(path.len(), 2);
4608 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4609 total_amount_paid_msat += path.last().unwrap().fee_msat;
4611 assert_eq!(total_amount_paid_msat, 90_000);
4616 fn min_criteria_consistency() {
4617 // Test that we don't use an inconsistent metric between updating and walking nodes during
4618 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
4619 // was updated with a different criterion from the heap sorting, resulting in loops in
4620 // calculated paths. We test for that specific case here.
4622 // We construct a network that looks like this:
4624 // node2 -1(3)2- node3
4628 // node1 -1(5)2- node4 -1(1)2- node6
4634 // We create a loop on the side of our real path - our destination is node 6, with a
4635 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
4636 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
4637 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
4638 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
4639 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
4640 // "previous hop" being set to node 3, creating a loop in the path.
4641 let secp_ctx = Secp256k1::new();
4642 let logger = Arc::new(test_utils::TestLogger::new());
4643 let network = Arc::new(NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash()));
4644 let net_graph_msg_handler = NetGraphMsgHandler::new(Arc::clone(&network), None, Arc::clone(&logger));
4645 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4646 let scorer = test_utils::TestScorer::with_penalty(0);
4647 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4648 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4649 let payment_params = PaymentParameters::from_node_id(nodes[6]);
4651 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
4652 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4653 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4654 short_channel_id: 6,
4657 cltv_expiry_delta: (6 << 4) | 0,
4658 htlc_minimum_msat: 0,
4659 htlc_maximum_msat: OptionalField::Absent,
4661 fee_proportional_millionths: 0,
4662 excess_data: Vec::new()
4664 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
4666 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4667 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4668 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4669 short_channel_id: 5,
4672 cltv_expiry_delta: (5 << 4) | 0,
4673 htlc_minimum_msat: 0,
4674 htlc_maximum_msat: OptionalField::Absent,
4676 fee_proportional_millionths: 0,
4677 excess_data: Vec::new()
4679 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
4681 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
4682 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4683 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4684 short_channel_id: 4,
4687 cltv_expiry_delta: (4 << 4) | 0,
4688 htlc_minimum_msat: 0,
4689 htlc_maximum_msat: OptionalField::Absent,
4691 fee_proportional_millionths: 0,
4692 excess_data: Vec::new()
4694 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
4696 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
4697 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
4698 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4699 short_channel_id: 3,
4702 cltv_expiry_delta: (3 << 4) | 0,
4703 htlc_minimum_msat: 0,
4704 htlc_maximum_msat: OptionalField::Absent,
4706 fee_proportional_millionths: 0,
4707 excess_data: Vec::new()
4709 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
4711 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
4712 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4713 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4714 short_channel_id: 2,
4717 cltv_expiry_delta: (2 << 4) | 0,
4718 htlc_minimum_msat: 0,
4719 htlc_maximum_msat: OptionalField::Absent,
4721 fee_proportional_millionths: 0,
4722 excess_data: Vec::new()
4725 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
4726 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4727 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4728 short_channel_id: 1,
4731 cltv_expiry_delta: (1 << 4) | 0,
4732 htlc_minimum_msat: 100,
4733 htlc_maximum_msat: OptionalField::Absent,
4735 fee_proportional_millionths: 0,
4736 excess_data: Vec::new()
4738 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
4741 // Now ensure the route flows simply over nodes 1 and 4 to 6.
4742 let route = get_route(&our_id, &payment_params, &network.read_only(), None, 10_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4743 assert_eq!(route.paths.len(), 1);
4744 assert_eq!(route.paths[0].len(), 3);
4746 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
4747 assert_eq!(route.paths[0][0].short_channel_id, 6);
4748 assert_eq!(route.paths[0][0].fee_msat, 100);
4749 assert_eq!(route.paths[0][0].cltv_expiry_delta, (5 << 4) | 0);
4750 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(1));
4751 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(6));
4753 assert_eq!(route.paths[0][1].pubkey, nodes[4]);
4754 assert_eq!(route.paths[0][1].short_channel_id, 5);
4755 assert_eq!(route.paths[0][1].fee_msat, 0);
4756 assert_eq!(route.paths[0][1].cltv_expiry_delta, (1 << 4) | 0);
4757 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(4));
4758 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(5));
4760 assert_eq!(route.paths[0][2].pubkey, nodes[6]);
4761 assert_eq!(route.paths[0][2].short_channel_id, 1);
4762 assert_eq!(route.paths[0][2].fee_msat, 10_000);
4763 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
4764 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
4765 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(1));
4771 fn exact_fee_liquidity_limit() {
4772 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
4773 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
4774 // we calculated fees on a higher value, resulting in us ignoring such paths.
4775 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4776 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
4777 let scorer = test_utils::TestScorer::with_penalty(0);
4778 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4779 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4780 let payment_params = PaymentParameters::from_node_id(nodes[2]);
4782 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
4784 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4785 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4786 short_channel_id: 2,
4789 cltv_expiry_delta: 0,
4790 htlc_minimum_msat: 0,
4791 htlc_maximum_msat: OptionalField::Present(85_000),
4793 fee_proportional_millionths: 0,
4794 excess_data: Vec::new()
4797 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4798 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4799 short_channel_id: 12,
4802 cltv_expiry_delta: (4 << 4) | 1,
4803 htlc_minimum_msat: 0,
4804 htlc_maximum_msat: OptionalField::Present(270_000),
4806 fee_proportional_millionths: 1000000,
4807 excess_data: Vec::new()
4811 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
4812 // 200% fee charged channel 13 in the 1-to-2 direction.
4813 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4814 assert_eq!(route.paths.len(), 1);
4815 assert_eq!(route.paths[0].len(), 2);
4817 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
4818 assert_eq!(route.paths[0][0].short_channel_id, 12);
4819 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
4820 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
4821 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
4822 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
4824 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
4825 assert_eq!(route.paths[0][1].short_channel_id, 13);
4826 assert_eq!(route.paths[0][1].fee_msat, 90_000);
4827 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
4828 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
4829 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
4834 fn htlc_max_reduction_below_min() {
4835 // Test that if, while walking the graph, we reduce the value being sent to meet an
4836 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
4837 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
4838 // resulting in us thinking there is no possible path, even if other paths exist.
4839 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4840 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4841 let scorer = test_utils::TestScorer::with_penalty(0);
4842 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4843 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4844 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
4846 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
4847 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
4848 // then try to send 90_000.
4849 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4850 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4851 short_channel_id: 2,
4854 cltv_expiry_delta: 0,
4855 htlc_minimum_msat: 0,
4856 htlc_maximum_msat: OptionalField::Present(80_000),
4858 fee_proportional_millionths: 0,
4859 excess_data: Vec::new()
4861 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4862 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4863 short_channel_id: 4,
4866 cltv_expiry_delta: (4 << 4) | 1,
4867 htlc_minimum_msat: 90_000,
4868 htlc_maximum_msat: OptionalField::Absent,
4870 fee_proportional_millionths: 0,
4871 excess_data: Vec::new()
4875 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
4876 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
4877 // expensive) channels 12-13 path.
4878 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4879 assert_eq!(route.paths.len(), 1);
4880 assert_eq!(route.paths[0].len(), 2);
4882 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
4883 assert_eq!(route.paths[0][0].short_channel_id, 12);
4884 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
4885 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
4886 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
4887 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
4889 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
4890 assert_eq!(route.paths[0][1].short_channel_id, 13);
4891 assert_eq!(route.paths[0][1].fee_msat, 90_000);
4892 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
4893 assert_eq!(route.paths[0][1].node_features.le_flags(), InvoiceFeatures::known().le_flags());
4894 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
4899 fn multiple_direct_first_hops() {
4900 // Previously we'd only ever considered one first hop path per counterparty.
4901 // However, as we don't restrict users to one channel per peer, we really need to support
4902 // looking at all first hop paths.
4903 // Here we test that we do not ignore all-but-the-last first hop paths per counterparty (as
4904 // we used to do by overwriting the `first_hop_targets` hashmap entry) and that we can MPP
4905 // route over multiple channels with the same first hop.
4906 let secp_ctx = Secp256k1::new();
4907 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4908 let logger = Arc::new(test_utils::TestLogger::new());
4909 let network_graph = NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash());
4910 let scorer = test_utils::TestScorer::with_penalty(0);
4911 let payment_params = PaymentParameters::from_node_id(nodes[0]).with_features(InvoiceFeatures::known());
4912 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4913 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4916 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
4917 &get_channel_details(Some(3), nodes[0], InitFeatures::known(), 200_000),
4918 &get_channel_details(Some(2), nodes[0], InitFeatures::known(), 10_000),
4919 ]), 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4920 assert_eq!(route.paths.len(), 1);
4921 assert_eq!(route.paths[0].len(), 1);
4923 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
4924 assert_eq!(route.paths[0][0].short_channel_id, 3);
4925 assert_eq!(route.paths[0][0].fee_msat, 100_000);
4928 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
4929 &get_channel_details(Some(3), nodes[0], InitFeatures::known(), 50_000),
4930 &get_channel_details(Some(2), nodes[0], InitFeatures::known(), 50_000),
4931 ]), 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4932 assert_eq!(route.paths.len(), 2);
4933 assert_eq!(route.paths[0].len(), 1);
4934 assert_eq!(route.paths[1].len(), 1);
4936 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
4937 assert_eq!(route.paths[0][0].short_channel_id, 3);
4938 assert_eq!(route.paths[0][0].fee_msat, 50_000);
4940 assert_eq!(route.paths[1][0].pubkey, nodes[0]);
4941 assert_eq!(route.paths[1][0].short_channel_id, 2);
4942 assert_eq!(route.paths[1][0].fee_msat, 50_000);
4946 // If we have a bunch of outbound channels to the same node, where most are not
4947 // sufficient to pay the full payment, but one is, we should default to just using the
4948 // one single channel that has sufficient balance, avoiding MPP.
4950 // If we have several options above the 3xpayment value threshold, we should pick the
4951 // smallest of them, avoiding further fragmenting our available outbound balance to
4953 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
4954 &get_channel_details(Some(2), nodes[0], InitFeatures::known(), 50_000),
4955 &get_channel_details(Some(3), nodes[0], InitFeatures::known(), 50_000),
4956 &get_channel_details(Some(5), nodes[0], InitFeatures::known(), 50_000),
4957 &get_channel_details(Some(6), nodes[0], InitFeatures::known(), 300_000),
4958 &get_channel_details(Some(7), nodes[0], InitFeatures::known(), 50_000),
4959 &get_channel_details(Some(8), nodes[0], InitFeatures::known(), 50_000),
4960 &get_channel_details(Some(9), nodes[0], InitFeatures::known(), 50_000),
4961 &get_channel_details(Some(4), nodes[0], InitFeatures::known(), 1_000_000),
4962 ]), 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4963 assert_eq!(route.paths.len(), 1);
4964 assert_eq!(route.paths[0].len(), 1);
4966 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
4967 assert_eq!(route.paths[0][0].short_channel_id, 6);
4968 assert_eq!(route.paths[0][0].fee_msat, 100_000);
4973 fn prefers_shorter_route_with_higher_fees() {
4974 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4975 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4976 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
4978 // Without penalizing each hop 100 msats, a longer path with lower fees is chosen.
4979 let scorer = test_utils::TestScorer::with_penalty(0);
4980 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4981 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4982 let route = get_route(
4983 &our_id, &payment_params, &network_graph.read_only(), None, 100, 42,
4984 Arc::clone(&logger), &scorer, &random_seed_bytes
4986 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4988 assert_eq!(route.get_total_fees(), 100);
4989 assert_eq!(route.get_total_amount(), 100);
4990 assert_eq!(path, vec![2, 4, 6, 11, 8]);
4992 // Applying a 100 msat penalty to each hop results in taking channels 7 and 10 to nodes[6]
4993 // from nodes[2] rather than channel 6, 11, and 8, even though the longer path is cheaper.
4994 let scorer = test_utils::TestScorer::with_penalty(100);
4995 let route = get_route(
4996 &our_id, &payment_params, &network_graph.read_only(), None, 100, 42,
4997 Arc::clone(&logger), &scorer, &random_seed_bytes
4999 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5001 assert_eq!(route.get_total_fees(), 300);
5002 assert_eq!(route.get_total_amount(), 100);
5003 assert_eq!(path, vec![2, 4, 7, 10]);
5006 struct BadChannelScorer {
5007 short_channel_id: u64,
5011 impl Writeable for BadChannelScorer {
5012 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), ::io::Error> { unimplemented!() }
5014 impl Score for BadChannelScorer {
5015 fn channel_penalty_msat(&self, short_channel_id: u64, _send_amt: u64, _capacity_msat: u64, _source: &NodeId, _target: &NodeId) -> u64 {
5016 if short_channel_id == self.short_channel_id { u64::max_value() } else { 0 }
5019 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
5020 fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
5023 struct BadNodeScorer {
5028 impl Writeable for BadNodeScorer {
5029 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), ::io::Error> { unimplemented!() }
5032 impl Score for BadNodeScorer {
5033 fn channel_penalty_msat(&self, _short_channel_id: u64, _send_amt: u64, _capacity_msat: u64, _source: &NodeId, target: &NodeId) -> u64 {
5034 if *target == self.node_id { u64::max_value() } else { 0 }
5037 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
5038 fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
5042 fn avoids_routing_through_bad_channels_and_nodes() {
5043 let (secp_ctx, network, _, _, logger) = build_graph();
5044 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5045 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
5046 let network_graph = network.read_only();
5048 // A path to nodes[6] exists when no penalties are applied to any channel.
5049 let scorer = test_utils::TestScorer::with_penalty(0);
5050 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5051 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5052 let route = get_route(
5053 &our_id, &payment_params, &network_graph, None, 100, 42,
5054 Arc::clone(&logger), &scorer, &random_seed_bytes
5056 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5058 assert_eq!(route.get_total_fees(), 100);
5059 assert_eq!(route.get_total_amount(), 100);
5060 assert_eq!(path, vec![2, 4, 6, 11, 8]);
5062 // A different path to nodes[6] exists if channel 6 cannot be routed over.
5063 let scorer = BadChannelScorer { short_channel_id: 6 };
5064 let route = get_route(
5065 &our_id, &payment_params, &network_graph, None, 100, 42,
5066 Arc::clone(&logger), &scorer, &random_seed_bytes
5068 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5070 assert_eq!(route.get_total_fees(), 300);
5071 assert_eq!(route.get_total_amount(), 100);
5072 assert_eq!(path, vec![2, 4, 7, 10]);
5074 // A path to nodes[6] does not exist if nodes[2] cannot be routed through.
5075 let scorer = BadNodeScorer { node_id: NodeId::from_pubkey(&nodes[2]) };
5077 &our_id, &payment_params, &network_graph, None, 100, 42,
5078 Arc::clone(&logger), &scorer, &random_seed_bytes
5080 Err(LightningError { err, .. } ) => {
5081 assert_eq!(err, "Failed to find a path to the given destination");
5083 Ok(_) => panic!("Expected error"),
5088 fn total_fees_single_path() {
5092 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5093 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5094 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5097 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5098 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5099 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5102 pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
5103 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5104 short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0
5107 payment_params: None,
5110 assert_eq!(route.get_total_fees(), 250);
5111 assert_eq!(route.get_total_amount(), 225);
5115 fn total_fees_multi_path() {
5119 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5120 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5121 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5124 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5125 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5126 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5130 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5131 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5132 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5135 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5136 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5137 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5140 payment_params: None,
5143 assert_eq!(route.get_total_fees(), 200);
5144 assert_eq!(route.get_total_amount(), 300);
5148 fn total_empty_route_no_panic() {
5149 // In an earlier version of `Route::get_total_fees` and `Route::get_total_amount`, they
5150 // would both panic if the route was completely empty. We test to ensure they return 0
5151 // here, even though its somewhat nonsensical as a route.
5152 let route = Route { paths: Vec::new(), payment_params: None };
5154 assert_eq!(route.get_total_fees(), 0);
5155 assert_eq!(route.get_total_amount(), 0);
5159 fn limits_total_cltv_delta() {
5160 let (secp_ctx, network, _, _, logger) = build_graph();
5161 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5162 let network_graph = network.read_only();
5164 let scorer = test_utils::TestScorer::with_penalty(0);
5166 // Make sure that generally there is at least one route available
5167 let feasible_max_total_cltv_delta = 1008;
5168 let feasible_payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes))
5169 .with_max_total_cltv_expiry_delta(feasible_max_total_cltv_delta);
5170 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5171 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5172 let route = get_route(&our_id, &feasible_payment_params, &network_graph, None, 100, 0, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5173 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5174 assert_ne!(path.len(), 0);
5176 // But not if we exclude all paths on the basis of their accumulated CLTV delta
5177 let fail_max_total_cltv_delta = 23;
5178 let fail_payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes))
5179 .with_max_total_cltv_expiry_delta(fail_max_total_cltv_delta);
5180 match get_route(&our_id, &fail_payment_params, &network_graph, None, 100, 0, Arc::clone(&logger), &scorer, &random_seed_bytes)
5182 Err(LightningError { err, .. } ) => {
5183 assert_eq!(err, "Failed to find a path to the given destination");
5185 Ok(_) => panic!("Expected error"),
5190 fn adds_and_limits_cltv_offset() {
5191 let (secp_ctx, network_graph, _, _, logger) = build_graph();
5192 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5194 let scorer = test_utils::TestScorer::with_penalty(0);
5196 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
5197 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5198 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5199 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5200 assert_eq!(route.paths.len(), 1);
5202 let cltv_expiry_deltas_before = route.paths[0].iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5204 // Check whether the offset added to the last hop by default is in [1 .. DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA]
5205 let mut route_default = route.clone();
5206 add_random_cltv_offset(&mut route_default, &payment_params, &network_graph.read_only(), &random_seed_bytes);
5207 let cltv_expiry_deltas_default = route_default.paths[0].iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5208 assert_eq!(cltv_expiry_deltas_before.split_last().unwrap().1, cltv_expiry_deltas_default.split_last().unwrap().1);
5209 assert!(cltv_expiry_deltas_default.last() > cltv_expiry_deltas_before.last());
5210 assert!(cltv_expiry_deltas_default.last().unwrap() <= &DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA);
5212 // Check that no offset is added when we restrict the max_total_cltv_expiry_delta
5213 let mut route_limited = route.clone();
5214 let limited_max_total_cltv_expiry_delta = cltv_expiry_deltas_before.iter().sum();
5215 let limited_payment_params = payment_params.with_max_total_cltv_expiry_delta(limited_max_total_cltv_expiry_delta);
5216 add_random_cltv_offset(&mut route_limited, &limited_payment_params, &network_graph.read_only(), &random_seed_bytes);
5217 let cltv_expiry_deltas_limited = route_limited.paths[0].iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5218 assert_eq!(cltv_expiry_deltas_before, cltv_expiry_deltas_limited);
5222 fn adds_plausible_cltv_offset() {
5223 let (secp_ctx, network, _, _, logger) = build_graph();
5224 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5225 let network_graph = network.read_only();
5226 let network_nodes = network_graph.nodes();
5227 let network_channels = network_graph.channels();
5228 let scorer = test_utils::TestScorer::with_penalty(0);
5229 let payment_params = PaymentParameters::from_node_id(nodes[3]);
5230 let keys_manager = test_utils::TestKeysInterface::new(&[4u8; 32], Network::Testnet);
5231 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5233 let mut route = get_route(&our_id, &payment_params, &network_graph, None, 100, 0,
5234 Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5235 add_random_cltv_offset(&mut route, &payment_params, &network_graph, &random_seed_bytes);
5237 let mut path_plausibility = vec![];
5239 for p in route.paths {
5240 // 1. Select random observation point
5241 let mut prng = ChaCha20::new(&random_seed_bytes, &[0u8; 12]);
5242 let mut random_bytes = [0u8; ::core::mem::size_of::<usize>()];
5244 prng.process_in_place(&mut random_bytes);
5245 let random_path_index = usize::from_be_bytes(random_bytes).wrapping_rem(p.len());
5246 let observation_point = NodeId::from_pubkey(&p.get(random_path_index).unwrap().pubkey);
5248 // 2. Calculate what CLTV expiry delta we would observe there
5249 let observed_cltv_expiry_delta: u32 = p[random_path_index..].iter().map(|h| h.cltv_expiry_delta).sum();
5251 // 3. Starting from the observation point, find candidate paths
5252 let mut candidates: VecDeque<(NodeId, Vec<u32>)> = VecDeque::new();
5253 candidates.push_back((observation_point, vec![]));
5255 let mut found_plausible_candidate = false;
5257 'candidate_loop: while let Some((cur_node_id, cur_path_cltv_deltas)) = candidates.pop_front() {
5258 if let Some(remaining) = observed_cltv_expiry_delta.checked_sub(cur_path_cltv_deltas.iter().sum::<u32>()) {
5259 if remaining == 0 || remaining.wrapping_rem(40) == 0 || remaining.wrapping_rem(144) == 0 {
5260 found_plausible_candidate = true;
5261 break 'candidate_loop;
5265 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
5266 for channel_id in &cur_node.channels {
5267 if let Some(channel_info) = network_channels.get(&channel_id) {
5268 if let Some((dir_info, next_id)) = channel_info.as_directed_from(&cur_node_id) {
5269 if let Some(channel_update_info) = dir_info.direction() {
5270 let next_cltv_expiry_delta = channel_update_info.cltv_expiry_delta as u32;
5271 if cur_path_cltv_deltas.iter().sum::<u32>()
5272 .saturating_add(next_cltv_expiry_delta) <= observed_cltv_expiry_delta {
5273 let mut new_path_cltv_deltas = cur_path_cltv_deltas.clone();
5274 new_path_cltv_deltas.push(next_cltv_expiry_delta);
5275 candidates.push_back((*next_id, new_path_cltv_deltas));
5284 path_plausibility.push(found_plausible_candidate);
5286 assert!(path_plausibility.iter().all(|x| *x));
5289 #[cfg(not(feature = "no-std"))]
5290 pub(super) fn random_init_seed() -> u64 {
5291 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
5292 use core::hash::{BuildHasher, Hasher};
5293 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
5294 println!("Using seed of {}", seed);
5297 #[cfg(not(feature = "no-std"))]
5298 use util::ser::Readable;
5301 #[cfg(not(feature = "no-std"))]
5302 fn generate_routes() {
5303 use routing::scoring::{ProbabilisticScorer, ProbabilisticScoringParameters};
5305 let mut d = match super::test_utils::get_route_file() {
5312 let graph = NetworkGraph::read(&mut d).unwrap();
5313 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5314 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5316 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
5317 let mut seed = random_init_seed() as usize;
5318 let nodes = graph.read_only().nodes().clone();
5319 'load_endpoints: for _ in 0..10 {
5321 seed = seed.overflowing_mul(0xdeadbeef).0;
5322 let src = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5323 seed = seed.overflowing_mul(0xdeadbeef).0;
5324 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5325 let payment_params = PaymentParameters::from_node_id(dst);
5326 let amt = seed as u64 % 200_000_000;
5327 let params = ProbabilisticScoringParameters::default();
5328 let scorer = ProbabilisticScorer::new(params, &graph);
5329 if get_route(src, &payment_params, &graph.read_only(), None, amt, 42, &test_utils::TestLogger::new(), &scorer, &random_seed_bytes).is_ok() {
5330 continue 'load_endpoints;
5337 #[cfg(not(feature = "no-std"))]
5338 fn generate_routes_mpp() {
5339 use routing::scoring::{ProbabilisticScorer, ProbabilisticScoringParameters};
5341 let mut d = match super::test_utils::get_route_file() {
5348 let graph = NetworkGraph::read(&mut d).unwrap();
5349 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5350 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5352 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
5353 let mut seed = random_init_seed() as usize;
5354 let nodes = graph.read_only().nodes().clone();
5355 'load_endpoints: for _ in 0..10 {
5357 seed = seed.overflowing_mul(0xdeadbeef).0;
5358 let src = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5359 seed = seed.overflowing_mul(0xdeadbeef).0;
5360 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5361 let payment_params = PaymentParameters::from_node_id(dst).with_features(InvoiceFeatures::known());
5362 let amt = seed as u64 % 200_000_000;
5363 let params = ProbabilisticScoringParameters::default();
5364 let scorer = ProbabilisticScorer::new(params, &graph);
5365 if get_route(src, &payment_params, &graph.read_only(), None, amt, 42, &test_utils::TestLogger::new(), &scorer, &random_seed_bytes).is_ok() {
5366 continue 'load_endpoints;
5373 #[cfg(all(test, not(feature = "no-std")))]
5374 pub(crate) mod test_utils {
5376 /// Tries to open a network graph file, or panics with a URL to fetch it.
5377 pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
5378 let res = File::open("net_graph-2021-05-31.bin") // By default we're run in RL/lightning
5379 .or_else(|_| File::open("lightning/net_graph-2021-05-31.bin")) // We may be run manually in RL/
5380 .or_else(|_| { // Fall back to guessing based on the binary location
5381 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
5382 let mut path = std::env::current_exe().unwrap();
5383 path.pop(); // lightning-...
5385 path.pop(); // debug
5386 path.pop(); // target
5387 path.push("lightning");
5388 path.push("net_graph-2021-05-31.bin");
5389 eprintln!("{}", path.to_str().unwrap());
5392 .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");
5393 #[cfg(require_route_graph_test)]
5394 return Ok(res.unwrap());
5395 #[cfg(not(require_route_graph_test))]
5400 #[cfg(all(test, feature = "_bench_unstable", not(feature = "no-std")))]
5403 use bitcoin::hashes::Hash;
5404 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
5405 use chain::transaction::OutPoint;
5406 use chain::keysinterface::{KeysManager,KeysInterface};
5407 use ln::channelmanager::{ChannelCounterparty, ChannelDetails};
5408 use ln::features::{InitFeatures, InvoiceFeatures};
5409 use routing::scoring::{FixedPenaltyScorer, ProbabilisticScorer, ProbabilisticScoringParameters, Scorer};
5410 use util::logger::{Logger, Record};
5414 struct DummyLogger {}
5415 impl Logger for DummyLogger {
5416 fn log(&self, _record: &Record) {}
5419 fn read_network_graph() -> NetworkGraph {
5420 let mut d = test_utils::get_route_file().unwrap();
5421 NetworkGraph::read(&mut d).unwrap()
5424 fn payer_pubkey() -> PublicKey {
5425 let secp_ctx = Secp256k1::new();
5426 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
5430 fn first_hop(node_id: PublicKey) -> ChannelDetails {
5432 channel_id: [0; 32],
5433 counterparty: ChannelCounterparty {
5434 features: InitFeatures::known(),
5436 unspendable_punishment_reserve: 0,
5437 forwarding_info: None,
5439 funding_txo: Some(OutPoint {
5440 txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0
5443 short_channel_id: Some(1),
5444 inbound_scid_alias: None,
5445 channel_value_satoshis: 10_000_000,
5447 balance_msat: 10_000_000,
5448 outbound_capacity_msat: 10_000_000,
5449 inbound_capacity_msat: 0,
5450 unspendable_punishment_reserve: None,
5451 confirmations_required: None,
5452 force_close_spend_delay: None,
5454 is_funding_locked: true,
5461 fn generate_routes_with_zero_penalty_scorer(bench: &mut Bencher) {
5462 let network_graph = read_network_graph();
5463 let scorer = FixedPenaltyScorer::with_penalty(0);
5464 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::empty());
5468 fn generate_mpp_routes_with_zero_penalty_scorer(bench: &mut Bencher) {
5469 let network_graph = read_network_graph();
5470 let scorer = FixedPenaltyScorer::with_penalty(0);
5471 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::known());
5475 fn generate_routes_with_default_scorer(bench: &mut Bencher) {
5476 let network_graph = read_network_graph();
5477 let scorer = Scorer::default();
5478 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::empty());
5482 fn generate_mpp_routes_with_default_scorer(bench: &mut Bencher) {
5483 let network_graph = read_network_graph();
5484 let scorer = Scorer::default();
5485 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::known());
5489 fn generate_routes_with_probabilistic_scorer(bench: &mut Bencher) {
5490 let network_graph = read_network_graph();
5491 let params = ProbabilisticScoringParameters::default();
5492 let scorer = ProbabilisticScorer::new(params, &network_graph);
5493 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::empty());
5497 fn generate_mpp_routes_with_probabilistic_scorer(bench: &mut Bencher) {
5498 let network_graph = read_network_graph();
5499 let params = ProbabilisticScoringParameters::default();
5500 let scorer = ProbabilisticScorer::new(params, &network_graph);
5501 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::known());
5504 fn generate_routes<S: Score>(
5505 bench: &mut Bencher, graph: &NetworkGraph, mut scorer: S, features: InvoiceFeatures
5507 let nodes = graph.read_only().nodes().clone();
5508 let payer = payer_pubkey();
5509 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
5510 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5512 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
5513 let mut routes = Vec::new();
5514 let mut route_endpoints = Vec::new();
5515 let mut seed: usize = 0xdeadbeef;
5516 'load_endpoints: for _ in 0..150 {
5519 let src = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5521 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5522 let params = PaymentParameters::from_node_id(dst).with_features(features.clone());
5523 let first_hop = first_hop(src);
5524 let amt = seed as u64 % 1_000_000;
5525 if let Ok(route) = get_route(&payer, ¶ms, &graph.read_only(), Some(&[&first_hop]), amt, 42, &DummyLogger{}, &scorer, &random_seed_bytes) {
5527 route_endpoints.push((first_hop, params, amt));
5528 continue 'load_endpoints;
5533 // ...and seed the scorer with success and failure data...
5534 for route in routes {
5535 let amount = route.get_total_amount();
5536 if amount < 250_000 {
5537 for path in route.paths {
5538 scorer.payment_path_successful(&path.iter().collect::<Vec<_>>());
5540 } else if amount > 750_000 {
5541 for path in route.paths {
5542 let short_channel_id = path[path.len() / 2].short_channel_id;
5543 scorer.payment_path_failed(&path.iter().collect::<Vec<_>>(), short_channel_id);
5548 // Because we've changed channel scores, its possible we'll take different routes to the
5549 // selected destinations, possibly causing us to fail because, eg, the newly-selected path
5550 // requires a too-high CLTV delta.
5551 route_endpoints.retain(|(first_hop, params, amt)| {
5552 get_route(&payer, params, &graph.read_only(), Some(&[first_hop]), *amt, 42, &DummyLogger{}, &scorer, &random_seed_bytes).is_ok()
5554 route_endpoints.truncate(100);
5555 assert_eq!(route_endpoints.len(), 100);
5557 // ...then benchmark finding paths between the nodes we learned.
5560 let (first_hop, params, amt) = &route_endpoints[idx % route_endpoints.len()];
5561 assert!(get_route(&payer, params, &graph.read_only(), Some(&[first_hop]), *amt, 42, &DummyLogger{}, &scorer, &random_seed_bytes).is_ok());