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 log_trace!(logger, "Building path from {} (payee) to {} (us/payer) for value {} msat.", payment_params.payee_pubkey, our_node_pubkey, final_value_msat);
818 macro_rules! add_entry {
819 // Adds entry which goes from $src_node_id to $dest_node_id over the $candidate hop.
820 // $next_hops_fee_msat represents the fees paid for using all the channels *after* this one,
821 // since that value has to be transferred over this channel.
822 // Returns whether this channel caused an update to `targets`.
823 ( $candidate: expr, $src_node_id: expr, $dest_node_id: expr, $next_hops_fee_msat: expr,
824 $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr,
825 $next_hops_path_penalty_msat: expr, $next_hops_cltv_delta: expr ) => { {
826 // We "return" whether we updated the path at the end, via this:
827 let mut did_add_update_path_to_src_node = false;
828 // Channels to self should not be used. This is more of belt-and-suspenders, because in
829 // practice these cases should be caught earlier:
830 // - for regular channels at channel announcement (TODO)
831 // - for first and last hops early in get_route
832 if $src_node_id != $dest_node_id {
833 let short_channel_id = $candidate.short_channel_id();
834 let available_liquidity_msat = bookkept_channels_liquidity_available_msat
835 .entry(short_channel_id)
836 .or_insert_with(|| $candidate.effective_capacity().as_msat());
838 // It is tricky to subtract $next_hops_fee_msat from available liquidity here.
839 // It may be misleading because we might later choose to reduce the value transferred
840 // over these channels, and the channel which was insufficient might become sufficient.
841 // Worst case: we drop a good channel here because it can't cover the high following
842 // fees caused by one expensive channel, but then this channel could have been used
843 // if the amount being transferred over this path is lower.
844 // We do this for now, but this is a subject for removal.
845 if let Some(available_value_contribution_msat) = available_liquidity_msat.checked_sub($next_hops_fee_msat) {
847 // Routing Fragmentation Mitigation heuristic:
849 // Routing fragmentation across many payment paths increases the overall routing
850 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
851 // Taking too many smaller paths also increases the chance of payment failure.
852 // Thus to avoid this effect, we require from our collected links to provide
853 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
855 // This requirement is currently 5% of the remaining-to-be-collected value.
856 // This means as we successfully advance in our collection,
857 // the absolute liquidity contribution is lowered,
858 // thus increasing the number of potential channels to be selected.
860 // Derive the minimal liquidity contribution with a ratio of 20 (5%, rounded up)
861 // or 100% if we're not allowed to do multipath payments.
862 let minimal_value_contribution_msat: u64 = if allow_mpp {
863 (recommended_value_msat - already_collected_value_msat + 19) / 20
867 // Verify the liquidity offered by this channel complies to the minimal contribution.
868 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
870 // Do not consider candidates that exceed the maximum total cltv expiry limit.
871 // In order to already account for some of the privacy enhancing random CLTV
872 // expiry delta offset we add on top later, we subtract a rough estimate
873 // (2*MEDIAN_HOP_CLTV_EXPIRY_DELTA) here.
874 let max_total_cltv_expiry_delta = (payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta)
875 .checked_sub(2*MEDIAN_HOP_CLTV_EXPIRY_DELTA)
876 .unwrap_or(payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta);
877 let hop_total_cltv_delta = ($next_hops_cltv_delta as u32)
878 .saturating_add($candidate.cltv_expiry_delta());
879 let doesnt_exceed_cltv_delta_limit = hop_total_cltv_delta <= max_total_cltv_expiry_delta;
881 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
882 // Includes paying fees for the use of the following channels.
883 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
884 Some(result) => result,
885 // Can't overflow due to how the values were computed right above.
886 None => unreachable!(),
888 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
889 let over_path_minimum_msat = amount_to_transfer_over_msat >= $candidate.htlc_minimum_msat() &&
890 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
892 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
893 // bother considering this channel.
894 // Since we're choosing amount_to_transfer_over_msat as maximum possible, it can
895 // be only reduced later (not increased), so this channel should just be skipped
896 // as not sufficient.
897 if !over_path_minimum_msat && doesnt_exceed_cltv_delta_limit {
898 hit_minimum_limit = true;
899 } else if contributes_sufficient_value && doesnt_exceed_cltv_delta_limit {
900 // Note that low contribution here (limited by available_liquidity_msat)
901 // might violate htlc_minimum_msat on the hops which are next along the
902 // payment path (upstream to the payee). To avoid that, we recompute
903 // path fees knowing the final path contribution after constructing it.
904 let path_htlc_minimum_msat = compute_fees($next_hops_path_htlc_minimum_msat, $candidate.fees())
905 .and_then(|fee_msat| fee_msat.checked_add($next_hops_path_htlc_minimum_msat))
906 .map(|fee_msat| cmp::max(fee_msat, $candidate.htlc_minimum_msat()))
907 .unwrap_or_else(|| u64::max_value());
908 let hm_entry = dist.entry($src_node_id);
909 let old_entry = hm_entry.or_insert_with(|| {
910 // If there was previously no known way to access the source node
911 // (recall it goes payee-to-payer) of short_channel_id, first add a
912 // semi-dummy record just to compute the fees to reach the source node.
913 // This will affect our decision on selecting short_channel_id
914 // as a way to reach the $dest_node_id.
915 let mut fee_base_msat = 0;
916 let mut fee_proportional_millionths = 0;
917 if let Some(Some(fees)) = network_nodes.get(&$src_node_id).map(|node| node.lowest_inbound_channel_fees) {
918 fee_base_msat = fees.base_msat;
919 fee_proportional_millionths = fees.proportional_millionths;
922 node_id: $dest_node_id.clone(),
923 candidate: $candidate.clone(),
925 src_lowest_inbound_fees: RoutingFees {
926 base_msat: fee_base_msat,
927 proportional_millionths: fee_proportional_millionths,
929 next_hops_fee_msat: u64::max_value(),
930 hop_use_fee_msat: u64::max_value(),
931 total_fee_msat: u64::max_value(),
932 path_htlc_minimum_msat,
933 path_penalty_msat: u64::max_value(),
934 was_processed: false,
935 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
936 value_contribution_msat,
940 #[allow(unused_mut)] // We only use the mut in cfg(test)
941 let mut should_process = !old_entry.was_processed;
942 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
944 // In test/fuzzing builds, we do extra checks to make sure the skipping
945 // of already-seen nodes only happens in cases we expect (see below).
946 if !should_process { should_process = true; }
950 let mut hop_use_fee_msat = 0;
951 let mut total_fee_msat = $next_hops_fee_msat;
953 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
954 // will have the same effective-fee
955 if $src_node_id != our_node_id {
956 match compute_fees(amount_to_transfer_over_msat, $candidate.fees()) {
957 // max_value means we'll always fail
958 // the old_entry.total_fee_msat > total_fee_msat check
959 None => total_fee_msat = u64::max_value(),
961 hop_use_fee_msat = fee_msat;
962 total_fee_msat += hop_use_fee_msat;
963 // When calculating the lowest inbound fees to a node, we
964 // calculate fees here not based on the actual value we think
965 // will flow over this channel, but on the minimum value that
966 // we'll accept flowing over it. The minimum accepted value
967 // is a constant through each path collection run, ensuring
968 // consistent basis. Otherwise we may later find a
969 // different path to the source node that is more expensive,
970 // but which we consider to be cheaper because we are capacity
971 // constrained and the relative fee becomes lower.
972 match compute_fees(minimal_value_contribution_msat, old_entry.src_lowest_inbound_fees)
973 .map(|a| a.checked_add(total_fee_msat)) {
978 total_fee_msat = u64::max_value();
985 let path_penalty_msat = $next_hops_path_penalty_msat.saturating_add(
986 scorer.channel_penalty_msat(short_channel_id, amount_to_transfer_over_msat,
987 *available_liquidity_msat, &$src_node_id, &$dest_node_id));
988 let new_graph_node = RouteGraphNode {
989 node_id: $src_node_id,
990 lowest_fee_to_peer_through_node: total_fee_msat,
991 lowest_fee_to_node: $next_hops_fee_msat as u64 + hop_use_fee_msat,
992 total_cltv_delta: hop_total_cltv_delta,
993 value_contribution_msat: value_contribution_msat,
994 path_htlc_minimum_msat,
998 // Update the way of reaching $src_node_id with the given short_channel_id (from $dest_node_id),
999 // if this way is cheaper than the already known
1000 // (considering the cost to "reach" this channel from the route destination,
1001 // the cost of using this channel,
1002 // and the cost of routing to the source node of this channel).
1003 // Also, consider that htlc_minimum_msat_difference, because we might end up
1004 // paying it. Consider the following exploit:
1005 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
1006 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
1007 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
1008 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
1010 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
1011 // but it may require additional tracking - we don't want to double-count
1012 // the fees included in $next_hops_path_htlc_minimum_msat, but also
1013 // can't use something that may decrease on future hops.
1014 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat)
1015 .saturating_add(old_entry.path_penalty_msat);
1016 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat)
1017 .saturating_add(path_penalty_msat);
1019 if !old_entry.was_processed && new_cost < old_cost {
1020 targets.push(new_graph_node);
1021 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
1022 old_entry.hop_use_fee_msat = hop_use_fee_msat;
1023 old_entry.total_fee_msat = total_fee_msat;
1024 old_entry.node_id = $dest_node_id.clone();
1025 old_entry.candidate = $candidate.clone();
1026 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
1027 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
1028 old_entry.path_penalty_msat = path_penalty_msat;
1029 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
1031 old_entry.value_contribution_msat = value_contribution_msat;
1033 did_add_update_path_to_src_node = true;
1034 } else if old_entry.was_processed && new_cost < old_cost {
1035 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
1037 // If we're skipping processing a node which was previously
1038 // processed even though we found another path to it with a
1039 // cheaper fee, check that it was because the second path we
1040 // found (which we are processing now) has a lower value
1041 // contribution due to an HTLC minimum limit.
1043 // e.g. take a graph with two paths from node 1 to node 2, one
1044 // through channel A, and one through channel B. Channel A and
1045 // B are both in the to-process heap, with their scores set by
1046 // a higher htlc_minimum than fee.
1047 // Channel A is processed first, and the channels onwards from
1048 // node 1 are added to the to-process heap. Thereafter, we pop
1049 // Channel B off of the heap, note that it has a much more
1050 // restrictive htlc_maximum_msat, and recalculate the fees for
1051 // all of node 1's channels using the new, reduced, amount.
1053 // This would be bogus - we'd be selecting a higher-fee path
1054 // with a lower htlc_maximum_msat instead of the one we'd
1055 // already decided to use.
1056 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
1058 value_contribution_msat + path_penalty_msat <
1059 old_entry.value_contribution_msat + old_entry.path_penalty_msat
1067 did_add_update_path_to_src_node
1071 let empty_node_features = NodeFeatures::empty();
1072 // Find ways (channels with destination) to reach a given node and store them
1073 // in the corresponding data structures (routing graph etc).
1074 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
1075 // meaning how much will be paid in fees after this node (to the best of our knowledge).
1076 // This data can later be helpful to optimize routing (pay lower fees).
1077 macro_rules! add_entries_to_cheapest_to_target_node {
1078 ( $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 ) => {
1079 let skip_node = if let Some(elem) = dist.get_mut(&$node_id) {
1080 let was_processed = elem.was_processed;
1081 elem.was_processed = true;
1084 // Entries are added to dist in add_entry!() when there is a channel from a node.
1085 // Because there are no channels from payee, it will not have a dist entry at this point.
1086 // If we're processing any other node, it is always be the result of a channel from it.
1087 assert_eq!($node_id, payee_node_id);
1092 if let Some(first_channels) = first_hop_targets.get(&$node_id) {
1093 for details in first_channels {
1094 let candidate = CandidateRouteHop::FirstHop { details };
1095 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);
1099 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
1102 &empty_node_features
1105 if !features.requires_unknown_bits() {
1106 for chan_id in $node.channels.iter() {
1107 let chan = network_channels.get(chan_id).unwrap();
1108 if !chan.features.requires_unknown_bits() {
1109 let (directed_channel, source) =
1110 chan.as_directed_to(&$node_id).expect("inconsistent NetworkGraph");
1111 if first_hops.is_none() || *source != our_node_id {
1112 if let Some(direction) = directed_channel.direction() {
1113 if direction.enabled {
1114 let candidate = CandidateRouteHop::PublicHop {
1115 info: directed_channel.with_update().unwrap(),
1116 short_channel_id: *chan_id,
1118 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);
1129 let mut payment_paths = Vec::<PaymentPath>::new();
1131 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
1132 'paths_collection: loop {
1133 // For every new path, start from scratch, except
1134 // bookkept_channels_liquidity_available_msat, which will improve
1135 // the further iterations of path finding. Also don't erase first_hop_targets.
1138 hit_minimum_limit = false;
1140 // If first hop is a private channel and the only way to reach the payee, this is the only
1141 // place where it could be added.
1142 if let Some(first_channels) = first_hop_targets.get(&payee_node_id) {
1143 for details in first_channels {
1144 let candidate = CandidateRouteHop::FirstHop { details };
1145 let added = add_entry!(candidate, our_node_id, payee_node_id, 0, path_value_msat, 0, 0u64, 0);
1146 log_trace!(logger, "{} direct route to payee via SCID {}", if added { "Added" } else { "Skipped" }, candidate.short_channel_id());
1150 // Add the payee as a target, so that the payee-to-payer
1151 // search algorithm knows what to start with.
1152 match network_nodes.get(&payee_node_id) {
1153 // The payee is not in our network graph, so nothing to add here.
1154 // There is still a chance of reaching them via last_hops though,
1155 // so don't yet fail the payment here.
1156 // If not, targets.pop() will not even let us enter the loop in step 2.
1159 add_entries_to_cheapest_to_target_node!(node, payee_node_id, 0, path_value_msat, 0, 0u64, 0);
1164 // If a caller provided us with last hops, add them to routing targets. Since this happens
1165 // earlier than general path finding, they will be somewhat prioritized, although currently
1166 // it matters only if the fees are exactly the same.
1167 for route in payment_params.route_hints.iter().filter(|route| !route.0.is_empty()) {
1168 let first_hop_in_route = &(route.0)[0];
1169 let have_hop_src_in_graph =
1170 // Only add the hops in this route to our candidate set if either
1171 // we have a direct channel to the first hop or the first hop is
1172 // in the regular network graph.
1173 first_hop_targets.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some() ||
1174 network_nodes.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some();
1175 if have_hop_src_in_graph {
1176 // We start building the path from reverse, i.e., from payee
1177 // to the first RouteHintHop in the path.
1178 let hop_iter = route.0.iter().rev();
1179 let prev_hop_iter = core::iter::once(&payment_params.payee_pubkey).chain(
1180 route.0.iter().skip(1).rev().map(|hop| &hop.src_node_id));
1181 let mut hop_used = true;
1182 let mut aggregate_next_hops_fee_msat: u64 = 0;
1183 let mut aggregate_next_hops_path_htlc_minimum_msat: u64 = 0;
1184 let mut aggregate_next_hops_path_penalty_msat: u64 = 0;
1185 let mut aggregate_next_hops_cltv_delta: u32 = 0;
1187 for (idx, (hop, prev_hop_id)) in hop_iter.zip(prev_hop_iter).enumerate() {
1188 let source = NodeId::from_pubkey(&hop.src_node_id);
1189 let target = NodeId::from_pubkey(&prev_hop_id);
1190 let candidate = network_channels
1191 .get(&hop.short_channel_id)
1192 .and_then(|channel| channel.as_directed_to(&target))
1193 .and_then(|(channel, _)| channel.with_update())
1194 .map(|info| CandidateRouteHop::PublicHop {
1196 short_channel_id: hop.short_channel_id,
1198 .unwrap_or_else(|| CandidateRouteHop::PrivateHop { hint: hop });
1199 let capacity_msat = candidate.effective_capacity().as_msat();
1200 aggregate_next_hops_path_penalty_msat = aggregate_next_hops_path_penalty_msat
1201 .saturating_add(scorer.channel_penalty_msat(hop.short_channel_id, final_value_msat, capacity_msat, &source, &target));
1203 aggregate_next_hops_cltv_delta = aggregate_next_hops_cltv_delta
1204 .saturating_add(hop.cltv_expiry_delta as u32);
1206 if !add_entry!(candidate, source, target, aggregate_next_hops_fee_msat, path_value_msat, aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat, aggregate_next_hops_cltv_delta) {
1207 // If this hop was not used then there is no use checking the preceding hops
1208 // in the RouteHint. We can break by just searching for a direct channel between
1209 // last checked hop and first_hop_targets
1213 // Searching for a direct channel between last checked hop and first_hop_targets
1214 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&prev_hop_id)) {
1215 for details in first_channels {
1216 let candidate = CandidateRouteHop::FirstHop { details };
1217 add_entry!(candidate, our_node_id, NodeId::from_pubkey(&prev_hop_id), aggregate_next_hops_fee_msat, path_value_msat, aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat, aggregate_next_hops_cltv_delta);
1225 // In the next values of the iterator, the aggregate fees already reflects
1226 // the sum of value sent from payer (final_value_msat) and routing fees
1227 // for the last node in the RouteHint. We need to just add the fees to
1228 // route through the current node so that the preceeding node (next iteration)
1230 let hops_fee = compute_fees(aggregate_next_hops_fee_msat + final_value_msat, hop.fees)
1231 .map_or(None, |inc| inc.checked_add(aggregate_next_hops_fee_msat));
1232 aggregate_next_hops_fee_msat = if let Some(val) = hops_fee { val } else { break; };
1234 let hop_htlc_minimum_msat = candidate.htlc_minimum_msat();
1235 let hop_htlc_minimum_msat_inc = if let Some(val) = compute_fees(aggregate_next_hops_path_htlc_minimum_msat, hop.fees) { val } else { break; };
1236 let hops_path_htlc_minimum = aggregate_next_hops_path_htlc_minimum_msat
1237 .checked_add(hop_htlc_minimum_msat_inc);
1238 aggregate_next_hops_path_htlc_minimum_msat = if let Some(val) = hops_path_htlc_minimum { cmp::max(hop_htlc_minimum_msat, val) } else { break; };
1240 if idx == route.0.len() - 1 {
1241 // The last hop in this iterator is the first hop in
1242 // overall RouteHint.
1243 // If this hop connects to a node with which we have a direct channel,
1244 // ignore the network graph and, if the last hop was added, add our
1245 // direct channel to the candidate set.
1247 // Note that we *must* check if the last hop was added as `add_entry`
1248 // always assumes that the third argument is a node to which we have a
1250 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&hop.src_node_id)) {
1251 for details in first_channels {
1252 let candidate = CandidateRouteHop::FirstHop { details };
1253 add_entry!(candidate, our_node_id, NodeId::from_pubkey(&hop.src_node_id), aggregate_next_hops_fee_msat, path_value_msat, aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat, aggregate_next_hops_cltv_delta);
1261 log_trace!(logger, "Starting main path collection loop with {} nodes pre-filled from first/last hops.", targets.len());
1263 // At this point, targets are filled with the data from first and
1264 // last hops communicated by the caller, and the payment receiver.
1265 let mut found_new_path = false;
1268 // If this loop terminates due the exhaustion of targets, two situations are possible:
1269 // - not enough outgoing liquidity:
1270 // 0 < already_collected_value_msat < final_value_msat
1271 // - enough outgoing liquidity:
1272 // final_value_msat <= already_collected_value_msat < recommended_value_msat
1273 // Both these cases (and other cases except reaching recommended_value_msat) mean that
1274 // paths_collection will be stopped because found_new_path==false.
1275 // This is not necessarily a routing failure.
1276 'path_construction: while let Some(RouteGraphNode { node_id, lowest_fee_to_node, total_cltv_delta, value_contribution_msat, path_htlc_minimum_msat, path_penalty_msat, .. }) = targets.pop() {
1278 // Since we're going payee-to-payer, hitting our node as a target means we should stop
1279 // traversing the graph and arrange the path out of what we found.
1280 if node_id == our_node_id {
1281 let mut new_entry = dist.remove(&our_node_id).unwrap();
1282 let mut ordered_hops = vec!((new_entry.clone(), NodeFeatures::empty()));
1285 let mut features_set = false;
1286 if let Some(first_channels) = first_hop_targets.get(&ordered_hops.last().unwrap().0.node_id) {
1287 for details in first_channels {
1288 if details.short_channel_id.unwrap() == ordered_hops.last().unwrap().0.candidate.short_channel_id() {
1289 ordered_hops.last_mut().unwrap().1 = details.counterparty.features.to_context();
1290 features_set = true;
1296 if let Some(node) = network_nodes.get(&ordered_hops.last().unwrap().0.node_id) {
1297 if let Some(node_info) = node.announcement_info.as_ref() {
1298 ordered_hops.last_mut().unwrap().1 = node_info.features.clone();
1300 ordered_hops.last_mut().unwrap().1 = NodeFeatures::empty();
1303 // We can fill in features for everything except hops which were
1304 // provided via the invoice we're paying. We could guess based on the
1305 // recipient's features but for now we simply avoid guessing at all.
1309 // Means we succesfully traversed from the payer to the payee, now
1310 // save this path for the payment route. Also, update the liquidity
1311 // remaining on the used hops, so that we take them into account
1312 // while looking for more paths.
1313 if ordered_hops.last().unwrap().0.node_id == payee_node_id {
1317 new_entry = match dist.remove(&ordered_hops.last().unwrap().0.node_id) {
1318 Some(payment_hop) => payment_hop,
1319 // We can't arrive at None because, if we ever add an entry to targets,
1320 // we also fill in the entry in dist (see add_entry!).
1321 None => unreachable!(),
1323 // We "propagate" the fees one hop backward (topologically) here,
1324 // so that fees paid for a HTLC forwarding on the current channel are
1325 // associated with the previous channel (where they will be subtracted).
1326 ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
1327 ordered_hops.push((new_entry.clone(), NodeFeatures::empty()));
1329 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
1330 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
1332 log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: \n {:#?}",
1333 ordered_hops.len(), value_contribution_msat, ordered_hops.iter().map(|h| &(h.0)).collect::<Vec<&PathBuildingHop>>());
1335 let mut payment_path = PaymentPath {hops: ordered_hops};
1337 // We could have possibly constructed a slightly inconsistent path: since we reduce
1338 // value being transferred along the way, we could have violated htlc_minimum_msat
1339 // on some channels we already passed (assuming dest->source direction). Here, we
1340 // recompute the fees again, so that if that's the case, we match the currently
1341 // underpaid htlc_minimum_msat with fees.
1342 payment_path.update_value_and_recompute_fees(cmp::min(value_contribution_msat, final_value_msat));
1344 // Since a path allows to transfer as much value as
1345 // the smallest channel it has ("bottleneck"), we should recompute
1346 // the fees so sender HTLC don't overpay fees when traversing
1347 // larger channels than the bottleneck. This may happen because
1348 // when we were selecting those channels we were not aware how much value
1349 // this path will transfer, and the relative fee for them
1350 // might have been computed considering a larger value.
1351 // Remember that we used these channels so that we don't rely
1352 // on the same liquidity in future paths.
1353 let mut prevented_redundant_path_selection = false;
1354 for (payment_hop, _) in payment_path.hops.iter() {
1355 let channel_liquidity_available_msat = bookkept_channels_liquidity_available_msat.get_mut(&payment_hop.candidate.short_channel_id()).unwrap();
1356 let mut spent_on_hop_msat = value_contribution_msat;
1357 let next_hops_fee_msat = payment_hop.next_hops_fee_msat;
1358 spent_on_hop_msat += next_hops_fee_msat;
1359 if spent_on_hop_msat == *channel_liquidity_available_msat {
1360 // If this path used all of this channel's available liquidity, we know
1361 // this path will not be selected again in the next loop iteration.
1362 prevented_redundant_path_selection = true;
1364 *channel_liquidity_available_msat -= spent_on_hop_msat;
1366 if !prevented_redundant_path_selection {
1367 // If we weren't capped by hitting a liquidity limit on a channel in the path,
1368 // we'll probably end up picking the same path again on the next iteration.
1369 // Decrease the available liquidity of a hop in the middle of the path.
1370 let victim_scid = payment_path.hops[(payment_path.hops.len() - 1) / 2].0.candidate.short_channel_id();
1371 log_trace!(logger, "Disabling channel {} for future path building iterations to avoid duplicates.", victim_scid);
1372 let victim_liquidity = bookkept_channels_liquidity_available_msat.get_mut(&victim_scid).unwrap();
1373 *victim_liquidity = 0;
1376 // Track the total amount all our collected paths allow to send so that we:
1377 // - know when to stop looking for more paths
1378 // - know which of the hops are useless considering how much more sats we need
1379 // (contributes_sufficient_value)
1380 already_collected_value_msat += value_contribution_msat;
1382 payment_paths.push(payment_path);
1383 found_new_path = true;
1384 break 'path_construction;
1387 // If we found a path back to the payee, we shouldn't try to process it again. This is
1388 // the equivalent of the `elem.was_processed` check in
1389 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
1390 if node_id == payee_node_id { continue 'path_construction; }
1392 // Otherwise, since the current target node is not us,
1393 // keep "unrolling" the payment graph from payee to payer by
1394 // finding a way to reach the current target from the payer side.
1395 match network_nodes.get(&node_id) {
1398 add_entries_to_cheapest_to_target_node!(node, node_id, lowest_fee_to_node, value_contribution_msat, path_htlc_minimum_msat, path_penalty_msat, total_cltv_delta);
1404 // If we don't support MPP, no use trying to gather more value ever.
1405 break 'paths_collection;
1409 // Stop either when the recommended value is reached or if no new path was found in this
1411 // In the latter case, making another path finding attempt won't help,
1412 // because we deterministically terminated the search due to low liquidity.
1413 if already_collected_value_msat >= recommended_value_msat || !found_new_path {
1414 log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
1415 already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
1416 break 'paths_collection;
1417 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
1418 // Further, if this was our first walk of the graph, and we weren't limited by an
1419 // htlc_minimum_msat, return immediately because this path should suffice. If we were
1420 // limited by an htlc_minimum_msat value, find another path with a higher value,
1421 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
1422 // still keeping a lower total fee than this path.
1423 if !hit_minimum_limit {
1424 log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
1425 break 'paths_collection;
1427 log_trace!(logger, "Collected our payment amount on the first pass, but running again to collect extra paths with a potentially higher limit.");
1428 path_value_msat = recommended_value_msat;
1433 if payment_paths.len() == 0 {
1434 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1437 if already_collected_value_msat < final_value_msat {
1438 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1441 // Sort by total fees and take the best paths.
1442 payment_paths.sort_unstable_by_key(|path| path.get_total_fee_paid_msat());
1443 if payment_paths.len() > 50 {
1444 payment_paths.truncate(50);
1447 // Draw multiple sufficient routes by randomly combining the selected paths.
1448 let mut drawn_routes = Vec::new();
1449 let mut prng = ChaCha20::new(random_seed_bytes, &[0u8; 12]);
1450 let mut random_index_bytes = [0u8; ::core::mem::size_of::<usize>()];
1452 let num_permutations = payment_paths.len();
1453 for _ in 0..num_permutations {
1454 let mut cur_route = Vec::<PaymentPath>::new();
1455 let mut aggregate_route_value_msat = 0;
1458 // Do a Fisher-Yates shuffle to create a random permutation of the payment paths
1459 for cur_index in (1..payment_paths.len()).rev() {
1460 prng.process_in_place(&mut random_index_bytes);
1461 let random_index = usize::from_be_bytes(random_index_bytes).wrapping_rem(cur_index+1);
1462 payment_paths.swap(cur_index, random_index);
1466 for payment_path in &payment_paths {
1467 cur_route.push(payment_path.clone());
1468 aggregate_route_value_msat += payment_path.get_value_msat();
1469 if aggregate_route_value_msat > final_value_msat {
1470 // Last path likely overpaid. Substract it from the most expensive
1471 // (in terms of proportional fee) path in this route and recompute fees.
1472 // This might be not the most economically efficient way, but fewer paths
1473 // also makes routing more reliable.
1474 let mut overpaid_value_msat = aggregate_route_value_msat - final_value_msat;
1476 // First, we drop some expensive low-value paths entirely if possible, since fewer
1477 // paths is better: the payment is less likely to fail. In order to do so, we sort
1478 // by value and fall back to total fees paid, i.e., in case of equal values we
1479 // prefer lower cost paths.
1480 cur_route.sort_unstable_by(|a, b| {
1481 a.get_value_msat().cmp(&b.get_value_msat())
1482 // Reverse ordering for fees, so we drop higher-fee paths first
1483 .then_with(|| b.get_total_fee_paid_msat().saturating_add(b.get_path_penalty_msat())
1484 .cmp(&a.get_total_fee_paid_msat().saturating_add(a.get_path_penalty_msat())))
1487 // We should make sure that at least 1 path left.
1488 let mut paths_left = cur_route.len();
1489 cur_route.retain(|path| {
1490 if paths_left == 1 {
1493 let mut keep = true;
1494 let path_value_msat = path.get_value_msat();
1495 if path_value_msat <= overpaid_value_msat {
1497 overpaid_value_msat -= path_value_msat;
1503 if overpaid_value_msat == 0 {
1507 assert!(cur_route.len() > 0);
1510 // Now, subtract the overpaid value from the most-expensive path.
1511 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1512 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1513 cur_route.sort_unstable_by_key(|path| { path.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>() });
1514 let expensive_payment_path = cur_route.first_mut().unwrap();
1516 // We already dropped all the small value paths above, meaning all the
1517 // remaining paths are larger than remaining overpaid_value_msat.
1518 // Thus, this can't be negative.
1519 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
1520 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
1524 drawn_routes.push(cur_route);
1528 // Select the best route by lowest total fee.
1529 drawn_routes.sort_unstable_by_key(|paths| paths.iter().map(|path| path.get_total_fee_paid_msat()).sum::<u64>());
1530 let mut selected_paths = Vec::<Vec<Result<RouteHop, LightningError>>>::new();
1531 for payment_path in drawn_routes.first().unwrap() {
1532 let mut path = payment_path.hops.iter().map(|(payment_hop, node_features)| {
1534 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)})?,
1535 node_features: node_features.clone(),
1536 short_channel_id: payment_hop.candidate.short_channel_id(),
1537 channel_features: payment_hop.candidate.features(),
1538 fee_msat: payment_hop.fee_msat,
1539 cltv_expiry_delta: payment_hop.candidate.cltv_expiry_delta(),
1541 }).collect::<Vec<_>>();
1542 // Propagate the cltv_expiry_delta one hop backwards since the delta from the current hop is
1543 // applicable for the previous hop.
1544 path.iter_mut().rev().fold(final_cltv_expiry_delta, |prev_cltv_expiry_delta, hop| {
1545 core::mem::replace(&mut hop.as_mut().unwrap().cltv_expiry_delta, prev_cltv_expiry_delta)
1547 selected_paths.push(path);
1550 if let Some(features) = &payment_params.features {
1551 for path in selected_paths.iter_mut() {
1552 if let Ok(route_hop) = path.last_mut().unwrap() {
1553 route_hop.node_features = features.to_context();
1559 paths: selected_paths.into_iter().map(|path| path.into_iter().collect()).collect::<Result<Vec<_>, _>>()?,
1560 payment_params: Some(payment_params.clone()),
1562 log_info!(logger, "Got route to {}: {}", payment_params.payee_pubkey, log_route!(route));
1566 // When an adversarial intermediary node observes a payment, it may be able to infer its
1567 // destination, if the remaining CLTV expiry delta exactly matches a feasible path in the network
1568 // graph. In order to improve privacy, this method obfuscates the CLTV expiry deltas along the
1569 // payment path by adding a randomized 'shadow route' offset to the final hop.
1570 fn add_random_cltv_offset(route: &mut Route, payment_params: &PaymentParameters, network_graph: &ReadOnlyNetworkGraph, random_seed_bytes: &[u8; 32]) {
1571 let network_channels = network_graph.channels();
1572 let network_nodes = network_graph.nodes();
1574 for path in route.paths.iter_mut() {
1575 let mut shadow_ctlv_expiry_delta_offset: u32 = 0;
1577 // Choose the last publicly known node as the starting point for the random walk
1578 if let Some(starting_hop) = path.iter().rev().find(|h| network_nodes.contains_key(&NodeId::from_pubkey(&h.pubkey))) {
1579 let mut cur_node_id = NodeId::from_pubkey(&starting_hop.pubkey);
1581 // Init PRNG with path nonce
1582 let mut path_nonce = [0u8; 12];
1583 path_nonce.copy_from_slice(&cur_node_id.as_slice()[..12]);
1584 let mut prng = ChaCha20::new(random_seed_bytes, &path_nonce);
1585 let mut random_path_bytes = [0u8; ::core::mem::size_of::<usize>()];
1587 // Pick a random path length in [1 .. 3]
1588 prng.process_in_place(&mut random_path_bytes);
1589 let random_walk_length = usize::from_be_bytes(random_path_bytes).wrapping_rem(3).wrapping_add(1);
1591 for _random_hop in 0..random_walk_length {
1592 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
1593 // Randomly choose the next hop
1594 prng.process_in_place(&mut random_path_bytes);
1595 if let Some(random_channel) = usize::from_be_bytes(random_path_bytes).checked_rem(cur_node.channels.len())
1596 .and_then(|index| cur_node.channels.get(index))
1597 .and_then(|id| network_channels.get(id)) {
1598 random_channel.as_directed_from(&cur_node_id).map(|(dir_info, next_id)| {
1599 dir_info.direction().map(|channel_update_info|
1600 shadow_ctlv_expiry_delta_offset = shadow_ctlv_expiry_delta_offset
1601 .checked_add(channel_update_info.cltv_expiry_delta.into())
1602 .unwrap_or(shadow_ctlv_expiry_delta_offset));
1603 cur_node_id = *next_id;
1609 // If the entire path is private, choose a random offset from multiples of
1610 // MEDIAN_HOP_CLTV_EXPIRY_DELTA
1611 let mut prng = ChaCha20::new(random_seed_bytes, &[0u8; 8]);
1612 let mut random_bytes = [0u8; 4];
1613 prng.process_in_place(&mut random_bytes);
1614 let random_walk_length = u32::from_be_bytes(random_bytes).wrapping_rem(3).wrapping_add(1);
1615 shadow_ctlv_expiry_delta_offset = random_walk_length * MEDIAN_HOP_CLTV_EXPIRY_DELTA;
1618 // Limit the total offset to reduce the worst-case locked liquidity timevalue
1619 const MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET: u32 = 3*144;
1620 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET);
1622 // Limit the offset so we never exceed the max_total_cltv_expiry_delta. To improve plausibility,
1623 // we choose the limit to be the largest possible multiple of MEDIAN_HOP_CLTV_EXPIRY_DELTA.
1624 let path_total_cltv_expiry_delta: u32 = path.iter().map(|h| h.cltv_expiry_delta).sum();
1625 let mut max_path_offset = payment_params.max_total_cltv_expiry_delta - path_total_cltv_expiry_delta;
1626 max_path_offset = cmp::max(
1627 max_path_offset - (max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA),
1628 max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA);
1629 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, max_path_offset);
1631 // Add 'shadow' CLTV offset to the final hop
1632 if let Some(last_hop) = path.last_mut() {
1633 last_hop.cltv_expiry_delta = last_hop.cltv_expiry_delta
1634 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(last_hop.cltv_expiry_delta);
1641 use routing::network_graph::{NetworkGraph, NetGraphMsgHandler, NodeId};
1642 use routing::router::{get_route, add_random_cltv_offset, PaymentParameters, Route, RouteHint, RouteHintHop, RouteHop, RoutingFees, DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA};
1643 use routing::scoring::Score;
1644 use chain::transaction::OutPoint;
1645 use chain::keysinterface::KeysInterface;
1646 use ln::features::{ChannelFeatures, InitFeatures, InvoiceFeatures, NodeFeatures};
1647 use ln::msgs::{ErrorAction, LightningError, OptionalField, UnsignedChannelAnnouncement, ChannelAnnouncement, RoutingMessageHandler,
1648 NodeAnnouncement, UnsignedNodeAnnouncement, ChannelUpdate, UnsignedChannelUpdate};
1649 use ln::channelmanager;
1650 use util::test_utils;
1651 use util::chacha20::ChaCha20;
1652 use util::ser::Writeable;
1654 use util::ser::Writer;
1656 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
1657 use bitcoin::hashes::Hash;
1658 use bitcoin::network::constants::Network;
1659 use bitcoin::blockdata::constants::genesis_block;
1660 use bitcoin::blockdata::script::Builder;
1661 use bitcoin::blockdata::opcodes;
1662 use bitcoin::blockdata::transaction::TxOut;
1666 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
1667 use bitcoin::secp256k1::{Secp256k1, All};
1670 use sync::{self, Arc};
1672 fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
1673 features: InitFeatures, outbound_capacity_msat: u64) -> channelmanager::ChannelDetails {
1674 channelmanager::ChannelDetails {
1675 channel_id: [0; 32],
1676 counterparty: channelmanager::ChannelCounterparty {
1679 unspendable_punishment_reserve: 0,
1680 forwarding_info: None,
1682 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
1684 inbound_scid_alias: None,
1685 channel_value_satoshis: 0,
1688 outbound_capacity_msat,
1689 inbound_capacity_msat: 42,
1690 unspendable_punishment_reserve: None,
1691 confirmations_required: None,
1692 force_close_spend_delay: None,
1693 is_outbound: true, is_funding_locked: true,
1694 is_usable: true, is_public: true,
1698 // Using the same keys for LN and BTC ids
1700 net_graph_msg_handler: &NetGraphMsgHandler<Arc<NetworkGraph>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1701 secp_ctx: &Secp256k1<All>, node_1_privkey: &SecretKey, node_2_privkey: &SecretKey, features: ChannelFeatures, short_channel_id: u64
1703 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1704 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1706 let unsigned_announcement = UnsignedChannelAnnouncement {
1708 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1712 bitcoin_key_1: node_id_1,
1713 bitcoin_key_2: node_id_2,
1714 excess_data: Vec::new(),
1717 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1718 let valid_announcement = ChannelAnnouncement {
1719 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1720 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1721 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1722 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1723 contents: unsigned_announcement.clone(),
1725 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1726 Ok(res) => assert!(res),
1732 net_graph_msg_handler: &NetGraphMsgHandler<Arc<NetworkGraph>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1733 secp_ctx: &Secp256k1<All>, node_privkey: &SecretKey, update: UnsignedChannelUpdate
1735 let msghash = hash_to_message!(&Sha256dHash::hash(&update.encode()[..])[..]);
1736 let valid_channel_update = ChannelUpdate {
1737 signature: secp_ctx.sign(&msghash, node_privkey),
1738 contents: update.clone()
1741 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1742 Ok(res) => assert!(res),
1747 fn add_or_update_node(
1748 net_graph_msg_handler: &NetGraphMsgHandler<Arc<NetworkGraph>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1749 secp_ctx: &Secp256k1<All>, node_privkey: &SecretKey, features: NodeFeatures, timestamp: u32
1751 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
1752 let unsigned_announcement = UnsignedNodeAnnouncement {
1758 addresses: Vec::new(),
1759 excess_address_data: Vec::new(),
1760 excess_data: Vec::new(),
1762 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1763 let valid_announcement = NodeAnnouncement {
1764 signature: secp_ctx.sign(&msghash, node_privkey),
1765 contents: unsigned_announcement.clone()
1768 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1774 fn get_nodes(secp_ctx: &Secp256k1<All>) -> (SecretKey, PublicKey, Vec<SecretKey>, Vec<PublicKey>) {
1775 let privkeys: Vec<SecretKey> = (2..10).map(|i| {
1776 SecretKey::from_slice(&hex::decode(format!("{:02x}", i).repeat(32)).unwrap()[..]).unwrap()
1779 let pubkeys = privkeys.iter().map(|secret| PublicKey::from_secret_key(&secp_ctx, secret)).collect();
1781 let our_privkey = SecretKey::from_slice(&hex::decode("01".repeat(32)).unwrap()[..]).unwrap();
1782 let our_id = PublicKey::from_secret_key(&secp_ctx, &our_privkey);
1784 (our_privkey, our_id, privkeys, pubkeys)
1787 fn id_to_feature_flags(id: u8) -> Vec<u8> {
1788 // Set the feature flags to the id'th odd (ie non-required) feature bit so that we can
1789 // test for it later.
1790 let idx = (id - 1) * 2 + 1;
1792 vec![1 << (idx - 8*3), 0, 0, 0]
1793 } else if idx > 8*2 {
1794 vec![1 << (idx - 8*2), 0, 0]
1795 } else if idx > 8*1 {
1796 vec![1 << (idx - 8*1), 0]
1802 fn build_graph() -> (
1804 sync::Arc<NetworkGraph>,
1805 NetGraphMsgHandler<sync::Arc<NetworkGraph>, sync::Arc<test_utils::TestChainSource>, sync::Arc<crate::util::test_utils::TestLogger>>,
1806 sync::Arc<test_utils::TestChainSource>,
1807 sync::Arc<test_utils::TestLogger>,
1809 let secp_ctx = Secp256k1::new();
1810 let logger = Arc::new(test_utils::TestLogger::new());
1811 let chain_monitor = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1812 let network_graph = Arc::new(NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash()));
1813 let net_graph_msg_handler = NetGraphMsgHandler::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
1814 // Build network from our_id to node6:
1816 // -1(1)2- node0 -1(3)2-
1818 // our_id -1(12)2- node7 -1(13)2--- node2
1820 // -1(2)2- node1 -1(4)2-
1823 // chan1 1-to-2: disabled
1824 // chan1 2-to-1: enabled, 0 fee
1826 // chan2 1-to-2: enabled, ignored fee
1827 // chan2 2-to-1: enabled, 0 fee
1829 // chan3 1-to-2: enabled, 0 fee
1830 // chan3 2-to-1: enabled, 100 msat fee
1832 // chan4 1-to-2: enabled, 100% fee
1833 // chan4 2-to-1: enabled, 0 fee
1835 // chan12 1-to-2: enabled, ignored fee
1836 // chan12 2-to-1: enabled, 0 fee
1838 // chan13 1-to-2: enabled, 200% fee
1839 // chan13 2-to-1: enabled, 0 fee
1842 // -1(5)2- node3 -1(8)2--
1846 // node2--1(6)2- node4 -1(9)2--- node6 (not in global route map)
1848 // -1(7)2- node5 -1(10)2-
1850 // Channels 5, 8, 9 and 10 are private channels.
1852 // chan5 1-to-2: enabled, 100 msat fee
1853 // chan5 2-to-1: enabled, 0 fee
1855 // chan6 1-to-2: enabled, 0 fee
1856 // chan6 2-to-1: enabled, 0 fee
1858 // chan7 1-to-2: enabled, 100% fee
1859 // chan7 2-to-1: enabled, 0 fee
1861 // chan8 1-to-2: enabled, variable fee (0 then 1000 msat)
1862 // chan8 2-to-1: enabled, 0 fee
1864 // chan9 1-to-2: enabled, 1001 msat fee
1865 // chan9 2-to-1: enabled, 0 fee
1867 // chan10 1-to-2: enabled, 0 fee
1868 // chan10 2-to-1: enabled, 0 fee
1870 // chan11 1-to-2: enabled, 0 fee
1871 // chan11 2-to-1: enabled, 0 fee
1873 let (our_privkey, _, privkeys, _) = get_nodes(&secp_ctx);
1875 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[0], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
1876 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1877 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1878 short_channel_id: 1,
1881 cltv_expiry_delta: 0,
1882 htlc_minimum_msat: 0,
1883 htlc_maximum_msat: OptionalField::Absent,
1885 fee_proportional_millionths: 0,
1886 excess_data: Vec::new()
1889 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
1891 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
1892 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1893 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1894 short_channel_id: 2,
1897 cltv_expiry_delta: (5 << 4) | 3,
1898 htlc_minimum_msat: 0,
1899 htlc_maximum_msat: OptionalField::Absent,
1900 fee_base_msat: u32::max_value(),
1901 fee_proportional_millionths: u32::max_value(),
1902 excess_data: Vec::new()
1904 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1905 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1906 short_channel_id: 2,
1909 cltv_expiry_delta: 0,
1910 htlc_minimum_msat: 0,
1911 htlc_maximum_msat: OptionalField::Absent,
1913 fee_proportional_millionths: 0,
1914 excess_data: Vec::new()
1917 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
1919 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[7], ChannelFeatures::from_le_bytes(id_to_feature_flags(12)), 12);
1920 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1921 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1922 short_channel_id: 12,
1925 cltv_expiry_delta: (5 << 4) | 3,
1926 htlc_minimum_msat: 0,
1927 htlc_maximum_msat: OptionalField::Absent,
1928 fee_base_msat: u32::max_value(),
1929 fee_proportional_millionths: u32::max_value(),
1930 excess_data: Vec::new()
1932 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1933 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1934 short_channel_id: 12,
1937 cltv_expiry_delta: 0,
1938 htlc_minimum_msat: 0,
1939 htlc_maximum_msat: OptionalField::Absent,
1941 fee_proportional_millionths: 0,
1942 excess_data: Vec::new()
1945 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], NodeFeatures::from_le_bytes(id_to_feature_flags(8)), 0);
1947 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
1948 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1949 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1950 short_channel_id: 3,
1953 cltv_expiry_delta: (3 << 4) | 1,
1954 htlc_minimum_msat: 0,
1955 htlc_maximum_msat: OptionalField::Absent,
1957 fee_proportional_millionths: 0,
1958 excess_data: Vec::new()
1960 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1961 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1962 short_channel_id: 3,
1965 cltv_expiry_delta: (3 << 4) | 2,
1966 htlc_minimum_msat: 0,
1967 htlc_maximum_msat: OptionalField::Absent,
1969 fee_proportional_millionths: 0,
1970 excess_data: Vec::new()
1973 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
1974 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1975 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1976 short_channel_id: 4,
1979 cltv_expiry_delta: (4 << 4) | 1,
1980 htlc_minimum_msat: 0,
1981 htlc_maximum_msat: OptionalField::Absent,
1983 fee_proportional_millionths: 1000000,
1984 excess_data: Vec::new()
1986 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1987 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1988 short_channel_id: 4,
1991 cltv_expiry_delta: (4 << 4) | 2,
1992 htlc_minimum_msat: 0,
1993 htlc_maximum_msat: OptionalField::Absent,
1995 fee_proportional_millionths: 0,
1996 excess_data: Vec::new()
1999 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(13)), 13);
2000 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2001 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2002 short_channel_id: 13,
2005 cltv_expiry_delta: (13 << 4) | 1,
2006 htlc_minimum_msat: 0,
2007 htlc_maximum_msat: OptionalField::Absent,
2009 fee_proportional_millionths: 2000000,
2010 excess_data: Vec::new()
2012 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2013 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2014 short_channel_id: 13,
2017 cltv_expiry_delta: (13 << 4) | 2,
2018 htlc_minimum_msat: 0,
2019 htlc_maximum_msat: OptionalField::Absent,
2021 fee_proportional_millionths: 0,
2022 excess_data: Vec::new()
2025 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
2027 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
2028 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2029 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2030 short_channel_id: 6,
2033 cltv_expiry_delta: (6 << 4) | 1,
2034 htlc_minimum_msat: 0,
2035 htlc_maximum_msat: OptionalField::Absent,
2037 fee_proportional_millionths: 0,
2038 excess_data: Vec::new()
2040 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
2041 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2042 short_channel_id: 6,
2045 cltv_expiry_delta: (6 << 4) | 2,
2046 htlc_minimum_msat: 0,
2047 htlc_maximum_msat: OptionalField::Absent,
2049 fee_proportional_millionths: 0,
2050 excess_data: Vec::new(),
2053 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(11)), 11);
2054 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
2055 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2056 short_channel_id: 11,
2059 cltv_expiry_delta: (11 << 4) | 1,
2060 htlc_minimum_msat: 0,
2061 htlc_maximum_msat: OptionalField::Absent,
2063 fee_proportional_millionths: 0,
2064 excess_data: Vec::new()
2066 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
2067 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2068 short_channel_id: 11,
2071 cltv_expiry_delta: (11 << 4) | 2,
2072 htlc_minimum_msat: 0,
2073 htlc_maximum_msat: OptionalField::Absent,
2075 fee_proportional_millionths: 0,
2076 excess_data: Vec::new()
2079 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(5)), 0);
2081 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
2083 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[5], ChannelFeatures::from_le_bytes(id_to_feature_flags(7)), 7);
2084 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2085 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2086 short_channel_id: 7,
2089 cltv_expiry_delta: (7 << 4) | 1,
2090 htlc_minimum_msat: 0,
2091 htlc_maximum_msat: OptionalField::Absent,
2093 fee_proportional_millionths: 1000000,
2094 excess_data: Vec::new()
2096 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[5], UnsignedChannelUpdate {
2097 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2098 short_channel_id: 7,
2101 cltv_expiry_delta: (7 << 4) | 2,
2102 htlc_minimum_msat: 0,
2103 htlc_maximum_msat: OptionalField::Absent,
2105 fee_proportional_millionths: 0,
2106 excess_data: Vec::new()
2109 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[5], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
2111 (secp_ctx, network_graph, net_graph_msg_handler, chain_monitor, logger)
2115 fn simple_route_test() {
2116 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2117 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2118 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2119 let scorer = test_utils::TestScorer::with_penalty(0);
2120 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2121 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2123 // Simple route to 2 via 1
2125 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) {
2126 assert_eq!(err, "Cannot send a payment of 0 msat");
2127 } else { panic!(); }
2129 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2130 assert_eq!(route.paths[0].len(), 2);
2132 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2133 assert_eq!(route.paths[0][0].short_channel_id, 2);
2134 assert_eq!(route.paths[0][0].fee_msat, 100);
2135 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2136 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2137 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2139 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2140 assert_eq!(route.paths[0][1].short_channel_id, 4);
2141 assert_eq!(route.paths[0][1].fee_msat, 100);
2142 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2143 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2144 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2148 fn invalid_first_hop_test() {
2149 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2150 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2151 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2152 let scorer = test_utils::TestScorer::with_penalty(0);
2153 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2154 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2156 // Simple route to 2 via 1
2158 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
2160 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) =
2161 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) {
2162 assert_eq!(err, "First hop cannot have our_node_pubkey as a destination.");
2163 } else { panic!(); }
2165 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2166 assert_eq!(route.paths[0].len(), 2);
2170 fn htlc_minimum_test() {
2171 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2172 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2173 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2174 let scorer = test_utils::TestScorer::with_penalty(0);
2175 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2176 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2178 // Simple route to 2 via 1
2180 // Disable other paths
2181 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2182 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2183 short_channel_id: 12,
2185 flags: 2, // to disable
2186 cltv_expiry_delta: 0,
2187 htlc_minimum_msat: 0,
2188 htlc_maximum_msat: OptionalField::Absent,
2190 fee_proportional_millionths: 0,
2191 excess_data: Vec::new()
2193 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2194 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2195 short_channel_id: 3,
2197 flags: 2, // to disable
2198 cltv_expiry_delta: 0,
2199 htlc_minimum_msat: 0,
2200 htlc_maximum_msat: OptionalField::Absent,
2202 fee_proportional_millionths: 0,
2203 excess_data: Vec::new()
2205 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2206 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2207 short_channel_id: 13,
2209 flags: 2, // to disable
2210 cltv_expiry_delta: 0,
2211 htlc_minimum_msat: 0,
2212 htlc_maximum_msat: OptionalField::Absent,
2214 fee_proportional_millionths: 0,
2215 excess_data: Vec::new()
2217 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2218 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2219 short_channel_id: 6,
2221 flags: 2, // to disable
2222 cltv_expiry_delta: 0,
2223 htlc_minimum_msat: 0,
2224 htlc_maximum_msat: OptionalField::Absent,
2226 fee_proportional_millionths: 0,
2227 excess_data: Vec::new()
2229 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2230 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2231 short_channel_id: 7,
2233 flags: 2, // to disable
2234 cltv_expiry_delta: 0,
2235 htlc_minimum_msat: 0,
2236 htlc_maximum_msat: OptionalField::Absent,
2238 fee_proportional_millionths: 0,
2239 excess_data: Vec::new()
2242 // Check against amount_to_transfer_over_msat.
2243 // Set minimal HTLC of 200_000_000 msat.
2244 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2245 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2246 short_channel_id: 2,
2249 cltv_expiry_delta: 0,
2250 htlc_minimum_msat: 200_000_000,
2251 htlc_maximum_msat: OptionalField::Absent,
2253 fee_proportional_millionths: 0,
2254 excess_data: Vec::new()
2257 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
2259 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2260 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2261 short_channel_id: 4,
2264 cltv_expiry_delta: 0,
2265 htlc_minimum_msat: 0,
2266 htlc_maximum_msat: OptionalField::Present(199_999_999),
2268 fee_proportional_millionths: 0,
2269 excess_data: Vec::new()
2272 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
2273 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) {
2274 assert_eq!(err, "Failed to find a path to the given destination");
2275 } else { panic!(); }
2277 // Lift the restriction on the first hop.
2278 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2279 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2280 short_channel_id: 2,
2283 cltv_expiry_delta: 0,
2284 htlc_minimum_msat: 0,
2285 htlc_maximum_msat: OptionalField::Absent,
2287 fee_proportional_millionths: 0,
2288 excess_data: Vec::new()
2291 // A payment above the minimum should pass
2292 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();
2293 assert_eq!(route.paths[0].len(), 2);
2297 fn htlc_minimum_overpay_test() {
2298 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2299 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2300 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
2301 let scorer = test_utils::TestScorer::with_penalty(0);
2302 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2303 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2305 // A route to node#2 via two paths.
2306 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
2307 // Thus, they can't send 60 without overpaying.
2308 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2309 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2310 short_channel_id: 2,
2313 cltv_expiry_delta: 0,
2314 htlc_minimum_msat: 35_000,
2315 htlc_maximum_msat: OptionalField::Present(40_000),
2317 fee_proportional_millionths: 0,
2318 excess_data: Vec::new()
2320 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2321 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2322 short_channel_id: 12,
2325 cltv_expiry_delta: 0,
2326 htlc_minimum_msat: 35_000,
2327 htlc_maximum_msat: OptionalField::Present(40_000),
2329 fee_proportional_millionths: 0,
2330 excess_data: Vec::new()
2334 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2335 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2336 short_channel_id: 13,
2339 cltv_expiry_delta: 0,
2340 htlc_minimum_msat: 0,
2341 htlc_maximum_msat: OptionalField::Absent,
2343 fee_proportional_millionths: 0,
2344 excess_data: Vec::new()
2346 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2347 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2348 short_channel_id: 4,
2351 cltv_expiry_delta: 0,
2352 htlc_minimum_msat: 0,
2353 htlc_maximum_msat: OptionalField::Absent,
2355 fee_proportional_millionths: 0,
2356 excess_data: Vec::new()
2359 // Disable other paths
2360 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2361 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2362 short_channel_id: 1,
2364 flags: 2, // to disable
2365 cltv_expiry_delta: 0,
2366 htlc_minimum_msat: 0,
2367 htlc_maximum_msat: OptionalField::Absent,
2369 fee_proportional_millionths: 0,
2370 excess_data: Vec::new()
2373 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 60_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2374 // Overpay fees to hit htlc_minimum_msat.
2375 let overpaid_fees = route.paths[0][0].fee_msat + route.paths[1][0].fee_msat;
2376 // TODO: this could be better balanced to overpay 10k and not 15k.
2377 assert_eq!(overpaid_fees, 15_000);
2379 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
2380 // while taking even more fee to match htlc_minimum_msat.
2381 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2382 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2383 short_channel_id: 12,
2386 cltv_expiry_delta: 0,
2387 htlc_minimum_msat: 65_000,
2388 htlc_maximum_msat: OptionalField::Present(80_000),
2390 fee_proportional_millionths: 0,
2391 excess_data: Vec::new()
2393 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2394 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2395 short_channel_id: 2,
2398 cltv_expiry_delta: 0,
2399 htlc_minimum_msat: 0,
2400 htlc_maximum_msat: OptionalField::Absent,
2402 fee_proportional_millionths: 0,
2403 excess_data: Vec::new()
2405 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2406 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2407 short_channel_id: 4,
2410 cltv_expiry_delta: 0,
2411 htlc_minimum_msat: 0,
2412 htlc_maximum_msat: OptionalField::Absent,
2414 fee_proportional_millionths: 100_000,
2415 excess_data: Vec::new()
2418 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 60_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2419 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
2420 assert_eq!(route.paths.len(), 1);
2421 assert_eq!(route.paths[0][0].short_channel_id, 12);
2422 let fees = route.paths[0][0].fee_msat;
2423 assert_eq!(fees, 5_000);
2425 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2426 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
2427 // the other channel.
2428 assert_eq!(route.paths.len(), 1);
2429 assert_eq!(route.paths[0][0].short_channel_id, 2);
2430 let fees = route.paths[0][0].fee_msat;
2431 assert_eq!(fees, 5_000);
2435 fn disable_channels_test() {
2436 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2437 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2438 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2439 let scorer = test_utils::TestScorer::with_penalty(0);
2440 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2441 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2443 // // Disable channels 4 and 12 by flags=2
2444 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2445 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2446 short_channel_id: 4,
2448 flags: 2, // to disable
2449 cltv_expiry_delta: 0,
2450 htlc_minimum_msat: 0,
2451 htlc_maximum_msat: OptionalField::Absent,
2453 fee_proportional_millionths: 0,
2454 excess_data: Vec::new()
2456 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2457 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2458 short_channel_id: 12,
2460 flags: 2, // to disable
2461 cltv_expiry_delta: 0,
2462 htlc_minimum_msat: 0,
2463 htlc_maximum_msat: OptionalField::Absent,
2465 fee_proportional_millionths: 0,
2466 excess_data: Vec::new()
2469 // If all the channels require some features we don't understand, route should fail
2470 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) {
2471 assert_eq!(err, "Failed to find a path to the given destination");
2472 } else { panic!(); }
2474 // If we specify a channel to node7, that overrides our local channel view and that gets used
2475 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2476 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();
2477 assert_eq!(route.paths[0].len(), 2);
2479 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2480 assert_eq!(route.paths[0][0].short_channel_id, 42);
2481 assert_eq!(route.paths[0][0].fee_msat, 200);
2482 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2483 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2484 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2486 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2487 assert_eq!(route.paths[0][1].short_channel_id, 13);
2488 assert_eq!(route.paths[0][1].fee_msat, 100);
2489 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2490 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2491 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2495 fn disable_node_test() {
2496 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2497 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2498 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2499 let scorer = test_utils::TestScorer::with_penalty(0);
2500 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2501 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2503 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
2504 let mut unknown_features = NodeFeatures::known();
2505 unknown_features.set_unknown_feature_required();
2506 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
2507 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
2508 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
2510 // If all nodes require some features we don't understand, route should fail
2511 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) {
2512 assert_eq!(err, "Failed to find a path to the given destination");
2513 } else { panic!(); }
2515 // If we specify a channel to node7, that overrides our local channel view and that gets used
2516 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2517 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();
2518 assert_eq!(route.paths[0].len(), 2);
2520 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2521 assert_eq!(route.paths[0][0].short_channel_id, 42);
2522 assert_eq!(route.paths[0][0].fee_msat, 200);
2523 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2524 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2525 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2527 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2528 assert_eq!(route.paths[0][1].short_channel_id, 13);
2529 assert_eq!(route.paths[0][1].fee_msat, 100);
2530 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2531 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2532 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2534 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
2535 // naively) assume that the user checked the feature bits on the invoice, which override
2536 // the node_announcement.
2540 fn our_chans_test() {
2541 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2542 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2543 let scorer = test_utils::TestScorer::with_penalty(0);
2544 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2545 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2547 // Route to 1 via 2 and 3 because our channel to 1 is disabled
2548 let payment_params = PaymentParameters::from_node_id(nodes[0]);
2549 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2550 assert_eq!(route.paths[0].len(), 3);
2552 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2553 assert_eq!(route.paths[0][0].short_channel_id, 2);
2554 assert_eq!(route.paths[0][0].fee_msat, 200);
2555 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2556 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2557 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2559 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2560 assert_eq!(route.paths[0][1].short_channel_id, 4);
2561 assert_eq!(route.paths[0][1].fee_msat, 100);
2562 assert_eq!(route.paths[0][1].cltv_expiry_delta, (3 << 4) | 2);
2563 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2564 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2566 assert_eq!(route.paths[0][2].pubkey, nodes[0]);
2567 assert_eq!(route.paths[0][2].short_channel_id, 3);
2568 assert_eq!(route.paths[0][2].fee_msat, 100);
2569 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
2570 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(1));
2571 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(3));
2573 // If we specify a channel to node7, that overrides our local channel view and that gets used
2574 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2575 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2576 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();
2577 assert_eq!(route.paths[0].len(), 2);
2579 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2580 assert_eq!(route.paths[0][0].short_channel_id, 42);
2581 assert_eq!(route.paths[0][0].fee_msat, 200);
2582 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2583 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2584 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2586 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2587 assert_eq!(route.paths[0][1].short_channel_id, 13);
2588 assert_eq!(route.paths[0][1].fee_msat, 100);
2589 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2590 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2591 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2594 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2595 let zero_fees = RoutingFees {
2597 proportional_millionths: 0,
2599 vec![RouteHint(vec![RouteHintHop {
2600 src_node_id: nodes[3],
2601 short_channel_id: 8,
2603 cltv_expiry_delta: (8 << 4) | 1,
2604 htlc_minimum_msat: None,
2605 htlc_maximum_msat: None,
2607 ]), RouteHint(vec![RouteHintHop {
2608 src_node_id: nodes[4],
2609 short_channel_id: 9,
2612 proportional_millionths: 0,
2614 cltv_expiry_delta: (9 << 4) | 1,
2615 htlc_minimum_msat: None,
2616 htlc_maximum_msat: None,
2617 }]), RouteHint(vec![RouteHintHop {
2618 src_node_id: nodes[5],
2619 short_channel_id: 10,
2621 cltv_expiry_delta: (10 << 4) | 1,
2622 htlc_minimum_msat: None,
2623 htlc_maximum_msat: None,
2627 fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2628 let zero_fees = RoutingFees {
2630 proportional_millionths: 0,
2632 vec![RouteHint(vec![RouteHintHop {
2633 src_node_id: nodes[2],
2634 short_channel_id: 5,
2637 proportional_millionths: 0,
2639 cltv_expiry_delta: (5 << 4) | 1,
2640 htlc_minimum_msat: None,
2641 htlc_maximum_msat: None,
2643 src_node_id: nodes[3],
2644 short_channel_id: 8,
2646 cltv_expiry_delta: (8 << 4) | 1,
2647 htlc_minimum_msat: None,
2648 htlc_maximum_msat: None,
2650 ]), RouteHint(vec![RouteHintHop {
2651 src_node_id: nodes[4],
2652 short_channel_id: 9,
2655 proportional_millionths: 0,
2657 cltv_expiry_delta: (9 << 4) | 1,
2658 htlc_minimum_msat: None,
2659 htlc_maximum_msat: None,
2660 }]), RouteHint(vec![RouteHintHop {
2661 src_node_id: nodes[5],
2662 short_channel_id: 10,
2664 cltv_expiry_delta: (10 << 4) | 1,
2665 htlc_minimum_msat: None,
2666 htlc_maximum_msat: None,
2671 fn partial_route_hint_test() {
2672 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2673 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2674 let scorer = test_utils::TestScorer::with_penalty(0);
2675 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2676 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2678 // Simple test across 2, 3, 5, and 4 via a last_hop channel
2679 // Tests the behaviour when the RouteHint contains a suboptimal hop.
2680 // RouteHint may be partially used by the algo to build the best path.
2682 // First check that last hop can't have its source as the payee.
2683 let invalid_last_hop = RouteHint(vec![RouteHintHop {
2684 src_node_id: nodes[6],
2685 short_channel_id: 8,
2688 proportional_millionths: 0,
2690 cltv_expiry_delta: (8 << 4) | 1,
2691 htlc_minimum_msat: None,
2692 htlc_maximum_msat: None,
2695 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
2696 invalid_last_hops.push(invalid_last_hop);
2698 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(invalid_last_hops);
2699 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) {
2700 assert_eq!(err, "Route hint cannot have the payee as the source.");
2701 } else { panic!(); }
2704 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops_multi_private_channels(&nodes));
2705 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2706 assert_eq!(route.paths[0].len(), 5);
2708 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2709 assert_eq!(route.paths[0][0].short_channel_id, 2);
2710 assert_eq!(route.paths[0][0].fee_msat, 100);
2711 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2712 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2713 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2715 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2716 assert_eq!(route.paths[0][1].short_channel_id, 4);
2717 assert_eq!(route.paths[0][1].fee_msat, 0);
2718 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
2719 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2720 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2722 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2723 assert_eq!(route.paths[0][2].short_channel_id, 6);
2724 assert_eq!(route.paths[0][2].fee_msat, 0);
2725 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
2726 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2727 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2729 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2730 assert_eq!(route.paths[0][3].short_channel_id, 11);
2731 assert_eq!(route.paths[0][3].fee_msat, 0);
2732 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
2733 // If we have a peer in the node map, we'll use their features here since we don't have
2734 // a way of figuring out their features from the invoice:
2735 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2736 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2738 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2739 assert_eq!(route.paths[0][4].short_channel_id, 8);
2740 assert_eq!(route.paths[0][4].fee_msat, 100);
2741 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2742 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2743 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2746 fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2747 let zero_fees = RoutingFees {
2749 proportional_millionths: 0,
2751 vec![RouteHint(vec![RouteHintHop {
2752 src_node_id: nodes[3],
2753 short_channel_id: 8,
2755 cltv_expiry_delta: (8 << 4) | 1,
2756 htlc_minimum_msat: None,
2757 htlc_maximum_msat: None,
2758 }]), RouteHint(vec![
2760 ]), RouteHint(vec![RouteHintHop {
2761 src_node_id: nodes[5],
2762 short_channel_id: 10,
2764 cltv_expiry_delta: (10 << 4) | 1,
2765 htlc_minimum_msat: None,
2766 htlc_maximum_msat: None,
2771 fn ignores_empty_last_hops_test() {
2772 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2773 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2774 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(empty_last_hop(&nodes));
2775 let scorer = test_utils::TestScorer::with_penalty(0);
2776 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2777 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2779 // Test handling of an empty RouteHint passed in Invoice.
2781 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2782 assert_eq!(route.paths[0].len(), 5);
2784 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2785 assert_eq!(route.paths[0][0].short_channel_id, 2);
2786 assert_eq!(route.paths[0][0].fee_msat, 100);
2787 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2788 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2789 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2791 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2792 assert_eq!(route.paths[0][1].short_channel_id, 4);
2793 assert_eq!(route.paths[0][1].fee_msat, 0);
2794 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
2795 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2796 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2798 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2799 assert_eq!(route.paths[0][2].short_channel_id, 6);
2800 assert_eq!(route.paths[0][2].fee_msat, 0);
2801 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
2802 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2803 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2805 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2806 assert_eq!(route.paths[0][3].short_channel_id, 11);
2807 assert_eq!(route.paths[0][3].fee_msat, 0);
2808 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
2809 // If we have a peer in the node map, we'll use their features here since we don't have
2810 // a way of figuring out their features from the invoice:
2811 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2812 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2814 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2815 assert_eq!(route.paths[0][4].short_channel_id, 8);
2816 assert_eq!(route.paths[0][4].fee_msat, 100);
2817 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2818 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2819 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2822 /// Builds a trivial last-hop hint that passes through the two nodes given, with channel 0xff00
2824 fn multi_hop_last_hops_hint(hint_hops: [PublicKey; 2]) -> Vec<RouteHint> {
2825 let zero_fees = RoutingFees {
2827 proportional_millionths: 0,
2829 vec![RouteHint(vec![RouteHintHop {
2830 src_node_id: hint_hops[0],
2831 short_channel_id: 0xff00,
2834 proportional_millionths: 0,
2836 cltv_expiry_delta: (5 << 4) | 1,
2837 htlc_minimum_msat: None,
2838 htlc_maximum_msat: None,
2840 src_node_id: hint_hops[1],
2841 short_channel_id: 0xff01,
2843 cltv_expiry_delta: (8 << 4) | 1,
2844 htlc_minimum_msat: None,
2845 htlc_maximum_msat: None,
2850 fn multi_hint_last_hops_test() {
2851 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2852 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2853 let last_hops = multi_hop_last_hops_hint([nodes[2], nodes[3]]);
2854 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops.clone());
2855 let scorer = test_utils::TestScorer::with_penalty(0);
2856 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2857 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2858 // Test through channels 2, 3, 0xff00, 0xff01.
2859 // Test shows that multiple hop hints are considered.
2861 // Disabling channels 6 & 7 by flags=2
2862 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2863 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2864 short_channel_id: 6,
2866 flags: 2, // to disable
2867 cltv_expiry_delta: 0,
2868 htlc_minimum_msat: 0,
2869 htlc_maximum_msat: OptionalField::Absent,
2871 fee_proportional_millionths: 0,
2872 excess_data: Vec::new()
2874 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2875 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2876 short_channel_id: 7,
2878 flags: 2, // to disable
2879 cltv_expiry_delta: 0,
2880 htlc_minimum_msat: 0,
2881 htlc_maximum_msat: OptionalField::Absent,
2883 fee_proportional_millionths: 0,
2884 excess_data: Vec::new()
2887 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2888 assert_eq!(route.paths[0].len(), 4);
2890 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2891 assert_eq!(route.paths[0][0].short_channel_id, 2);
2892 assert_eq!(route.paths[0][0].fee_msat, 200);
2893 assert_eq!(route.paths[0][0].cltv_expiry_delta, 65);
2894 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2895 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2897 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2898 assert_eq!(route.paths[0][1].short_channel_id, 4);
2899 assert_eq!(route.paths[0][1].fee_msat, 100);
2900 assert_eq!(route.paths[0][1].cltv_expiry_delta, 81);
2901 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2902 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2904 assert_eq!(route.paths[0][2].pubkey, nodes[3]);
2905 assert_eq!(route.paths[0][2].short_channel_id, last_hops[0].0[0].short_channel_id);
2906 assert_eq!(route.paths[0][2].fee_msat, 0);
2907 assert_eq!(route.paths[0][2].cltv_expiry_delta, 129);
2908 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(4));
2909 assert_eq!(route.paths[0][2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2911 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2912 assert_eq!(route.paths[0][3].short_channel_id, last_hops[0].0[1].short_channel_id);
2913 assert_eq!(route.paths[0][3].fee_msat, 100);
2914 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2915 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2916 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2920 fn private_multi_hint_last_hops_test() {
2921 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2922 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2924 let non_announced_privkey = SecretKey::from_slice(&hex::decode(format!("{:02x}", 0xf0).repeat(32)).unwrap()[..]).unwrap();
2925 let non_announced_pubkey = PublicKey::from_secret_key(&secp_ctx, &non_announced_privkey);
2927 let last_hops = multi_hop_last_hops_hint([nodes[2], non_announced_pubkey]);
2928 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops.clone());
2929 let scorer = test_utils::TestScorer::with_penalty(0);
2930 // Test through channels 2, 3, 0xff00, 0xff01.
2931 // Test shows that multiple hop hints are considered.
2933 // Disabling channels 6 & 7 by flags=2
2934 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2935 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2936 short_channel_id: 6,
2938 flags: 2, // to disable
2939 cltv_expiry_delta: 0,
2940 htlc_minimum_msat: 0,
2941 htlc_maximum_msat: OptionalField::Absent,
2943 fee_proportional_millionths: 0,
2944 excess_data: Vec::new()
2946 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2947 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2948 short_channel_id: 7,
2950 flags: 2, // to disable
2951 cltv_expiry_delta: 0,
2952 htlc_minimum_msat: 0,
2953 htlc_maximum_msat: OptionalField::Absent,
2955 fee_proportional_millionths: 0,
2956 excess_data: Vec::new()
2959 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &[42u8; 32]).unwrap();
2960 assert_eq!(route.paths[0].len(), 4);
2962 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2963 assert_eq!(route.paths[0][0].short_channel_id, 2);
2964 assert_eq!(route.paths[0][0].fee_msat, 200);
2965 assert_eq!(route.paths[0][0].cltv_expiry_delta, 65);
2966 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2967 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2969 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2970 assert_eq!(route.paths[0][1].short_channel_id, 4);
2971 assert_eq!(route.paths[0][1].fee_msat, 100);
2972 assert_eq!(route.paths[0][1].cltv_expiry_delta, 81);
2973 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2974 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2976 assert_eq!(route.paths[0][2].pubkey, non_announced_pubkey);
2977 assert_eq!(route.paths[0][2].short_channel_id, last_hops[0].0[0].short_channel_id);
2978 assert_eq!(route.paths[0][2].fee_msat, 0);
2979 assert_eq!(route.paths[0][2].cltv_expiry_delta, 129);
2980 assert_eq!(route.paths[0][2].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2981 assert_eq!(route.paths[0][2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2983 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2984 assert_eq!(route.paths[0][3].short_channel_id, last_hops[0].0[1].short_channel_id);
2985 assert_eq!(route.paths[0][3].fee_msat, 100);
2986 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2987 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2988 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2991 fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2992 let zero_fees = RoutingFees {
2994 proportional_millionths: 0,
2996 vec![RouteHint(vec![RouteHintHop {
2997 src_node_id: nodes[4],
2998 short_channel_id: 11,
3000 cltv_expiry_delta: (11 << 4) | 1,
3001 htlc_minimum_msat: None,
3002 htlc_maximum_msat: None,
3004 src_node_id: nodes[3],
3005 short_channel_id: 8,
3007 cltv_expiry_delta: (8 << 4) | 1,
3008 htlc_minimum_msat: None,
3009 htlc_maximum_msat: None,
3010 }]), RouteHint(vec![RouteHintHop {
3011 src_node_id: nodes[4],
3012 short_channel_id: 9,
3015 proportional_millionths: 0,
3017 cltv_expiry_delta: (9 << 4) | 1,
3018 htlc_minimum_msat: None,
3019 htlc_maximum_msat: None,
3020 }]), RouteHint(vec![RouteHintHop {
3021 src_node_id: nodes[5],
3022 short_channel_id: 10,
3024 cltv_expiry_delta: (10 << 4) | 1,
3025 htlc_minimum_msat: None,
3026 htlc_maximum_msat: None,
3031 fn last_hops_with_public_channel_test() {
3032 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3033 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3034 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops_with_public_channel(&nodes));
3035 let scorer = test_utils::TestScorer::with_penalty(0);
3036 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3037 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3038 // This test shows that public routes can be present in the invoice
3039 // which would be handled in the same manner.
3041 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3042 assert_eq!(route.paths[0].len(), 5);
3044 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3045 assert_eq!(route.paths[0][0].short_channel_id, 2);
3046 assert_eq!(route.paths[0][0].fee_msat, 100);
3047 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
3048 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3049 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3051 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3052 assert_eq!(route.paths[0][1].short_channel_id, 4);
3053 assert_eq!(route.paths[0][1].fee_msat, 0);
3054 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
3055 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3056 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3058 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
3059 assert_eq!(route.paths[0][2].short_channel_id, 6);
3060 assert_eq!(route.paths[0][2].fee_msat, 0);
3061 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
3062 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
3063 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
3065 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
3066 assert_eq!(route.paths[0][3].short_channel_id, 11);
3067 assert_eq!(route.paths[0][3].fee_msat, 0);
3068 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
3069 // If we have a peer in the node map, we'll use their features here since we don't have
3070 // a way of figuring out their features from the invoice:
3071 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
3072 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
3074 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
3075 assert_eq!(route.paths[0][4].short_channel_id, 8);
3076 assert_eq!(route.paths[0][4].fee_msat, 100);
3077 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
3078 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
3079 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3083 fn our_chans_last_hop_connect_test() {
3084 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3085 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3086 let scorer = test_utils::TestScorer::with_penalty(0);
3087 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3088 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3090 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
3091 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3092 let mut last_hops = last_hops(&nodes);
3093 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops.clone());
3094 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();
3095 assert_eq!(route.paths[0].len(), 2);
3097 assert_eq!(route.paths[0][0].pubkey, nodes[3]);
3098 assert_eq!(route.paths[0][0].short_channel_id, 42);
3099 assert_eq!(route.paths[0][0].fee_msat, 0);
3100 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 4) | 1);
3101 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
3102 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3104 assert_eq!(route.paths[0][1].pubkey, nodes[6]);
3105 assert_eq!(route.paths[0][1].short_channel_id, 8);
3106 assert_eq!(route.paths[0][1].fee_msat, 100);
3107 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
3108 assert_eq!(route.paths[0][1].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
3109 assert_eq!(route.paths[0][1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3111 last_hops[0].0[0].fees.base_msat = 1000;
3113 // Revert to via 6 as the fee on 8 goes up
3114 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops);
3115 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3116 assert_eq!(route.paths[0].len(), 4);
3118 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3119 assert_eq!(route.paths[0][0].short_channel_id, 2);
3120 assert_eq!(route.paths[0][0].fee_msat, 200); // fee increased as its % of value transferred across node
3121 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
3122 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3123 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3125 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3126 assert_eq!(route.paths[0][1].short_channel_id, 4);
3127 assert_eq!(route.paths[0][1].fee_msat, 100);
3128 assert_eq!(route.paths[0][1].cltv_expiry_delta, (7 << 4) | 1);
3129 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3130 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3132 assert_eq!(route.paths[0][2].pubkey, nodes[5]);
3133 assert_eq!(route.paths[0][2].short_channel_id, 7);
3134 assert_eq!(route.paths[0][2].fee_msat, 0);
3135 assert_eq!(route.paths[0][2].cltv_expiry_delta, (10 << 4) | 1);
3136 // If we have a peer in the node map, we'll use their features here since we don't have
3137 // a way of figuring out their features from the invoice:
3138 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
3139 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(7));
3141 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
3142 assert_eq!(route.paths[0][3].short_channel_id, 10);
3143 assert_eq!(route.paths[0][3].fee_msat, 100);
3144 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
3145 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
3146 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3148 // ...but still use 8 for larger payments as 6 has a variable feerate
3149 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 2000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3150 assert_eq!(route.paths[0].len(), 5);
3152 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3153 assert_eq!(route.paths[0][0].short_channel_id, 2);
3154 assert_eq!(route.paths[0][0].fee_msat, 3000);
3155 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
3156 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3157 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3159 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3160 assert_eq!(route.paths[0][1].short_channel_id, 4);
3161 assert_eq!(route.paths[0][1].fee_msat, 0);
3162 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
3163 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3164 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3166 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
3167 assert_eq!(route.paths[0][2].short_channel_id, 6);
3168 assert_eq!(route.paths[0][2].fee_msat, 0);
3169 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
3170 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
3171 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
3173 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
3174 assert_eq!(route.paths[0][3].short_channel_id, 11);
3175 assert_eq!(route.paths[0][3].fee_msat, 1000);
3176 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
3177 // If we have a peer in the node map, we'll use their features here since we don't have
3178 // a way of figuring out their features from the invoice:
3179 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
3180 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
3182 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
3183 assert_eq!(route.paths[0][4].short_channel_id, 8);
3184 assert_eq!(route.paths[0][4].fee_msat, 2000);
3185 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
3186 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
3187 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3190 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> {
3191 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
3192 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3193 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3195 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
3196 let last_hops = RouteHint(vec![RouteHintHop {
3197 src_node_id: middle_node_id,
3198 short_channel_id: 8,
3201 proportional_millionths: last_hop_fee_prop,
3203 cltv_expiry_delta: (8 << 4) | 1,
3204 htlc_minimum_msat: None,
3205 htlc_maximum_msat: last_hop_htlc_max,
3207 let payment_params = PaymentParameters::from_node_id(target_node_id).with_route_hints(vec![last_hops]);
3208 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
3209 let scorer = test_utils::TestScorer::with_penalty(0);
3210 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3211 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3212 get_route(&source_node_id, &payment_params, &NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash()).read_only(),
3213 Some(&our_chans.iter().collect::<Vec<_>>()), route_val, 42, &test_utils::TestLogger::new(), &scorer, &random_seed_bytes)
3217 fn unannounced_path_test() {
3218 // We should be able to send a payment to a destination without any help of a routing graph
3219 // if we have a channel with a common counterparty that appears in the first and last hop
3221 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
3223 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3224 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3225 assert_eq!(route.paths[0].len(), 2);
3227 assert_eq!(route.paths[0][0].pubkey, middle_node_id);
3228 assert_eq!(route.paths[0][0].short_channel_id, 42);
3229 assert_eq!(route.paths[0][0].fee_msat, 1001);
3230 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 4) | 1);
3231 assert_eq!(route.paths[0][0].node_features.le_flags(), &[0b11]);
3232 assert_eq!(route.paths[0][0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3234 assert_eq!(route.paths[0][1].pubkey, target_node_id);
3235 assert_eq!(route.paths[0][1].short_channel_id, 8);
3236 assert_eq!(route.paths[0][1].fee_msat, 1000000);
3237 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
3238 assert_eq!(route.paths[0][1].node_features.le_flags(), &[0; 0]); // We dont pass flags in from invoices yet
3239 assert_eq!(route.paths[0][1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3243 fn overflow_unannounced_path_test_liquidity_underflow() {
3244 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
3245 // the last-hop had a fee which overflowed a u64, we'd panic.
3246 // This was due to us adding the first-hop from us unconditionally, causing us to think
3247 // we'd built a path (as our node is in the "best candidate" set), when we had not.
3248 // In this test, we previously hit a subtraction underflow due to having less available
3249 // liquidity at the last hop than 0.
3250 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());
3254 fn overflow_unannounced_path_test_feerate_overflow() {
3255 // This tests for the same case as above, except instead of hitting a subtraction
3256 // underflow, we hit a case where the fee charged at a hop overflowed.
3257 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());
3261 fn available_amount_while_routing_test() {
3262 // Tests whether we choose the correct available channel amount while routing.
3264 let (secp_ctx, network_graph, mut net_graph_msg_handler, chain_monitor, logger) = build_graph();
3265 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3266 let scorer = test_utils::TestScorer::with_penalty(0);
3267 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3268 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3269 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
3271 // We will use a simple single-path route from
3272 // our node to node2 via node0: channels {1, 3}.
3274 // First disable all other paths.
3275 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3276 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3277 short_channel_id: 2,
3280 cltv_expiry_delta: 0,
3281 htlc_minimum_msat: 0,
3282 htlc_maximum_msat: OptionalField::Present(100_000),
3284 fee_proportional_millionths: 0,
3285 excess_data: Vec::new()
3287 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3288 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3289 short_channel_id: 12,
3292 cltv_expiry_delta: 0,
3293 htlc_minimum_msat: 0,
3294 htlc_maximum_msat: OptionalField::Present(100_000),
3296 fee_proportional_millionths: 0,
3297 excess_data: Vec::new()
3300 // Make the first channel (#1) very permissive,
3301 // and we will be testing all limits on the second channel.
3302 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3303 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3304 short_channel_id: 1,
3307 cltv_expiry_delta: 0,
3308 htlc_minimum_msat: 0,
3309 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3311 fee_proportional_millionths: 0,
3312 excess_data: Vec::new()
3315 // First, let's see if routing works if we have absolutely no idea about the available amount.
3316 // In this case, it should be set to 250_000 sats.
3317 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3318 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3319 short_channel_id: 3,
3322 cltv_expiry_delta: 0,
3323 htlc_minimum_msat: 0,
3324 htlc_maximum_msat: OptionalField::Absent,
3326 fee_proportional_millionths: 0,
3327 excess_data: Vec::new()
3331 // Attempt to route more than available results in a failure.
3332 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3333 &our_id, &payment_params, &network_graph.read_only(), None, 250_000_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3334 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3335 } else { panic!(); }
3339 // Now, attempt to route an exact amount we have should be fine.
3340 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();
3341 assert_eq!(route.paths.len(), 1);
3342 let path = route.paths.last().unwrap();
3343 assert_eq!(path.len(), 2);
3344 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3345 assert_eq!(path.last().unwrap().fee_msat, 250_000_000);
3348 // Check that setting outbound_capacity_msat in first_hops limits the channels.
3349 // Disable channel #1 and use another first hop.
3350 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3351 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3352 short_channel_id: 1,
3355 cltv_expiry_delta: 0,
3356 htlc_minimum_msat: 0,
3357 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3359 fee_proportional_millionths: 0,
3360 excess_data: Vec::new()
3363 // Now, limit the first_hop by the outbound_capacity_msat of 200_000 sats.
3364 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
3367 // Attempt to route more than available results in a failure.
3368 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3369 &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) {
3370 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3371 } else { panic!(); }
3375 // Now, attempt to route an exact amount we have should be fine.
3376 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();
3377 assert_eq!(route.paths.len(), 1);
3378 let path = route.paths.last().unwrap();
3379 assert_eq!(path.len(), 2);
3380 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3381 assert_eq!(path.last().unwrap().fee_msat, 200_000_000);
3384 // Enable channel #1 back.
3385 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3386 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3387 short_channel_id: 1,
3390 cltv_expiry_delta: 0,
3391 htlc_minimum_msat: 0,
3392 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3394 fee_proportional_millionths: 0,
3395 excess_data: Vec::new()
3399 // Now let's see if routing works if we know only htlc_maximum_msat.
3400 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3401 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3402 short_channel_id: 3,
3405 cltv_expiry_delta: 0,
3406 htlc_minimum_msat: 0,
3407 htlc_maximum_msat: OptionalField::Present(15_000),
3409 fee_proportional_millionths: 0,
3410 excess_data: Vec::new()
3414 // Attempt to route more than available results in a failure.
3415 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3416 &our_id, &payment_params, &network_graph.read_only(), None, 15_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3417 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3418 } else { panic!(); }
3422 // Now, attempt to route an exact amount we have should be fine.
3423 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 15_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3424 assert_eq!(route.paths.len(), 1);
3425 let path = route.paths.last().unwrap();
3426 assert_eq!(path.len(), 2);
3427 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3428 assert_eq!(path.last().unwrap().fee_msat, 15_000);
3431 // Now let's see if routing works if we know only capacity from the UTXO.
3433 // We can't change UTXO capacity on the fly, so we'll disable
3434 // the existing channel and add another one with the capacity we need.
3435 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3436 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3437 short_channel_id: 3,
3440 cltv_expiry_delta: 0,
3441 htlc_minimum_msat: 0,
3442 htlc_maximum_msat: OptionalField::Absent,
3444 fee_proportional_millionths: 0,
3445 excess_data: Vec::new()
3448 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
3449 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
3450 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
3451 .push_opcode(opcodes::all::OP_PUSHNUM_2)
3452 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
3454 *chain_monitor.utxo_ret.lock().unwrap() = Ok(TxOut { value: 15, script_pubkey: good_script.clone() });
3455 net_graph_msg_handler.add_chain_access(Some(chain_monitor));
3457 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
3458 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3459 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3460 short_channel_id: 333,
3463 cltv_expiry_delta: (3 << 4) | 1,
3464 htlc_minimum_msat: 0,
3465 htlc_maximum_msat: OptionalField::Absent,
3467 fee_proportional_millionths: 0,
3468 excess_data: Vec::new()
3470 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3471 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3472 short_channel_id: 333,
3475 cltv_expiry_delta: (3 << 4) | 2,
3476 htlc_minimum_msat: 0,
3477 htlc_maximum_msat: OptionalField::Absent,
3479 fee_proportional_millionths: 0,
3480 excess_data: Vec::new()
3484 // Attempt to route more than available results in a failure.
3485 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3486 &our_id, &payment_params, &network_graph.read_only(), None, 15_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3487 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3488 } else { panic!(); }
3492 // Now, attempt to route an exact amount we have should be fine.
3493 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 15_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3494 assert_eq!(route.paths.len(), 1);
3495 let path = route.paths.last().unwrap();
3496 assert_eq!(path.len(), 2);
3497 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3498 assert_eq!(path.last().unwrap().fee_msat, 15_000);
3501 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
3502 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3503 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3504 short_channel_id: 333,
3507 cltv_expiry_delta: 0,
3508 htlc_minimum_msat: 0,
3509 htlc_maximum_msat: OptionalField::Present(10_000),
3511 fee_proportional_millionths: 0,
3512 excess_data: Vec::new()
3516 // Attempt to route more than available results in a failure.
3517 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3518 &our_id, &payment_params, &network_graph.read_only(), None, 10_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3519 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3520 } else { panic!(); }
3524 // Now, attempt to route an exact amount we have should be fine.
3525 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 10_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3526 assert_eq!(route.paths.len(), 1);
3527 let path = route.paths.last().unwrap();
3528 assert_eq!(path.len(), 2);
3529 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3530 assert_eq!(path.last().unwrap().fee_msat, 10_000);
3535 fn available_liquidity_last_hop_test() {
3536 // Check that available liquidity properly limits the path even when only
3537 // one of the latter hops is limited.
3538 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3539 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3540 let scorer = test_utils::TestScorer::with_penalty(0);
3541 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3542 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3543 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
3545 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3546 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
3547 // Total capacity: 50 sats.
3549 // Disable other potential paths.
3550 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3551 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3552 short_channel_id: 2,
3555 cltv_expiry_delta: 0,
3556 htlc_minimum_msat: 0,
3557 htlc_maximum_msat: OptionalField::Present(100_000),
3559 fee_proportional_millionths: 0,
3560 excess_data: Vec::new()
3562 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3563 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3564 short_channel_id: 7,
3567 cltv_expiry_delta: 0,
3568 htlc_minimum_msat: 0,
3569 htlc_maximum_msat: OptionalField::Present(100_000),
3571 fee_proportional_millionths: 0,
3572 excess_data: Vec::new()
3577 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3578 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3579 short_channel_id: 12,
3582 cltv_expiry_delta: 0,
3583 htlc_minimum_msat: 0,
3584 htlc_maximum_msat: OptionalField::Present(100_000),
3586 fee_proportional_millionths: 0,
3587 excess_data: Vec::new()
3589 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3590 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3591 short_channel_id: 13,
3594 cltv_expiry_delta: 0,
3595 htlc_minimum_msat: 0,
3596 htlc_maximum_msat: OptionalField::Present(100_000),
3598 fee_proportional_millionths: 0,
3599 excess_data: Vec::new()
3602 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3603 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3604 short_channel_id: 6,
3607 cltv_expiry_delta: 0,
3608 htlc_minimum_msat: 0,
3609 htlc_maximum_msat: OptionalField::Present(50_000),
3611 fee_proportional_millionths: 0,
3612 excess_data: Vec::new()
3614 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3615 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3616 short_channel_id: 11,
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()
3627 // Attempt to route more than available results in a failure.
3628 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3629 &our_id, &payment_params, &network_graph.read_only(), None, 60_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3630 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3631 } else { panic!(); }
3635 // Now, attempt to route 49 sats (just a bit below the capacity).
3636 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 49_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3637 assert_eq!(route.paths.len(), 1);
3638 let mut total_amount_paid_msat = 0;
3639 for path in &route.paths {
3640 assert_eq!(path.len(), 4);
3641 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3642 total_amount_paid_msat += path.last().unwrap().fee_msat;
3644 assert_eq!(total_amount_paid_msat, 49_000);
3648 // Attempt to route an exact amount is also fine
3649 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3650 assert_eq!(route.paths.len(), 1);
3651 let mut total_amount_paid_msat = 0;
3652 for path in &route.paths {
3653 assert_eq!(path.len(), 4);
3654 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3655 total_amount_paid_msat += path.last().unwrap().fee_msat;
3657 assert_eq!(total_amount_paid_msat, 50_000);
3662 fn ignore_fee_first_hop_test() {
3663 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3664 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3665 let scorer = test_utils::TestScorer::with_penalty(0);
3666 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3667 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3668 let payment_params = PaymentParameters::from_node_id(nodes[2]);
3670 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3671 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3672 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3673 short_channel_id: 1,
3676 cltv_expiry_delta: 0,
3677 htlc_minimum_msat: 0,
3678 htlc_maximum_msat: OptionalField::Present(100_000),
3679 fee_base_msat: 1_000_000,
3680 fee_proportional_millionths: 0,
3681 excess_data: Vec::new()
3683 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3684 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3685 short_channel_id: 3,
3688 cltv_expiry_delta: 0,
3689 htlc_minimum_msat: 0,
3690 htlc_maximum_msat: OptionalField::Present(50_000),
3692 fee_proportional_millionths: 0,
3693 excess_data: Vec::new()
3697 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3698 assert_eq!(route.paths.len(), 1);
3699 let mut total_amount_paid_msat = 0;
3700 for path in &route.paths {
3701 assert_eq!(path.len(), 2);
3702 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3703 total_amount_paid_msat += path.last().unwrap().fee_msat;
3705 assert_eq!(total_amount_paid_msat, 50_000);
3710 fn simple_mpp_route_test() {
3711 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3712 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3713 let scorer = test_utils::TestScorer::with_penalty(0);
3714 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3715 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3716 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
3718 // We need a route consisting of 3 paths:
3719 // From our node to node2 via node0, node7, node1 (three paths one hop each).
3720 // To achieve this, the amount being transferred should be around
3721 // the total capacity of these 3 paths.
3723 // First, we set limits on these (previously unlimited) channels.
3724 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
3726 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3727 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3728 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3729 short_channel_id: 1,
3732 cltv_expiry_delta: 0,
3733 htlc_minimum_msat: 0,
3734 htlc_maximum_msat: OptionalField::Present(100_000),
3736 fee_proportional_millionths: 0,
3737 excess_data: Vec::new()
3739 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3740 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3741 short_channel_id: 3,
3744 cltv_expiry_delta: 0,
3745 htlc_minimum_msat: 0,
3746 htlc_maximum_msat: OptionalField::Present(50_000),
3748 fee_proportional_millionths: 0,
3749 excess_data: Vec::new()
3752 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
3753 // (total limit 60).
3754 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3755 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3756 short_channel_id: 12,
3759 cltv_expiry_delta: 0,
3760 htlc_minimum_msat: 0,
3761 htlc_maximum_msat: OptionalField::Present(60_000),
3763 fee_proportional_millionths: 0,
3764 excess_data: Vec::new()
3766 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3767 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3768 short_channel_id: 13,
3771 cltv_expiry_delta: 0,
3772 htlc_minimum_msat: 0,
3773 htlc_maximum_msat: OptionalField::Present(60_000),
3775 fee_proportional_millionths: 0,
3776 excess_data: Vec::new()
3779 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
3780 // (total capacity 180 sats).
3781 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3782 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3783 short_channel_id: 2,
3786 cltv_expiry_delta: 0,
3787 htlc_minimum_msat: 0,
3788 htlc_maximum_msat: OptionalField::Present(200_000),
3790 fee_proportional_millionths: 0,
3791 excess_data: Vec::new()
3793 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3794 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3795 short_channel_id: 4,
3798 cltv_expiry_delta: 0,
3799 htlc_minimum_msat: 0,
3800 htlc_maximum_msat: OptionalField::Present(180_000),
3802 fee_proportional_millionths: 0,
3803 excess_data: Vec::new()
3807 // Attempt to route more than available results in a failure.
3808 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3809 &our_id, &payment_params, &network_graph.read_only(), None, 300_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3810 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3811 } else { panic!(); }
3815 // Now, attempt to route 250 sats (just a bit below the capacity).
3816 // Our algorithm should provide us with these 3 paths.
3817 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 250_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3818 assert_eq!(route.paths.len(), 3);
3819 let mut total_amount_paid_msat = 0;
3820 for path in &route.paths {
3821 assert_eq!(path.len(), 2);
3822 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3823 total_amount_paid_msat += path.last().unwrap().fee_msat;
3825 assert_eq!(total_amount_paid_msat, 250_000);
3829 // Attempt to route an exact amount is also fine
3830 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 290_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3831 assert_eq!(route.paths.len(), 3);
3832 let mut total_amount_paid_msat = 0;
3833 for path in &route.paths {
3834 assert_eq!(path.len(), 2);
3835 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3836 total_amount_paid_msat += path.last().unwrap().fee_msat;
3838 assert_eq!(total_amount_paid_msat, 290_000);
3843 fn long_mpp_route_test() {
3844 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3845 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3846 let scorer = test_utils::TestScorer::with_penalty(0);
3847 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3848 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3849 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
3851 // We need a route consisting of 3 paths:
3852 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3853 // Note that these paths overlap (channels 5, 12, 13).
3854 // We will route 300 sats.
3855 // Each path will have 100 sats capacity, those channels which
3856 // are used twice will have 200 sats capacity.
3858 // Disable other potential paths.
3859 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3860 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3861 short_channel_id: 2,
3864 cltv_expiry_delta: 0,
3865 htlc_minimum_msat: 0,
3866 htlc_maximum_msat: OptionalField::Present(100_000),
3868 fee_proportional_millionths: 0,
3869 excess_data: Vec::new()
3871 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3872 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3873 short_channel_id: 7,
3876 cltv_expiry_delta: 0,
3877 htlc_minimum_msat: 0,
3878 htlc_maximum_msat: OptionalField::Present(100_000),
3880 fee_proportional_millionths: 0,
3881 excess_data: Vec::new()
3884 // Path via {node0, node2} is channels {1, 3, 5}.
3885 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3886 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3887 short_channel_id: 1,
3890 cltv_expiry_delta: 0,
3891 htlc_minimum_msat: 0,
3892 htlc_maximum_msat: OptionalField::Present(100_000),
3894 fee_proportional_millionths: 0,
3895 excess_data: Vec::new()
3897 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3898 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3899 short_channel_id: 3,
3902 cltv_expiry_delta: 0,
3903 htlc_minimum_msat: 0,
3904 htlc_maximum_msat: OptionalField::Present(100_000),
3906 fee_proportional_millionths: 0,
3907 excess_data: Vec::new()
3910 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3911 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3912 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3913 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3914 short_channel_id: 5,
3917 cltv_expiry_delta: 0,
3918 htlc_minimum_msat: 0,
3919 htlc_maximum_msat: OptionalField::Present(200_000),
3921 fee_proportional_millionths: 0,
3922 excess_data: Vec::new()
3925 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3926 // Add 100 sats to the capacities of {12, 13}, because these channels
3927 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3928 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3929 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3930 short_channel_id: 12,
3933 cltv_expiry_delta: 0,
3934 htlc_minimum_msat: 0,
3935 htlc_maximum_msat: OptionalField::Present(200_000),
3937 fee_proportional_millionths: 0,
3938 excess_data: Vec::new()
3940 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3941 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3942 short_channel_id: 13,
3945 cltv_expiry_delta: 0,
3946 htlc_minimum_msat: 0,
3947 htlc_maximum_msat: OptionalField::Present(200_000),
3949 fee_proportional_millionths: 0,
3950 excess_data: Vec::new()
3953 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3954 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3955 short_channel_id: 6,
3958 cltv_expiry_delta: 0,
3959 htlc_minimum_msat: 0,
3960 htlc_maximum_msat: OptionalField::Present(100_000),
3962 fee_proportional_millionths: 0,
3963 excess_data: Vec::new()
3965 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3966 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3967 short_channel_id: 11,
3970 cltv_expiry_delta: 0,
3971 htlc_minimum_msat: 0,
3972 htlc_maximum_msat: OptionalField::Present(100_000),
3974 fee_proportional_millionths: 0,
3975 excess_data: Vec::new()
3978 // Path via {node7, node2} is channels {12, 13, 5}.
3979 // We already limited them to 200 sats (they are used twice for 100 sats).
3980 // Nothing to do here.
3983 // Attempt to route more than available results in a failure.
3984 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3985 &our_id, &payment_params, &network_graph.read_only(), None, 350_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3986 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3987 } else { panic!(); }
3991 // Now, attempt to route 300 sats (exact amount we can route).
3992 // Our algorithm should provide us with these 3 paths, 100 sats each.
3993 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 300_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3994 assert_eq!(route.paths.len(), 3);
3996 let mut total_amount_paid_msat = 0;
3997 for path in &route.paths {
3998 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3999 total_amount_paid_msat += path.last().unwrap().fee_msat;
4001 assert_eq!(total_amount_paid_msat, 300_000);
4007 fn mpp_cheaper_route_test() {
4008 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4009 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4010 let scorer = test_utils::TestScorer::with_penalty(0);
4011 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4012 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4013 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
4015 // This test checks that if we have two cheaper paths and one more expensive path,
4016 // so that liquidity-wise any 2 of 3 combination is sufficient,
4017 // two cheaper paths will be taken.
4018 // These paths have equal available liquidity.
4020 // We need a combination of 3 paths:
4021 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
4022 // Note that these paths overlap (channels 5, 12, 13).
4023 // Each path will have 100 sats capacity, those channels which
4024 // are used twice will have 200 sats capacity.
4026 // Disable other potential paths.
4027 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4028 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4029 short_channel_id: 2,
4032 cltv_expiry_delta: 0,
4033 htlc_minimum_msat: 0,
4034 htlc_maximum_msat: OptionalField::Present(100_000),
4036 fee_proportional_millionths: 0,
4037 excess_data: Vec::new()
4039 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4040 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4041 short_channel_id: 7,
4044 cltv_expiry_delta: 0,
4045 htlc_minimum_msat: 0,
4046 htlc_maximum_msat: OptionalField::Present(100_000),
4048 fee_proportional_millionths: 0,
4049 excess_data: Vec::new()
4052 // Path via {node0, node2} is channels {1, 3, 5}.
4053 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4054 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4055 short_channel_id: 1,
4058 cltv_expiry_delta: 0,
4059 htlc_minimum_msat: 0,
4060 htlc_maximum_msat: OptionalField::Present(100_000),
4062 fee_proportional_millionths: 0,
4063 excess_data: Vec::new()
4065 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4066 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4067 short_channel_id: 3,
4070 cltv_expiry_delta: 0,
4071 htlc_minimum_msat: 0,
4072 htlc_maximum_msat: OptionalField::Present(100_000),
4074 fee_proportional_millionths: 0,
4075 excess_data: Vec::new()
4078 // Capacity of 200 sats because this channel will be used by 3rd path as well.
4079 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4080 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4081 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4082 short_channel_id: 5,
4085 cltv_expiry_delta: 0,
4086 htlc_minimum_msat: 0,
4087 htlc_maximum_msat: OptionalField::Present(200_000),
4089 fee_proportional_millionths: 0,
4090 excess_data: Vec::new()
4093 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4094 // Add 100 sats to the capacities of {12, 13}, because these channels
4095 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
4096 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4097 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4098 short_channel_id: 12,
4101 cltv_expiry_delta: 0,
4102 htlc_minimum_msat: 0,
4103 htlc_maximum_msat: OptionalField::Present(200_000),
4105 fee_proportional_millionths: 0,
4106 excess_data: Vec::new()
4108 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4109 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4110 short_channel_id: 13,
4113 cltv_expiry_delta: 0,
4114 htlc_minimum_msat: 0,
4115 htlc_maximum_msat: OptionalField::Present(200_000),
4117 fee_proportional_millionths: 0,
4118 excess_data: Vec::new()
4121 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4122 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4123 short_channel_id: 6,
4126 cltv_expiry_delta: 0,
4127 htlc_minimum_msat: 0,
4128 htlc_maximum_msat: OptionalField::Present(100_000),
4129 fee_base_msat: 1_000,
4130 fee_proportional_millionths: 0,
4131 excess_data: Vec::new()
4133 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4134 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4135 short_channel_id: 11,
4138 cltv_expiry_delta: 0,
4139 htlc_minimum_msat: 0,
4140 htlc_maximum_msat: OptionalField::Present(100_000),
4142 fee_proportional_millionths: 0,
4143 excess_data: Vec::new()
4146 // Path via {node7, node2} is channels {12, 13, 5}.
4147 // We already limited them to 200 sats (they are used twice for 100 sats).
4148 // Nothing to do here.
4151 // Now, attempt to route 180 sats.
4152 // Our algorithm should provide us with these 2 paths.
4153 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 180_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4154 assert_eq!(route.paths.len(), 2);
4156 let mut total_value_transferred_msat = 0;
4157 let mut total_paid_msat = 0;
4158 for path in &route.paths {
4159 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
4160 total_value_transferred_msat += path.last().unwrap().fee_msat;
4162 total_paid_msat += hop.fee_msat;
4165 // If we paid fee, this would be higher.
4166 assert_eq!(total_value_transferred_msat, 180_000);
4167 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
4168 assert_eq!(total_fees_paid, 0);
4173 fn fees_on_mpp_route_test() {
4174 // This test makes sure that MPP algorithm properly takes into account
4175 // fees charged on the channels, by making the fees impactful:
4176 // if the fee is not properly accounted for, the behavior is different.
4177 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4178 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4179 let scorer = test_utils::TestScorer::with_penalty(0);
4180 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4181 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4182 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
4184 // We need a route consisting of 2 paths:
4185 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
4186 // We will route 200 sats, Each path will have 100 sats capacity.
4188 // This test is not particularly stable: e.g.,
4189 // there's a way to route via {node0, node2, node4}.
4190 // It works while pathfinding is deterministic, but can be broken otherwise.
4191 // It's fine to ignore this concern for now.
4193 // Disable other potential paths.
4194 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4195 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4196 short_channel_id: 2,
4199 cltv_expiry_delta: 0,
4200 htlc_minimum_msat: 0,
4201 htlc_maximum_msat: OptionalField::Present(100_000),
4203 fee_proportional_millionths: 0,
4204 excess_data: Vec::new()
4207 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4208 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4209 short_channel_id: 7,
4212 cltv_expiry_delta: 0,
4213 htlc_minimum_msat: 0,
4214 htlc_maximum_msat: OptionalField::Present(100_000),
4216 fee_proportional_millionths: 0,
4217 excess_data: Vec::new()
4220 // Path via {node0, node2} is channels {1, 3, 5}.
4221 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4222 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4223 short_channel_id: 1,
4226 cltv_expiry_delta: 0,
4227 htlc_minimum_msat: 0,
4228 htlc_maximum_msat: OptionalField::Present(100_000),
4230 fee_proportional_millionths: 0,
4231 excess_data: Vec::new()
4233 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4234 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4235 short_channel_id: 3,
4238 cltv_expiry_delta: 0,
4239 htlc_minimum_msat: 0,
4240 htlc_maximum_msat: OptionalField::Present(100_000),
4242 fee_proportional_millionths: 0,
4243 excess_data: Vec::new()
4246 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4247 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4248 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4249 short_channel_id: 5,
4252 cltv_expiry_delta: 0,
4253 htlc_minimum_msat: 0,
4254 htlc_maximum_msat: OptionalField::Present(100_000),
4256 fee_proportional_millionths: 0,
4257 excess_data: Vec::new()
4260 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4261 // All channels should be 100 sats capacity. But for the fee experiment,
4262 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
4263 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
4264 // 100 sats (and pay 150 sats in fees for the use of channel 6),
4265 // so no matter how large are other channels,
4266 // the whole path will be limited by 100 sats with just these 2 conditions:
4267 // - channel 12 capacity is 250 sats
4268 // - fee for channel 6 is 150 sats
4269 // Let's test this by enforcing these 2 conditions and removing other limits.
4270 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4271 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4272 short_channel_id: 12,
4275 cltv_expiry_delta: 0,
4276 htlc_minimum_msat: 0,
4277 htlc_maximum_msat: OptionalField::Present(250_000),
4279 fee_proportional_millionths: 0,
4280 excess_data: Vec::new()
4282 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4283 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4284 short_channel_id: 13,
4287 cltv_expiry_delta: 0,
4288 htlc_minimum_msat: 0,
4289 htlc_maximum_msat: OptionalField::Absent,
4291 fee_proportional_millionths: 0,
4292 excess_data: Vec::new()
4295 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4296 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4297 short_channel_id: 6,
4300 cltv_expiry_delta: 0,
4301 htlc_minimum_msat: 0,
4302 htlc_maximum_msat: OptionalField::Absent,
4303 fee_base_msat: 150_000,
4304 fee_proportional_millionths: 0,
4305 excess_data: Vec::new()
4307 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4308 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4309 short_channel_id: 11,
4312 cltv_expiry_delta: 0,
4313 htlc_minimum_msat: 0,
4314 htlc_maximum_msat: OptionalField::Absent,
4316 fee_proportional_millionths: 0,
4317 excess_data: Vec::new()
4321 // Attempt to route more than available results in a failure.
4322 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4323 &our_id, &payment_params, &network_graph.read_only(), None, 210_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
4324 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4325 } else { panic!(); }
4329 // Now, attempt to route 200 sats (exact amount we can route).
4330 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 200_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4331 assert_eq!(route.paths.len(), 2);
4333 let mut total_amount_paid_msat = 0;
4334 for path in &route.paths {
4335 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
4336 total_amount_paid_msat += path.last().unwrap().fee_msat;
4338 assert_eq!(total_amount_paid_msat, 200_000);
4339 assert_eq!(route.get_total_fees(), 150_000);
4344 fn mpp_with_last_hops() {
4345 // Previously, if we tried to send an MPP payment to a destination which was only reachable
4346 // via a single last-hop route hint, we'd fail to route if we first collected routes
4347 // totaling close but not quite enough to fund the full payment.
4349 // This was because we considered last-hop hints to have exactly the sought payment amount
4350 // instead of the amount we were trying to collect, needlessly limiting our path searching
4351 // at the very first hop.
4353 // Specifically, this interacted with our "all paths must fund at least 5% of total target"
4354 // criterion to cause us to refuse all routes at the last hop hint which would be considered
4355 // to only have the remaining to-collect amount in available liquidity.
4357 // This bug appeared in production in some specific channel configurations.
4358 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4359 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4360 let scorer = test_utils::TestScorer::with_penalty(0);
4361 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4362 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4363 let payment_params = PaymentParameters::from_node_id(PublicKey::from_slice(&[02; 33]).unwrap()).with_features(InvoiceFeatures::known())
4364 .with_route_hints(vec![RouteHint(vec![RouteHintHop {
4365 src_node_id: nodes[2],
4366 short_channel_id: 42,
4367 fees: RoutingFees { base_msat: 0, proportional_millionths: 0 },
4368 cltv_expiry_delta: 42,
4369 htlc_minimum_msat: None,
4370 htlc_maximum_msat: None,
4373 // Keep only two paths from us to nodes[2], both with a 99sat HTLC maximum, with one with
4374 // no fee and one with a 1msat fee. Previously, trying to route 100 sats to nodes[2] here
4375 // would first use the no-fee route and then fail to find a path along the second route as
4376 // we think we can only send up to 1 additional sat over the last-hop but refuse to as its
4377 // under 5% of our payment amount.
4378 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4379 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4380 short_channel_id: 1,
4383 cltv_expiry_delta: (5 << 4) | 5,
4384 htlc_minimum_msat: 0,
4385 htlc_maximum_msat: OptionalField::Present(99_000),
4386 fee_base_msat: u32::max_value(),
4387 fee_proportional_millionths: u32::max_value(),
4388 excess_data: Vec::new()
4390 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4391 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4392 short_channel_id: 2,
4395 cltv_expiry_delta: (5 << 4) | 3,
4396 htlc_minimum_msat: 0,
4397 htlc_maximum_msat: OptionalField::Present(99_000),
4398 fee_base_msat: u32::max_value(),
4399 fee_proportional_millionths: u32::max_value(),
4400 excess_data: Vec::new()
4402 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4403 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4404 short_channel_id: 4,
4407 cltv_expiry_delta: (4 << 4) | 1,
4408 htlc_minimum_msat: 0,
4409 htlc_maximum_msat: OptionalField::Absent,
4411 fee_proportional_millionths: 0,
4412 excess_data: Vec::new()
4414 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4415 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4416 short_channel_id: 13,
4418 flags: 0|2, // Channel disabled
4419 cltv_expiry_delta: (13 << 4) | 1,
4420 htlc_minimum_msat: 0,
4421 htlc_maximum_msat: OptionalField::Absent,
4423 fee_proportional_millionths: 2000000,
4424 excess_data: Vec::new()
4427 // Get a route for 100 sats and check that we found the MPP route no problem and didn't
4429 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4430 assert_eq!(route.paths.len(), 2);
4431 // Paths are somewhat randomly ordered, but:
4432 // * the first is channel 2 (1 msat fee) -> channel 4 -> channel 42
4433 // * the second is channel 1 (0 fee, but 99 sat maximum) -> channel 3 -> channel 42
4434 assert_eq!(route.paths[0][0].short_channel_id, 2);
4435 assert_eq!(route.paths[0][0].fee_msat, 1);
4436 assert_eq!(route.paths[0][2].fee_msat, 1_000);
4437 assert_eq!(route.paths[1][0].short_channel_id, 1);
4438 assert_eq!(route.paths[1][0].fee_msat, 0);
4439 assert_eq!(route.paths[1][2].fee_msat, 99_000);
4440 assert_eq!(route.get_total_fees(), 1);
4441 assert_eq!(route.get_total_amount(), 100_000);
4445 fn drop_lowest_channel_mpp_route_test() {
4446 // This test checks that low-capacity channel is dropped when after
4447 // path finding we realize that we found more capacity than we need.
4448 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4449 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4450 let scorer = test_utils::TestScorer::with_penalty(0);
4451 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4452 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4453 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
4455 // We need a route consisting of 3 paths:
4456 // From our node to node2 via node0, node7, node1 (three paths one hop each).
4458 // The first and the second paths should be sufficient, but the third should be
4459 // cheaper, so that we select it but drop later.
4461 // First, we set limits on these (previously unlimited) channels.
4462 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
4464 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
4465 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4466 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4467 short_channel_id: 1,
4470 cltv_expiry_delta: 0,
4471 htlc_minimum_msat: 0,
4472 htlc_maximum_msat: OptionalField::Present(100_000),
4474 fee_proportional_millionths: 0,
4475 excess_data: Vec::new()
4477 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4478 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4479 short_channel_id: 3,
4482 cltv_expiry_delta: 0,
4483 htlc_minimum_msat: 0,
4484 htlc_maximum_msat: OptionalField::Present(50_000),
4486 fee_proportional_millionths: 0,
4487 excess_data: Vec::new()
4490 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
4491 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4492 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4493 short_channel_id: 12,
4496 cltv_expiry_delta: 0,
4497 htlc_minimum_msat: 0,
4498 htlc_maximum_msat: OptionalField::Present(60_000),
4500 fee_proportional_millionths: 0,
4501 excess_data: Vec::new()
4503 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4504 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4505 short_channel_id: 13,
4508 cltv_expiry_delta: 0,
4509 htlc_minimum_msat: 0,
4510 htlc_maximum_msat: OptionalField::Present(60_000),
4512 fee_proportional_millionths: 0,
4513 excess_data: Vec::new()
4516 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
4517 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4518 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4519 short_channel_id: 2,
4522 cltv_expiry_delta: 0,
4523 htlc_minimum_msat: 0,
4524 htlc_maximum_msat: OptionalField::Present(20_000),
4526 fee_proportional_millionths: 0,
4527 excess_data: Vec::new()
4529 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4530 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4531 short_channel_id: 4,
4534 cltv_expiry_delta: 0,
4535 htlc_minimum_msat: 0,
4536 htlc_maximum_msat: OptionalField::Present(20_000),
4538 fee_proportional_millionths: 0,
4539 excess_data: Vec::new()
4543 // Attempt to route more than available results in a failure.
4544 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4545 &our_id, &payment_params, &network_graph.read_only(), None, 150_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
4546 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4547 } else { panic!(); }
4551 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
4552 // Our algorithm should provide us with these 3 paths.
4553 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 125_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4554 assert_eq!(route.paths.len(), 3);
4555 let mut total_amount_paid_msat = 0;
4556 for path in &route.paths {
4557 assert_eq!(path.len(), 2);
4558 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4559 total_amount_paid_msat += path.last().unwrap().fee_msat;
4561 assert_eq!(total_amount_paid_msat, 125_000);
4565 // Attempt to route without the last small cheap channel
4566 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4567 assert_eq!(route.paths.len(), 2);
4568 let mut total_amount_paid_msat = 0;
4569 for path in &route.paths {
4570 assert_eq!(path.len(), 2);
4571 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4572 total_amount_paid_msat += path.last().unwrap().fee_msat;
4574 assert_eq!(total_amount_paid_msat, 90_000);
4579 fn min_criteria_consistency() {
4580 // Test that we don't use an inconsistent metric between updating and walking nodes during
4581 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
4582 // was updated with a different criterion from the heap sorting, resulting in loops in
4583 // calculated paths. We test for that specific case here.
4585 // We construct a network that looks like this:
4587 // node2 -1(3)2- node3
4591 // node1 -1(5)2- node4 -1(1)2- node6
4597 // We create a loop on the side of our real path - our destination is node 6, with a
4598 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
4599 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
4600 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
4601 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
4602 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
4603 // "previous hop" being set to node 3, creating a loop in the path.
4604 let secp_ctx = Secp256k1::new();
4605 let logger = Arc::new(test_utils::TestLogger::new());
4606 let network = Arc::new(NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash()));
4607 let net_graph_msg_handler = NetGraphMsgHandler::new(Arc::clone(&network), None, Arc::clone(&logger));
4608 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4609 let scorer = test_utils::TestScorer::with_penalty(0);
4610 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4611 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4612 let payment_params = PaymentParameters::from_node_id(nodes[6]);
4614 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
4615 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4616 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4617 short_channel_id: 6,
4620 cltv_expiry_delta: (6 << 4) | 0,
4621 htlc_minimum_msat: 0,
4622 htlc_maximum_msat: OptionalField::Absent,
4624 fee_proportional_millionths: 0,
4625 excess_data: Vec::new()
4627 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
4629 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4630 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4631 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4632 short_channel_id: 5,
4635 cltv_expiry_delta: (5 << 4) | 0,
4636 htlc_minimum_msat: 0,
4637 htlc_maximum_msat: OptionalField::Absent,
4639 fee_proportional_millionths: 0,
4640 excess_data: Vec::new()
4642 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
4644 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
4645 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4646 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4647 short_channel_id: 4,
4650 cltv_expiry_delta: (4 << 4) | 0,
4651 htlc_minimum_msat: 0,
4652 htlc_maximum_msat: OptionalField::Absent,
4654 fee_proportional_millionths: 0,
4655 excess_data: Vec::new()
4657 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
4659 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
4660 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
4661 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4662 short_channel_id: 3,
4665 cltv_expiry_delta: (3 << 4) | 0,
4666 htlc_minimum_msat: 0,
4667 htlc_maximum_msat: OptionalField::Absent,
4669 fee_proportional_millionths: 0,
4670 excess_data: Vec::new()
4672 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
4674 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
4675 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4676 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4677 short_channel_id: 2,
4680 cltv_expiry_delta: (2 << 4) | 0,
4681 htlc_minimum_msat: 0,
4682 htlc_maximum_msat: OptionalField::Absent,
4684 fee_proportional_millionths: 0,
4685 excess_data: Vec::new()
4688 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
4689 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4690 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4691 short_channel_id: 1,
4694 cltv_expiry_delta: (1 << 4) | 0,
4695 htlc_minimum_msat: 100,
4696 htlc_maximum_msat: OptionalField::Absent,
4698 fee_proportional_millionths: 0,
4699 excess_data: Vec::new()
4701 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
4704 // Now ensure the route flows simply over nodes 1 and 4 to 6.
4705 let route = get_route(&our_id, &payment_params, &network.read_only(), None, 10_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4706 assert_eq!(route.paths.len(), 1);
4707 assert_eq!(route.paths[0].len(), 3);
4709 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
4710 assert_eq!(route.paths[0][0].short_channel_id, 6);
4711 assert_eq!(route.paths[0][0].fee_msat, 100);
4712 assert_eq!(route.paths[0][0].cltv_expiry_delta, (5 << 4) | 0);
4713 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(1));
4714 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(6));
4716 assert_eq!(route.paths[0][1].pubkey, nodes[4]);
4717 assert_eq!(route.paths[0][1].short_channel_id, 5);
4718 assert_eq!(route.paths[0][1].fee_msat, 0);
4719 assert_eq!(route.paths[0][1].cltv_expiry_delta, (1 << 4) | 0);
4720 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(4));
4721 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(5));
4723 assert_eq!(route.paths[0][2].pubkey, nodes[6]);
4724 assert_eq!(route.paths[0][2].short_channel_id, 1);
4725 assert_eq!(route.paths[0][2].fee_msat, 10_000);
4726 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
4727 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
4728 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(1));
4734 fn exact_fee_liquidity_limit() {
4735 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
4736 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
4737 // we calculated fees on a higher value, resulting in us ignoring such paths.
4738 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4739 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
4740 let scorer = test_utils::TestScorer::with_penalty(0);
4741 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4742 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4743 let payment_params = PaymentParameters::from_node_id(nodes[2]);
4745 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
4747 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4748 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4749 short_channel_id: 2,
4752 cltv_expiry_delta: 0,
4753 htlc_minimum_msat: 0,
4754 htlc_maximum_msat: OptionalField::Present(85_000),
4756 fee_proportional_millionths: 0,
4757 excess_data: Vec::new()
4760 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4761 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4762 short_channel_id: 12,
4765 cltv_expiry_delta: (4 << 4) | 1,
4766 htlc_minimum_msat: 0,
4767 htlc_maximum_msat: OptionalField::Present(270_000),
4769 fee_proportional_millionths: 1000000,
4770 excess_data: Vec::new()
4774 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
4775 // 200% fee charged channel 13 in the 1-to-2 direction.
4776 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4777 assert_eq!(route.paths.len(), 1);
4778 assert_eq!(route.paths[0].len(), 2);
4780 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
4781 assert_eq!(route.paths[0][0].short_channel_id, 12);
4782 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
4783 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
4784 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
4785 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
4787 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
4788 assert_eq!(route.paths[0][1].short_channel_id, 13);
4789 assert_eq!(route.paths[0][1].fee_msat, 90_000);
4790 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
4791 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
4792 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
4797 fn htlc_max_reduction_below_min() {
4798 // Test that if, while walking the graph, we reduce the value being sent to meet an
4799 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
4800 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
4801 // resulting in us thinking there is no possible path, even if other paths exist.
4802 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4803 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4804 let scorer = test_utils::TestScorer::with_penalty(0);
4805 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4806 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4807 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
4809 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
4810 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
4811 // then try to send 90_000.
4812 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4813 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4814 short_channel_id: 2,
4817 cltv_expiry_delta: 0,
4818 htlc_minimum_msat: 0,
4819 htlc_maximum_msat: OptionalField::Present(80_000),
4821 fee_proportional_millionths: 0,
4822 excess_data: Vec::new()
4824 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4825 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4826 short_channel_id: 4,
4829 cltv_expiry_delta: (4 << 4) | 1,
4830 htlc_minimum_msat: 90_000,
4831 htlc_maximum_msat: OptionalField::Absent,
4833 fee_proportional_millionths: 0,
4834 excess_data: Vec::new()
4838 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
4839 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
4840 // expensive) channels 12-13 path.
4841 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4842 assert_eq!(route.paths.len(), 1);
4843 assert_eq!(route.paths[0].len(), 2);
4845 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
4846 assert_eq!(route.paths[0][0].short_channel_id, 12);
4847 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
4848 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
4849 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
4850 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
4852 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
4853 assert_eq!(route.paths[0][1].short_channel_id, 13);
4854 assert_eq!(route.paths[0][1].fee_msat, 90_000);
4855 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
4856 assert_eq!(route.paths[0][1].node_features.le_flags(), InvoiceFeatures::known().le_flags());
4857 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
4862 fn multiple_direct_first_hops() {
4863 // Previously we'd only ever considered one first hop path per counterparty.
4864 // However, as we don't restrict users to one channel per peer, we really need to support
4865 // looking at all first hop paths.
4866 // Here we test that we do not ignore all-but-the-last first hop paths per counterparty (as
4867 // we used to do by overwriting the `first_hop_targets` hashmap entry) and that we can MPP
4868 // route over multiple channels with the same first hop.
4869 let secp_ctx = Secp256k1::new();
4870 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4871 let logger = Arc::new(test_utils::TestLogger::new());
4872 let network_graph = NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash());
4873 let scorer = test_utils::TestScorer::with_penalty(0);
4874 let payment_params = PaymentParameters::from_node_id(nodes[0]).with_features(InvoiceFeatures::known());
4875 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4876 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4879 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
4880 &get_channel_details(Some(3), nodes[0], InitFeatures::known(), 200_000),
4881 &get_channel_details(Some(2), nodes[0], InitFeatures::known(), 10_000),
4882 ]), 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4883 assert_eq!(route.paths.len(), 1);
4884 assert_eq!(route.paths[0].len(), 1);
4886 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
4887 assert_eq!(route.paths[0][0].short_channel_id, 3);
4888 assert_eq!(route.paths[0][0].fee_msat, 100_000);
4891 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
4892 &get_channel_details(Some(3), nodes[0], InitFeatures::known(), 50_000),
4893 &get_channel_details(Some(2), nodes[0], InitFeatures::known(), 50_000),
4894 ]), 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4895 assert_eq!(route.paths.len(), 2);
4896 assert_eq!(route.paths[0].len(), 1);
4897 assert_eq!(route.paths[1].len(), 1);
4899 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
4900 assert_eq!(route.paths[0][0].short_channel_id, 3);
4901 assert_eq!(route.paths[0][0].fee_msat, 50_000);
4903 assert_eq!(route.paths[1][0].pubkey, nodes[0]);
4904 assert_eq!(route.paths[1][0].short_channel_id, 2);
4905 assert_eq!(route.paths[1][0].fee_msat, 50_000);
4910 fn prefers_shorter_route_with_higher_fees() {
4911 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4912 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4913 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
4915 // Without penalizing each hop 100 msats, a longer path with lower fees is chosen.
4916 let scorer = test_utils::TestScorer::with_penalty(0);
4917 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4918 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4919 let route = get_route(
4920 &our_id, &payment_params, &network_graph.read_only(), None, 100, 42,
4921 Arc::clone(&logger), &scorer, &random_seed_bytes
4923 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4925 assert_eq!(route.get_total_fees(), 100);
4926 assert_eq!(route.get_total_amount(), 100);
4927 assert_eq!(path, vec![2, 4, 6, 11, 8]);
4929 // Applying a 100 msat penalty to each hop results in taking channels 7 and 10 to nodes[6]
4930 // from nodes[2] rather than channel 6, 11, and 8, even though the longer path is cheaper.
4931 let scorer = test_utils::TestScorer::with_penalty(100);
4932 let route = get_route(
4933 &our_id, &payment_params, &network_graph.read_only(), None, 100, 42,
4934 Arc::clone(&logger), &scorer, &random_seed_bytes
4936 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4938 assert_eq!(route.get_total_fees(), 300);
4939 assert_eq!(route.get_total_amount(), 100);
4940 assert_eq!(path, vec![2, 4, 7, 10]);
4943 struct BadChannelScorer {
4944 short_channel_id: u64,
4948 impl Writeable for BadChannelScorer {
4949 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), ::io::Error> { unimplemented!() }
4951 impl Score for BadChannelScorer {
4952 fn channel_penalty_msat(&self, short_channel_id: u64, _send_amt: u64, _capacity_msat: u64, _source: &NodeId, _target: &NodeId) -> u64 {
4953 if short_channel_id == self.short_channel_id { u64::max_value() } else { 0 }
4956 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
4957 fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
4960 struct BadNodeScorer {
4965 impl Writeable for BadNodeScorer {
4966 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), ::io::Error> { unimplemented!() }
4969 impl Score for BadNodeScorer {
4970 fn channel_penalty_msat(&self, _short_channel_id: u64, _send_amt: u64, _capacity_msat: u64, _source: &NodeId, target: &NodeId) -> u64 {
4971 if *target == self.node_id { u64::max_value() } else { 0 }
4974 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
4975 fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
4979 fn avoids_routing_through_bad_channels_and_nodes() {
4980 let (secp_ctx, network, _, _, logger) = build_graph();
4981 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4982 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
4983 let network_graph = network.read_only();
4985 // A path to nodes[6] exists when no penalties are applied to any channel.
4986 let scorer = test_utils::TestScorer::with_penalty(0);
4987 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4988 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4989 let route = get_route(
4990 &our_id, &payment_params, &network_graph, None, 100, 42,
4991 Arc::clone(&logger), &scorer, &random_seed_bytes
4993 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4995 assert_eq!(route.get_total_fees(), 100);
4996 assert_eq!(route.get_total_amount(), 100);
4997 assert_eq!(path, vec![2, 4, 6, 11, 8]);
4999 // A different path to nodes[6] exists if channel 6 cannot be routed over.
5000 let scorer = BadChannelScorer { short_channel_id: 6 };
5001 let route = get_route(
5002 &our_id, &payment_params, &network_graph, None, 100, 42,
5003 Arc::clone(&logger), &scorer, &random_seed_bytes
5005 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5007 assert_eq!(route.get_total_fees(), 300);
5008 assert_eq!(route.get_total_amount(), 100);
5009 assert_eq!(path, vec![2, 4, 7, 10]);
5011 // A path to nodes[6] does not exist if nodes[2] cannot be routed through.
5012 let scorer = BadNodeScorer { node_id: NodeId::from_pubkey(&nodes[2]) };
5014 &our_id, &payment_params, &network_graph, None, 100, 42,
5015 Arc::clone(&logger), &scorer, &random_seed_bytes
5017 Err(LightningError { err, .. } ) => {
5018 assert_eq!(err, "Failed to find a path to the given destination");
5020 Ok(_) => panic!("Expected error"),
5025 fn total_fees_single_path() {
5029 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5030 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5031 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5034 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5035 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5036 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5039 pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
5040 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5041 short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0
5044 payment_params: None,
5047 assert_eq!(route.get_total_fees(), 250);
5048 assert_eq!(route.get_total_amount(), 225);
5052 fn total_fees_multi_path() {
5056 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5057 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5058 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5061 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5062 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5063 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5067 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5068 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5069 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5072 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5073 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5074 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5077 payment_params: None,
5080 assert_eq!(route.get_total_fees(), 200);
5081 assert_eq!(route.get_total_amount(), 300);
5085 fn total_empty_route_no_panic() {
5086 // In an earlier version of `Route::get_total_fees` and `Route::get_total_amount`, they
5087 // would both panic if the route was completely empty. We test to ensure they return 0
5088 // here, even though its somewhat nonsensical as a route.
5089 let route = Route { paths: Vec::new(), payment_params: None };
5091 assert_eq!(route.get_total_fees(), 0);
5092 assert_eq!(route.get_total_amount(), 0);
5096 fn limits_total_cltv_delta() {
5097 let (secp_ctx, network, _, _, logger) = build_graph();
5098 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5099 let network_graph = network.read_only();
5101 let scorer = test_utils::TestScorer::with_penalty(0);
5103 // Make sure that generally there is at least one route available
5104 let feasible_max_total_cltv_delta = 1008;
5105 let feasible_payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes))
5106 .with_max_total_cltv_expiry_delta(feasible_max_total_cltv_delta);
5107 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5108 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5109 let route = get_route(&our_id, &feasible_payment_params, &network_graph, None, 100, 0, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5110 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5111 assert_ne!(path.len(), 0);
5113 // But not if we exclude all paths on the basis of their accumulated CLTV delta
5114 let fail_max_total_cltv_delta = 23;
5115 let fail_payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes))
5116 .with_max_total_cltv_expiry_delta(fail_max_total_cltv_delta);
5117 match get_route(&our_id, &fail_payment_params, &network_graph, None, 100, 0, Arc::clone(&logger), &scorer, &random_seed_bytes)
5119 Err(LightningError { err, .. } ) => {
5120 assert_eq!(err, "Failed to find a path to the given destination");
5122 Ok(_) => panic!("Expected error"),
5127 fn adds_and_limits_cltv_offset() {
5128 let (secp_ctx, network_graph, _, _, logger) = build_graph();
5129 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5131 let scorer = test_utils::TestScorer::with_penalty(0);
5133 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
5134 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5135 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5136 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5137 assert_eq!(route.paths.len(), 1);
5139 let cltv_expiry_deltas_before = route.paths[0].iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5141 // Check whether the offset added to the last hop by default is in [1 .. DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA]
5142 let mut route_default = route.clone();
5143 add_random_cltv_offset(&mut route_default, &payment_params, &network_graph.read_only(), &random_seed_bytes);
5144 let cltv_expiry_deltas_default = route_default.paths[0].iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5145 assert_eq!(cltv_expiry_deltas_before.split_last().unwrap().1, cltv_expiry_deltas_default.split_last().unwrap().1);
5146 assert!(cltv_expiry_deltas_default.last() > cltv_expiry_deltas_before.last());
5147 assert!(cltv_expiry_deltas_default.last().unwrap() <= &DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA);
5149 // Check that no offset is added when we restrict the max_total_cltv_expiry_delta
5150 let mut route_limited = route.clone();
5151 let limited_max_total_cltv_expiry_delta = cltv_expiry_deltas_before.iter().sum();
5152 let limited_payment_params = payment_params.with_max_total_cltv_expiry_delta(limited_max_total_cltv_expiry_delta);
5153 add_random_cltv_offset(&mut route_limited, &limited_payment_params, &network_graph.read_only(), &random_seed_bytes);
5154 let cltv_expiry_deltas_limited = route_limited.paths[0].iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5155 assert_eq!(cltv_expiry_deltas_before, cltv_expiry_deltas_limited);
5159 fn adds_plausible_cltv_offset() {
5160 let (secp_ctx, network, _, _, logger) = build_graph();
5161 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5162 let network_graph = network.read_only();
5163 let network_nodes = network_graph.nodes();
5164 let network_channels = network_graph.channels();
5165 let scorer = test_utils::TestScorer::with_penalty(0);
5166 let payment_params = PaymentParameters::from_node_id(nodes[3]);
5167 let keys_manager = test_utils::TestKeysInterface::new(&[4u8; 32], Network::Testnet);
5168 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5170 let mut route = get_route(&our_id, &payment_params, &network_graph, None, 100, 0,
5171 Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5172 add_random_cltv_offset(&mut route, &payment_params, &network_graph, &random_seed_bytes);
5174 let mut path_plausibility = vec![];
5176 for p in route.paths {
5177 // 1. Select random observation point
5178 let mut prng = ChaCha20::new(&random_seed_bytes, &[0u8; 12]);
5179 let mut random_bytes = [0u8; ::core::mem::size_of::<usize>()];
5181 prng.process_in_place(&mut random_bytes);
5182 let random_path_index = usize::from_be_bytes(random_bytes).wrapping_rem(p.len());
5183 let observation_point = NodeId::from_pubkey(&p.get(random_path_index).unwrap().pubkey);
5185 // 2. Calculate what CLTV expiry delta we would observe there
5186 let observed_cltv_expiry_delta: u32 = p[random_path_index..].iter().map(|h| h.cltv_expiry_delta).sum();
5188 // 3. Starting from the observation point, find candidate paths
5189 let mut candidates: VecDeque<(NodeId, Vec<u32>)> = VecDeque::new();
5190 candidates.push_back((observation_point, vec![]));
5192 let mut found_plausible_candidate = false;
5194 'candidate_loop: while let Some((cur_node_id, cur_path_cltv_deltas)) = candidates.pop_front() {
5195 if let Some(remaining) = observed_cltv_expiry_delta.checked_sub(cur_path_cltv_deltas.iter().sum::<u32>()) {
5196 if remaining == 0 || remaining.wrapping_rem(40) == 0 || remaining.wrapping_rem(144) == 0 {
5197 found_plausible_candidate = true;
5198 break 'candidate_loop;
5202 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
5203 for channel_id in &cur_node.channels {
5204 if let Some(channel_info) = network_channels.get(&channel_id) {
5205 if let Some((dir_info, next_id)) = channel_info.as_directed_from(&cur_node_id) {
5206 if let Some(channel_update_info) = dir_info.direction() {
5207 let next_cltv_expiry_delta = channel_update_info.cltv_expiry_delta as u32;
5208 if cur_path_cltv_deltas.iter().sum::<u32>()
5209 .saturating_add(next_cltv_expiry_delta) <= observed_cltv_expiry_delta {
5210 let mut new_path_cltv_deltas = cur_path_cltv_deltas.clone();
5211 new_path_cltv_deltas.push(next_cltv_expiry_delta);
5212 candidates.push_back((*next_id, new_path_cltv_deltas));
5221 path_plausibility.push(found_plausible_candidate);
5223 assert!(path_plausibility.iter().all(|x| *x));
5226 #[cfg(not(feature = "no-std"))]
5227 pub(super) fn random_init_seed() -> u64 {
5228 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
5229 use core::hash::{BuildHasher, Hasher};
5230 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
5231 println!("Using seed of {}", seed);
5234 #[cfg(not(feature = "no-std"))]
5235 use util::ser::Readable;
5238 #[cfg(not(feature = "no-std"))]
5239 fn generate_routes() {
5240 use routing::scoring::{ProbabilisticScorer, ProbabilisticScoringParameters};
5242 let mut d = match super::test_utils::get_route_file() {
5249 let graph = NetworkGraph::read(&mut d).unwrap();
5250 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5251 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5253 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
5254 let mut seed = random_init_seed() as usize;
5255 let nodes = graph.read_only().nodes().clone();
5256 'load_endpoints: for _ in 0..10 {
5258 seed = seed.overflowing_mul(0xdeadbeef).0;
5259 let src = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5260 seed = seed.overflowing_mul(0xdeadbeef).0;
5261 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5262 let payment_params = PaymentParameters::from_node_id(dst);
5263 let amt = seed as u64 % 200_000_000;
5264 let params = ProbabilisticScoringParameters::default();
5265 let scorer = ProbabilisticScorer::new(params, &graph);
5266 if get_route(src, &payment_params, &graph.read_only(), None, amt, 42, &test_utils::TestLogger::new(), &scorer, &random_seed_bytes).is_ok() {
5267 continue 'load_endpoints;
5274 #[cfg(not(feature = "no-std"))]
5275 fn generate_routes_mpp() {
5276 use routing::scoring::{ProbabilisticScorer, ProbabilisticScoringParameters};
5278 let mut d = match super::test_utils::get_route_file() {
5285 let graph = NetworkGraph::read(&mut d).unwrap();
5286 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5287 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5289 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
5290 let mut seed = random_init_seed() as usize;
5291 let nodes = graph.read_only().nodes().clone();
5292 'load_endpoints: for _ in 0..10 {
5294 seed = seed.overflowing_mul(0xdeadbeef).0;
5295 let src = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5296 seed = seed.overflowing_mul(0xdeadbeef).0;
5297 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5298 let payment_params = PaymentParameters::from_node_id(dst).with_features(InvoiceFeatures::known());
5299 let amt = seed as u64 % 200_000_000;
5300 let params = ProbabilisticScoringParameters::default();
5301 let scorer = ProbabilisticScorer::new(params, &graph);
5302 if get_route(src, &payment_params, &graph.read_only(), None, amt, 42, &test_utils::TestLogger::new(), &scorer, &random_seed_bytes).is_ok() {
5303 continue 'load_endpoints;
5310 #[cfg(all(test, not(feature = "no-std")))]
5311 pub(crate) mod test_utils {
5313 /// Tries to open a network graph file, or panics with a URL to fetch it.
5314 pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
5315 let res = File::open("net_graph-2021-05-31.bin") // By default we're run in RL/lightning
5316 .or_else(|_| File::open("lightning/net_graph-2021-05-31.bin")) // We may be run manually in RL/
5317 .or_else(|_| { // Fall back to guessing based on the binary location
5318 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
5319 let mut path = std::env::current_exe().unwrap();
5320 path.pop(); // lightning-...
5322 path.pop(); // debug
5323 path.pop(); // target
5324 path.push("lightning");
5325 path.push("net_graph-2021-05-31.bin");
5326 eprintln!("{}", path.to_str().unwrap());
5329 .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");
5330 #[cfg(require_route_graph_test)]
5331 return Ok(res.unwrap());
5332 #[cfg(not(require_route_graph_test))]
5337 #[cfg(all(test, feature = "_bench_unstable", not(feature = "no-std")))]
5340 use bitcoin::hashes::Hash;
5341 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
5342 use chain::transaction::OutPoint;
5343 use chain::keysinterface::{KeysManager,KeysInterface};
5344 use ln::channelmanager::{ChannelCounterparty, ChannelDetails};
5345 use ln::features::{InitFeatures, InvoiceFeatures};
5346 use routing::scoring::{FixedPenaltyScorer, ProbabilisticScorer, ProbabilisticScoringParameters, Scorer};
5347 use util::logger::{Logger, Record};
5351 struct DummyLogger {}
5352 impl Logger for DummyLogger {
5353 fn log(&self, _record: &Record) {}
5356 fn read_network_graph() -> NetworkGraph {
5357 let mut d = test_utils::get_route_file().unwrap();
5358 NetworkGraph::read(&mut d).unwrap()
5361 fn payer_pubkey() -> PublicKey {
5362 let secp_ctx = Secp256k1::new();
5363 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
5367 fn first_hop(node_id: PublicKey) -> ChannelDetails {
5369 channel_id: [0; 32],
5370 counterparty: ChannelCounterparty {
5371 features: InitFeatures::known(),
5373 unspendable_punishment_reserve: 0,
5374 forwarding_info: None,
5376 funding_txo: Some(OutPoint {
5377 txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0
5379 short_channel_id: Some(1),
5380 inbound_scid_alias: None,
5381 channel_value_satoshis: 10_000_000,
5383 balance_msat: 10_000_000,
5384 outbound_capacity_msat: 10_000_000,
5385 inbound_capacity_msat: 0,
5386 unspendable_punishment_reserve: None,
5387 confirmations_required: None,
5388 force_close_spend_delay: None,
5390 is_funding_locked: true,
5397 fn generate_routes_with_zero_penalty_scorer(bench: &mut Bencher) {
5398 let network_graph = read_network_graph();
5399 let scorer = FixedPenaltyScorer::with_penalty(0);
5400 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::empty());
5404 fn generate_mpp_routes_with_zero_penalty_scorer(bench: &mut Bencher) {
5405 let network_graph = read_network_graph();
5406 let scorer = FixedPenaltyScorer::with_penalty(0);
5407 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::known());
5411 fn generate_routes_with_default_scorer(bench: &mut Bencher) {
5412 let network_graph = read_network_graph();
5413 let scorer = Scorer::default();
5414 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::empty());
5418 fn generate_mpp_routes_with_default_scorer(bench: &mut Bencher) {
5419 let network_graph = read_network_graph();
5420 let scorer = Scorer::default();
5421 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::known());
5425 fn generate_routes_with_probabilistic_scorer(bench: &mut Bencher) {
5426 let network_graph = read_network_graph();
5427 let params = ProbabilisticScoringParameters::default();
5428 let scorer = ProbabilisticScorer::new(params, &network_graph);
5429 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::empty());
5433 fn generate_mpp_routes_with_probabilistic_scorer(bench: &mut Bencher) {
5434 let network_graph = read_network_graph();
5435 let params = ProbabilisticScoringParameters::default();
5436 let scorer = ProbabilisticScorer::new(params, &network_graph);
5437 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::known());
5440 fn generate_routes<S: Score>(
5441 bench: &mut Bencher, graph: &NetworkGraph, mut scorer: S, features: InvoiceFeatures
5443 let nodes = graph.read_only().nodes().clone();
5444 let payer = payer_pubkey();
5445 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
5446 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5448 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
5449 let mut routes = Vec::new();
5450 let mut route_endpoints = Vec::new();
5451 let mut seed: usize = 0xdeadbeef;
5452 'load_endpoints: for _ in 0..150 {
5455 let src = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5457 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5458 let params = PaymentParameters::from_node_id(dst).with_features(features.clone());
5459 let first_hop = first_hop(src);
5460 let amt = seed as u64 % 1_000_000;
5461 if let Ok(route) = get_route(&payer, ¶ms, &graph.read_only(), Some(&[&first_hop]), amt, 42, &DummyLogger{}, &scorer, &random_seed_bytes) {
5463 route_endpoints.push((first_hop, params, amt));
5464 continue 'load_endpoints;
5469 // ...and seed the scorer with success and failure data...
5470 for route in routes {
5471 let amount = route.get_total_amount();
5472 if amount < 250_000 {
5473 for path in route.paths {
5474 scorer.payment_path_successful(&path.iter().collect::<Vec<_>>());
5476 } else if amount > 750_000 {
5477 for path in route.paths {
5478 let short_channel_id = path[path.len() / 2].short_channel_id;
5479 scorer.payment_path_failed(&path.iter().collect::<Vec<_>>(), short_channel_id);
5484 // Because we've changed channel scores, its possible we'll take different routes to the
5485 // selected destinations, possibly causing us to fail because, eg, the newly-selected path
5486 // requires a too-high CLTV delta.
5487 route_endpoints.retain(|(first_hop, params, amt)| {
5488 get_route(&payer, params, &graph.read_only(), Some(&[first_hop]), *amt, 42, &DummyLogger{}, &scorer, &random_seed_bytes).is_ok()
5490 route_endpoints.truncate(100);
5491 assert_eq!(route_endpoints.len(), 100);
5493 // ...then benchmark finding paths between the nodes we learned.
5496 let (first_hop, params, amt) = &route_endpoints[idx % route_endpoints.len()];
5497 assert!(get_route(&payer, params, &graph.read_only(), Some(&[first_hop]), *amt, 42, &DummyLogger{}, &scorer, &random_seed_bytes).is_ok());