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::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::{ChannelUsage, 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. Each entry represents a list of hops, NOT
69 /// INCLUDING our own, where the last hop is the destination. Thus, this must always be at
70 /// least length one. While the maximum length of any given path is variable, keeping the length
71 /// of any path less or equal to 19 should currently ensure it is viable.
72 pub paths: Vec<Vec<RouteHop>>,
73 /// The `payment_params` parameter passed to [`find_route`].
74 /// This is used by `ChannelManager` to track information which may be required for retries,
75 /// provided back to you via [`Event::PaymentPathFailed`].
77 /// [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed
78 pub payment_params: Option<PaymentParameters>,
81 pub(crate) trait RoutePath {
82 /// Gets the fees for a given path, excluding any excess paid to the recipient.
83 fn get_path_fees(&self) -> u64;
85 impl RoutePath for Vec<RouteHop> {
86 fn get_path_fees(&self) -> u64 {
87 // Do not count last hop of each path since that's the full value of the payment
88 self.split_last().map(|(_, path_prefix)| path_prefix).unwrap_or(&[])
89 .iter().map(|hop| &hop.fee_msat)
95 /// Returns the total amount of fees paid on this [`Route`].
97 /// This doesn't include any extra payment made to the recipient, which can happen in excess of
98 /// the amount passed to [`find_route`]'s `params.final_value_msat`.
99 pub fn get_total_fees(&self) -> u64 {
100 self.paths.iter().map(|path| path.get_path_fees()).sum()
103 /// Returns the total amount paid on this [`Route`], excluding the fees.
104 pub fn get_total_amount(&self) -> u64 {
105 return self.paths.iter()
106 .map(|path| path.split_last().map(|(hop, _)| hop.fee_msat).unwrap_or(0))
111 const SERIALIZATION_VERSION: u8 = 1;
112 const MIN_SERIALIZATION_VERSION: u8 = 1;
114 impl Writeable for Route {
115 fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
116 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
117 (self.paths.len() as u64).write(writer)?;
118 for hops in self.paths.iter() {
119 (hops.len() as u8).write(writer)?;
120 for hop in hops.iter() {
124 write_tlv_fields!(writer, {
125 (1, self.payment_params, option),
131 impl Readable for Route {
132 fn read<R: io::Read>(reader: &mut R) -> Result<Route, DecodeError> {
133 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
134 let path_count: u64 = Readable::read(reader)?;
135 let mut paths = Vec::with_capacity(cmp::min(path_count, 128) as usize);
136 for _ in 0..path_count {
137 let hop_count: u8 = Readable::read(reader)?;
138 let mut hops = Vec::with_capacity(hop_count as usize);
139 for _ in 0..hop_count {
140 hops.push(Readable::read(reader)?);
144 let mut payment_params = None;
145 read_tlv_fields!(reader, {
146 (1, payment_params, option),
148 Ok(Route { paths, payment_params })
152 /// Parameters needed to find a [`Route`].
154 /// Passed to [`find_route`] and also provided in [`Event::PaymentPathFailed`] for retrying a failed
157 /// [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed
158 #[derive(Clone, Debug)]
159 pub struct RouteParameters {
160 /// The parameters of the failed payment path.
161 pub payment_params: PaymentParameters,
163 /// The amount in msats sent on the failed payment path.
164 pub final_value_msat: u64,
166 /// The CLTV on the final hop of the failed payment path.
167 pub final_cltv_expiry_delta: u32,
170 impl_writeable_tlv_based!(RouteParameters, {
171 (0, payment_params, required),
172 (2, final_value_msat, required),
173 (4, final_cltv_expiry_delta, required),
176 /// Maximum total CTLV difference we allow for a full payment path.
177 pub const DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA: u32 = 1008;
179 // The median hop CLTV expiry delta currently seen in the network.
180 const MEDIAN_HOP_CLTV_EXPIRY_DELTA: u32 = 40;
182 // During routing, we only consider paths shorter than our maximum length estimate.
183 // In the legacy onion format, the maximum number of hops used to be a fixed value of 20.
184 // However, in the TLV onion format, there is no fixed maximum length, but the `hop_payloads`
185 // field is always 1300 bytes. As the `tlv_payload` for each hop may vary in length, we have to
186 // estimate how many hops the route may have so that it actually fits the `hop_payloads` field.
188 // We estimate 3+32 (payload length and HMAC) + 2+8 (amt_to_forward) + 2+4 (outgoing_cltv_value) +
189 // 2+8 (short_channel_id) = 61 bytes for each intermediate hop and 3+32
190 // (payload length and HMAC) + 2+8 (amt_to_forward) + 2+4 (outgoing_cltv_value) + 2+32+8
191 // (payment_secret and total_msat) = 93 bytes for the final hop.
192 // Since the length of the potentially included `payment_metadata` is unknown to us, we round
193 // down from (1300-93) / 61 = 19.78... to arrive at a conservative estimate of 19.
194 const MAX_PATH_LENGTH_ESTIMATE: u8 = 19;
196 /// The recipient of a payment.
197 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
198 pub struct PaymentParameters {
199 /// The node id of the payee.
200 pub payee_pubkey: PublicKey,
202 /// Features supported by the payee.
204 /// May be set from the payee's invoice or via [`for_keysend`]. May be `None` if the invoice
205 /// does not contain any features.
207 /// [`for_keysend`]: Self::for_keysend
208 pub features: Option<InvoiceFeatures>,
210 /// Hints for routing to the payee, containing channels connecting the payee to public nodes.
211 pub route_hints: Vec<RouteHint>,
213 /// Expiration of a payment to the payee, in seconds relative to the UNIX epoch.
214 pub expiry_time: Option<u64>,
216 /// The maximum total CLTV delta we accept for the route.
217 pub max_total_cltv_expiry_delta: u32,
220 impl_writeable_tlv_based!(PaymentParameters, {
221 (0, payee_pubkey, required),
222 (1, max_total_cltv_expiry_delta, (default_value, DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA)),
223 (2, features, option),
224 (4, route_hints, vec_type),
225 (6, expiry_time, option),
228 impl PaymentParameters {
229 /// Creates a payee with the node id of the given `pubkey`.
230 pub fn from_node_id(payee_pubkey: PublicKey) -> Self {
236 max_total_cltv_expiry_delta: DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA,
240 /// Creates a payee with the node id of the given `pubkey` to use for keysend payments.
241 pub fn for_keysend(payee_pubkey: PublicKey) -> Self {
242 Self::from_node_id(payee_pubkey).with_features(InvoiceFeatures::for_keysend())
245 /// Includes the payee's features.
247 /// (C-not exported) since bindings don't support move semantics
248 pub fn with_features(self, features: InvoiceFeatures) -> Self {
249 Self { features: Some(features), ..self }
252 /// Includes hints for routing to the payee.
254 /// (C-not exported) since bindings don't support move semantics
255 pub fn with_route_hints(self, route_hints: Vec<RouteHint>) -> Self {
256 Self { route_hints, ..self }
259 /// Includes a payment expiration in seconds relative to the UNIX epoch.
261 /// (C-not exported) since bindings don't support move semantics
262 pub fn with_expiry_time(self, expiry_time: u64) -> Self {
263 Self { expiry_time: Some(expiry_time), ..self }
266 /// Includes a limit for the total CLTV expiry delta which is considered during routing
268 /// (C-not exported) since bindings don't support move semantics
269 pub fn with_max_total_cltv_expiry_delta(self, max_total_cltv_expiry_delta: u32) -> Self {
270 Self { max_total_cltv_expiry_delta, ..self }
274 /// A list of hops along a payment path terminating with a channel to the recipient.
275 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
276 pub struct RouteHint(pub Vec<RouteHintHop>);
278 impl Writeable for RouteHint {
279 fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
280 (self.0.len() as u64).write(writer)?;
281 for hop in self.0.iter() {
288 impl Readable for RouteHint {
289 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
290 let hop_count: u64 = Readable::read(reader)?;
291 let mut hops = Vec::with_capacity(cmp::min(hop_count, 16) as usize);
292 for _ in 0..hop_count {
293 hops.push(Readable::read(reader)?);
299 /// A channel descriptor for a hop along a payment path.
300 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
301 pub struct RouteHintHop {
302 /// The node_id of the non-target end of the route
303 pub src_node_id: PublicKey,
304 /// The short_channel_id of this channel
305 pub short_channel_id: u64,
306 /// The fees which must be paid to use this channel
307 pub fees: RoutingFees,
308 /// The difference in CLTV values between this node and the next node.
309 pub cltv_expiry_delta: u16,
310 /// The minimum value, in msat, which must be relayed to the next hop.
311 pub htlc_minimum_msat: Option<u64>,
312 /// The maximum value in msat available for routing with a single HTLC.
313 pub htlc_maximum_msat: Option<u64>,
316 impl_writeable_tlv_based!(RouteHintHop, {
317 (0, src_node_id, required),
318 (1, htlc_minimum_msat, option),
319 (2, short_channel_id, required),
320 (3, htlc_maximum_msat, option),
322 (6, cltv_expiry_delta, required),
325 #[derive(Eq, PartialEq)]
326 struct RouteGraphNode {
328 lowest_fee_to_peer_through_node: u64,
329 lowest_fee_to_node: u64,
330 total_cltv_delta: u32,
331 // The maximum value a yet-to-be-constructed payment path might flow through this node.
332 // This value is upper-bounded by us by:
333 // - how much is needed for a path being constructed
334 // - how much value can channels following this node (up to the destination) can contribute,
335 // considering their capacity and fees
336 value_contribution_msat: u64,
337 /// The effective htlc_minimum_msat at this hop. If a later hop on the path had a higher HTLC
338 /// minimum, we use it, plus the fees required at each earlier hop to meet it.
339 path_htlc_minimum_msat: u64,
340 /// All penalties incurred from this hop on the way to the destination, as calculated using
342 path_penalty_msat: u64,
343 /// The number of hops walked up to this node.
344 path_length_to_node: u8,
347 impl cmp::Ord for RouteGraphNode {
348 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
349 let other_score = cmp::max(other.lowest_fee_to_peer_through_node, other.path_htlc_minimum_msat)
350 .saturating_add(other.path_penalty_msat);
351 let self_score = cmp::max(self.lowest_fee_to_peer_through_node, self.path_htlc_minimum_msat)
352 .saturating_add(self.path_penalty_msat);
353 other_score.cmp(&self_score).then_with(|| other.node_id.cmp(&self.node_id))
357 impl cmp::PartialOrd for RouteGraphNode {
358 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
359 Some(self.cmp(other))
363 /// A wrapper around the various hop representations.
365 /// Used to construct a [`PathBuildingHop`] and to estimate [`EffectiveCapacity`].
366 #[derive(Clone, Debug)]
367 enum CandidateRouteHop<'a> {
368 /// A hop from the payer, where the outbound liquidity is known.
370 details: &'a ChannelDetails,
372 /// A hop found in the [`NetworkGraph`], where the channel capacity may or may not be known.
374 info: DirectedChannelInfoWithUpdate<'a>,
375 short_channel_id: u64,
377 /// A hop to the payee found in the payment invoice, though not necessarily a direct channel.
379 hint: &'a RouteHintHop,
383 impl<'a> CandidateRouteHop<'a> {
384 fn short_channel_id(&self) -> u64 {
386 CandidateRouteHop::FirstHop { details } => details.short_channel_id.unwrap(),
387 CandidateRouteHop::PublicHop { short_channel_id, .. } => *short_channel_id,
388 CandidateRouteHop::PrivateHop { hint } => hint.short_channel_id,
392 // NOTE: This may alloc memory so avoid calling it in a hot code path.
393 fn features(&self) -> ChannelFeatures {
395 CandidateRouteHop::FirstHop { details } => details.counterparty.features.to_context(),
396 CandidateRouteHop::PublicHop { info, .. } => info.channel().features.clone(),
397 CandidateRouteHop::PrivateHop { .. } => ChannelFeatures::empty(),
401 fn cltv_expiry_delta(&self) -> u32 {
403 CandidateRouteHop::FirstHop { .. } => 0,
404 CandidateRouteHop::PublicHop { info, .. } => info.direction().cltv_expiry_delta as u32,
405 CandidateRouteHop::PrivateHop { hint } => hint.cltv_expiry_delta as u32,
409 fn htlc_minimum_msat(&self) -> u64 {
411 CandidateRouteHop::FirstHop { .. } => 0,
412 CandidateRouteHop::PublicHop { info, .. } => info.direction().htlc_minimum_msat,
413 CandidateRouteHop::PrivateHop { hint } => hint.htlc_minimum_msat.unwrap_or(0),
417 fn htlc_maximum_msat(&self) -> u64 {
419 CandidateRouteHop::FirstHop { details } => details.next_outbound_htlc_limit_msat,
420 CandidateRouteHop::PublicHop { info, .. } => info.htlc_maximum_msat(),
421 CandidateRouteHop::PrivateHop { hint } => {
422 hint.htlc_maximum_msat.unwrap_or(u64::max_value())
427 fn fees(&self) -> RoutingFees {
429 CandidateRouteHop::FirstHop { .. } => RoutingFees {
430 base_msat: 0, proportional_millionths: 0,
432 CandidateRouteHop::PublicHop { info, .. } => info.direction().fees,
433 CandidateRouteHop::PrivateHop { hint } => hint.fees,
437 fn effective_capacity(&self) -> EffectiveCapacity {
439 CandidateRouteHop::FirstHop { details } => EffectiveCapacity::ExactLiquidity {
440 liquidity_msat: details.next_outbound_htlc_limit_msat,
442 CandidateRouteHop::PublicHop { info, .. } => info.effective_capacity(),
443 CandidateRouteHop::PrivateHop { .. } => EffectiveCapacity::Infinite,
448 /// It's useful to keep track of the hops associated with the fees required to use them,
449 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
450 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
451 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
453 struct PathBuildingHop<'a> {
454 // Note that this should be dropped in favor of loading it from CandidateRouteHop, but doing so
455 // is a larger refactor and will require careful performance analysis.
457 candidate: CandidateRouteHop<'a>,
460 /// Minimal fees required to route to the source node of the current hop via any of its inbound channels.
461 src_lowest_inbound_fees: RoutingFees,
462 /// All the fees paid *after* this channel on the way to the destination
463 next_hops_fee_msat: u64,
464 /// Fee paid for the use of the current channel (see candidate.fees()).
465 /// The value will be actually deducted from the counterparty balance on the previous link.
466 hop_use_fee_msat: u64,
467 /// Used to compare channels when choosing the for routing.
468 /// Includes paying for the use of a hop and the following hops, as well as
469 /// an estimated cost of reaching this hop.
470 /// Might get stale when fees are recomputed. Primarily for internal use.
472 /// A mirror of the same field in RouteGraphNode. Note that this is only used during the graph
473 /// walk and may be invalid thereafter.
474 path_htlc_minimum_msat: u64,
475 /// All penalties incurred from this channel on the way to the destination, as calculated using
477 path_penalty_msat: u64,
478 /// If we've already processed a node as the best node, we shouldn't process it again. Normally
479 /// we'd just ignore it if we did as all channels would have a higher new fee, but because we
480 /// may decrease the amounts in use as we walk the graph, the actual calculated fee may
481 /// decrease as well. Thus, we have to explicitly track which nodes have been processed and
482 /// avoid processing them again.
484 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
485 // In tests, we apply further sanity checks on cases where we skip nodes we already processed
486 // to ensure it is specifically in cases where the fee has gone down because of a decrease in
487 // value_contribution_msat, which requires tracking it here. See comments below where it is
488 // used for more info.
489 value_contribution_msat: u64,
492 impl<'a> core::fmt::Debug for PathBuildingHop<'a> {
493 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
494 let mut debug_struct = f.debug_struct("PathBuildingHop");
496 .field("node_id", &self.node_id)
497 .field("short_channel_id", &self.candidate.short_channel_id())
498 .field("total_fee_msat", &self.total_fee_msat)
499 .field("next_hops_fee_msat", &self.next_hops_fee_msat)
500 .field("hop_use_fee_msat", &self.hop_use_fee_msat)
501 .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)))
502 .field("path_penalty_msat", &self.path_penalty_msat)
503 .field("path_htlc_minimum_msat", &self.path_htlc_minimum_msat)
504 .field("cltv_expiry_delta", &self.candidate.cltv_expiry_delta());
505 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
506 let debug_struct = debug_struct
507 .field("value_contribution_msat", &self.value_contribution_msat);
508 debug_struct.finish()
512 // Instantiated with a list of hops with correct data in them collected during path finding,
513 // an instance of this struct should be further modified only via given methods.
515 struct PaymentPath<'a> {
516 hops: Vec<(PathBuildingHop<'a>, NodeFeatures)>,
519 impl<'a> PaymentPath<'a> {
520 // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
521 fn get_value_msat(&self) -> u64 {
522 self.hops.last().unwrap().0.fee_msat
525 fn get_path_penalty_msat(&self) -> u64 {
526 self.hops.first().map(|h| h.0.path_penalty_msat).unwrap_or(u64::max_value())
529 fn get_total_fee_paid_msat(&self) -> u64 {
530 if self.hops.len() < 1 {
534 // Can't use next_hops_fee_msat because it gets outdated.
535 for (i, (hop, _)) in self.hops.iter().enumerate() {
536 if i != self.hops.len() - 1 {
537 result += hop.fee_msat;
543 fn get_cost_msat(&self) -> u64 {
544 self.get_total_fee_paid_msat().saturating_add(self.get_path_penalty_msat())
547 // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
548 // to change fees may result in an inconsistency.
550 // Sometimes we call this function right after constructing a path which is inconsistent in
551 // that it the value being transferred has decreased while we were doing path finding, leading
552 // to the fees being paid not lining up with the actual limits.
554 // Note that this function is not aware of the available_liquidity limit, and thus does not
555 // support increasing the value being transferred.
556 fn update_value_and_recompute_fees(&mut self, value_msat: u64) {
557 assert!(value_msat <= self.hops.last().unwrap().0.fee_msat);
559 let mut total_fee_paid_msat = 0 as u64;
560 for i in (0..self.hops.len()).rev() {
561 let last_hop = i == self.hops.len() - 1;
563 // For non-last-hop, this value will represent the fees paid on the current hop. It
564 // will consist of the fees for the use of the next hop, and extra fees to match
565 // htlc_minimum_msat of the current channel. Last hop is handled separately.
566 let mut cur_hop_fees_msat = 0;
568 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().0.hop_use_fee_msat;
571 let mut cur_hop = &mut self.hops.get_mut(i).unwrap().0;
572 cur_hop.next_hops_fee_msat = total_fee_paid_msat;
573 // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
574 // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
575 // set it too high just to maliciously take more fees by exploiting this
576 // match htlc_minimum_msat logic.
577 let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
578 if let Some(extra_fees_msat) = cur_hop.candidate.htlc_minimum_msat().checked_sub(cur_hop_transferred_amount_msat) {
579 // Note that there is a risk that *previous hops* (those closer to us, as we go
580 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
582 // This might make us end up with a broken route, although this should be super-rare
583 // in practice, both because of how healthy channels look like, and how we pick
584 // channels in add_entry.
585 // Also, this can't be exploited more heavily than *announce a free path and fail
587 cur_hop_transferred_amount_msat += extra_fees_msat;
588 total_fee_paid_msat += extra_fees_msat;
589 cur_hop_fees_msat += extra_fees_msat;
593 // Final hop is a special case: it usually has just value_msat (by design), but also
594 // it still could overpay for the htlc_minimum_msat.
595 cur_hop.fee_msat = cur_hop_transferred_amount_msat;
597 // Propagate updated fees for the use of the channels to one hop back, where they
598 // will be actually paid (fee_msat). The last hop is handled above separately.
599 cur_hop.fee_msat = cur_hop_fees_msat;
602 // Fee for the use of the current hop which will be deducted on the previous hop.
603 // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
604 // this channel is free for us.
606 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.candidate.fees()) {
607 cur_hop.hop_use_fee_msat = new_fee;
608 total_fee_paid_msat += new_fee;
610 // It should not be possible because this function is called only to reduce the
611 // value. In that case, compute_fee was already called with the same fees for
612 // larger amount and there was no overflow.
620 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
621 let proportional_fee_millions =
622 amount_msat.checked_mul(channel_fees.proportional_millionths as u64);
623 if let Some(new_fee) = proportional_fee_millions.and_then(|part| {
624 (channel_fees.base_msat as u64).checked_add(part / 1_000_000) }) {
628 // This function may be (indirectly) called without any verification,
629 // with channel_fees provided by a caller. We should handle it gracefully.
634 /// The default `features` we assume for a node in a route, when no `features` are known about that
637 /// Default features are:
638 /// * variable_length_onion_optional
639 fn default_node_features() -> NodeFeatures {
640 let mut features = NodeFeatures::empty();
641 features.set_variable_length_onion_optional();
645 /// Finds a route from us (payer) to the given target node (payee).
647 /// If the payee provided features in their invoice, they should be provided via `params.payee`.
648 /// Without this, MPP will only be used if the payee's features are available in the network graph.
650 /// Private routing paths between a public node and the target may be included in `params.payee`.
652 /// If some channels aren't announced, it may be useful to fill in `first_hops` with the results
653 /// from [`ChannelManager::list_usable_channels`]. If it is filled in, the view of our local
654 /// channels from [`NetworkGraph`] will be ignored, and only those in `first_hops` will be used.
656 /// The fees on channels from us to the next hop are ignored as they are assumed to all be equal.
657 /// However, the enabled/disabled bit on such channels as well as the `htlc_minimum_msat` /
658 /// `htlc_maximum_msat` *are* checked as they may change based on the receiving node.
662 /// May be used to re-compute a [`Route`] when handling a [`Event::PaymentPathFailed`]. Any
663 /// adjustments to the [`NetworkGraph`] and channel scores should be made prior to calling this
668 /// Panics if first_hops contains channels without short_channel_ids;
669 /// [`ChannelManager::list_usable_channels`] will never include such channels.
671 /// [`ChannelManager::list_usable_channels`]: crate::ln::channelmanager::ChannelManager::list_usable_channels
672 /// [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed
673 pub fn find_route<L: Deref, S: Score>(
674 our_node_pubkey: &PublicKey, route_params: &RouteParameters, network: &NetworkGraph,
675 first_hops: Option<&[&ChannelDetails]>, logger: L, scorer: &S, random_seed_bytes: &[u8; 32]
676 ) -> Result<Route, LightningError>
677 where L::Target: Logger {
678 let network_graph = network.read_only();
680 our_node_pubkey, &route_params.payment_params, &network_graph, first_hops, route_params.final_value_msat,
681 route_params.final_cltv_expiry_delta, logger, scorer, random_seed_bytes
684 add_random_cltv_offset(&mut route, &route_params.payment_params, &network_graph, random_seed_bytes);
687 Err(err) => Err(err),
691 pub(crate) fn get_route<L: Deref, S: Score>(
692 our_node_pubkey: &PublicKey, payment_params: &PaymentParameters, network_graph: &ReadOnlyNetworkGraph,
693 first_hops: Option<&[&ChannelDetails]>, final_value_msat: u64, final_cltv_expiry_delta: u32,
694 logger: L, scorer: &S, random_seed_bytes: &[u8; 32]
695 ) -> Result<Route, LightningError>
696 where L::Target: Logger {
697 let payee_node_id = NodeId::from_pubkey(&payment_params.payee_pubkey);
698 let our_node_id = NodeId::from_pubkey(&our_node_pubkey);
700 if payee_node_id == our_node_id {
701 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
704 if final_value_msat > MAX_VALUE_MSAT {
705 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
708 if final_value_msat == 0 {
709 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
712 for route in payment_params.route_hints.iter() {
713 for hop in &route.0 {
714 if hop.src_node_id == payment_params.payee_pubkey {
715 return Err(LightningError{err: "Route hint cannot have the payee as the source.".to_owned(), action: ErrorAction::IgnoreError});
719 if payment_params.max_total_cltv_expiry_delta <= final_cltv_expiry_delta {
720 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});
723 // The general routing idea is the following:
724 // 1. Fill first/last hops communicated by the caller.
725 // 2. Attempt to construct a path from payer to payee for transferring
726 // any ~sufficient (described later) value.
727 // If succeed, remember which channels were used and how much liquidity they have available,
728 // so that future paths don't rely on the same liquidity.
729 // 3. Proceed to the next step if:
730 // - we hit the recommended target value;
731 // - OR if we could not construct a new path. Any next attempt will fail too.
732 // Otherwise, repeat step 2.
733 // 4. See if we managed to collect paths which aggregately are able to transfer target value
734 // (not recommended value).
735 // 5. If yes, proceed. If not, fail routing.
736 // 6. Randomly combine paths into routes having enough to fulfill the payment. (TODO: knapsack)
737 // 7. Of all the found paths, select only those with the lowest total fee.
738 // 8. The last path in every selected route is likely to be more than we need.
739 // Reduce its value-to-transfer and recompute fees.
740 // 9. Choose the best route by the lowest total fee.
742 // As for the actual search algorithm,
743 // we do a payee-to-payer pseudo-Dijkstra's sorting by each node's distance from the payee
744 // plus the minimum per-HTLC fee to get from it to another node (aka "shitty pseudo-A*").
746 // We are not a faithful Dijkstra's implementation because we can change values which impact
747 // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
748 // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) than
749 // the value we are currently attempting to send over a path, we simply reduce the value being
750 // sent along the path for any hops after that channel. This may imply that later fees (which
751 // we've already tabulated) are lower because a smaller value is passing through the channels
752 // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
753 // channels which were selected earlier (and which may still be used for other paths without a
754 // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
757 // One potentially problematic case for this algorithm would be if there are many
758 // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
759 // graph walking), we may never find a path which is not liquidity-limited and has lower
760 // proportional fee (and only lower absolute fee when considering the ultimate value sent).
761 // Because we only consider paths with at least 5% of the total value being sent, the damage
762 // from such a case should be limited, however this could be further reduced in the future by
763 // calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
764 // limits for the purposes of fee calculation.
766 // Alternatively, we could store more detailed path information in the heap (targets, below)
767 // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
768 // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
769 // and practically (as we would need to store dynamically-allocated path information in heap
770 // objects, increasing malloc traffic and indirect memory access significantly). Further, the
771 // results of such an algorithm would likely be biased towards lower-value paths.
773 // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
774 // outside of our current search value, running a path search more times to gather candidate
775 // paths at different values. While this may be acceptable, further path searches may increase
776 // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
777 // graph for candidate paths, calculating the maximum value which can realistically be sent at
778 // the same time, remaining generic across different payment values.
780 // TODO: There are a few tweaks we could do, including possibly pre-calculating more stuff
781 // to use as the A* heuristic beyond just the cost to get one node further than the current
784 let network_channels = network_graph.channels();
785 let network_nodes = network_graph.nodes();
787 // Allow MPP only if we have a features set from somewhere that indicates the payee supports
788 // it. If the payee supports it they're supposed to include it in the invoice, so that should
790 let allow_mpp = if let Some(features) = &payment_params.features {
791 features.supports_basic_mpp()
792 } else if let Some(node) = network_nodes.get(&payee_node_id) {
793 if let Some(node_info) = node.announcement_info.as_ref() {
794 node_info.features.supports_basic_mpp()
797 log_trace!(logger, "Searching for a route from payer {} to payee {} {} MPP and {} first hops {}overriding the network graph", our_node_pubkey,
798 payment_params.payee_pubkey, if allow_mpp { "with" } else { "without" },
799 first_hops.map(|hops| hops.len()).unwrap_or(0), if first_hops.is_some() { "" } else { "not " });
802 // Prepare the data we'll use for payee-to-payer search by
803 // inserting first hops suggested by the caller as targets.
804 // Our search will then attempt to reach them while traversing from the payee node.
805 let mut first_hop_targets: HashMap<_, Vec<&ChannelDetails>> =
806 HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
807 if let Some(hops) = first_hops {
809 if chan.short_channel_id.is_none() {
810 panic!("first_hops should be filled in with usable channels, not pending ones");
812 if chan.counterparty.node_id == *our_node_pubkey {
813 return Err(LightningError{err: "First hop cannot have our_node_pubkey as a destination.".to_owned(), action: ErrorAction::IgnoreError});
816 .entry(NodeId::from_pubkey(&chan.counterparty.node_id))
817 .or_insert(Vec::new())
820 if first_hop_targets.is_empty() {
821 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
825 // The main heap containing all candidate next-hops sorted by their score (max(A* fee,
826 // htlc_minimum)). Ideally this would be a heap which allowed cheap score reduction instead of
827 // adding duplicate entries when we find a better path to a given node.
828 let mut targets: BinaryHeap<RouteGraphNode> = BinaryHeap::new();
830 // Map from node_id to information about the best current path to that node, including feerate
832 let mut dist: HashMap<NodeId, PathBuildingHop> = HashMap::with_capacity(network_nodes.len());
834 // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
835 // indicating that we may wish to try again with a higher value, potentially paying to meet an
836 // htlc_minimum with extra fees while still finding a cheaper path.
837 let mut hit_minimum_limit;
839 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
840 // We start with a path_value of the exact amount we want, and if that generates a route we may
841 // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
842 // amount we want in total across paths, selecting the best subset at the end.
843 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
844 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
845 let mut path_value_msat = final_value_msat;
847 // Keep track of how much liquidity has been used in selected channels. Used to determine
848 // if the channel can be used by additional MPP paths or to inform path finding decisions. It is
849 // aware of direction *only* to ensure that the correct htlc_maximum_msat value is used. Hence,
850 // liquidity used in one direction will not offset any used in the opposite direction.
851 let mut used_channel_liquidities: HashMap<(u64, bool), u64> =
852 HashMap::with_capacity(network_nodes.len());
854 // Keeping track of how much value we already collected across other paths. Helps to decide:
855 // - how much a new path should be transferring (upper bound);
856 // - whether a channel should be disregarded because
857 // it's available liquidity is too small comparing to how much more we need to collect;
858 // - when we want to stop looking for new paths.
859 let mut already_collected_value_msat = 0;
861 for (_, channels) in first_hop_targets.iter_mut() {
862 // Sort the first_hops channels to the same node(s) in priority order of which channel we'd
865 // First, if channels are below `recommended_value_msat`, sort them in descending order,
866 // preferring larger channels to avoid splitting the payment into more MPP parts than is
869 // Second, because simply always sorting in descending order would always use our largest
870 // available outbound capacity, needlessly fragmenting our available channel capacities,
871 // sort channels above `recommended_value_msat` in ascending order, preferring channels
872 // which have enough, but not too much, capacity for the payment.
873 channels.sort_unstable_by(|chan_a, chan_b| {
874 if chan_b.next_outbound_htlc_limit_msat < recommended_value_msat || chan_a.next_outbound_htlc_limit_msat < recommended_value_msat {
875 // Sort in descending order
876 chan_b.next_outbound_htlc_limit_msat.cmp(&chan_a.next_outbound_htlc_limit_msat)
878 // Sort in ascending order
879 chan_a.next_outbound_htlc_limit_msat.cmp(&chan_b.next_outbound_htlc_limit_msat)
884 log_trace!(logger, "Building path from {} (payee) to {} (us/payer) for value {} msat.", payment_params.payee_pubkey, our_node_pubkey, final_value_msat);
886 macro_rules! add_entry {
887 // Adds entry which goes from $src_node_id to $dest_node_id over the $candidate hop.
888 // $next_hops_fee_msat represents the fees paid for using all the channels *after* this one,
889 // since that value has to be transferred over this channel.
890 // Returns whether this channel caused an update to `targets`.
891 ( $candidate: expr, $src_node_id: expr, $dest_node_id: expr, $next_hops_fee_msat: expr,
892 $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr,
893 $next_hops_path_penalty_msat: expr, $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => { {
894 // We "return" whether we updated the path at the end, via this:
895 let mut did_add_update_path_to_src_node = false;
896 // Channels to self should not be used. This is more of belt-and-suspenders, because in
897 // practice these cases should be caught earlier:
898 // - for regular channels at channel announcement (TODO)
899 // - for first and last hops early in get_route
900 if $src_node_id != $dest_node_id {
901 let short_channel_id = $candidate.short_channel_id();
902 let htlc_maximum_msat = $candidate.htlc_maximum_msat();
904 // It is tricky to subtract $next_hops_fee_msat from available liquidity here.
905 // It may be misleading because we might later choose to reduce the value transferred
906 // over these channels, and the channel which was insufficient might become sufficient.
907 // Worst case: we drop a good channel here because it can't cover the high following
908 // fees caused by one expensive channel, but then this channel could have been used
909 // if the amount being transferred over this path is lower.
910 // We do this for now, but this is a subject for removal.
911 if let Some(mut available_value_contribution_msat) = htlc_maximum_msat.checked_sub($next_hops_fee_msat) {
912 let used_liquidity_msat = used_channel_liquidities
913 .get(&(short_channel_id, $src_node_id < $dest_node_id))
914 .map_or(0, |used_liquidity_msat| {
915 available_value_contribution_msat = available_value_contribution_msat
916 .saturating_sub(*used_liquidity_msat);
920 // Routing Fragmentation Mitigation heuristic:
922 // Routing fragmentation across many payment paths increases the overall routing
923 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
924 // Taking too many smaller paths also increases the chance of payment failure.
925 // Thus to avoid this effect, we require from our collected links to provide
926 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
928 // This requirement is currently 5% of the remaining-to-be-collected value.
929 // This means as we successfully advance in our collection,
930 // the absolute liquidity contribution is lowered,
931 // thus increasing the number of potential channels to be selected.
933 // Derive the minimal liquidity contribution with a ratio of 20 (5%, rounded up)
934 // or 100% if we're not allowed to do multipath payments.
935 let minimal_value_contribution_msat: u64 = if allow_mpp {
936 (recommended_value_msat - already_collected_value_msat + 19) / 20
940 // Verify the liquidity offered by this channel complies to the minimal contribution.
941 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
942 // Do not consider candidate hops that would exceed the maximum path length.
943 let path_length_to_node = $next_hops_path_length + 1;
944 let doesnt_exceed_max_path_length = path_length_to_node <= MAX_PATH_LENGTH_ESTIMATE;
946 // Do not consider candidates that exceed the maximum total cltv expiry limit.
947 // In order to already account for some of the privacy enhancing random CLTV
948 // expiry delta offset we add on top later, we subtract a rough estimate
949 // (2*MEDIAN_HOP_CLTV_EXPIRY_DELTA) here.
950 let max_total_cltv_expiry_delta = (payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta)
951 .checked_sub(2*MEDIAN_HOP_CLTV_EXPIRY_DELTA)
952 .unwrap_or(payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta);
953 let hop_total_cltv_delta = ($next_hops_cltv_delta as u32)
954 .saturating_add($candidate.cltv_expiry_delta());
955 let doesnt_exceed_cltv_delta_limit = hop_total_cltv_delta <= max_total_cltv_expiry_delta;
957 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
958 // Includes paying fees for the use of the following channels.
959 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
960 Some(result) => result,
961 // Can't overflow due to how the values were computed right above.
962 None => unreachable!(),
964 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
965 let over_path_minimum_msat = amount_to_transfer_over_msat >= $candidate.htlc_minimum_msat() &&
966 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
968 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
969 let may_overpay_to_meet_path_minimum_msat =
970 ((amount_to_transfer_over_msat < $candidate.htlc_minimum_msat() &&
971 recommended_value_msat > $candidate.htlc_minimum_msat()) ||
972 (amount_to_transfer_over_msat < $next_hops_path_htlc_minimum_msat &&
973 recommended_value_msat > $next_hops_path_htlc_minimum_msat));
975 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
976 // bother considering this channel. If retrying with recommended_value_msat may
977 // allow us to hit the HTLC minimum limit, set htlc_minimum_limit so that we go
978 // around again with a higher amount.
979 if contributes_sufficient_value && doesnt_exceed_max_path_length &&
980 doesnt_exceed_cltv_delta_limit && may_overpay_to_meet_path_minimum_msat {
981 hit_minimum_limit = true;
982 } else if contributes_sufficient_value && doesnt_exceed_max_path_length &&
983 doesnt_exceed_cltv_delta_limit && over_path_minimum_msat {
984 // Note that low contribution here (limited by available_liquidity_msat)
985 // might violate htlc_minimum_msat on the hops which are next along the
986 // payment path (upstream to the payee). To avoid that, we recompute
987 // path fees knowing the final path contribution after constructing it.
988 let path_htlc_minimum_msat = compute_fees($next_hops_path_htlc_minimum_msat, $candidate.fees())
989 .and_then(|fee_msat| fee_msat.checked_add($next_hops_path_htlc_minimum_msat))
990 .map(|fee_msat| cmp::max(fee_msat, $candidate.htlc_minimum_msat()))
991 .unwrap_or_else(|| u64::max_value());
992 let hm_entry = dist.entry($src_node_id);
993 let old_entry = hm_entry.or_insert_with(|| {
994 // If there was previously no known way to access the source node
995 // (recall it goes payee-to-payer) of short_channel_id, first add a
996 // semi-dummy record just to compute the fees to reach the source node.
997 // This will affect our decision on selecting short_channel_id
998 // as a way to reach the $dest_node_id.
999 let mut fee_base_msat = 0;
1000 let mut fee_proportional_millionths = 0;
1001 if let Some(Some(fees)) = network_nodes.get(&$src_node_id).map(|node| node.lowest_inbound_channel_fees) {
1002 fee_base_msat = fees.base_msat;
1003 fee_proportional_millionths = fees.proportional_millionths;
1006 node_id: $dest_node_id.clone(),
1007 candidate: $candidate.clone(),
1009 src_lowest_inbound_fees: RoutingFees {
1010 base_msat: fee_base_msat,
1011 proportional_millionths: fee_proportional_millionths,
1013 next_hops_fee_msat: u64::max_value(),
1014 hop_use_fee_msat: u64::max_value(),
1015 total_fee_msat: u64::max_value(),
1016 path_htlc_minimum_msat,
1017 path_penalty_msat: u64::max_value(),
1018 was_processed: false,
1019 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
1020 value_contribution_msat,
1024 #[allow(unused_mut)] // We only use the mut in cfg(test)
1025 let mut should_process = !old_entry.was_processed;
1026 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
1028 // In test/fuzzing builds, we do extra checks to make sure the skipping
1029 // of already-seen nodes only happens in cases we expect (see below).
1030 if !should_process { should_process = true; }
1034 let mut hop_use_fee_msat = 0;
1035 let mut total_fee_msat = $next_hops_fee_msat;
1037 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
1038 // will have the same effective-fee
1039 if $src_node_id != our_node_id {
1040 match compute_fees(amount_to_transfer_over_msat, $candidate.fees()) {
1041 // max_value means we'll always fail
1042 // the old_entry.total_fee_msat > total_fee_msat check
1043 None => total_fee_msat = u64::max_value(),
1045 hop_use_fee_msat = fee_msat;
1046 total_fee_msat += hop_use_fee_msat;
1047 // When calculating the lowest inbound fees to a node, we
1048 // calculate fees here not based on the actual value we think
1049 // will flow over this channel, but on the minimum value that
1050 // we'll accept flowing over it. The minimum accepted value
1051 // is a constant through each path collection run, ensuring
1052 // consistent basis. Otherwise we may later find a
1053 // different path to the source node that is more expensive,
1054 // but which we consider to be cheaper because we are capacity
1055 // constrained and the relative fee becomes lower.
1056 match compute_fees(minimal_value_contribution_msat, old_entry.src_lowest_inbound_fees)
1057 .map(|a| a.checked_add(total_fee_msat)) {
1062 total_fee_msat = u64::max_value();
1069 let channel_usage = ChannelUsage {
1070 amount_msat: amount_to_transfer_over_msat,
1071 inflight_htlc_msat: used_liquidity_msat,
1072 effective_capacity: $candidate.effective_capacity(),
1074 let channel_penalty_msat = scorer.channel_penalty_msat(
1075 short_channel_id, &$src_node_id, &$dest_node_id, channel_usage
1077 let path_penalty_msat = $next_hops_path_penalty_msat
1078 .saturating_add(channel_penalty_msat);
1079 let new_graph_node = RouteGraphNode {
1080 node_id: $src_node_id,
1081 lowest_fee_to_peer_through_node: total_fee_msat,
1082 lowest_fee_to_node: $next_hops_fee_msat as u64 + hop_use_fee_msat,
1083 total_cltv_delta: hop_total_cltv_delta,
1084 value_contribution_msat: value_contribution_msat,
1085 path_htlc_minimum_msat,
1087 path_length_to_node,
1090 // Update the way of reaching $src_node_id with the given short_channel_id (from $dest_node_id),
1091 // if this way is cheaper than the already known
1092 // (considering the cost to "reach" this channel from the route destination,
1093 // the cost of using this channel,
1094 // and the cost of routing to the source node of this channel).
1095 // Also, consider that htlc_minimum_msat_difference, because we might end up
1096 // paying it. Consider the following exploit:
1097 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
1098 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
1099 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
1100 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
1102 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
1103 // but it may require additional tracking - we don't want to double-count
1104 // the fees included in $next_hops_path_htlc_minimum_msat, but also
1105 // can't use something that may decrease on future hops.
1106 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat)
1107 .saturating_add(old_entry.path_penalty_msat);
1108 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat)
1109 .saturating_add(path_penalty_msat);
1111 if !old_entry.was_processed && new_cost < old_cost {
1112 targets.push(new_graph_node);
1113 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
1114 old_entry.hop_use_fee_msat = hop_use_fee_msat;
1115 old_entry.total_fee_msat = total_fee_msat;
1116 old_entry.node_id = $dest_node_id.clone();
1117 old_entry.candidate = $candidate.clone();
1118 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
1119 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
1120 old_entry.path_penalty_msat = path_penalty_msat;
1121 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
1123 old_entry.value_contribution_msat = value_contribution_msat;
1125 did_add_update_path_to_src_node = true;
1126 } else if old_entry.was_processed && new_cost < old_cost {
1127 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
1129 // If we're skipping processing a node which was previously
1130 // processed even though we found another path to it with a
1131 // cheaper fee, check that it was because the second path we
1132 // found (which we are processing now) has a lower value
1133 // contribution due to an HTLC minimum limit.
1135 // e.g. take a graph with two paths from node 1 to node 2, one
1136 // through channel A, and one through channel B. Channel A and
1137 // B are both in the to-process heap, with their scores set by
1138 // a higher htlc_minimum than fee.
1139 // Channel A is processed first, and the channels onwards from
1140 // node 1 are added to the to-process heap. Thereafter, we pop
1141 // Channel B off of the heap, note that it has a much more
1142 // restrictive htlc_maximum_msat, and recalculate the fees for
1143 // all of node 1's channels using the new, reduced, amount.
1145 // This would be bogus - we'd be selecting a higher-fee path
1146 // with a lower htlc_maximum_msat instead of the one we'd
1147 // already decided to use.
1148 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
1150 value_contribution_msat + path_penalty_msat <
1151 old_entry.value_contribution_msat + old_entry.path_penalty_msat
1159 did_add_update_path_to_src_node
1163 let default_node_features = default_node_features();
1165 // Find ways (channels with destination) to reach a given node and store them
1166 // in the corresponding data structures (routing graph etc).
1167 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
1168 // meaning how much will be paid in fees after this node (to the best of our knowledge).
1169 // This data can later be helpful to optimize routing (pay lower fees).
1170 macro_rules! add_entries_to_cheapest_to_target_node {
1171 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr, $next_hops_value_contribution: expr,
1172 $next_hops_path_htlc_minimum_msat: expr, $next_hops_path_penalty_msat: expr,
1173 $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => {
1174 let skip_node = if let Some(elem) = dist.get_mut(&$node_id) {
1175 let was_processed = elem.was_processed;
1176 elem.was_processed = true;
1179 // Entries are added to dist in add_entry!() when there is a channel from a node.
1180 // Because there are no channels from payee, it will not have a dist entry at this point.
1181 // If we're processing any other node, it is always be the result of a channel from it.
1182 assert_eq!($node_id, payee_node_id);
1187 if let Some(first_channels) = first_hop_targets.get(&$node_id) {
1188 for details in first_channels {
1189 let candidate = CandidateRouteHop::FirstHop { details };
1190 add_entry!(candidate, our_node_id, $node_id, $fee_to_target_msat,
1191 $next_hops_value_contribution,
1192 $next_hops_path_htlc_minimum_msat, $next_hops_path_penalty_msat,
1193 $next_hops_cltv_delta, $next_hops_path_length);
1197 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
1200 &default_node_features
1203 if !features.requires_unknown_bits() {
1204 for chan_id in $node.channels.iter() {
1205 let chan = network_channels.get(chan_id).unwrap();
1206 if !chan.features.requires_unknown_bits() {
1207 let (directed_channel, source) =
1208 chan.as_directed_to(&$node_id).expect("inconsistent NetworkGraph");
1209 if first_hops.is_none() || *source != our_node_id {
1210 if let Some(direction) = directed_channel.direction() {
1211 if direction.enabled {
1212 let candidate = CandidateRouteHop::PublicHop {
1213 info: directed_channel.with_update().unwrap(),
1214 short_channel_id: *chan_id,
1216 add_entry!(candidate, *source, $node_id,
1217 $fee_to_target_msat,
1218 $next_hops_value_contribution,
1219 $next_hops_path_htlc_minimum_msat,
1220 $next_hops_path_penalty_msat,
1221 $next_hops_cltv_delta, $next_hops_path_length);
1232 let mut payment_paths = Vec::<PaymentPath>::new();
1234 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
1235 'paths_collection: loop {
1236 // For every new path, start from scratch, except for used_channel_liquidities, which
1237 // helps to avoid reusing previously selected paths in future iterations.
1240 hit_minimum_limit = false;
1242 // If first hop is a private channel and the only way to reach the payee, this is the only
1243 // place where it could be added.
1244 if let Some(first_channels) = first_hop_targets.get(&payee_node_id) {
1245 for details in first_channels {
1246 let candidate = CandidateRouteHop::FirstHop { details };
1247 let added = add_entry!(candidate, our_node_id, payee_node_id, 0, path_value_msat,
1249 log_trace!(logger, "{} direct route to payee via SCID {}",
1250 if added { "Added" } else { "Skipped" }, candidate.short_channel_id());
1254 // Add the payee as a target, so that the payee-to-payer
1255 // search algorithm knows what to start with.
1256 match network_nodes.get(&payee_node_id) {
1257 // The payee is not in our network graph, so nothing to add here.
1258 // There is still a chance of reaching them via last_hops though,
1259 // so don't yet fail the payment here.
1260 // If not, targets.pop() will not even let us enter the loop in step 2.
1263 add_entries_to_cheapest_to_target_node!(node, payee_node_id, 0, path_value_msat, 0, 0u64, 0, 0);
1268 // If a caller provided us with last hops, add them to routing targets. Since this happens
1269 // earlier than general path finding, they will be somewhat prioritized, although currently
1270 // it matters only if the fees are exactly the same.
1271 for route in payment_params.route_hints.iter().filter(|route| !route.0.is_empty()) {
1272 let first_hop_in_route = &(route.0)[0];
1273 let have_hop_src_in_graph =
1274 // Only add the hops in this route to our candidate set if either
1275 // we have a direct channel to the first hop or the first hop is
1276 // in the regular network graph.
1277 first_hop_targets.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some() ||
1278 network_nodes.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some();
1279 if have_hop_src_in_graph {
1280 // We start building the path from reverse, i.e., from payee
1281 // to the first RouteHintHop in the path.
1282 let hop_iter = route.0.iter().rev();
1283 let prev_hop_iter = core::iter::once(&payment_params.payee_pubkey).chain(
1284 route.0.iter().skip(1).rev().map(|hop| &hop.src_node_id));
1285 let mut hop_used = true;
1286 let mut aggregate_next_hops_fee_msat: u64 = 0;
1287 let mut aggregate_next_hops_path_htlc_minimum_msat: u64 = 0;
1288 let mut aggregate_next_hops_path_penalty_msat: u64 = 0;
1289 let mut aggregate_next_hops_cltv_delta: u32 = 0;
1290 let mut aggregate_next_hops_path_length: u8 = 0;
1292 for (idx, (hop, prev_hop_id)) in hop_iter.zip(prev_hop_iter).enumerate() {
1293 let source = NodeId::from_pubkey(&hop.src_node_id);
1294 let target = NodeId::from_pubkey(&prev_hop_id);
1295 let candidate = network_channels
1296 .get(&hop.short_channel_id)
1297 .and_then(|channel| channel.as_directed_to(&target))
1298 .and_then(|(channel, _)| channel.with_update())
1299 .map(|info| CandidateRouteHop::PublicHop {
1301 short_channel_id: hop.short_channel_id,
1303 .unwrap_or_else(|| CandidateRouteHop::PrivateHop { hint: hop });
1305 if !add_entry!(candidate, source, target, aggregate_next_hops_fee_msat,
1306 path_value_msat, aggregate_next_hops_path_htlc_minimum_msat,
1307 aggregate_next_hops_path_penalty_msat,
1308 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length) {
1309 // If this hop was not used then there is no use checking the preceding
1310 // hops in the RouteHint. We can break by just searching for a direct
1311 // channel between last checked hop and first_hop_targets.
1315 let used_liquidity_msat = used_channel_liquidities
1316 .get(&(hop.short_channel_id, source < target)).copied().unwrap_or(0);
1317 let channel_usage = ChannelUsage {
1318 amount_msat: final_value_msat + aggregate_next_hops_fee_msat,
1319 inflight_htlc_msat: used_liquidity_msat,
1320 effective_capacity: candidate.effective_capacity(),
1322 let channel_penalty_msat = scorer.channel_penalty_msat(
1323 hop.short_channel_id, &source, &target, channel_usage
1325 aggregate_next_hops_path_penalty_msat = aggregate_next_hops_path_penalty_msat
1326 .saturating_add(channel_penalty_msat);
1328 aggregate_next_hops_cltv_delta = aggregate_next_hops_cltv_delta
1329 .saturating_add(hop.cltv_expiry_delta as u32);
1331 aggregate_next_hops_path_length = aggregate_next_hops_path_length
1334 // Searching for a direct channel between last checked hop and first_hop_targets
1335 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&prev_hop_id)) {
1336 for details in first_channels {
1337 let candidate = CandidateRouteHop::FirstHop { details };
1338 add_entry!(candidate, our_node_id, NodeId::from_pubkey(&prev_hop_id),
1339 aggregate_next_hops_fee_msat, path_value_msat,
1340 aggregate_next_hops_path_htlc_minimum_msat,
1341 aggregate_next_hops_path_penalty_msat, aggregate_next_hops_cltv_delta,
1342 aggregate_next_hops_path_length);
1350 // In the next values of the iterator, the aggregate fees already reflects
1351 // the sum of value sent from payer (final_value_msat) and routing fees
1352 // for the last node in the RouteHint. We need to just add the fees to
1353 // route through the current node so that the preceding node (next iteration)
1355 let hops_fee = compute_fees(aggregate_next_hops_fee_msat + final_value_msat, hop.fees)
1356 .map_or(None, |inc| inc.checked_add(aggregate_next_hops_fee_msat));
1357 aggregate_next_hops_fee_msat = if let Some(val) = hops_fee { val } else { break; };
1359 let hop_htlc_minimum_msat = candidate.htlc_minimum_msat();
1360 let hop_htlc_minimum_msat_inc = if let Some(val) = compute_fees(aggregate_next_hops_path_htlc_minimum_msat, hop.fees) { val } else { break; };
1361 let hops_path_htlc_minimum = aggregate_next_hops_path_htlc_minimum_msat
1362 .checked_add(hop_htlc_minimum_msat_inc);
1363 aggregate_next_hops_path_htlc_minimum_msat = if let Some(val) = hops_path_htlc_minimum { cmp::max(hop_htlc_minimum_msat, val) } else { break; };
1365 if idx == route.0.len() - 1 {
1366 // The last hop in this iterator is the first hop in
1367 // overall RouteHint.
1368 // If this hop connects to a node with which we have a direct channel,
1369 // ignore the network graph and, if the last hop was added, add our
1370 // direct channel to the candidate set.
1372 // Note that we *must* check if the last hop was added as `add_entry`
1373 // always assumes that the third argument is a node to which we have a
1375 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&hop.src_node_id)) {
1376 for details in first_channels {
1377 let candidate = CandidateRouteHop::FirstHop { details };
1378 add_entry!(candidate, our_node_id,
1379 NodeId::from_pubkey(&hop.src_node_id),
1380 aggregate_next_hops_fee_msat, path_value_msat,
1381 aggregate_next_hops_path_htlc_minimum_msat,
1382 aggregate_next_hops_path_penalty_msat,
1383 aggregate_next_hops_cltv_delta,
1384 aggregate_next_hops_path_length);
1392 log_trace!(logger, "Starting main path collection loop with {} nodes pre-filled from first/last hops.", targets.len());
1394 // At this point, targets are filled with the data from first and
1395 // last hops communicated by the caller, and the payment receiver.
1396 let mut found_new_path = false;
1399 // If this loop terminates due the exhaustion of targets, two situations are possible:
1400 // - not enough outgoing liquidity:
1401 // 0 < already_collected_value_msat < final_value_msat
1402 // - enough outgoing liquidity:
1403 // final_value_msat <= already_collected_value_msat < recommended_value_msat
1404 // Both these cases (and other cases except reaching recommended_value_msat) mean that
1405 // paths_collection will be stopped because found_new_path==false.
1406 // This is not necessarily a routing failure.
1407 '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, path_length_to_node, .. }) = targets.pop() {
1409 // Since we're going payee-to-payer, hitting our node as a target means we should stop
1410 // traversing the graph and arrange the path out of what we found.
1411 if node_id == our_node_id {
1412 let mut new_entry = dist.remove(&our_node_id).unwrap();
1413 let mut ordered_hops: Vec<(PathBuildingHop, NodeFeatures)> = vec!((new_entry.clone(), default_node_features.clone()));
1416 let mut features_set = false;
1417 if let Some(first_channels) = first_hop_targets.get(&ordered_hops.last().unwrap().0.node_id) {
1418 for details in first_channels {
1419 if details.short_channel_id.unwrap() == ordered_hops.last().unwrap().0.candidate.short_channel_id() {
1420 ordered_hops.last_mut().unwrap().1 = details.counterparty.features.to_context();
1421 features_set = true;
1427 if let Some(node) = network_nodes.get(&ordered_hops.last().unwrap().0.node_id) {
1428 if let Some(node_info) = node.announcement_info.as_ref() {
1429 ordered_hops.last_mut().unwrap().1 = node_info.features.clone();
1431 ordered_hops.last_mut().unwrap().1 = default_node_features.clone();
1434 // We can fill in features for everything except hops which were
1435 // provided via the invoice we're paying. We could guess based on the
1436 // recipient's features but for now we simply avoid guessing at all.
1440 // Means we succesfully traversed from the payer to the payee, now
1441 // save this path for the payment route. Also, update the liquidity
1442 // remaining on the used hops, so that we take them into account
1443 // while looking for more paths.
1444 if ordered_hops.last().unwrap().0.node_id == payee_node_id {
1448 new_entry = match dist.remove(&ordered_hops.last().unwrap().0.node_id) {
1449 Some(payment_hop) => payment_hop,
1450 // We can't arrive at None because, if we ever add an entry to targets,
1451 // we also fill in the entry in dist (see add_entry!).
1452 None => unreachable!(),
1454 // We "propagate" the fees one hop backward (topologically) here,
1455 // so that fees paid for a HTLC forwarding on the current channel are
1456 // associated with the previous channel (where they will be subtracted).
1457 ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
1458 ordered_hops.push((new_entry.clone(), default_node_features.clone()));
1460 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
1461 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
1463 log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: \n {:#?}",
1464 ordered_hops.len(), value_contribution_msat, ordered_hops.iter().map(|h| &(h.0)).collect::<Vec<&PathBuildingHop>>());
1466 let mut payment_path = PaymentPath {hops: ordered_hops};
1468 // We could have possibly constructed a slightly inconsistent path: since we reduce
1469 // value being transferred along the way, we could have violated htlc_minimum_msat
1470 // on some channels we already passed (assuming dest->source direction). Here, we
1471 // recompute the fees again, so that if that's the case, we match the currently
1472 // underpaid htlc_minimum_msat with fees.
1473 payment_path.update_value_and_recompute_fees(cmp::min(value_contribution_msat, final_value_msat));
1475 // Since a path allows to transfer as much value as
1476 // the smallest channel it has ("bottleneck"), we should recompute
1477 // the fees so sender HTLC don't overpay fees when traversing
1478 // larger channels than the bottleneck. This may happen because
1479 // when we were selecting those channels we were not aware how much value
1480 // this path will transfer, and the relative fee for them
1481 // might have been computed considering a larger value.
1482 // Remember that we used these channels so that we don't rely
1483 // on the same liquidity in future paths.
1484 let mut prevented_redundant_path_selection = false;
1485 let prev_hop_iter = core::iter::once(&our_node_id)
1486 .chain(payment_path.hops.iter().map(|(hop, _)| &hop.node_id));
1487 for (prev_hop, (hop, _)) in prev_hop_iter.zip(payment_path.hops.iter()) {
1488 let spent_on_hop_msat = value_contribution_msat + hop.next_hops_fee_msat;
1489 let used_liquidity_msat = used_channel_liquidities
1490 .entry((hop.candidate.short_channel_id(), *prev_hop < hop.node_id))
1491 .and_modify(|used_liquidity_msat| *used_liquidity_msat += spent_on_hop_msat)
1492 .or_insert(spent_on_hop_msat);
1493 if *used_liquidity_msat == hop.candidate.htlc_maximum_msat() {
1494 // If this path used all of this channel's available liquidity, we know
1495 // this path will not be selected again in the next loop iteration.
1496 prevented_redundant_path_selection = true;
1498 debug_assert!(*used_liquidity_msat <= hop.candidate.htlc_maximum_msat());
1500 if !prevented_redundant_path_selection {
1501 // If we weren't capped by hitting a liquidity limit on a channel in the path,
1502 // we'll probably end up picking the same path again on the next iteration.
1503 // Decrease the available liquidity of a hop in the middle of the path.
1504 let victim_scid = payment_path.hops[(payment_path.hops.len()) / 2].0.candidate.short_channel_id();
1505 let exhausted = u64::max_value();
1506 log_trace!(logger, "Disabling channel {} for future path building iterations to avoid duplicates.", victim_scid);
1507 *used_channel_liquidities.entry((victim_scid, false)).or_default() = exhausted;
1508 *used_channel_liquidities.entry((victim_scid, true)).or_default() = exhausted;
1511 // Track the total amount all our collected paths allow to send so that we:
1512 // - know when to stop looking for more paths
1513 // - know which of the hops are useless considering how much more sats we need
1514 // (contributes_sufficient_value)
1515 already_collected_value_msat += value_contribution_msat;
1517 payment_paths.push(payment_path);
1518 found_new_path = true;
1519 break 'path_construction;
1522 // If we found a path back to the payee, we shouldn't try to process it again. This is
1523 // the equivalent of the `elem.was_processed` check in
1524 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
1525 if node_id == payee_node_id { continue 'path_construction; }
1527 // Otherwise, since the current target node is not us,
1528 // keep "unrolling" the payment graph from payee to payer by
1529 // finding a way to reach the current target from the payer side.
1530 match network_nodes.get(&node_id) {
1533 add_entries_to_cheapest_to_target_node!(node, node_id, lowest_fee_to_node,
1534 value_contribution_msat, path_htlc_minimum_msat, path_penalty_msat,
1535 total_cltv_delta, path_length_to_node);
1541 // If we don't support MPP, no use trying to gather more value ever.
1542 break 'paths_collection;
1546 // Stop either when the recommended value is reached or if no new path was found in this
1548 // In the latter case, making another path finding attempt won't help,
1549 // because we deterministically terminated the search due to low liquidity.
1550 if already_collected_value_msat >= recommended_value_msat || !found_new_path {
1551 log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
1552 already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
1553 break 'paths_collection;
1554 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
1555 // Further, if this was our first walk of the graph, and we weren't limited by an
1556 // htlc_minimum_msat, return immediately because this path should suffice. If we were
1557 // limited by an htlc_minimum_msat value, find another path with a higher value,
1558 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
1559 // still keeping a lower total fee than this path.
1560 if !hit_minimum_limit {
1561 log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
1562 break 'paths_collection;
1564 log_trace!(logger, "Collected our payment amount on the first pass, but running again to collect extra paths with a potentially higher limit.");
1565 path_value_msat = recommended_value_msat;
1570 if payment_paths.len() == 0 {
1571 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1574 if already_collected_value_msat < final_value_msat {
1575 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1578 // Sort by total fees and take the best paths.
1579 payment_paths.sort_unstable_by_key(|path| path.get_total_fee_paid_msat());
1580 if payment_paths.len() > 50 {
1581 payment_paths.truncate(50);
1584 // Draw multiple sufficient routes by randomly combining the selected paths.
1585 let mut drawn_routes = Vec::new();
1586 let mut prng = ChaCha20::new(random_seed_bytes, &[0u8; 12]);
1587 let mut random_index_bytes = [0u8; ::core::mem::size_of::<usize>()];
1589 let num_permutations = payment_paths.len();
1590 for _ in 0..num_permutations {
1591 let mut cur_route = Vec::<PaymentPath>::new();
1592 let mut aggregate_route_value_msat = 0;
1595 // Do a Fisher-Yates shuffle to create a random permutation of the payment paths
1596 for cur_index in (1..payment_paths.len()).rev() {
1597 prng.process_in_place(&mut random_index_bytes);
1598 let random_index = usize::from_be_bytes(random_index_bytes).wrapping_rem(cur_index+1);
1599 payment_paths.swap(cur_index, random_index);
1603 for payment_path in &payment_paths {
1604 cur_route.push(payment_path.clone());
1605 aggregate_route_value_msat += payment_path.get_value_msat();
1606 if aggregate_route_value_msat > final_value_msat {
1607 // Last path likely overpaid. Substract it from the most expensive
1608 // (in terms of proportional fee) path in this route and recompute fees.
1609 // This might be not the most economically efficient way, but fewer paths
1610 // also makes routing more reliable.
1611 let mut overpaid_value_msat = aggregate_route_value_msat - final_value_msat;
1613 // First, we drop some expensive low-value paths entirely if possible, since fewer
1614 // paths is better: the payment is less likely to fail. In order to do so, we sort
1615 // by value and fall back to total fees paid, i.e., in case of equal values we
1616 // prefer lower cost paths.
1617 cur_route.sort_unstable_by(|a, b| {
1618 a.get_value_msat().cmp(&b.get_value_msat())
1619 // Reverse ordering for cost, so we drop higher-cost paths first
1620 .then_with(|| b.get_cost_msat().cmp(&a.get_cost_msat()))
1623 // We should make sure that at least 1 path left.
1624 let mut paths_left = cur_route.len();
1625 cur_route.retain(|path| {
1626 if paths_left == 1 {
1629 let mut keep = true;
1630 let path_value_msat = path.get_value_msat();
1631 if path_value_msat <= overpaid_value_msat {
1633 overpaid_value_msat -= path_value_msat;
1639 if overpaid_value_msat == 0 {
1643 assert!(cur_route.len() > 0);
1646 // Now, subtract the overpaid value from the most-expensive path.
1647 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1648 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1649 cur_route.sort_unstable_by_key(|path| { path.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>() });
1650 let expensive_payment_path = cur_route.first_mut().unwrap();
1652 // We already dropped all the small value paths above, meaning all the
1653 // remaining paths are larger than remaining overpaid_value_msat.
1654 // Thus, this can't be negative.
1655 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
1656 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
1660 drawn_routes.push(cur_route);
1664 // Select the best route by lowest total cost.
1665 drawn_routes.sort_unstable_by_key(|paths| paths.iter().map(|path| path.get_cost_msat()).sum::<u64>());
1666 let mut selected_paths = Vec::<Vec<Result<RouteHop, LightningError>>>::new();
1667 for payment_path in drawn_routes.first().unwrap() {
1668 let mut path = payment_path.hops.iter().map(|(payment_hop, node_features)| {
1670 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)})?,
1671 node_features: node_features.clone(),
1672 short_channel_id: payment_hop.candidate.short_channel_id(),
1673 channel_features: payment_hop.candidate.features(),
1674 fee_msat: payment_hop.fee_msat,
1675 cltv_expiry_delta: payment_hop.candidate.cltv_expiry_delta(),
1677 }).collect::<Vec<_>>();
1678 // Propagate the cltv_expiry_delta one hop backwards since the delta from the current hop is
1679 // applicable for the previous hop.
1680 path.iter_mut().rev().fold(final_cltv_expiry_delta, |prev_cltv_expiry_delta, hop| {
1681 core::mem::replace(&mut hop.as_mut().unwrap().cltv_expiry_delta, prev_cltv_expiry_delta)
1683 selected_paths.push(path);
1686 if let Some(features) = &payment_params.features {
1687 for path in selected_paths.iter_mut() {
1688 if let Ok(route_hop) = path.last_mut().unwrap() {
1689 route_hop.node_features = features.to_context();
1695 paths: selected_paths.into_iter().map(|path| path.into_iter().collect()).collect::<Result<Vec<_>, _>>()?,
1696 payment_params: Some(payment_params.clone()),
1698 log_info!(logger, "Got route to {}: {}", payment_params.payee_pubkey, log_route!(route));
1702 // When an adversarial intermediary node observes a payment, it may be able to infer its
1703 // destination, if the remaining CLTV expiry delta exactly matches a feasible path in the network
1704 // graph. In order to improve privacy, this method obfuscates the CLTV expiry deltas along the
1705 // payment path by adding a randomized 'shadow route' offset to the final hop.
1706 fn add_random_cltv_offset(route: &mut Route, payment_params: &PaymentParameters, network_graph: &ReadOnlyNetworkGraph, random_seed_bytes: &[u8; 32]) {
1707 let network_channels = network_graph.channels();
1708 let network_nodes = network_graph.nodes();
1710 for path in route.paths.iter_mut() {
1711 let mut shadow_ctlv_expiry_delta_offset: u32 = 0;
1713 // Remember the last three nodes of the random walk and avoid looping back on them.
1714 // Init with the last three nodes from the actual path, if possible.
1715 let mut nodes_to_avoid: [NodeId; 3] = [NodeId::from_pubkey(&path.last().unwrap().pubkey),
1716 NodeId::from_pubkey(&path.get(path.len().saturating_sub(2)).unwrap().pubkey),
1717 NodeId::from_pubkey(&path.get(path.len().saturating_sub(3)).unwrap().pubkey)];
1719 // Choose the last publicly known node as the starting point for the random walk.
1720 let mut cur_hop: Option<NodeId> = None;
1721 let mut path_nonce = [0u8; 12];
1722 if let Some(starting_hop) = path.iter().rev()
1723 .find(|h| network_nodes.contains_key(&NodeId::from_pubkey(&h.pubkey))) {
1724 cur_hop = Some(NodeId::from_pubkey(&starting_hop.pubkey));
1725 path_nonce.copy_from_slice(&cur_hop.unwrap().as_slice()[..12]);
1728 // Init PRNG with the path-dependant nonce, which is static for private paths.
1729 let mut prng = ChaCha20::new(random_seed_bytes, &path_nonce);
1730 let mut random_path_bytes = [0u8; ::core::mem::size_of::<usize>()];
1732 // Pick a random path length in [1 .. 3]
1733 prng.process_in_place(&mut random_path_bytes);
1734 let random_walk_length = usize::from_be_bytes(random_path_bytes).wrapping_rem(3).wrapping_add(1);
1736 for random_hop in 0..random_walk_length {
1737 // If we don't find a suitable offset in the public network graph, we default to
1738 // MEDIAN_HOP_CLTV_EXPIRY_DELTA.
1739 let mut random_hop_offset = MEDIAN_HOP_CLTV_EXPIRY_DELTA;
1741 if let Some(cur_node_id) = cur_hop {
1742 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
1743 // Randomly choose the next unvisited hop.
1744 prng.process_in_place(&mut random_path_bytes);
1745 if let Some(random_channel) = usize::from_be_bytes(random_path_bytes)
1746 .checked_rem(cur_node.channels.len())
1747 .and_then(|index| cur_node.channels.get(index))
1748 .and_then(|id| network_channels.get(id)) {
1749 random_channel.as_directed_from(&cur_node_id).map(|(dir_info, next_id)| {
1750 if !nodes_to_avoid.iter().any(|x| x == next_id) {
1751 nodes_to_avoid[random_hop] = *next_id;
1752 dir_info.direction().map(|channel_update_info| {
1753 random_hop_offset = channel_update_info.cltv_expiry_delta.into();
1754 cur_hop = Some(*next_id);
1762 shadow_ctlv_expiry_delta_offset = shadow_ctlv_expiry_delta_offset
1763 .checked_add(random_hop_offset)
1764 .unwrap_or(shadow_ctlv_expiry_delta_offset);
1767 // Limit the total offset to reduce the worst-case locked liquidity timevalue
1768 const MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET: u32 = 3*144;
1769 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET);
1771 // Limit the offset so we never exceed the max_total_cltv_expiry_delta. To improve plausibility,
1772 // we choose the limit to be the largest possible multiple of MEDIAN_HOP_CLTV_EXPIRY_DELTA.
1773 let path_total_cltv_expiry_delta: u32 = path.iter().map(|h| h.cltv_expiry_delta).sum();
1774 let mut max_path_offset = payment_params.max_total_cltv_expiry_delta - path_total_cltv_expiry_delta;
1775 max_path_offset = cmp::max(
1776 max_path_offset - (max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA),
1777 max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA);
1778 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, max_path_offset);
1780 // Add 'shadow' CLTV offset to the final hop
1781 if let Some(last_hop) = path.last_mut() {
1782 last_hop.cltv_expiry_delta = last_hop.cltv_expiry_delta
1783 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(last_hop.cltv_expiry_delta);
1790 use routing::network_graph::{NetworkGraph, NetGraphMsgHandler, NodeId};
1791 use routing::router::{get_route, add_random_cltv_offset, default_node_features,
1792 PaymentParameters, Route, RouteHint, RouteHintHop, RouteHop, RoutingFees,
1793 DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA, MAX_PATH_LENGTH_ESTIMATE};
1794 use routing::scoring::{ChannelUsage, Score};
1795 use chain::transaction::OutPoint;
1796 use chain::keysinterface::KeysInterface;
1797 use ln::features::{ChannelFeatures, InitFeatures, InvoiceFeatures, NodeFeatures};
1798 use ln::msgs::{ErrorAction, LightningError, OptionalField, UnsignedChannelAnnouncement, ChannelAnnouncement, RoutingMessageHandler,
1799 NodeAnnouncement, UnsignedNodeAnnouncement, ChannelUpdate, UnsignedChannelUpdate};
1800 use ln::channelmanager;
1801 use util::test_utils;
1802 use util::chacha20::ChaCha20;
1803 use util::ser::Writeable;
1805 use util::ser::Writer;
1807 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
1808 use bitcoin::hashes::Hash;
1809 use bitcoin::network::constants::Network;
1810 use bitcoin::blockdata::constants::genesis_block;
1811 use bitcoin::blockdata::script::Builder;
1812 use bitcoin::blockdata::opcodes;
1813 use bitcoin::blockdata::transaction::TxOut;
1817 use bitcoin::secp256k1::{PublicKey,SecretKey};
1818 use bitcoin::secp256k1::{Secp256k1, All};
1821 use sync::{self, Arc};
1823 fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
1824 features: InitFeatures, outbound_capacity_msat: u64) -> channelmanager::ChannelDetails {
1825 channelmanager::ChannelDetails {
1826 channel_id: [0; 32],
1827 counterparty: channelmanager::ChannelCounterparty {
1830 unspendable_punishment_reserve: 0,
1831 forwarding_info: None,
1832 outbound_htlc_minimum_msat: None,
1833 outbound_htlc_maximum_msat: None,
1835 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
1838 inbound_scid_alias: None,
1839 channel_value_satoshis: 0,
1842 outbound_capacity_msat,
1843 next_outbound_htlc_limit_msat: outbound_capacity_msat,
1844 inbound_capacity_msat: 42,
1845 unspendable_punishment_reserve: None,
1846 confirmations_required: None,
1847 force_close_spend_delay: None,
1848 is_outbound: true, is_funding_locked: true,
1849 is_usable: true, is_public: true,
1850 inbound_htlc_minimum_msat: None,
1851 inbound_htlc_maximum_msat: None,
1855 // Using the same keys for LN and BTC ids
1857 net_graph_msg_handler: &NetGraphMsgHandler<Arc<NetworkGraph>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1858 secp_ctx: &Secp256k1<All>, node_1_privkey: &SecretKey, node_2_privkey: &SecretKey, features: ChannelFeatures, short_channel_id: u64
1860 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1861 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1863 let unsigned_announcement = UnsignedChannelAnnouncement {
1865 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1869 bitcoin_key_1: node_id_1,
1870 bitcoin_key_2: node_id_2,
1871 excess_data: Vec::new(),
1874 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1875 let valid_announcement = ChannelAnnouncement {
1876 node_signature_1: secp_ctx.sign_ecdsa(&msghash, node_1_privkey),
1877 node_signature_2: secp_ctx.sign_ecdsa(&msghash, node_2_privkey),
1878 bitcoin_signature_1: secp_ctx.sign_ecdsa(&msghash, node_1_privkey),
1879 bitcoin_signature_2: secp_ctx.sign_ecdsa(&msghash, node_2_privkey),
1880 contents: unsigned_announcement.clone(),
1882 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1883 Ok(res) => assert!(res),
1889 net_graph_msg_handler: &NetGraphMsgHandler<Arc<NetworkGraph>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1890 secp_ctx: &Secp256k1<All>, node_privkey: &SecretKey, update: UnsignedChannelUpdate
1892 let msghash = hash_to_message!(&Sha256dHash::hash(&update.encode()[..])[..]);
1893 let valid_channel_update = ChannelUpdate {
1894 signature: secp_ctx.sign_ecdsa(&msghash, node_privkey),
1895 contents: update.clone()
1898 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1899 Ok(res) => assert!(res),
1904 fn add_or_update_node(
1905 net_graph_msg_handler: &NetGraphMsgHandler<Arc<NetworkGraph>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1906 secp_ctx: &Secp256k1<All>, node_privkey: &SecretKey, features: NodeFeatures, timestamp: u32
1908 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
1909 let unsigned_announcement = UnsignedNodeAnnouncement {
1915 addresses: Vec::new(),
1916 excess_address_data: Vec::new(),
1917 excess_data: Vec::new(),
1919 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1920 let valid_announcement = NodeAnnouncement {
1921 signature: secp_ctx.sign_ecdsa(&msghash, node_privkey),
1922 contents: unsigned_announcement.clone()
1925 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1931 fn get_nodes(secp_ctx: &Secp256k1<All>) -> (SecretKey, PublicKey, Vec<SecretKey>, Vec<PublicKey>) {
1932 let privkeys: Vec<SecretKey> = (2..22).map(|i| {
1933 SecretKey::from_slice(&hex::decode(format!("{:02x}", i).repeat(32)).unwrap()[..]).unwrap()
1936 let pubkeys = privkeys.iter().map(|secret| PublicKey::from_secret_key(&secp_ctx, secret)).collect();
1938 let our_privkey = SecretKey::from_slice(&hex::decode("01".repeat(32)).unwrap()[..]).unwrap();
1939 let our_id = PublicKey::from_secret_key(&secp_ctx, &our_privkey);
1941 (our_privkey, our_id, privkeys, pubkeys)
1944 fn id_to_feature_flags(id: u8) -> Vec<u8> {
1945 // Set the feature flags to the id'th odd (ie non-required) feature bit so that we can
1946 // test for it later.
1947 let idx = (id - 1) * 2 + 1;
1949 vec![1 << (idx - 8*3), 0, 0, 0]
1950 } else if idx > 8*2 {
1951 vec![1 << (idx - 8*2), 0, 0]
1952 } else if idx > 8*1 {
1953 vec![1 << (idx - 8*1), 0]
1959 fn build_line_graph() -> (
1960 Secp256k1<All>, sync::Arc<NetworkGraph>, NetGraphMsgHandler<sync::Arc<NetworkGraph>,
1961 sync::Arc<test_utils::TestChainSource>, sync::Arc<crate::util::test_utils::TestLogger>>,
1962 sync::Arc<test_utils::TestChainSource>, sync::Arc<test_utils::TestLogger>,
1964 let secp_ctx = Secp256k1::new();
1965 let logger = Arc::new(test_utils::TestLogger::new());
1966 let chain_monitor = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1967 let network_graph = Arc::new(NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash()));
1968 let net_graph_msg_handler = NetGraphMsgHandler::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
1970 // Build network from our_id to node 19:
1971 // our_id -1(1)2- node0 -1(2)2- node1 - ... - node19
1972 let (our_privkey, _, privkeys, _) = get_nodes(&secp_ctx);
1974 for (idx, (cur_privkey, next_privkey)) in core::iter::once(&our_privkey)
1975 .chain(privkeys.iter()).zip(privkeys.iter()).enumerate() {
1976 let cur_short_channel_id = (idx as u64) + 1;
1977 add_channel(&net_graph_msg_handler, &secp_ctx, &cur_privkey, &next_privkey,
1978 ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), cur_short_channel_id);
1979 update_channel(&net_graph_msg_handler, &secp_ctx, &cur_privkey, UnsignedChannelUpdate {
1980 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1981 short_channel_id: cur_short_channel_id,
1982 timestamp: idx as u32,
1984 cltv_expiry_delta: 0,
1985 htlc_minimum_msat: 0,
1986 htlc_maximum_msat: OptionalField::Absent,
1988 fee_proportional_millionths: 0,
1989 excess_data: Vec::new()
1991 update_channel(&net_graph_msg_handler, &secp_ctx, &next_privkey, UnsignedChannelUpdate {
1992 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1993 short_channel_id: cur_short_channel_id,
1994 timestamp: (idx as u32)+1,
1996 cltv_expiry_delta: 0,
1997 htlc_minimum_msat: 0,
1998 htlc_maximum_msat: OptionalField::Absent,
2000 fee_proportional_millionths: 0,
2001 excess_data: Vec::new()
2003 add_or_update_node(&net_graph_msg_handler, &secp_ctx, next_privkey,
2004 NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
2007 (secp_ctx, network_graph, net_graph_msg_handler, chain_monitor, logger)
2010 fn build_graph() -> (
2012 sync::Arc<NetworkGraph>,
2013 NetGraphMsgHandler<sync::Arc<NetworkGraph>, sync::Arc<test_utils::TestChainSource>, sync::Arc<crate::util::test_utils::TestLogger>>,
2014 sync::Arc<test_utils::TestChainSource>,
2015 sync::Arc<test_utils::TestLogger>,
2017 let secp_ctx = Secp256k1::new();
2018 let logger = Arc::new(test_utils::TestLogger::new());
2019 let chain_monitor = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
2020 let network_graph = Arc::new(NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash()));
2021 let net_graph_msg_handler = NetGraphMsgHandler::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
2022 // Build network from our_id to node6:
2024 // -1(1)2- node0 -1(3)2-
2026 // our_id -1(12)2- node7 -1(13)2--- node2
2028 // -1(2)2- node1 -1(4)2-
2031 // chan1 1-to-2: disabled
2032 // chan1 2-to-1: enabled, 0 fee
2034 // chan2 1-to-2: enabled, ignored fee
2035 // chan2 2-to-1: enabled, 0 fee
2037 // chan3 1-to-2: enabled, 0 fee
2038 // chan3 2-to-1: enabled, 100 msat fee
2040 // chan4 1-to-2: enabled, 100% fee
2041 // chan4 2-to-1: enabled, 0 fee
2043 // chan12 1-to-2: enabled, ignored fee
2044 // chan12 2-to-1: enabled, 0 fee
2046 // chan13 1-to-2: enabled, 200% fee
2047 // chan13 2-to-1: enabled, 0 fee
2050 // -1(5)2- node3 -1(8)2--
2054 // node2--1(6)2- node4 -1(9)2--- node6 (not in global route map)
2056 // -1(7)2- node5 -1(10)2-
2058 // Channels 5, 8, 9 and 10 are private channels.
2060 // chan5 1-to-2: enabled, 100 msat fee
2061 // chan5 2-to-1: enabled, 0 fee
2063 // chan6 1-to-2: enabled, 0 fee
2064 // chan6 2-to-1: enabled, 0 fee
2066 // chan7 1-to-2: enabled, 100% fee
2067 // chan7 2-to-1: enabled, 0 fee
2069 // chan8 1-to-2: enabled, variable fee (0 then 1000 msat)
2070 // chan8 2-to-1: enabled, 0 fee
2072 // chan9 1-to-2: enabled, 1001 msat fee
2073 // chan9 2-to-1: enabled, 0 fee
2075 // chan10 1-to-2: enabled, 0 fee
2076 // chan10 2-to-1: enabled, 0 fee
2078 // chan11 1-to-2: enabled, 0 fee
2079 // chan11 2-to-1: enabled, 0 fee
2081 let (our_privkey, _, privkeys, _) = get_nodes(&secp_ctx);
2083 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[0], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
2084 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2085 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2086 short_channel_id: 1,
2089 cltv_expiry_delta: 0,
2090 htlc_minimum_msat: 0,
2091 htlc_maximum_msat: OptionalField::Absent,
2093 fee_proportional_millionths: 0,
2094 excess_data: Vec::new()
2097 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
2099 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
2100 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2101 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2102 short_channel_id: 2,
2105 cltv_expiry_delta: (5 << 4) | 3,
2106 htlc_minimum_msat: 0,
2107 htlc_maximum_msat: OptionalField::Absent,
2108 fee_base_msat: u32::max_value(),
2109 fee_proportional_millionths: u32::max_value(),
2110 excess_data: Vec::new()
2112 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2113 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2114 short_channel_id: 2,
2117 cltv_expiry_delta: 0,
2118 htlc_minimum_msat: 0,
2119 htlc_maximum_msat: OptionalField::Absent,
2121 fee_proportional_millionths: 0,
2122 excess_data: Vec::new()
2125 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
2127 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[7], ChannelFeatures::from_le_bytes(id_to_feature_flags(12)), 12);
2128 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2129 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2130 short_channel_id: 12,
2133 cltv_expiry_delta: (5 << 4) | 3,
2134 htlc_minimum_msat: 0,
2135 htlc_maximum_msat: OptionalField::Absent,
2136 fee_base_msat: u32::max_value(),
2137 fee_proportional_millionths: u32::max_value(),
2138 excess_data: Vec::new()
2140 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2141 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2142 short_channel_id: 12,
2145 cltv_expiry_delta: 0,
2146 htlc_minimum_msat: 0,
2147 htlc_maximum_msat: OptionalField::Absent,
2149 fee_proportional_millionths: 0,
2150 excess_data: Vec::new()
2153 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], NodeFeatures::from_le_bytes(id_to_feature_flags(8)), 0);
2155 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
2156 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2157 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2158 short_channel_id: 3,
2161 cltv_expiry_delta: (3 << 4) | 1,
2162 htlc_minimum_msat: 0,
2163 htlc_maximum_msat: OptionalField::Absent,
2165 fee_proportional_millionths: 0,
2166 excess_data: Vec::new()
2168 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2169 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2170 short_channel_id: 3,
2173 cltv_expiry_delta: (3 << 4) | 2,
2174 htlc_minimum_msat: 0,
2175 htlc_maximum_msat: OptionalField::Absent,
2177 fee_proportional_millionths: 0,
2178 excess_data: Vec::new()
2181 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
2182 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2183 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2184 short_channel_id: 4,
2187 cltv_expiry_delta: (4 << 4) | 1,
2188 htlc_minimum_msat: 0,
2189 htlc_maximum_msat: OptionalField::Absent,
2191 fee_proportional_millionths: 1000000,
2192 excess_data: Vec::new()
2194 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2195 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2196 short_channel_id: 4,
2199 cltv_expiry_delta: (4 << 4) | 2,
2200 htlc_minimum_msat: 0,
2201 htlc_maximum_msat: OptionalField::Absent,
2203 fee_proportional_millionths: 0,
2204 excess_data: Vec::new()
2207 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(13)), 13);
2208 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2209 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2210 short_channel_id: 13,
2213 cltv_expiry_delta: (13 << 4) | 1,
2214 htlc_minimum_msat: 0,
2215 htlc_maximum_msat: OptionalField::Absent,
2217 fee_proportional_millionths: 2000000,
2218 excess_data: Vec::new()
2220 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2221 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2222 short_channel_id: 13,
2225 cltv_expiry_delta: (13 << 4) | 2,
2226 htlc_minimum_msat: 0,
2227 htlc_maximum_msat: OptionalField::Absent,
2229 fee_proportional_millionths: 0,
2230 excess_data: Vec::new()
2233 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
2235 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
2236 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2237 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2238 short_channel_id: 6,
2241 cltv_expiry_delta: (6 << 4) | 1,
2242 htlc_minimum_msat: 0,
2243 htlc_maximum_msat: OptionalField::Absent,
2245 fee_proportional_millionths: 0,
2246 excess_data: Vec::new()
2248 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
2249 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2250 short_channel_id: 6,
2253 cltv_expiry_delta: (6 << 4) | 2,
2254 htlc_minimum_msat: 0,
2255 htlc_maximum_msat: OptionalField::Absent,
2257 fee_proportional_millionths: 0,
2258 excess_data: Vec::new(),
2261 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(11)), 11);
2262 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
2263 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2264 short_channel_id: 11,
2267 cltv_expiry_delta: (11 << 4) | 1,
2268 htlc_minimum_msat: 0,
2269 htlc_maximum_msat: OptionalField::Absent,
2271 fee_proportional_millionths: 0,
2272 excess_data: Vec::new()
2274 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
2275 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2276 short_channel_id: 11,
2279 cltv_expiry_delta: (11 << 4) | 2,
2280 htlc_minimum_msat: 0,
2281 htlc_maximum_msat: OptionalField::Absent,
2283 fee_proportional_millionths: 0,
2284 excess_data: Vec::new()
2287 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(5)), 0);
2289 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
2291 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[5], ChannelFeatures::from_le_bytes(id_to_feature_flags(7)), 7);
2292 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2293 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2294 short_channel_id: 7,
2297 cltv_expiry_delta: (7 << 4) | 1,
2298 htlc_minimum_msat: 0,
2299 htlc_maximum_msat: OptionalField::Absent,
2301 fee_proportional_millionths: 1000000,
2302 excess_data: Vec::new()
2304 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[5], UnsignedChannelUpdate {
2305 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2306 short_channel_id: 7,
2309 cltv_expiry_delta: (7 << 4) | 2,
2310 htlc_minimum_msat: 0,
2311 htlc_maximum_msat: OptionalField::Absent,
2313 fee_proportional_millionths: 0,
2314 excess_data: Vec::new()
2317 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[5], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
2319 (secp_ctx, network_graph, net_graph_msg_handler, chain_monitor, logger)
2323 fn simple_route_test() {
2324 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2325 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2326 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2327 let scorer = test_utils::TestScorer::with_penalty(0);
2328 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2329 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2331 // Simple route to 2 via 1
2333 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) {
2334 assert_eq!(err, "Cannot send a payment of 0 msat");
2335 } else { panic!(); }
2337 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2338 assert_eq!(route.paths[0].len(), 2);
2340 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2341 assert_eq!(route.paths[0][0].short_channel_id, 2);
2342 assert_eq!(route.paths[0][0].fee_msat, 100);
2343 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2344 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2345 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2347 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2348 assert_eq!(route.paths[0][1].short_channel_id, 4);
2349 assert_eq!(route.paths[0][1].fee_msat, 100);
2350 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2351 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2352 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2356 fn invalid_first_hop_test() {
2357 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2358 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2359 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2360 let scorer = test_utils::TestScorer::with_penalty(0);
2361 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2362 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2364 // Simple route to 2 via 1
2366 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
2368 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) =
2369 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) {
2370 assert_eq!(err, "First hop cannot have our_node_pubkey as a destination.");
2371 } else { panic!(); }
2373 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2374 assert_eq!(route.paths[0].len(), 2);
2378 fn htlc_minimum_test() {
2379 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2380 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2381 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2382 let scorer = test_utils::TestScorer::with_penalty(0);
2383 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2384 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2386 // Simple route to 2 via 1
2388 // Disable other paths
2389 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2390 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2391 short_channel_id: 12,
2393 flags: 2, // to disable
2394 cltv_expiry_delta: 0,
2395 htlc_minimum_msat: 0,
2396 htlc_maximum_msat: OptionalField::Absent,
2398 fee_proportional_millionths: 0,
2399 excess_data: Vec::new()
2401 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2402 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2403 short_channel_id: 3,
2405 flags: 2, // to disable
2406 cltv_expiry_delta: 0,
2407 htlc_minimum_msat: 0,
2408 htlc_maximum_msat: OptionalField::Absent,
2410 fee_proportional_millionths: 0,
2411 excess_data: Vec::new()
2413 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2414 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2415 short_channel_id: 13,
2417 flags: 2, // to disable
2418 cltv_expiry_delta: 0,
2419 htlc_minimum_msat: 0,
2420 htlc_maximum_msat: OptionalField::Absent,
2422 fee_proportional_millionths: 0,
2423 excess_data: Vec::new()
2425 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2426 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2427 short_channel_id: 6,
2429 flags: 2, // to disable
2430 cltv_expiry_delta: 0,
2431 htlc_minimum_msat: 0,
2432 htlc_maximum_msat: OptionalField::Absent,
2434 fee_proportional_millionths: 0,
2435 excess_data: Vec::new()
2437 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2438 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2439 short_channel_id: 7,
2441 flags: 2, // to disable
2442 cltv_expiry_delta: 0,
2443 htlc_minimum_msat: 0,
2444 htlc_maximum_msat: OptionalField::Absent,
2446 fee_proportional_millionths: 0,
2447 excess_data: Vec::new()
2450 // Check against amount_to_transfer_over_msat.
2451 // Set minimal HTLC of 200_000_000 msat.
2452 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2453 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2454 short_channel_id: 2,
2457 cltv_expiry_delta: 0,
2458 htlc_minimum_msat: 200_000_000,
2459 htlc_maximum_msat: OptionalField::Absent,
2461 fee_proportional_millionths: 0,
2462 excess_data: Vec::new()
2465 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
2467 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2468 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2469 short_channel_id: 4,
2472 cltv_expiry_delta: 0,
2473 htlc_minimum_msat: 0,
2474 htlc_maximum_msat: OptionalField::Present(199_999_999),
2476 fee_proportional_millionths: 0,
2477 excess_data: Vec::new()
2480 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
2481 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) {
2482 assert_eq!(err, "Failed to find a path to the given destination");
2483 } else { panic!(); }
2485 // Lift the restriction on the first hop.
2486 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2487 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2488 short_channel_id: 2,
2491 cltv_expiry_delta: 0,
2492 htlc_minimum_msat: 0,
2493 htlc_maximum_msat: OptionalField::Absent,
2495 fee_proportional_millionths: 0,
2496 excess_data: Vec::new()
2499 // A payment above the minimum should pass
2500 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();
2501 assert_eq!(route.paths[0].len(), 2);
2505 fn htlc_minimum_overpay_test() {
2506 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2507 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2508 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
2509 let scorer = test_utils::TestScorer::with_penalty(0);
2510 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2511 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2513 // A route to node#2 via two paths.
2514 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
2515 // Thus, they can't send 60 without overpaying.
2516 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2517 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2518 short_channel_id: 2,
2521 cltv_expiry_delta: 0,
2522 htlc_minimum_msat: 35_000,
2523 htlc_maximum_msat: OptionalField::Present(40_000),
2525 fee_proportional_millionths: 0,
2526 excess_data: Vec::new()
2528 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2529 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2530 short_channel_id: 12,
2533 cltv_expiry_delta: 0,
2534 htlc_minimum_msat: 35_000,
2535 htlc_maximum_msat: OptionalField::Present(40_000),
2537 fee_proportional_millionths: 0,
2538 excess_data: Vec::new()
2542 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2543 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2544 short_channel_id: 13,
2547 cltv_expiry_delta: 0,
2548 htlc_minimum_msat: 0,
2549 htlc_maximum_msat: OptionalField::Absent,
2551 fee_proportional_millionths: 0,
2552 excess_data: Vec::new()
2554 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2555 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2556 short_channel_id: 4,
2559 cltv_expiry_delta: 0,
2560 htlc_minimum_msat: 0,
2561 htlc_maximum_msat: OptionalField::Absent,
2563 fee_proportional_millionths: 0,
2564 excess_data: Vec::new()
2567 // Disable other paths
2568 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2569 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2570 short_channel_id: 1,
2572 flags: 2, // to disable
2573 cltv_expiry_delta: 0,
2574 htlc_minimum_msat: 0,
2575 htlc_maximum_msat: OptionalField::Absent,
2577 fee_proportional_millionths: 0,
2578 excess_data: Vec::new()
2581 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 60_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2582 // Overpay fees to hit htlc_minimum_msat.
2583 let overpaid_fees = route.paths[0][0].fee_msat + route.paths[1][0].fee_msat;
2584 // TODO: this could be better balanced to overpay 10k and not 15k.
2585 assert_eq!(overpaid_fees, 15_000);
2587 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
2588 // while taking even more fee to match htlc_minimum_msat.
2589 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2590 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2591 short_channel_id: 12,
2594 cltv_expiry_delta: 0,
2595 htlc_minimum_msat: 65_000,
2596 htlc_maximum_msat: OptionalField::Present(80_000),
2598 fee_proportional_millionths: 0,
2599 excess_data: Vec::new()
2601 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2602 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2603 short_channel_id: 2,
2606 cltv_expiry_delta: 0,
2607 htlc_minimum_msat: 0,
2608 htlc_maximum_msat: OptionalField::Absent,
2610 fee_proportional_millionths: 0,
2611 excess_data: Vec::new()
2613 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2614 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2615 short_channel_id: 4,
2618 cltv_expiry_delta: 0,
2619 htlc_minimum_msat: 0,
2620 htlc_maximum_msat: OptionalField::Absent,
2622 fee_proportional_millionths: 100_000,
2623 excess_data: Vec::new()
2626 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 60_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2627 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
2628 assert_eq!(route.paths.len(), 1);
2629 assert_eq!(route.paths[0][0].short_channel_id, 12);
2630 let fees = route.paths[0][0].fee_msat;
2631 assert_eq!(fees, 5_000);
2633 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2634 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
2635 // the other channel.
2636 assert_eq!(route.paths.len(), 1);
2637 assert_eq!(route.paths[0][0].short_channel_id, 2);
2638 let fees = route.paths[0][0].fee_msat;
2639 assert_eq!(fees, 5_000);
2643 fn disable_channels_test() {
2644 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2645 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2646 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2647 let scorer = test_utils::TestScorer::with_penalty(0);
2648 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2649 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2651 // // Disable channels 4 and 12 by flags=2
2652 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2653 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2654 short_channel_id: 4,
2656 flags: 2, // to disable
2657 cltv_expiry_delta: 0,
2658 htlc_minimum_msat: 0,
2659 htlc_maximum_msat: OptionalField::Absent,
2661 fee_proportional_millionths: 0,
2662 excess_data: Vec::new()
2664 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2665 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2666 short_channel_id: 12,
2668 flags: 2, // to disable
2669 cltv_expiry_delta: 0,
2670 htlc_minimum_msat: 0,
2671 htlc_maximum_msat: OptionalField::Absent,
2673 fee_proportional_millionths: 0,
2674 excess_data: Vec::new()
2677 // If all the channels require some features we don't understand, route should fail
2678 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) {
2679 assert_eq!(err, "Failed to find a path to the given destination");
2680 } else { panic!(); }
2682 // If we specify a channel to node7, that overrides our local channel view and that gets used
2683 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2684 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();
2685 assert_eq!(route.paths[0].len(), 2);
2687 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2688 assert_eq!(route.paths[0][0].short_channel_id, 42);
2689 assert_eq!(route.paths[0][0].fee_msat, 200);
2690 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2691 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2692 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2694 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2695 assert_eq!(route.paths[0][1].short_channel_id, 13);
2696 assert_eq!(route.paths[0][1].fee_msat, 100);
2697 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2698 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2699 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2703 fn disable_node_test() {
2704 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2705 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2706 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2707 let scorer = test_utils::TestScorer::with_penalty(0);
2708 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2709 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2711 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
2712 let mut unknown_features = NodeFeatures::known();
2713 unknown_features.set_unknown_feature_required();
2714 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
2715 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
2716 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
2718 // If all nodes require some features we don't understand, route should fail
2719 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) {
2720 assert_eq!(err, "Failed to find a path to the given destination");
2721 } else { panic!(); }
2723 // If we specify a channel to node7, that overrides our local channel view and that gets used
2724 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2725 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();
2726 assert_eq!(route.paths[0].len(), 2);
2728 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2729 assert_eq!(route.paths[0][0].short_channel_id, 42);
2730 assert_eq!(route.paths[0][0].fee_msat, 200);
2731 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2732 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2733 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2735 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2736 assert_eq!(route.paths[0][1].short_channel_id, 13);
2737 assert_eq!(route.paths[0][1].fee_msat, 100);
2738 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2739 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2740 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2742 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
2743 // naively) assume that the user checked the feature bits on the invoice, which override
2744 // the node_announcement.
2748 fn our_chans_test() {
2749 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2750 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2751 let scorer = test_utils::TestScorer::with_penalty(0);
2752 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2753 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2755 // Route to 1 via 2 and 3 because our channel to 1 is disabled
2756 let payment_params = PaymentParameters::from_node_id(nodes[0]);
2757 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2758 assert_eq!(route.paths[0].len(), 3);
2760 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2761 assert_eq!(route.paths[0][0].short_channel_id, 2);
2762 assert_eq!(route.paths[0][0].fee_msat, 200);
2763 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2764 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2765 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2767 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2768 assert_eq!(route.paths[0][1].short_channel_id, 4);
2769 assert_eq!(route.paths[0][1].fee_msat, 100);
2770 assert_eq!(route.paths[0][1].cltv_expiry_delta, (3 << 4) | 2);
2771 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2772 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2774 assert_eq!(route.paths[0][2].pubkey, nodes[0]);
2775 assert_eq!(route.paths[0][2].short_channel_id, 3);
2776 assert_eq!(route.paths[0][2].fee_msat, 100);
2777 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
2778 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(1));
2779 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(3));
2781 // If we specify a channel to node7, that overrides our local channel view and that gets used
2782 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2783 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2784 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();
2785 assert_eq!(route.paths[0].len(), 2);
2787 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2788 assert_eq!(route.paths[0][0].short_channel_id, 42);
2789 assert_eq!(route.paths[0][0].fee_msat, 200);
2790 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2791 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2792 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2794 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2795 assert_eq!(route.paths[0][1].short_channel_id, 13);
2796 assert_eq!(route.paths[0][1].fee_msat, 100);
2797 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2798 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2799 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2802 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2803 let zero_fees = RoutingFees {
2805 proportional_millionths: 0,
2807 vec![RouteHint(vec![RouteHintHop {
2808 src_node_id: nodes[3],
2809 short_channel_id: 8,
2811 cltv_expiry_delta: (8 << 4) | 1,
2812 htlc_minimum_msat: None,
2813 htlc_maximum_msat: None,
2815 ]), RouteHint(vec![RouteHintHop {
2816 src_node_id: nodes[4],
2817 short_channel_id: 9,
2820 proportional_millionths: 0,
2822 cltv_expiry_delta: (9 << 4) | 1,
2823 htlc_minimum_msat: None,
2824 htlc_maximum_msat: None,
2825 }]), RouteHint(vec![RouteHintHop {
2826 src_node_id: nodes[5],
2827 short_channel_id: 10,
2829 cltv_expiry_delta: (10 << 4) | 1,
2830 htlc_minimum_msat: None,
2831 htlc_maximum_msat: None,
2835 fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2836 let zero_fees = RoutingFees {
2838 proportional_millionths: 0,
2840 vec![RouteHint(vec![RouteHintHop {
2841 src_node_id: nodes[2],
2842 short_channel_id: 5,
2845 proportional_millionths: 0,
2847 cltv_expiry_delta: (5 << 4) | 1,
2848 htlc_minimum_msat: None,
2849 htlc_maximum_msat: None,
2851 src_node_id: nodes[3],
2852 short_channel_id: 8,
2854 cltv_expiry_delta: (8 << 4) | 1,
2855 htlc_minimum_msat: None,
2856 htlc_maximum_msat: None,
2858 ]), RouteHint(vec![RouteHintHop {
2859 src_node_id: nodes[4],
2860 short_channel_id: 9,
2863 proportional_millionths: 0,
2865 cltv_expiry_delta: (9 << 4) | 1,
2866 htlc_minimum_msat: None,
2867 htlc_maximum_msat: None,
2868 }]), RouteHint(vec![RouteHintHop {
2869 src_node_id: nodes[5],
2870 short_channel_id: 10,
2872 cltv_expiry_delta: (10 << 4) | 1,
2873 htlc_minimum_msat: None,
2874 htlc_maximum_msat: None,
2879 fn partial_route_hint_test() {
2880 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2881 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2882 let scorer = test_utils::TestScorer::with_penalty(0);
2883 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2884 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2886 // Simple test across 2, 3, 5, and 4 via a last_hop channel
2887 // Tests the behaviour when the RouteHint contains a suboptimal hop.
2888 // RouteHint may be partially used by the algo to build the best path.
2890 // First check that last hop can't have its source as the payee.
2891 let invalid_last_hop = RouteHint(vec![RouteHintHop {
2892 src_node_id: nodes[6],
2893 short_channel_id: 8,
2896 proportional_millionths: 0,
2898 cltv_expiry_delta: (8 << 4) | 1,
2899 htlc_minimum_msat: None,
2900 htlc_maximum_msat: None,
2903 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
2904 invalid_last_hops.push(invalid_last_hop);
2906 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(invalid_last_hops);
2907 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) {
2908 assert_eq!(err, "Route hint cannot have the payee as the source.");
2909 } else { panic!(); }
2912 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops_multi_private_channels(&nodes));
2913 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2914 assert_eq!(route.paths[0].len(), 5);
2916 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2917 assert_eq!(route.paths[0][0].short_channel_id, 2);
2918 assert_eq!(route.paths[0][0].fee_msat, 100);
2919 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2920 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2921 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2923 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2924 assert_eq!(route.paths[0][1].short_channel_id, 4);
2925 assert_eq!(route.paths[0][1].fee_msat, 0);
2926 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
2927 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2928 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2930 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2931 assert_eq!(route.paths[0][2].short_channel_id, 6);
2932 assert_eq!(route.paths[0][2].fee_msat, 0);
2933 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
2934 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2935 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2937 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2938 assert_eq!(route.paths[0][3].short_channel_id, 11);
2939 assert_eq!(route.paths[0][3].fee_msat, 0);
2940 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
2941 // If we have a peer in the node map, we'll use their features here since we don't have
2942 // a way of figuring out their features from the invoice:
2943 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2944 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2946 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2947 assert_eq!(route.paths[0][4].short_channel_id, 8);
2948 assert_eq!(route.paths[0][4].fee_msat, 100);
2949 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2950 assert_eq!(route.paths[0][4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
2951 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2954 fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2955 let zero_fees = RoutingFees {
2957 proportional_millionths: 0,
2959 vec![RouteHint(vec![RouteHintHop {
2960 src_node_id: nodes[3],
2961 short_channel_id: 8,
2963 cltv_expiry_delta: (8 << 4) | 1,
2964 htlc_minimum_msat: None,
2965 htlc_maximum_msat: None,
2966 }]), RouteHint(vec![
2968 ]), RouteHint(vec![RouteHintHop {
2969 src_node_id: nodes[5],
2970 short_channel_id: 10,
2972 cltv_expiry_delta: (10 << 4) | 1,
2973 htlc_minimum_msat: None,
2974 htlc_maximum_msat: None,
2979 fn ignores_empty_last_hops_test() {
2980 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2981 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2982 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(empty_last_hop(&nodes));
2983 let scorer = test_utils::TestScorer::with_penalty(0);
2984 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2985 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2987 // Test handling of an empty RouteHint passed in Invoice.
2989 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2990 assert_eq!(route.paths[0].len(), 5);
2992 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2993 assert_eq!(route.paths[0][0].short_channel_id, 2);
2994 assert_eq!(route.paths[0][0].fee_msat, 100);
2995 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2996 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2997 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2999 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3000 assert_eq!(route.paths[0][1].short_channel_id, 4);
3001 assert_eq!(route.paths[0][1].fee_msat, 0);
3002 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
3003 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3004 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3006 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
3007 assert_eq!(route.paths[0][2].short_channel_id, 6);
3008 assert_eq!(route.paths[0][2].fee_msat, 0);
3009 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
3010 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
3011 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
3013 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
3014 assert_eq!(route.paths[0][3].short_channel_id, 11);
3015 assert_eq!(route.paths[0][3].fee_msat, 0);
3016 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
3017 // If we have a peer in the node map, we'll use their features here since we don't have
3018 // a way of figuring out their features from the invoice:
3019 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
3020 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
3022 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
3023 assert_eq!(route.paths[0][4].short_channel_id, 8);
3024 assert_eq!(route.paths[0][4].fee_msat, 100);
3025 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
3026 assert_eq!(route.paths[0][4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3027 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3030 /// Builds a trivial last-hop hint that passes through the two nodes given, with channel 0xff00
3032 fn multi_hop_last_hops_hint(hint_hops: [PublicKey; 2]) -> Vec<RouteHint> {
3033 let zero_fees = RoutingFees {
3035 proportional_millionths: 0,
3037 vec![RouteHint(vec![RouteHintHop {
3038 src_node_id: hint_hops[0],
3039 short_channel_id: 0xff00,
3042 proportional_millionths: 0,
3044 cltv_expiry_delta: (5 << 4) | 1,
3045 htlc_minimum_msat: None,
3046 htlc_maximum_msat: None,
3048 src_node_id: hint_hops[1],
3049 short_channel_id: 0xff01,
3051 cltv_expiry_delta: (8 << 4) | 1,
3052 htlc_minimum_msat: None,
3053 htlc_maximum_msat: None,
3058 fn multi_hint_last_hops_test() {
3059 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3060 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3061 let last_hops = multi_hop_last_hops_hint([nodes[2], nodes[3]]);
3062 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops.clone());
3063 let scorer = test_utils::TestScorer::with_penalty(0);
3064 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3065 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3066 // Test through channels 2, 3, 0xff00, 0xff01.
3067 // Test shows that multiple hop hints are considered.
3069 // Disabling channels 6 & 7 by flags=2
3070 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3071 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3072 short_channel_id: 6,
3074 flags: 2, // to disable
3075 cltv_expiry_delta: 0,
3076 htlc_minimum_msat: 0,
3077 htlc_maximum_msat: OptionalField::Absent,
3079 fee_proportional_millionths: 0,
3080 excess_data: Vec::new()
3082 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3083 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3084 short_channel_id: 7,
3086 flags: 2, // to disable
3087 cltv_expiry_delta: 0,
3088 htlc_minimum_msat: 0,
3089 htlc_maximum_msat: OptionalField::Absent,
3091 fee_proportional_millionths: 0,
3092 excess_data: Vec::new()
3095 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3096 assert_eq!(route.paths[0].len(), 4);
3098 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3099 assert_eq!(route.paths[0][0].short_channel_id, 2);
3100 assert_eq!(route.paths[0][0].fee_msat, 200);
3101 assert_eq!(route.paths[0][0].cltv_expiry_delta, 65);
3102 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3103 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3105 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3106 assert_eq!(route.paths[0][1].short_channel_id, 4);
3107 assert_eq!(route.paths[0][1].fee_msat, 100);
3108 assert_eq!(route.paths[0][1].cltv_expiry_delta, 81);
3109 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3110 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3112 assert_eq!(route.paths[0][2].pubkey, nodes[3]);
3113 assert_eq!(route.paths[0][2].short_channel_id, last_hops[0].0[0].short_channel_id);
3114 assert_eq!(route.paths[0][2].fee_msat, 0);
3115 assert_eq!(route.paths[0][2].cltv_expiry_delta, 129);
3116 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(4));
3117 assert_eq!(route.paths[0][2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3119 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
3120 assert_eq!(route.paths[0][3].short_channel_id, last_hops[0].0[1].short_channel_id);
3121 assert_eq!(route.paths[0][3].fee_msat, 100);
3122 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
3123 assert_eq!(route.paths[0][3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3124 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3128 fn private_multi_hint_last_hops_test() {
3129 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3130 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3132 let non_announced_privkey = SecretKey::from_slice(&hex::decode(format!("{:02x}", 0xf0).repeat(32)).unwrap()[..]).unwrap();
3133 let non_announced_pubkey = PublicKey::from_secret_key(&secp_ctx, &non_announced_privkey);
3135 let last_hops = multi_hop_last_hops_hint([nodes[2], non_announced_pubkey]);
3136 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops.clone());
3137 let scorer = test_utils::TestScorer::with_penalty(0);
3138 // Test through channels 2, 3, 0xff00, 0xff01.
3139 // Test shows that multiple hop hints are considered.
3141 // Disabling channels 6 & 7 by flags=2
3142 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3143 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3144 short_channel_id: 6,
3146 flags: 2, // to disable
3147 cltv_expiry_delta: 0,
3148 htlc_minimum_msat: 0,
3149 htlc_maximum_msat: OptionalField::Absent,
3151 fee_proportional_millionths: 0,
3152 excess_data: Vec::new()
3154 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3155 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3156 short_channel_id: 7,
3158 flags: 2, // to disable
3159 cltv_expiry_delta: 0,
3160 htlc_minimum_msat: 0,
3161 htlc_maximum_msat: OptionalField::Absent,
3163 fee_proportional_millionths: 0,
3164 excess_data: Vec::new()
3167 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &[42u8; 32]).unwrap();
3168 assert_eq!(route.paths[0].len(), 4);
3170 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3171 assert_eq!(route.paths[0][0].short_channel_id, 2);
3172 assert_eq!(route.paths[0][0].fee_msat, 200);
3173 assert_eq!(route.paths[0][0].cltv_expiry_delta, 65);
3174 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3175 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3177 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3178 assert_eq!(route.paths[0][1].short_channel_id, 4);
3179 assert_eq!(route.paths[0][1].fee_msat, 100);
3180 assert_eq!(route.paths[0][1].cltv_expiry_delta, 81);
3181 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3182 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3184 assert_eq!(route.paths[0][2].pubkey, non_announced_pubkey);
3185 assert_eq!(route.paths[0][2].short_channel_id, last_hops[0].0[0].short_channel_id);
3186 assert_eq!(route.paths[0][2].fee_msat, 0);
3187 assert_eq!(route.paths[0][2].cltv_expiry_delta, 129);
3188 assert_eq!(route.paths[0][2].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3189 assert_eq!(route.paths[0][2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3191 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
3192 assert_eq!(route.paths[0][3].short_channel_id, last_hops[0].0[1].short_channel_id);
3193 assert_eq!(route.paths[0][3].fee_msat, 100);
3194 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
3195 assert_eq!(route.paths[0][3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3196 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3199 fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3200 let zero_fees = RoutingFees {
3202 proportional_millionths: 0,
3204 vec![RouteHint(vec![RouteHintHop {
3205 src_node_id: nodes[4],
3206 short_channel_id: 11,
3208 cltv_expiry_delta: (11 << 4) | 1,
3209 htlc_minimum_msat: None,
3210 htlc_maximum_msat: None,
3212 src_node_id: nodes[3],
3213 short_channel_id: 8,
3215 cltv_expiry_delta: (8 << 4) | 1,
3216 htlc_minimum_msat: None,
3217 htlc_maximum_msat: None,
3218 }]), RouteHint(vec![RouteHintHop {
3219 src_node_id: nodes[4],
3220 short_channel_id: 9,
3223 proportional_millionths: 0,
3225 cltv_expiry_delta: (9 << 4) | 1,
3226 htlc_minimum_msat: None,
3227 htlc_maximum_msat: None,
3228 }]), RouteHint(vec![RouteHintHop {
3229 src_node_id: nodes[5],
3230 short_channel_id: 10,
3232 cltv_expiry_delta: (10 << 4) | 1,
3233 htlc_minimum_msat: None,
3234 htlc_maximum_msat: None,
3239 fn last_hops_with_public_channel_test() {
3240 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3241 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3242 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops_with_public_channel(&nodes));
3243 let scorer = test_utils::TestScorer::with_penalty(0);
3244 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3245 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3246 // This test shows that public routes can be present in the invoice
3247 // which would be handled in the same manner.
3249 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3250 assert_eq!(route.paths[0].len(), 5);
3252 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3253 assert_eq!(route.paths[0][0].short_channel_id, 2);
3254 assert_eq!(route.paths[0][0].fee_msat, 100);
3255 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
3256 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3257 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3259 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3260 assert_eq!(route.paths[0][1].short_channel_id, 4);
3261 assert_eq!(route.paths[0][1].fee_msat, 0);
3262 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
3263 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3264 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3266 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
3267 assert_eq!(route.paths[0][2].short_channel_id, 6);
3268 assert_eq!(route.paths[0][2].fee_msat, 0);
3269 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
3270 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
3271 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
3273 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
3274 assert_eq!(route.paths[0][3].short_channel_id, 11);
3275 assert_eq!(route.paths[0][3].fee_msat, 0);
3276 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
3277 // If we have a peer in the node map, we'll use their features here since we don't have
3278 // a way of figuring out their features from the invoice:
3279 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
3280 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
3282 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
3283 assert_eq!(route.paths[0][4].short_channel_id, 8);
3284 assert_eq!(route.paths[0][4].fee_msat, 100);
3285 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
3286 assert_eq!(route.paths[0][4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3287 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3291 fn our_chans_last_hop_connect_test() {
3292 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3293 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3294 let scorer = test_utils::TestScorer::with_penalty(0);
3295 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3296 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3298 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
3299 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3300 let mut last_hops = last_hops(&nodes);
3301 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops.clone());
3302 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();
3303 assert_eq!(route.paths[0].len(), 2);
3305 assert_eq!(route.paths[0][0].pubkey, nodes[3]);
3306 assert_eq!(route.paths[0][0].short_channel_id, 42);
3307 assert_eq!(route.paths[0][0].fee_msat, 0);
3308 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 4) | 1);
3309 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
3310 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3312 assert_eq!(route.paths[0][1].pubkey, nodes[6]);
3313 assert_eq!(route.paths[0][1].short_channel_id, 8);
3314 assert_eq!(route.paths[0][1].fee_msat, 100);
3315 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
3316 assert_eq!(route.paths[0][1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3317 assert_eq!(route.paths[0][1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3319 last_hops[0].0[0].fees.base_msat = 1000;
3321 // Revert to via 6 as the fee on 8 goes up
3322 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops);
3323 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3324 assert_eq!(route.paths[0].len(), 4);
3326 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3327 assert_eq!(route.paths[0][0].short_channel_id, 2);
3328 assert_eq!(route.paths[0][0].fee_msat, 200); // fee increased as its % of value transferred across node
3329 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
3330 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3331 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3333 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3334 assert_eq!(route.paths[0][1].short_channel_id, 4);
3335 assert_eq!(route.paths[0][1].fee_msat, 100);
3336 assert_eq!(route.paths[0][1].cltv_expiry_delta, (7 << 4) | 1);
3337 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3338 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3340 assert_eq!(route.paths[0][2].pubkey, nodes[5]);
3341 assert_eq!(route.paths[0][2].short_channel_id, 7);
3342 assert_eq!(route.paths[0][2].fee_msat, 0);
3343 assert_eq!(route.paths[0][2].cltv_expiry_delta, (10 << 4) | 1);
3344 // If we have a peer in the node map, we'll use their features here since we don't have
3345 // a way of figuring out their features from the invoice:
3346 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
3347 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(7));
3349 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
3350 assert_eq!(route.paths[0][3].short_channel_id, 10);
3351 assert_eq!(route.paths[0][3].fee_msat, 100);
3352 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
3353 assert_eq!(route.paths[0][3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3354 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3356 // ...but still use 8 for larger payments as 6 has a variable feerate
3357 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 2000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3358 assert_eq!(route.paths[0].len(), 5);
3360 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3361 assert_eq!(route.paths[0][0].short_channel_id, 2);
3362 assert_eq!(route.paths[0][0].fee_msat, 3000);
3363 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
3364 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3365 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3367 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3368 assert_eq!(route.paths[0][1].short_channel_id, 4);
3369 assert_eq!(route.paths[0][1].fee_msat, 0);
3370 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
3371 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3372 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3374 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
3375 assert_eq!(route.paths[0][2].short_channel_id, 6);
3376 assert_eq!(route.paths[0][2].fee_msat, 0);
3377 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
3378 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
3379 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
3381 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
3382 assert_eq!(route.paths[0][3].short_channel_id, 11);
3383 assert_eq!(route.paths[0][3].fee_msat, 1000);
3384 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
3385 // If we have a peer in the node map, we'll use their features here since we don't have
3386 // a way of figuring out their features from the invoice:
3387 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
3388 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
3390 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
3391 assert_eq!(route.paths[0][4].short_channel_id, 8);
3392 assert_eq!(route.paths[0][4].fee_msat, 2000);
3393 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
3394 assert_eq!(route.paths[0][4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3395 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3398 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> {
3399 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
3400 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3401 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3403 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
3404 let last_hops = RouteHint(vec![RouteHintHop {
3405 src_node_id: middle_node_id,
3406 short_channel_id: 8,
3409 proportional_millionths: last_hop_fee_prop,
3411 cltv_expiry_delta: (8 << 4) | 1,
3412 htlc_minimum_msat: None,
3413 htlc_maximum_msat: last_hop_htlc_max,
3415 let payment_params = PaymentParameters::from_node_id(target_node_id).with_route_hints(vec![last_hops]);
3416 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
3417 let scorer = test_utils::TestScorer::with_penalty(0);
3418 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3419 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3420 get_route(&source_node_id, &payment_params, &NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash()).read_only(),
3421 Some(&our_chans.iter().collect::<Vec<_>>()), route_val, 42, &test_utils::TestLogger::new(), &scorer, &random_seed_bytes)
3425 fn unannounced_path_test() {
3426 // We should be able to send a payment to a destination without any help of a routing graph
3427 // if we have a channel with a common counterparty that appears in the first and last hop
3429 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
3431 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3432 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3433 assert_eq!(route.paths[0].len(), 2);
3435 assert_eq!(route.paths[0][0].pubkey, middle_node_id);
3436 assert_eq!(route.paths[0][0].short_channel_id, 42);
3437 assert_eq!(route.paths[0][0].fee_msat, 1001);
3438 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 4) | 1);
3439 assert_eq!(route.paths[0][0].node_features.le_flags(), &[0b11]);
3440 assert_eq!(route.paths[0][0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3442 assert_eq!(route.paths[0][1].pubkey, target_node_id);
3443 assert_eq!(route.paths[0][1].short_channel_id, 8);
3444 assert_eq!(route.paths[0][1].fee_msat, 1000000);
3445 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
3446 assert_eq!(route.paths[0][1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3447 assert_eq!(route.paths[0][1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3451 fn overflow_unannounced_path_test_liquidity_underflow() {
3452 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
3453 // the last-hop had a fee which overflowed a u64, we'd panic.
3454 // This was due to us adding the first-hop from us unconditionally, causing us to think
3455 // we'd built a path (as our node is in the "best candidate" set), when we had not.
3456 // In this test, we previously hit a subtraction underflow due to having less available
3457 // liquidity at the last hop than 0.
3458 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());
3462 fn overflow_unannounced_path_test_feerate_overflow() {
3463 // This tests for the same case as above, except instead of hitting a subtraction
3464 // underflow, we hit a case where the fee charged at a hop overflowed.
3465 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());
3469 fn available_amount_while_routing_test() {
3470 // Tests whether we choose the correct available channel amount while routing.
3472 let (secp_ctx, network_graph, mut net_graph_msg_handler, chain_monitor, logger) = build_graph();
3473 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3474 let scorer = test_utils::TestScorer::with_penalty(0);
3475 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3476 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3477 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
3479 // We will use a simple single-path route from
3480 // our node to node2 via node0: channels {1, 3}.
3482 // First disable all other paths.
3483 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3484 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3485 short_channel_id: 2,
3488 cltv_expiry_delta: 0,
3489 htlc_minimum_msat: 0,
3490 htlc_maximum_msat: OptionalField::Present(100_000),
3492 fee_proportional_millionths: 0,
3493 excess_data: Vec::new()
3495 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3496 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3497 short_channel_id: 12,
3500 cltv_expiry_delta: 0,
3501 htlc_minimum_msat: 0,
3502 htlc_maximum_msat: OptionalField::Present(100_000),
3504 fee_proportional_millionths: 0,
3505 excess_data: Vec::new()
3508 // Make the first channel (#1) very permissive,
3509 // and we will be testing all limits on the second channel.
3510 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3511 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3512 short_channel_id: 1,
3515 cltv_expiry_delta: 0,
3516 htlc_minimum_msat: 0,
3517 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3519 fee_proportional_millionths: 0,
3520 excess_data: Vec::new()
3523 // First, let's see if routing works if we have absolutely no idea about the available amount.
3524 // In this case, it should be set to 250_000 sats.
3525 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3526 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3527 short_channel_id: 3,
3530 cltv_expiry_delta: 0,
3531 htlc_minimum_msat: 0,
3532 htlc_maximum_msat: OptionalField::Absent,
3534 fee_proportional_millionths: 0,
3535 excess_data: Vec::new()
3539 // Attempt to route more than available results in a failure.
3540 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3541 &our_id, &payment_params, &network_graph.read_only(), None, 250_000_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3542 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3543 } else { panic!(); }
3547 // Now, attempt to route an exact amount we have should be fine.
3548 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();
3549 assert_eq!(route.paths.len(), 1);
3550 let path = route.paths.last().unwrap();
3551 assert_eq!(path.len(), 2);
3552 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3553 assert_eq!(path.last().unwrap().fee_msat, 250_000_000);
3556 // Check that setting next_outbound_htlc_limit_msat in first_hops limits the channels.
3557 // Disable channel #1 and use another first hop.
3558 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3559 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3560 short_channel_id: 1,
3563 cltv_expiry_delta: 0,
3564 htlc_minimum_msat: 0,
3565 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3567 fee_proportional_millionths: 0,
3568 excess_data: Vec::new()
3571 // Now, limit the first_hop by the next_outbound_htlc_limit_msat of 200_000 sats.
3572 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
3575 // Attempt to route more than available results in a failure.
3576 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3577 &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) {
3578 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3579 } else { panic!(); }
3583 // Now, attempt to route an exact amount we have should be fine.
3584 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();
3585 assert_eq!(route.paths.len(), 1);
3586 let path = route.paths.last().unwrap();
3587 assert_eq!(path.len(), 2);
3588 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3589 assert_eq!(path.last().unwrap().fee_msat, 200_000_000);
3592 // Enable channel #1 back.
3593 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3594 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3595 short_channel_id: 1,
3598 cltv_expiry_delta: 0,
3599 htlc_minimum_msat: 0,
3600 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3602 fee_proportional_millionths: 0,
3603 excess_data: Vec::new()
3607 // Now let's see if routing works if we know only htlc_maximum_msat.
3608 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3609 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3610 short_channel_id: 3,
3613 cltv_expiry_delta: 0,
3614 htlc_minimum_msat: 0,
3615 htlc_maximum_msat: OptionalField::Present(15_000),
3617 fee_proportional_millionths: 0,
3618 excess_data: Vec::new()
3622 // Attempt to route more than available results in a failure.
3623 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3624 &our_id, &payment_params, &network_graph.read_only(), None, 15_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3625 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3626 } else { panic!(); }
3630 // Now, attempt to route an exact amount we have should be fine.
3631 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 15_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3632 assert_eq!(route.paths.len(), 1);
3633 let path = route.paths.last().unwrap();
3634 assert_eq!(path.len(), 2);
3635 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3636 assert_eq!(path.last().unwrap().fee_msat, 15_000);
3639 // Now let's see if routing works if we know only capacity from the UTXO.
3641 // We can't change UTXO capacity on the fly, so we'll disable
3642 // the existing channel and add another one with the capacity we need.
3643 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3644 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3645 short_channel_id: 3,
3648 cltv_expiry_delta: 0,
3649 htlc_minimum_msat: 0,
3650 htlc_maximum_msat: OptionalField::Absent,
3652 fee_proportional_millionths: 0,
3653 excess_data: Vec::new()
3656 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
3657 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
3658 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
3659 .push_opcode(opcodes::all::OP_PUSHNUM_2)
3660 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
3662 *chain_monitor.utxo_ret.lock().unwrap() = Ok(TxOut { value: 15, script_pubkey: good_script.clone() });
3663 net_graph_msg_handler.add_chain_access(Some(chain_monitor));
3665 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
3666 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3667 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3668 short_channel_id: 333,
3671 cltv_expiry_delta: (3 << 4) | 1,
3672 htlc_minimum_msat: 0,
3673 htlc_maximum_msat: OptionalField::Absent,
3675 fee_proportional_millionths: 0,
3676 excess_data: Vec::new()
3678 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3679 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3680 short_channel_id: 333,
3683 cltv_expiry_delta: (3 << 4) | 2,
3684 htlc_minimum_msat: 0,
3685 htlc_maximum_msat: OptionalField::Absent,
3687 fee_proportional_millionths: 0,
3688 excess_data: Vec::new()
3692 // Attempt to route more than available results in a failure.
3693 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3694 &our_id, &payment_params, &network_graph.read_only(), None, 15_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3695 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3696 } else { panic!(); }
3700 // Now, attempt to route an exact amount we have should be fine.
3701 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 15_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3702 assert_eq!(route.paths.len(), 1);
3703 let path = route.paths.last().unwrap();
3704 assert_eq!(path.len(), 2);
3705 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3706 assert_eq!(path.last().unwrap().fee_msat, 15_000);
3709 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
3710 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3711 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3712 short_channel_id: 333,
3715 cltv_expiry_delta: 0,
3716 htlc_minimum_msat: 0,
3717 htlc_maximum_msat: OptionalField::Present(10_000),
3719 fee_proportional_millionths: 0,
3720 excess_data: Vec::new()
3724 // Attempt to route more than available results in a failure.
3725 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3726 &our_id, &payment_params, &network_graph.read_only(), None, 10_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3727 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3728 } else { panic!(); }
3732 // Now, attempt to route an exact amount we have should be fine.
3733 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 10_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3734 assert_eq!(route.paths.len(), 1);
3735 let path = route.paths.last().unwrap();
3736 assert_eq!(path.len(), 2);
3737 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3738 assert_eq!(path.last().unwrap().fee_msat, 10_000);
3743 fn available_liquidity_last_hop_test() {
3744 // Check that available liquidity properly limits the path even when only
3745 // one of the latter hops is limited.
3746 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3747 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3748 let scorer = test_utils::TestScorer::with_penalty(0);
3749 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3750 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3751 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
3753 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3754 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
3755 // Total capacity: 50 sats.
3757 // Disable other potential paths.
3758 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3759 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3760 short_channel_id: 2,
3763 cltv_expiry_delta: 0,
3764 htlc_minimum_msat: 0,
3765 htlc_maximum_msat: OptionalField::Present(100_000),
3767 fee_proportional_millionths: 0,
3768 excess_data: Vec::new()
3770 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3771 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3772 short_channel_id: 7,
3775 cltv_expiry_delta: 0,
3776 htlc_minimum_msat: 0,
3777 htlc_maximum_msat: OptionalField::Present(100_000),
3779 fee_proportional_millionths: 0,
3780 excess_data: Vec::new()
3785 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3786 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3787 short_channel_id: 12,
3790 cltv_expiry_delta: 0,
3791 htlc_minimum_msat: 0,
3792 htlc_maximum_msat: OptionalField::Present(100_000),
3794 fee_proportional_millionths: 0,
3795 excess_data: Vec::new()
3797 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3798 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3799 short_channel_id: 13,
3802 cltv_expiry_delta: 0,
3803 htlc_minimum_msat: 0,
3804 htlc_maximum_msat: OptionalField::Present(100_000),
3806 fee_proportional_millionths: 0,
3807 excess_data: Vec::new()
3810 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3811 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3812 short_channel_id: 6,
3815 cltv_expiry_delta: 0,
3816 htlc_minimum_msat: 0,
3817 htlc_maximum_msat: OptionalField::Present(50_000),
3819 fee_proportional_millionths: 0,
3820 excess_data: Vec::new()
3822 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3823 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3824 short_channel_id: 11,
3827 cltv_expiry_delta: 0,
3828 htlc_minimum_msat: 0,
3829 htlc_maximum_msat: OptionalField::Present(100_000),
3831 fee_proportional_millionths: 0,
3832 excess_data: Vec::new()
3835 // Attempt to route more than available results in a failure.
3836 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3837 &our_id, &payment_params, &network_graph.read_only(), None, 60_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3838 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3839 } else { panic!(); }
3843 // Now, attempt to route 49 sats (just a bit below the capacity).
3844 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 49_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3845 assert_eq!(route.paths.len(), 1);
3846 let mut total_amount_paid_msat = 0;
3847 for path in &route.paths {
3848 assert_eq!(path.len(), 4);
3849 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3850 total_amount_paid_msat += path.last().unwrap().fee_msat;
3852 assert_eq!(total_amount_paid_msat, 49_000);
3856 // Attempt to route an exact amount is also fine
3857 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3858 assert_eq!(route.paths.len(), 1);
3859 let mut total_amount_paid_msat = 0;
3860 for path in &route.paths {
3861 assert_eq!(path.len(), 4);
3862 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3863 total_amount_paid_msat += path.last().unwrap().fee_msat;
3865 assert_eq!(total_amount_paid_msat, 50_000);
3870 fn ignore_fee_first_hop_test() {
3871 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3872 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3873 let scorer = test_utils::TestScorer::with_penalty(0);
3874 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3875 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3876 let payment_params = PaymentParameters::from_node_id(nodes[2]);
3878 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3879 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3880 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3881 short_channel_id: 1,
3884 cltv_expiry_delta: 0,
3885 htlc_minimum_msat: 0,
3886 htlc_maximum_msat: OptionalField::Present(100_000),
3887 fee_base_msat: 1_000_000,
3888 fee_proportional_millionths: 0,
3889 excess_data: Vec::new()
3891 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3892 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3893 short_channel_id: 3,
3896 cltv_expiry_delta: 0,
3897 htlc_minimum_msat: 0,
3898 htlc_maximum_msat: OptionalField::Present(50_000),
3900 fee_proportional_millionths: 0,
3901 excess_data: Vec::new()
3905 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3906 assert_eq!(route.paths.len(), 1);
3907 let mut total_amount_paid_msat = 0;
3908 for path in &route.paths {
3909 assert_eq!(path.len(), 2);
3910 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3911 total_amount_paid_msat += path.last().unwrap().fee_msat;
3913 assert_eq!(total_amount_paid_msat, 50_000);
3918 fn simple_mpp_route_test() {
3919 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3920 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3921 let scorer = test_utils::TestScorer::with_penalty(0);
3922 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3923 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3924 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
3926 // We need a route consisting of 3 paths:
3927 // From our node to node2 via node0, node7, node1 (three paths one hop each).
3928 // To achieve this, the amount being transferred should be around
3929 // the total capacity of these 3 paths.
3931 // First, we set limits on these (previously unlimited) channels.
3932 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
3934 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3935 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3936 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3937 short_channel_id: 1,
3940 cltv_expiry_delta: 0,
3941 htlc_minimum_msat: 0,
3942 htlc_maximum_msat: OptionalField::Present(100_000),
3944 fee_proportional_millionths: 0,
3945 excess_data: Vec::new()
3947 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3948 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3949 short_channel_id: 3,
3952 cltv_expiry_delta: 0,
3953 htlc_minimum_msat: 0,
3954 htlc_maximum_msat: OptionalField::Present(50_000),
3956 fee_proportional_millionths: 0,
3957 excess_data: Vec::new()
3960 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
3961 // (total limit 60).
3962 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3963 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3964 short_channel_id: 12,
3967 cltv_expiry_delta: 0,
3968 htlc_minimum_msat: 0,
3969 htlc_maximum_msat: OptionalField::Present(60_000),
3971 fee_proportional_millionths: 0,
3972 excess_data: Vec::new()
3974 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3975 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3976 short_channel_id: 13,
3979 cltv_expiry_delta: 0,
3980 htlc_minimum_msat: 0,
3981 htlc_maximum_msat: OptionalField::Present(60_000),
3983 fee_proportional_millionths: 0,
3984 excess_data: Vec::new()
3987 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
3988 // (total capacity 180 sats).
3989 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3990 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3991 short_channel_id: 2,
3994 cltv_expiry_delta: 0,
3995 htlc_minimum_msat: 0,
3996 htlc_maximum_msat: OptionalField::Present(200_000),
3998 fee_proportional_millionths: 0,
3999 excess_data: Vec::new()
4001 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4002 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4003 short_channel_id: 4,
4006 cltv_expiry_delta: 0,
4007 htlc_minimum_msat: 0,
4008 htlc_maximum_msat: OptionalField::Present(180_000),
4010 fee_proportional_millionths: 0,
4011 excess_data: Vec::new()
4015 // Attempt to route more than available results in a failure.
4016 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4017 &our_id, &payment_params, &network_graph.read_only(), None, 300_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
4018 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4019 } else { panic!(); }
4023 // Now, attempt to route 250 sats (just a bit below the capacity).
4024 // Our algorithm should provide us with these 3 paths.
4025 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 250_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4026 assert_eq!(route.paths.len(), 3);
4027 let mut total_amount_paid_msat = 0;
4028 for path in &route.paths {
4029 assert_eq!(path.len(), 2);
4030 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4031 total_amount_paid_msat += path.last().unwrap().fee_msat;
4033 assert_eq!(total_amount_paid_msat, 250_000);
4037 // Attempt to route an exact amount is also fine
4038 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 290_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4039 assert_eq!(route.paths.len(), 3);
4040 let mut total_amount_paid_msat = 0;
4041 for path in &route.paths {
4042 assert_eq!(path.len(), 2);
4043 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4044 total_amount_paid_msat += path.last().unwrap().fee_msat;
4046 assert_eq!(total_amount_paid_msat, 290_000);
4051 fn long_mpp_route_test() {
4052 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4053 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4054 let scorer = test_utils::TestScorer::with_penalty(0);
4055 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4056 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4057 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
4059 // We need a route consisting of 3 paths:
4060 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
4061 // Note that these paths overlap (channels 5, 12, 13).
4062 // We will route 300 sats.
4063 // Each path will have 100 sats capacity, those channels which
4064 // are used twice will have 200 sats capacity.
4066 // Disable other potential paths.
4067 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4068 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4069 short_channel_id: 2,
4072 cltv_expiry_delta: 0,
4073 htlc_minimum_msat: 0,
4074 htlc_maximum_msat: OptionalField::Present(100_000),
4076 fee_proportional_millionths: 0,
4077 excess_data: Vec::new()
4079 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4080 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4081 short_channel_id: 7,
4084 cltv_expiry_delta: 0,
4085 htlc_minimum_msat: 0,
4086 htlc_maximum_msat: OptionalField::Present(100_000),
4088 fee_proportional_millionths: 0,
4089 excess_data: Vec::new()
4092 // Path via {node0, node2} is channels {1, 3, 5}.
4093 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4094 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4095 short_channel_id: 1,
4098 cltv_expiry_delta: 0,
4099 htlc_minimum_msat: 0,
4100 htlc_maximum_msat: OptionalField::Present(100_000),
4102 fee_proportional_millionths: 0,
4103 excess_data: Vec::new()
4105 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4106 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4107 short_channel_id: 3,
4110 cltv_expiry_delta: 0,
4111 htlc_minimum_msat: 0,
4112 htlc_maximum_msat: OptionalField::Present(100_000),
4114 fee_proportional_millionths: 0,
4115 excess_data: Vec::new()
4118 // Capacity of 200 sats because this channel will be used by 3rd path as well.
4119 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4120 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4121 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4122 short_channel_id: 5,
4125 cltv_expiry_delta: 0,
4126 htlc_minimum_msat: 0,
4127 htlc_maximum_msat: OptionalField::Present(200_000),
4129 fee_proportional_millionths: 0,
4130 excess_data: Vec::new()
4133 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4134 // Add 100 sats to the capacities of {12, 13}, because these channels
4135 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
4136 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4137 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4138 short_channel_id: 12,
4141 cltv_expiry_delta: 0,
4142 htlc_minimum_msat: 0,
4143 htlc_maximum_msat: OptionalField::Present(200_000),
4145 fee_proportional_millionths: 0,
4146 excess_data: Vec::new()
4148 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4149 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4150 short_channel_id: 13,
4153 cltv_expiry_delta: 0,
4154 htlc_minimum_msat: 0,
4155 htlc_maximum_msat: OptionalField::Present(200_000),
4157 fee_proportional_millionths: 0,
4158 excess_data: Vec::new()
4161 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4162 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4163 short_channel_id: 6,
4166 cltv_expiry_delta: 0,
4167 htlc_minimum_msat: 0,
4168 htlc_maximum_msat: OptionalField::Present(100_000),
4170 fee_proportional_millionths: 0,
4171 excess_data: Vec::new()
4173 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4174 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4175 short_channel_id: 11,
4178 cltv_expiry_delta: 0,
4179 htlc_minimum_msat: 0,
4180 htlc_maximum_msat: OptionalField::Present(100_000),
4182 fee_proportional_millionths: 0,
4183 excess_data: Vec::new()
4186 // Path via {node7, node2} is channels {12, 13, 5}.
4187 // We already limited them to 200 sats (they are used twice for 100 sats).
4188 // Nothing to do here.
4191 // Attempt to route more than available results in a failure.
4192 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4193 &our_id, &payment_params, &network_graph.read_only(), None, 350_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
4194 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4195 } else { panic!(); }
4199 // Now, attempt to route 300 sats (exact amount we can route).
4200 // Our algorithm should provide us with these 3 paths, 100 sats each.
4201 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 300_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4202 assert_eq!(route.paths.len(), 3);
4204 let mut total_amount_paid_msat = 0;
4205 for path in &route.paths {
4206 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
4207 total_amount_paid_msat += path.last().unwrap().fee_msat;
4209 assert_eq!(total_amount_paid_msat, 300_000);
4215 fn mpp_cheaper_route_test() {
4216 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4217 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4218 let scorer = test_utils::TestScorer::with_penalty(0);
4219 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4220 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4221 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
4223 // This test checks that if we have two cheaper paths and one more expensive path,
4224 // so that liquidity-wise any 2 of 3 combination is sufficient,
4225 // two cheaper paths will be taken.
4226 // These paths have equal available liquidity.
4228 // We need a combination of 3 paths:
4229 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
4230 // Note that these paths overlap (channels 5, 12, 13).
4231 // Each path will have 100 sats capacity, those channels which
4232 // are used twice will have 200 sats capacity.
4234 // Disable other potential paths.
4235 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4236 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4237 short_channel_id: 2,
4240 cltv_expiry_delta: 0,
4241 htlc_minimum_msat: 0,
4242 htlc_maximum_msat: OptionalField::Present(100_000),
4244 fee_proportional_millionths: 0,
4245 excess_data: Vec::new()
4247 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4248 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4249 short_channel_id: 7,
4252 cltv_expiry_delta: 0,
4253 htlc_minimum_msat: 0,
4254 htlc_maximum_msat: OptionalField::Present(100_000),
4256 fee_proportional_millionths: 0,
4257 excess_data: Vec::new()
4260 // Path via {node0, node2} is channels {1, 3, 5}.
4261 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4262 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4263 short_channel_id: 1,
4266 cltv_expiry_delta: 0,
4267 htlc_minimum_msat: 0,
4268 htlc_maximum_msat: OptionalField::Present(100_000),
4270 fee_proportional_millionths: 0,
4271 excess_data: Vec::new()
4273 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4274 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4275 short_channel_id: 3,
4278 cltv_expiry_delta: 0,
4279 htlc_minimum_msat: 0,
4280 htlc_maximum_msat: OptionalField::Present(100_000),
4282 fee_proportional_millionths: 0,
4283 excess_data: Vec::new()
4286 // Capacity of 200 sats because this channel will be used by 3rd path as well.
4287 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4288 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4289 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4290 short_channel_id: 5,
4293 cltv_expiry_delta: 0,
4294 htlc_minimum_msat: 0,
4295 htlc_maximum_msat: OptionalField::Present(200_000),
4297 fee_proportional_millionths: 0,
4298 excess_data: Vec::new()
4301 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4302 // Add 100 sats to the capacities of {12, 13}, because these channels
4303 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
4304 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4305 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4306 short_channel_id: 12,
4309 cltv_expiry_delta: 0,
4310 htlc_minimum_msat: 0,
4311 htlc_maximum_msat: OptionalField::Present(200_000),
4313 fee_proportional_millionths: 0,
4314 excess_data: Vec::new()
4316 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4317 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4318 short_channel_id: 13,
4321 cltv_expiry_delta: 0,
4322 htlc_minimum_msat: 0,
4323 htlc_maximum_msat: OptionalField::Present(200_000),
4325 fee_proportional_millionths: 0,
4326 excess_data: Vec::new()
4329 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4330 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4331 short_channel_id: 6,
4334 cltv_expiry_delta: 0,
4335 htlc_minimum_msat: 0,
4336 htlc_maximum_msat: OptionalField::Present(100_000),
4337 fee_base_msat: 1_000,
4338 fee_proportional_millionths: 0,
4339 excess_data: Vec::new()
4341 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4342 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4343 short_channel_id: 11,
4346 cltv_expiry_delta: 0,
4347 htlc_minimum_msat: 0,
4348 htlc_maximum_msat: OptionalField::Present(100_000),
4350 fee_proportional_millionths: 0,
4351 excess_data: Vec::new()
4354 // Path via {node7, node2} is channels {12, 13, 5}.
4355 // We already limited them to 200 sats (they are used twice for 100 sats).
4356 // Nothing to do here.
4359 // Now, attempt to route 180 sats.
4360 // Our algorithm should provide us with these 2 paths.
4361 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 180_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4362 assert_eq!(route.paths.len(), 2);
4364 let mut total_value_transferred_msat = 0;
4365 let mut total_paid_msat = 0;
4366 for path in &route.paths {
4367 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
4368 total_value_transferred_msat += path.last().unwrap().fee_msat;
4370 total_paid_msat += hop.fee_msat;
4373 // If we paid fee, this would be higher.
4374 assert_eq!(total_value_transferred_msat, 180_000);
4375 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
4376 assert_eq!(total_fees_paid, 0);
4381 fn fees_on_mpp_route_test() {
4382 // This test makes sure that MPP algorithm properly takes into account
4383 // fees charged on the channels, by making the fees impactful:
4384 // if the fee is not properly accounted for, the behavior is different.
4385 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4386 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4387 let scorer = test_utils::TestScorer::with_penalty(0);
4388 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4389 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4390 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
4392 // We need a route consisting of 2 paths:
4393 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
4394 // We will route 200 sats, Each path will have 100 sats capacity.
4396 // This test is not particularly stable: e.g.,
4397 // there's a way to route via {node0, node2, node4}.
4398 // It works while pathfinding is deterministic, but can be broken otherwise.
4399 // It's fine to ignore this concern for now.
4401 // Disable other potential paths.
4402 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4403 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4404 short_channel_id: 2,
4407 cltv_expiry_delta: 0,
4408 htlc_minimum_msat: 0,
4409 htlc_maximum_msat: OptionalField::Present(100_000),
4411 fee_proportional_millionths: 0,
4412 excess_data: Vec::new()
4415 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4416 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4417 short_channel_id: 7,
4420 cltv_expiry_delta: 0,
4421 htlc_minimum_msat: 0,
4422 htlc_maximum_msat: OptionalField::Present(100_000),
4424 fee_proportional_millionths: 0,
4425 excess_data: Vec::new()
4428 // Path via {node0, node2} is channels {1, 3, 5}.
4429 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4430 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4431 short_channel_id: 1,
4434 cltv_expiry_delta: 0,
4435 htlc_minimum_msat: 0,
4436 htlc_maximum_msat: OptionalField::Present(100_000),
4438 fee_proportional_millionths: 0,
4439 excess_data: Vec::new()
4441 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4442 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4443 short_channel_id: 3,
4446 cltv_expiry_delta: 0,
4447 htlc_minimum_msat: 0,
4448 htlc_maximum_msat: OptionalField::Present(100_000),
4450 fee_proportional_millionths: 0,
4451 excess_data: Vec::new()
4454 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4455 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4456 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4457 short_channel_id: 5,
4460 cltv_expiry_delta: 0,
4461 htlc_minimum_msat: 0,
4462 htlc_maximum_msat: OptionalField::Present(100_000),
4464 fee_proportional_millionths: 0,
4465 excess_data: Vec::new()
4468 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4469 // All channels should be 100 sats capacity. But for the fee experiment,
4470 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
4471 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
4472 // 100 sats (and pay 150 sats in fees for the use of channel 6),
4473 // so no matter how large are other channels,
4474 // the whole path will be limited by 100 sats with just these 2 conditions:
4475 // - channel 12 capacity is 250 sats
4476 // - fee for channel 6 is 150 sats
4477 // Let's test this by enforcing these 2 conditions and removing other limits.
4478 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4479 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4480 short_channel_id: 12,
4483 cltv_expiry_delta: 0,
4484 htlc_minimum_msat: 0,
4485 htlc_maximum_msat: OptionalField::Present(250_000),
4487 fee_proportional_millionths: 0,
4488 excess_data: Vec::new()
4490 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4491 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4492 short_channel_id: 13,
4495 cltv_expiry_delta: 0,
4496 htlc_minimum_msat: 0,
4497 htlc_maximum_msat: OptionalField::Absent,
4499 fee_proportional_millionths: 0,
4500 excess_data: Vec::new()
4503 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4504 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4505 short_channel_id: 6,
4508 cltv_expiry_delta: 0,
4509 htlc_minimum_msat: 0,
4510 htlc_maximum_msat: OptionalField::Absent,
4511 fee_base_msat: 150_000,
4512 fee_proportional_millionths: 0,
4513 excess_data: Vec::new()
4515 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4516 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4517 short_channel_id: 11,
4520 cltv_expiry_delta: 0,
4521 htlc_minimum_msat: 0,
4522 htlc_maximum_msat: OptionalField::Absent,
4524 fee_proportional_millionths: 0,
4525 excess_data: Vec::new()
4529 // Attempt to route more than available results in a failure.
4530 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4531 &our_id, &payment_params, &network_graph.read_only(), None, 210_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
4532 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4533 } else { panic!(); }
4537 // Now, attempt to route 200 sats (exact amount we can route).
4538 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 200_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4539 assert_eq!(route.paths.len(), 2);
4541 let mut total_amount_paid_msat = 0;
4542 for path in &route.paths {
4543 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
4544 total_amount_paid_msat += path.last().unwrap().fee_msat;
4546 assert_eq!(total_amount_paid_msat, 200_000);
4547 assert_eq!(route.get_total_fees(), 150_000);
4552 fn mpp_with_last_hops() {
4553 // Previously, if we tried to send an MPP payment to a destination which was only reachable
4554 // via a single last-hop route hint, we'd fail to route if we first collected routes
4555 // totaling close but not quite enough to fund the full payment.
4557 // This was because we considered last-hop hints to have exactly the sought payment amount
4558 // instead of the amount we were trying to collect, needlessly limiting our path searching
4559 // at the very first hop.
4561 // Specifically, this interacted with our "all paths must fund at least 5% of total target"
4562 // criterion to cause us to refuse all routes at the last hop hint which would be considered
4563 // to only have the remaining to-collect amount in available liquidity.
4565 // This bug appeared in production in some specific channel configurations.
4566 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4567 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4568 let scorer = test_utils::TestScorer::with_penalty(0);
4569 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4570 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4571 let payment_params = PaymentParameters::from_node_id(PublicKey::from_slice(&[02; 33]).unwrap()).with_features(InvoiceFeatures::known())
4572 .with_route_hints(vec![RouteHint(vec![RouteHintHop {
4573 src_node_id: nodes[2],
4574 short_channel_id: 42,
4575 fees: RoutingFees { base_msat: 0, proportional_millionths: 0 },
4576 cltv_expiry_delta: 42,
4577 htlc_minimum_msat: None,
4578 htlc_maximum_msat: None,
4581 // Keep only two paths from us to nodes[2], both with a 99sat HTLC maximum, with one with
4582 // no fee and one with a 1msat fee. Previously, trying to route 100 sats to nodes[2] here
4583 // would first use the no-fee route and then fail to find a path along the second route as
4584 // we think we can only send up to 1 additional sat over the last-hop but refuse to as its
4585 // under 5% of our payment amount.
4586 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4587 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4588 short_channel_id: 1,
4591 cltv_expiry_delta: (5 << 4) | 5,
4592 htlc_minimum_msat: 0,
4593 htlc_maximum_msat: OptionalField::Present(99_000),
4594 fee_base_msat: u32::max_value(),
4595 fee_proportional_millionths: u32::max_value(),
4596 excess_data: Vec::new()
4598 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4599 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4600 short_channel_id: 2,
4603 cltv_expiry_delta: (5 << 4) | 3,
4604 htlc_minimum_msat: 0,
4605 htlc_maximum_msat: OptionalField::Present(99_000),
4606 fee_base_msat: u32::max_value(),
4607 fee_proportional_millionths: u32::max_value(),
4608 excess_data: Vec::new()
4610 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4611 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4612 short_channel_id: 4,
4615 cltv_expiry_delta: (4 << 4) | 1,
4616 htlc_minimum_msat: 0,
4617 htlc_maximum_msat: OptionalField::Absent,
4619 fee_proportional_millionths: 0,
4620 excess_data: Vec::new()
4622 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4623 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4624 short_channel_id: 13,
4626 flags: 0|2, // Channel disabled
4627 cltv_expiry_delta: (13 << 4) | 1,
4628 htlc_minimum_msat: 0,
4629 htlc_maximum_msat: OptionalField::Absent,
4631 fee_proportional_millionths: 2000000,
4632 excess_data: Vec::new()
4635 // Get a route for 100 sats and check that we found the MPP route no problem and didn't
4637 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4638 assert_eq!(route.paths.len(), 2);
4639 // Paths are somewhat randomly ordered, but:
4640 // * the first is channel 2 (1 msat fee) -> channel 4 -> channel 42
4641 // * the second is channel 1 (0 fee, but 99 sat maximum) -> channel 3 -> channel 42
4642 assert_eq!(route.paths[0][0].short_channel_id, 2);
4643 assert_eq!(route.paths[0][0].fee_msat, 1);
4644 assert_eq!(route.paths[0][2].fee_msat, 1_000);
4645 assert_eq!(route.paths[1][0].short_channel_id, 1);
4646 assert_eq!(route.paths[1][0].fee_msat, 0);
4647 assert_eq!(route.paths[1][2].fee_msat, 99_000);
4648 assert_eq!(route.get_total_fees(), 1);
4649 assert_eq!(route.get_total_amount(), 100_000);
4653 fn drop_lowest_channel_mpp_route_test() {
4654 // This test checks that low-capacity channel is dropped when after
4655 // path finding we realize that we found more capacity than we need.
4656 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4657 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4658 let scorer = test_utils::TestScorer::with_penalty(0);
4659 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4660 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4661 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
4663 // We need a route consisting of 3 paths:
4664 // From our node to node2 via node0, node7, node1 (three paths one hop each).
4666 // The first and the second paths should be sufficient, but the third should be
4667 // cheaper, so that we select it but drop later.
4669 // First, we set limits on these (previously unlimited) channels.
4670 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
4672 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
4673 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4674 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4675 short_channel_id: 1,
4678 cltv_expiry_delta: 0,
4679 htlc_minimum_msat: 0,
4680 htlc_maximum_msat: OptionalField::Present(100_000),
4682 fee_proportional_millionths: 0,
4683 excess_data: Vec::new()
4685 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4686 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4687 short_channel_id: 3,
4690 cltv_expiry_delta: 0,
4691 htlc_minimum_msat: 0,
4692 htlc_maximum_msat: OptionalField::Present(50_000),
4694 fee_proportional_millionths: 0,
4695 excess_data: Vec::new()
4698 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
4699 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4700 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4701 short_channel_id: 12,
4704 cltv_expiry_delta: 0,
4705 htlc_minimum_msat: 0,
4706 htlc_maximum_msat: OptionalField::Present(60_000),
4708 fee_proportional_millionths: 0,
4709 excess_data: Vec::new()
4711 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4712 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4713 short_channel_id: 13,
4716 cltv_expiry_delta: 0,
4717 htlc_minimum_msat: 0,
4718 htlc_maximum_msat: OptionalField::Present(60_000),
4720 fee_proportional_millionths: 0,
4721 excess_data: Vec::new()
4724 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
4725 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4726 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4727 short_channel_id: 2,
4730 cltv_expiry_delta: 0,
4731 htlc_minimum_msat: 0,
4732 htlc_maximum_msat: OptionalField::Present(20_000),
4734 fee_proportional_millionths: 0,
4735 excess_data: Vec::new()
4737 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4738 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4739 short_channel_id: 4,
4742 cltv_expiry_delta: 0,
4743 htlc_minimum_msat: 0,
4744 htlc_maximum_msat: OptionalField::Present(20_000),
4746 fee_proportional_millionths: 0,
4747 excess_data: Vec::new()
4751 // Attempt to route more than available results in a failure.
4752 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4753 &our_id, &payment_params, &network_graph.read_only(), None, 150_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
4754 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4755 } else { panic!(); }
4759 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
4760 // Our algorithm should provide us with these 3 paths.
4761 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 125_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4762 assert_eq!(route.paths.len(), 3);
4763 let mut total_amount_paid_msat = 0;
4764 for path in &route.paths {
4765 assert_eq!(path.len(), 2);
4766 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4767 total_amount_paid_msat += path.last().unwrap().fee_msat;
4769 assert_eq!(total_amount_paid_msat, 125_000);
4773 // Attempt to route without the last small cheap channel
4774 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4775 assert_eq!(route.paths.len(), 2);
4776 let mut total_amount_paid_msat = 0;
4777 for path in &route.paths {
4778 assert_eq!(path.len(), 2);
4779 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4780 total_amount_paid_msat += path.last().unwrap().fee_msat;
4782 assert_eq!(total_amount_paid_msat, 90_000);
4787 fn min_criteria_consistency() {
4788 // Test that we don't use an inconsistent metric between updating and walking nodes during
4789 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
4790 // was updated with a different criterion from the heap sorting, resulting in loops in
4791 // calculated paths. We test for that specific case here.
4793 // We construct a network that looks like this:
4795 // node2 -1(3)2- node3
4799 // node1 -1(5)2- node4 -1(1)2- node6
4805 // We create a loop on the side of our real path - our destination is node 6, with a
4806 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
4807 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
4808 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
4809 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
4810 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
4811 // "previous hop" being set to node 3, creating a loop in the path.
4812 let secp_ctx = Secp256k1::new();
4813 let logger = Arc::new(test_utils::TestLogger::new());
4814 let network = Arc::new(NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash()));
4815 let net_graph_msg_handler = NetGraphMsgHandler::new(Arc::clone(&network), None, Arc::clone(&logger));
4816 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4817 let scorer = test_utils::TestScorer::with_penalty(0);
4818 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4819 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4820 let payment_params = PaymentParameters::from_node_id(nodes[6]);
4822 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
4823 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4824 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4825 short_channel_id: 6,
4828 cltv_expiry_delta: (6 << 4) | 0,
4829 htlc_minimum_msat: 0,
4830 htlc_maximum_msat: OptionalField::Absent,
4832 fee_proportional_millionths: 0,
4833 excess_data: Vec::new()
4835 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
4837 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4838 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4839 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4840 short_channel_id: 5,
4843 cltv_expiry_delta: (5 << 4) | 0,
4844 htlc_minimum_msat: 0,
4845 htlc_maximum_msat: OptionalField::Absent,
4847 fee_proportional_millionths: 0,
4848 excess_data: Vec::new()
4850 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
4852 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
4853 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4854 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4855 short_channel_id: 4,
4858 cltv_expiry_delta: (4 << 4) | 0,
4859 htlc_minimum_msat: 0,
4860 htlc_maximum_msat: OptionalField::Absent,
4862 fee_proportional_millionths: 0,
4863 excess_data: Vec::new()
4865 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
4867 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
4868 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
4869 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4870 short_channel_id: 3,
4873 cltv_expiry_delta: (3 << 4) | 0,
4874 htlc_minimum_msat: 0,
4875 htlc_maximum_msat: OptionalField::Absent,
4877 fee_proportional_millionths: 0,
4878 excess_data: Vec::new()
4880 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
4882 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
4883 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4884 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4885 short_channel_id: 2,
4888 cltv_expiry_delta: (2 << 4) | 0,
4889 htlc_minimum_msat: 0,
4890 htlc_maximum_msat: OptionalField::Absent,
4892 fee_proportional_millionths: 0,
4893 excess_data: Vec::new()
4896 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
4897 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4898 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4899 short_channel_id: 1,
4902 cltv_expiry_delta: (1 << 4) | 0,
4903 htlc_minimum_msat: 100,
4904 htlc_maximum_msat: OptionalField::Absent,
4906 fee_proportional_millionths: 0,
4907 excess_data: Vec::new()
4909 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
4912 // Now ensure the route flows simply over nodes 1 and 4 to 6.
4913 let route = get_route(&our_id, &payment_params, &network.read_only(), None, 10_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4914 assert_eq!(route.paths.len(), 1);
4915 assert_eq!(route.paths[0].len(), 3);
4917 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
4918 assert_eq!(route.paths[0][0].short_channel_id, 6);
4919 assert_eq!(route.paths[0][0].fee_msat, 100);
4920 assert_eq!(route.paths[0][0].cltv_expiry_delta, (5 << 4) | 0);
4921 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(1));
4922 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(6));
4924 assert_eq!(route.paths[0][1].pubkey, nodes[4]);
4925 assert_eq!(route.paths[0][1].short_channel_id, 5);
4926 assert_eq!(route.paths[0][1].fee_msat, 0);
4927 assert_eq!(route.paths[0][1].cltv_expiry_delta, (1 << 4) | 0);
4928 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(4));
4929 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(5));
4931 assert_eq!(route.paths[0][2].pubkey, nodes[6]);
4932 assert_eq!(route.paths[0][2].short_channel_id, 1);
4933 assert_eq!(route.paths[0][2].fee_msat, 10_000);
4934 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
4935 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
4936 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(1));
4942 fn exact_fee_liquidity_limit() {
4943 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
4944 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
4945 // we calculated fees on a higher value, resulting in us ignoring such paths.
4946 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4947 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
4948 let scorer = test_utils::TestScorer::with_penalty(0);
4949 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4950 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4951 let payment_params = PaymentParameters::from_node_id(nodes[2]);
4953 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
4955 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4956 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4957 short_channel_id: 2,
4960 cltv_expiry_delta: 0,
4961 htlc_minimum_msat: 0,
4962 htlc_maximum_msat: OptionalField::Present(85_000),
4964 fee_proportional_millionths: 0,
4965 excess_data: Vec::new()
4968 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4969 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4970 short_channel_id: 12,
4973 cltv_expiry_delta: (4 << 4) | 1,
4974 htlc_minimum_msat: 0,
4975 htlc_maximum_msat: OptionalField::Present(270_000),
4977 fee_proportional_millionths: 1000000,
4978 excess_data: Vec::new()
4982 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
4983 // 200% fee charged channel 13 in the 1-to-2 direction.
4984 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4985 assert_eq!(route.paths.len(), 1);
4986 assert_eq!(route.paths[0].len(), 2);
4988 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
4989 assert_eq!(route.paths[0][0].short_channel_id, 12);
4990 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
4991 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
4992 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
4993 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
4995 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
4996 assert_eq!(route.paths[0][1].short_channel_id, 13);
4997 assert_eq!(route.paths[0][1].fee_msat, 90_000);
4998 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
4999 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
5000 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
5005 fn htlc_max_reduction_below_min() {
5006 // Test that if, while walking the graph, we reduce the value being sent to meet an
5007 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
5008 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
5009 // resulting in us thinking there is no possible path, even if other paths exist.
5010 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
5011 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5012 let scorer = test_utils::TestScorer::with_penalty(0);
5013 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5014 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5015 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
5017 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
5018 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
5019 // then try to send 90_000.
5020 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5021 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5022 short_channel_id: 2,
5025 cltv_expiry_delta: 0,
5026 htlc_minimum_msat: 0,
5027 htlc_maximum_msat: OptionalField::Present(80_000),
5029 fee_proportional_millionths: 0,
5030 excess_data: Vec::new()
5032 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5033 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5034 short_channel_id: 4,
5037 cltv_expiry_delta: (4 << 4) | 1,
5038 htlc_minimum_msat: 90_000,
5039 htlc_maximum_msat: OptionalField::Absent,
5041 fee_proportional_millionths: 0,
5042 excess_data: Vec::new()
5046 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
5047 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
5048 // expensive) channels 12-13 path.
5049 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5050 assert_eq!(route.paths.len(), 1);
5051 assert_eq!(route.paths[0].len(), 2);
5053 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
5054 assert_eq!(route.paths[0][0].short_channel_id, 12);
5055 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
5056 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
5057 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
5058 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
5060 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
5061 assert_eq!(route.paths[0][1].short_channel_id, 13);
5062 assert_eq!(route.paths[0][1].fee_msat, 90_000);
5063 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
5064 assert_eq!(route.paths[0][1].node_features.le_flags(), InvoiceFeatures::known().le_flags());
5065 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
5070 fn multiple_direct_first_hops() {
5071 // Previously we'd only ever considered one first hop path per counterparty.
5072 // However, as we don't restrict users to one channel per peer, we really need to support
5073 // looking at all first hop paths.
5074 // Here we test that we do not ignore all-but-the-last first hop paths per counterparty (as
5075 // we used to do by overwriting the `first_hop_targets` hashmap entry) and that we can MPP
5076 // route over multiple channels with the same first hop.
5077 let secp_ctx = Secp256k1::new();
5078 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5079 let logger = Arc::new(test_utils::TestLogger::new());
5080 let network_graph = NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash());
5081 let scorer = test_utils::TestScorer::with_penalty(0);
5082 let payment_params = PaymentParameters::from_node_id(nodes[0]).with_features(InvoiceFeatures::known());
5083 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5084 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5087 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
5088 &get_channel_details(Some(3), nodes[0], InitFeatures::known(), 200_000),
5089 &get_channel_details(Some(2), nodes[0], InitFeatures::known(), 10_000),
5090 ]), 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5091 assert_eq!(route.paths.len(), 1);
5092 assert_eq!(route.paths[0].len(), 1);
5094 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
5095 assert_eq!(route.paths[0][0].short_channel_id, 3);
5096 assert_eq!(route.paths[0][0].fee_msat, 100_000);
5099 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
5100 &get_channel_details(Some(3), nodes[0], InitFeatures::known(), 50_000),
5101 &get_channel_details(Some(2), nodes[0], InitFeatures::known(), 50_000),
5102 ]), 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5103 assert_eq!(route.paths.len(), 2);
5104 assert_eq!(route.paths[0].len(), 1);
5105 assert_eq!(route.paths[1].len(), 1);
5107 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
5108 assert_eq!(route.paths[0][0].short_channel_id, 3);
5109 assert_eq!(route.paths[0][0].fee_msat, 50_000);
5111 assert_eq!(route.paths[1][0].pubkey, nodes[0]);
5112 assert_eq!(route.paths[1][0].short_channel_id, 2);
5113 assert_eq!(route.paths[1][0].fee_msat, 50_000);
5117 // If we have a bunch of outbound channels to the same node, where most are not
5118 // sufficient to pay the full payment, but one is, we should default to just using the
5119 // one single channel that has sufficient balance, avoiding MPP.
5121 // If we have several options above the 3xpayment value threshold, we should pick the
5122 // smallest of them, avoiding further fragmenting our available outbound balance to
5124 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
5125 &get_channel_details(Some(2), nodes[0], InitFeatures::known(), 50_000),
5126 &get_channel_details(Some(3), nodes[0], InitFeatures::known(), 50_000),
5127 &get_channel_details(Some(5), nodes[0], InitFeatures::known(), 50_000),
5128 &get_channel_details(Some(6), nodes[0], InitFeatures::known(), 300_000),
5129 &get_channel_details(Some(7), nodes[0], InitFeatures::known(), 50_000),
5130 &get_channel_details(Some(8), nodes[0], InitFeatures::known(), 50_000),
5131 &get_channel_details(Some(9), nodes[0], InitFeatures::known(), 50_000),
5132 &get_channel_details(Some(4), nodes[0], InitFeatures::known(), 1_000_000),
5133 ]), 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5134 assert_eq!(route.paths.len(), 1);
5135 assert_eq!(route.paths[0].len(), 1);
5137 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
5138 assert_eq!(route.paths[0][0].short_channel_id, 6);
5139 assert_eq!(route.paths[0][0].fee_msat, 100_000);
5144 fn prefers_shorter_route_with_higher_fees() {
5145 let (secp_ctx, network_graph, _, _, logger) = build_graph();
5146 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5147 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
5149 // Without penalizing each hop 100 msats, a longer path with lower fees is chosen.
5150 let scorer = test_utils::TestScorer::with_penalty(0);
5151 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5152 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5153 let route = get_route(
5154 &our_id, &payment_params, &network_graph.read_only(), None, 100, 42,
5155 Arc::clone(&logger), &scorer, &random_seed_bytes
5157 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5159 assert_eq!(route.get_total_fees(), 100);
5160 assert_eq!(route.get_total_amount(), 100);
5161 assert_eq!(path, vec![2, 4, 6, 11, 8]);
5163 // Applying a 100 msat penalty to each hop results in taking channels 7 and 10 to nodes[6]
5164 // from nodes[2] rather than channel 6, 11, and 8, even though the longer path is cheaper.
5165 let scorer = test_utils::TestScorer::with_penalty(100);
5166 let route = get_route(
5167 &our_id, &payment_params, &network_graph.read_only(), None, 100, 42,
5168 Arc::clone(&logger), &scorer, &random_seed_bytes
5170 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5172 assert_eq!(route.get_total_fees(), 300);
5173 assert_eq!(route.get_total_amount(), 100);
5174 assert_eq!(path, vec![2, 4, 7, 10]);
5177 struct BadChannelScorer {
5178 short_channel_id: u64,
5182 impl Writeable for BadChannelScorer {
5183 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), ::io::Error> { unimplemented!() }
5185 impl Score for BadChannelScorer {
5186 fn channel_penalty_msat(&self, short_channel_id: u64, _: &NodeId, _: &NodeId, _: ChannelUsage) -> u64 {
5187 if short_channel_id == self.short_channel_id { u64::max_value() } else { 0 }
5190 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
5191 fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
5194 struct BadNodeScorer {
5199 impl Writeable for BadNodeScorer {
5200 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), ::io::Error> { unimplemented!() }
5203 impl Score for BadNodeScorer {
5204 fn channel_penalty_msat(&self, _: u64, _: &NodeId, target: &NodeId, _: ChannelUsage) -> u64 {
5205 if *target == self.node_id { u64::max_value() } else { 0 }
5208 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
5209 fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
5213 fn avoids_routing_through_bad_channels_and_nodes() {
5214 let (secp_ctx, network, _, _, logger) = build_graph();
5215 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5216 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
5217 let network_graph = network.read_only();
5219 // A path to nodes[6] exists when no penalties are applied to any channel.
5220 let scorer = test_utils::TestScorer::with_penalty(0);
5221 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5222 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5223 let route = get_route(
5224 &our_id, &payment_params, &network_graph, None, 100, 42,
5225 Arc::clone(&logger), &scorer, &random_seed_bytes
5227 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5229 assert_eq!(route.get_total_fees(), 100);
5230 assert_eq!(route.get_total_amount(), 100);
5231 assert_eq!(path, vec![2, 4, 6, 11, 8]);
5233 // A different path to nodes[6] exists if channel 6 cannot be routed over.
5234 let scorer = BadChannelScorer { short_channel_id: 6 };
5235 let route = get_route(
5236 &our_id, &payment_params, &network_graph, None, 100, 42,
5237 Arc::clone(&logger), &scorer, &random_seed_bytes
5239 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5241 assert_eq!(route.get_total_fees(), 300);
5242 assert_eq!(route.get_total_amount(), 100);
5243 assert_eq!(path, vec![2, 4, 7, 10]);
5245 // A path to nodes[6] does not exist if nodes[2] cannot be routed through.
5246 let scorer = BadNodeScorer { node_id: NodeId::from_pubkey(&nodes[2]) };
5248 &our_id, &payment_params, &network_graph, None, 100, 42,
5249 Arc::clone(&logger), &scorer, &random_seed_bytes
5251 Err(LightningError { err, .. } ) => {
5252 assert_eq!(err, "Failed to find a path to the given destination");
5254 Ok(_) => panic!("Expected error"),
5259 fn total_fees_single_path() {
5263 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5264 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5265 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5268 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5269 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5270 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5273 pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
5274 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5275 short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0
5278 payment_params: None,
5281 assert_eq!(route.get_total_fees(), 250);
5282 assert_eq!(route.get_total_amount(), 225);
5286 fn total_fees_multi_path() {
5290 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5291 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5292 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5295 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5296 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5297 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5301 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5302 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5303 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5306 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5307 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5308 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5311 payment_params: None,
5314 assert_eq!(route.get_total_fees(), 200);
5315 assert_eq!(route.get_total_amount(), 300);
5319 fn total_empty_route_no_panic() {
5320 // In an earlier version of `Route::get_total_fees` and `Route::get_total_amount`, they
5321 // would both panic if the route was completely empty. We test to ensure they return 0
5322 // here, even though its somewhat nonsensical as a route.
5323 let route = Route { paths: Vec::new(), payment_params: None };
5325 assert_eq!(route.get_total_fees(), 0);
5326 assert_eq!(route.get_total_amount(), 0);
5330 fn limits_total_cltv_delta() {
5331 let (secp_ctx, network, _, _, logger) = build_graph();
5332 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5333 let network_graph = network.read_only();
5335 let scorer = test_utils::TestScorer::with_penalty(0);
5337 // Make sure that generally there is at least one route available
5338 let feasible_max_total_cltv_delta = 1008;
5339 let feasible_payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes))
5340 .with_max_total_cltv_expiry_delta(feasible_max_total_cltv_delta);
5341 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5342 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5343 let route = get_route(&our_id, &feasible_payment_params, &network_graph, None, 100, 0, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5344 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5345 assert_ne!(path.len(), 0);
5347 // But not if we exclude all paths on the basis of their accumulated CLTV delta
5348 let fail_max_total_cltv_delta = 23;
5349 let fail_payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes))
5350 .with_max_total_cltv_expiry_delta(fail_max_total_cltv_delta);
5351 match get_route(&our_id, &fail_payment_params, &network_graph, None, 100, 0, Arc::clone(&logger), &scorer, &random_seed_bytes)
5353 Err(LightningError { err, .. } ) => {
5354 assert_eq!(err, "Failed to find a path to the given destination");
5356 Ok(_) => panic!("Expected error"),
5361 fn limits_path_length() {
5362 let (secp_ctx, network, _, _, logger) = build_line_graph();
5363 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5364 let network_graph = network.read_only();
5366 let scorer = test_utils::TestScorer::with_penalty(0);
5367 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5368 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5370 // First check we can actually create a long route on this graph.
5371 let feasible_payment_params = PaymentParameters::from_node_id(nodes[18]);
5372 let route = get_route(&our_id, &feasible_payment_params, &network_graph, None, 100, 0,
5373 Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5374 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5375 assert!(path.len() == MAX_PATH_LENGTH_ESTIMATE.into());
5377 // But we can't create a path surpassing the MAX_PATH_LENGTH_ESTIMATE limit.
5378 let fail_payment_params = PaymentParameters::from_node_id(nodes[19]);
5379 match get_route(&our_id, &fail_payment_params, &network_graph, None, 100, 0,
5380 Arc::clone(&logger), &scorer, &random_seed_bytes)
5382 Err(LightningError { err, .. } ) => {
5383 assert_eq!(err, "Failed to find a path to the given destination");
5385 Ok(_) => panic!("Expected error"),
5390 fn adds_and_limits_cltv_offset() {
5391 let (secp_ctx, network_graph, _, _, logger) = build_graph();
5392 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5394 let scorer = test_utils::TestScorer::with_penalty(0);
5396 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
5397 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5398 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5399 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5400 assert_eq!(route.paths.len(), 1);
5402 let cltv_expiry_deltas_before = route.paths[0].iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5404 // Check whether the offset added to the last hop by default is in [1 .. DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA]
5405 let mut route_default = route.clone();
5406 add_random_cltv_offset(&mut route_default, &payment_params, &network_graph.read_only(), &random_seed_bytes);
5407 let cltv_expiry_deltas_default = route_default.paths[0].iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5408 assert_eq!(cltv_expiry_deltas_before.split_last().unwrap().1, cltv_expiry_deltas_default.split_last().unwrap().1);
5409 assert!(cltv_expiry_deltas_default.last() > cltv_expiry_deltas_before.last());
5410 assert!(cltv_expiry_deltas_default.last().unwrap() <= &DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA);
5412 // Check that no offset is added when we restrict the max_total_cltv_expiry_delta
5413 let mut route_limited = route.clone();
5414 let limited_max_total_cltv_expiry_delta = cltv_expiry_deltas_before.iter().sum();
5415 let limited_payment_params = payment_params.with_max_total_cltv_expiry_delta(limited_max_total_cltv_expiry_delta);
5416 add_random_cltv_offset(&mut route_limited, &limited_payment_params, &network_graph.read_only(), &random_seed_bytes);
5417 let cltv_expiry_deltas_limited = route_limited.paths[0].iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5418 assert_eq!(cltv_expiry_deltas_before, cltv_expiry_deltas_limited);
5422 fn adds_plausible_cltv_offset() {
5423 let (secp_ctx, network, _, _, logger) = build_graph();
5424 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5425 let network_graph = network.read_only();
5426 let network_nodes = network_graph.nodes();
5427 let network_channels = network_graph.channels();
5428 let scorer = test_utils::TestScorer::with_penalty(0);
5429 let payment_params = PaymentParameters::from_node_id(nodes[3]);
5430 let keys_manager = test_utils::TestKeysInterface::new(&[4u8; 32], Network::Testnet);
5431 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5433 let mut route = get_route(&our_id, &payment_params, &network_graph, None, 100, 0,
5434 Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5435 add_random_cltv_offset(&mut route, &payment_params, &network_graph, &random_seed_bytes);
5437 let mut path_plausibility = vec![];
5439 for p in route.paths {
5440 // 1. Select random observation point
5441 let mut prng = ChaCha20::new(&random_seed_bytes, &[0u8; 12]);
5442 let mut random_bytes = [0u8; ::core::mem::size_of::<usize>()];
5444 prng.process_in_place(&mut random_bytes);
5445 let random_path_index = usize::from_be_bytes(random_bytes).wrapping_rem(p.len());
5446 let observation_point = NodeId::from_pubkey(&p.get(random_path_index).unwrap().pubkey);
5448 // 2. Calculate what CLTV expiry delta we would observe there
5449 let observed_cltv_expiry_delta: u32 = p[random_path_index..].iter().map(|h| h.cltv_expiry_delta).sum();
5451 // 3. Starting from the observation point, find candidate paths
5452 let mut candidates: VecDeque<(NodeId, Vec<u32>)> = VecDeque::new();
5453 candidates.push_back((observation_point, vec![]));
5455 let mut found_plausible_candidate = false;
5457 'candidate_loop: while let Some((cur_node_id, cur_path_cltv_deltas)) = candidates.pop_front() {
5458 if let Some(remaining) = observed_cltv_expiry_delta.checked_sub(cur_path_cltv_deltas.iter().sum::<u32>()) {
5459 if remaining == 0 || remaining.wrapping_rem(40) == 0 || remaining.wrapping_rem(144) == 0 {
5460 found_plausible_candidate = true;
5461 break 'candidate_loop;
5465 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
5466 for channel_id in &cur_node.channels {
5467 if let Some(channel_info) = network_channels.get(&channel_id) {
5468 if let Some((dir_info, next_id)) = channel_info.as_directed_from(&cur_node_id) {
5469 if let Some(channel_update_info) = dir_info.direction() {
5470 let next_cltv_expiry_delta = channel_update_info.cltv_expiry_delta as u32;
5471 if cur_path_cltv_deltas.iter().sum::<u32>()
5472 .saturating_add(next_cltv_expiry_delta) <= observed_cltv_expiry_delta {
5473 let mut new_path_cltv_deltas = cur_path_cltv_deltas.clone();
5474 new_path_cltv_deltas.push(next_cltv_expiry_delta);
5475 candidates.push_back((*next_id, new_path_cltv_deltas));
5484 path_plausibility.push(found_plausible_candidate);
5486 assert!(path_plausibility.iter().all(|x| *x));
5489 #[cfg(not(feature = "no-std"))]
5490 pub(super) fn random_init_seed() -> u64 {
5491 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
5492 use core::hash::{BuildHasher, Hasher};
5493 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
5494 println!("Using seed of {}", seed);
5497 #[cfg(not(feature = "no-std"))]
5498 use util::ser::Readable;
5501 #[cfg(not(feature = "no-std"))]
5502 fn generate_routes() {
5503 use routing::scoring::{ProbabilisticScorer, ProbabilisticScoringParameters};
5505 let mut d = match super::test_utils::get_route_file() {
5512 let graph = NetworkGraph::read(&mut d).unwrap();
5513 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5514 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5516 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
5517 let mut seed = random_init_seed() as usize;
5518 let nodes = graph.read_only().nodes().clone();
5519 'load_endpoints: for _ in 0..10 {
5521 seed = seed.overflowing_mul(0xdeadbeef).0;
5522 let src = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5523 seed = seed.overflowing_mul(0xdeadbeef).0;
5524 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5525 let payment_params = PaymentParameters::from_node_id(dst);
5526 let amt = seed as u64 % 200_000_000;
5527 let params = ProbabilisticScoringParameters::default();
5528 let logger = test_utils::TestLogger::new();
5529 let scorer = ProbabilisticScorer::new(params, &graph, &logger);
5530 if get_route(src, &payment_params, &graph.read_only(), None, amt, 42, &logger, &scorer, &random_seed_bytes).is_ok() {
5531 continue 'load_endpoints;
5538 #[cfg(not(feature = "no-std"))]
5539 fn generate_routes_mpp() {
5540 use routing::scoring::{ProbabilisticScorer, ProbabilisticScoringParameters};
5542 let mut d = match super::test_utils::get_route_file() {
5549 let graph = NetworkGraph::read(&mut d).unwrap();
5550 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5551 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5553 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
5554 let mut seed = random_init_seed() as usize;
5555 let nodes = graph.read_only().nodes().clone();
5556 'load_endpoints: for _ in 0..10 {
5558 seed = seed.overflowing_mul(0xdeadbeef).0;
5559 let src = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5560 seed = seed.overflowing_mul(0xdeadbeef).0;
5561 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5562 let payment_params = PaymentParameters::from_node_id(dst).with_features(InvoiceFeatures::known());
5563 let amt = seed as u64 % 200_000_000;
5564 let params = ProbabilisticScoringParameters::default();
5565 let logger = test_utils::TestLogger::new();
5566 let scorer = ProbabilisticScorer::new(params, &graph, &logger);
5567 if get_route(src, &payment_params, &graph.read_only(), None, amt, 42, &logger, &scorer, &random_seed_bytes).is_ok() {
5568 continue 'load_endpoints;
5575 #[cfg(all(test, not(feature = "no-std")))]
5576 pub(crate) mod test_utils {
5578 /// Tries to open a network graph file, or panics with a URL to fetch it.
5579 pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
5580 let res = File::open("net_graph-2021-05-31.bin") // By default we're run in RL/lightning
5581 .or_else(|_| File::open("lightning/net_graph-2021-05-31.bin")) // We may be run manually in RL/
5582 .or_else(|_| { // Fall back to guessing based on the binary location
5583 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
5584 let mut path = std::env::current_exe().unwrap();
5585 path.pop(); // lightning-...
5587 path.pop(); // debug
5588 path.pop(); // target
5589 path.push("lightning");
5590 path.push("net_graph-2021-05-31.bin");
5591 eprintln!("{}", path.to_str().unwrap());
5594 .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");
5595 #[cfg(require_route_graph_test)]
5596 return Ok(res.unwrap());
5597 #[cfg(not(require_route_graph_test))]
5602 #[cfg(all(test, feature = "_bench_unstable", not(feature = "no-std")))]
5605 use bitcoin::hashes::Hash;
5606 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
5607 use chain::transaction::OutPoint;
5608 use chain::keysinterface::{KeysManager,KeysInterface};
5609 use ln::channelmanager::{ChannelCounterparty, ChannelDetails};
5610 use ln::features::{InitFeatures, InvoiceFeatures};
5611 use routing::scoring::{FixedPenaltyScorer, ProbabilisticScorer, ProbabilisticScoringParameters, Scorer};
5612 use util::logger::{Logger, Record};
5613 use util::test_utils::TestLogger;
5617 struct DummyLogger {}
5618 impl Logger for DummyLogger {
5619 fn log(&self, _record: &Record) {}
5622 fn read_network_graph() -> NetworkGraph {
5623 let mut d = test_utils::get_route_file().unwrap();
5624 NetworkGraph::read(&mut d).unwrap()
5627 fn payer_pubkey() -> PublicKey {
5628 let secp_ctx = Secp256k1::new();
5629 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
5633 fn first_hop(node_id: PublicKey) -> ChannelDetails {
5635 channel_id: [0; 32],
5636 counterparty: ChannelCounterparty {
5637 features: InitFeatures::known(),
5639 unspendable_punishment_reserve: 0,
5640 forwarding_info: None,
5641 outbound_htlc_minimum_msat: None,
5642 outbound_htlc_maximum_msat: None,
5644 funding_txo: Some(OutPoint {
5645 txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0
5648 short_channel_id: Some(1),
5649 inbound_scid_alias: None,
5650 channel_value_satoshis: 10_000_000,
5652 balance_msat: 10_000_000,
5653 outbound_capacity_msat: 10_000_000,
5654 next_outbound_htlc_limit_msat: 10_000_000,
5655 inbound_capacity_msat: 0,
5656 unspendable_punishment_reserve: None,
5657 confirmations_required: None,
5658 force_close_spend_delay: None,
5660 is_funding_locked: true,
5663 inbound_htlc_minimum_msat: None,
5664 inbound_htlc_maximum_msat: None,
5669 fn generate_routes_with_zero_penalty_scorer(bench: &mut Bencher) {
5670 let network_graph = read_network_graph();
5671 let scorer = FixedPenaltyScorer::with_penalty(0);
5672 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::empty());
5676 fn generate_mpp_routes_with_zero_penalty_scorer(bench: &mut Bencher) {
5677 let network_graph = read_network_graph();
5678 let scorer = FixedPenaltyScorer::with_penalty(0);
5679 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::known());
5683 fn generate_routes_with_default_scorer(bench: &mut Bencher) {
5684 let network_graph = read_network_graph();
5685 let scorer = Scorer::default();
5686 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::empty());
5690 fn generate_mpp_routes_with_default_scorer(bench: &mut Bencher) {
5691 let network_graph = read_network_graph();
5692 let scorer = Scorer::default();
5693 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::known());
5697 fn generate_routes_with_probabilistic_scorer(bench: &mut Bencher) {
5698 let logger = TestLogger::new();
5699 let network_graph = read_network_graph();
5700 let params = ProbabilisticScoringParameters::default();
5701 let scorer = ProbabilisticScorer::new(params, &network_graph, &logger);
5702 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::empty());
5706 fn generate_mpp_routes_with_probabilistic_scorer(bench: &mut Bencher) {
5707 let logger = TestLogger::new();
5708 let network_graph = read_network_graph();
5709 let params = ProbabilisticScoringParameters::default();
5710 let scorer = ProbabilisticScorer::new(params, &network_graph, &logger);
5711 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::known());
5714 fn generate_routes<S: Score>(
5715 bench: &mut Bencher, graph: &NetworkGraph, mut scorer: S, features: InvoiceFeatures
5717 let nodes = graph.read_only().nodes().clone();
5718 let payer = payer_pubkey();
5719 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
5720 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5722 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
5723 let mut routes = Vec::new();
5724 let mut route_endpoints = Vec::new();
5725 let mut seed: usize = 0xdeadbeef;
5726 'load_endpoints: for _ in 0..150 {
5729 let src = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5731 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5732 let params = PaymentParameters::from_node_id(dst).with_features(features.clone());
5733 let first_hop = first_hop(src);
5734 let amt = seed as u64 % 1_000_000;
5735 if let Ok(route) = get_route(&payer, ¶ms, &graph.read_only(), Some(&[&first_hop]), amt, 42, &DummyLogger{}, &scorer, &random_seed_bytes) {
5737 route_endpoints.push((first_hop, params, amt));
5738 continue 'load_endpoints;
5743 // ...and seed the scorer with success and failure data...
5744 for route in routes {
5745 let amount = route.get_total_amount();
5746 if amount < 250_000 {
5747 for path in route.paths {
5748 scorer.payment_path_successful(&path.iter().collect::<Vec<_>>());
5750 } else if amount > 750_000 {
5751 for path in route.paths {
5752 let short_channel_id = path[path.len() / 2].short_channel_id;
5753 scorer.payment_path_failed(&path.iter().collect::<Vec<_>>(), short_channel_id);
5758 // Because we've changed channel scores, its possible we'll take different routes to the
5759 // selected destinations, possibly causing us to fail because, eg, the newly-selected path
5760 // requires a too-high CLTV delta.
5761 route_endpoints.retain(|(first_hop, params, amt)| {
5762 get_route(&payer, params, &graph.read_only(), Some(&[first_hop]), *amt, 42, &DummyLogger{}, &scorer, &random_seed_bytes).is_ok()
5764 route_endpoints.truncate(100);
5765 assert_eq!(route_endpoints.len(), 100);
5767 // ...then benchmark finding paths between the nodes we learned.
5770 let (first_hop, params, amt) = &route_endpoints[idx % route_endpoints.len()];
5771 assert!(get_route(&payer, params, &graph.read_only(), Some(&[first_hop]), *amt, 42, &DummyLogger{}, &scorer, &random_seed_bytes).is_ok());