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::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 available_liquidity_msat = htlc_maximum_msat - used_liquidity_msat;
1070 let path_penalty_msat = $next_hops_path_penalty_msat.saturating_add(
1071 scorer.channel_penalty_msat(short_channel_id, amount_to_transfer_over_msat,
1072 available_liquidity_msat, &$src_node_id, &$dest_node_id));
1073 let new_graph_node = RouteGraphNode {
1074 node_id: $src_node_id,
1075 lowest_fee_to_peer_through_node: total_fee_msat,
1076 lowest_fee_to_node: $next_hops_fee_msat as u64 + hop_use_fee_msat,
1077 total_cltv_delta: hop_total_cltv_delta,
1078 value_contribution_msat: value_contribution_msat,
1079 path_htlc_minimum_msat,
1081 path_length_to_node,
1084 // Update the way of reaching $src_node_id with the given short_channel_id (from $dest_node_id),
1085 // if this way is cheaper than the already known
1086 // (considering the cost to "reach" this channel from the route destination,
1087 // the cost of using this channel,
1088 // and the cost of routing to the source node of this channel).
1089 // Also, consider that htlc_minimum_msat_difference, because we might end up
1090 // paying it. Consider the following exploit:
1091 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
1092 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
1093 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
1094 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
1096 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
1097 // but it may require additional tracking - we don't want to double-count
1098 // the fees included in $next_hops_path_htlc_minimum_msat, but also
1099 // can't use something that may decrease on future hops.
1100 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat)
1101 .saturating_add(old_entry.path_penalty_msat);
1102 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat)
1103 .saturating_add(path_penalty_msat);
1105 if !old_entry.was_processed && new_cost < old_cost {
1106 targets.push(new_graph_node);
1107 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
1108 old_entry.hop_use_fee_msat = hop_use_fee_msat;
1109 old_entry.total_fee_msat = total_fee_msat;
1110 old_entry.node_id = $dest_node_id.clone();
1111 old_entry.candidate = $candidate.clone();
1112 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
1113 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
1114 old_entry.path_penalty_msat = path_penalty_msat;
1115 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
1117 old_entry.value_contribution_msat = value_contribution_msat;
1119 did_add_update_path_to_src_node = true;
1120 } else if old_entry.was_processed && new_cost < old_cost {
1121 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
1123 // If we're skipping processing a node which was previously
1124 // processed even though we found another path to it with a
1125 // cheaper fee, check that it was because the second path we
1126 // found (which we are processing now) has a lower value
1127 // contribution due to an HTLC minimum limit.
1129 // e.g. take a graph with two paths from node 1 to node 2, one
1130 // through channel A, and one through channel B. Channel A and
1131 // B are both in the to-process heap, with their scores set by
1132 // a higher htlc_minimum than fee.
1133 // Channel A is processed first, and the channels onwards from
1134 // node 1 are added to the to-process heap. Thereafter, we pop
1135 // Channel B off of the heap, note that it has a much more
1136 // restrictive htlc_maximum_msat, and recalculate the fees for
1137 // all of node 1's channels using the new, reduced, amount.
1139 // This would be bogus - we'd be selecting a higher-fee path
1140 // with a lower htlc_maximum_msat instead of the one we'd
1141 // already decided to use.
1142 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
1144 value_contribution_msat + path_penalty_msat <
1145 old_entry.value_contribution_msat + old_entry.path_penalty_msat
1153 did_add_update_path_to_src_node
1157 let default_node_features = default_node_features();
1159 // Find ways (channels with destination) to reach a given node and store them
1160 // in the corresponding data structures (routing graph etc).
1161 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
1162 // meaning how much will be paid in fees after this node (to the best of our knowledge).
1163 // This data can later be helpful to optimize routing (pay lower fees).
1164 macro_rules! add_entries_to_cheapest_to_target_node {
1165 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr, $next_hops_value_contribution: expr,
1166 $next_hops_path_htlc_minimum_msat: expr, $next_hops_path_penalty_msat: expr,
1167 $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => {
1168 let skip_node = if let Some(elem) = dist.get_mut(&$node_id) {
1169 let was_processed = elem.was_processed;
1170 elem.was_processed = true;
1173 // Entries are added to dist in add_entry!() when there is a channel from a node.
1174 // Because there are no channels from payee, it will not have a dist entry at this point.
1175 // If we're processing any other node, it is always be the result of a channel from it.
1176 assert_eq!($node_id, payee_node_id);
1181 if let Some(first_channels) = first_hop_targets.get(&$node_id) {
1182 for details in first_channels {
1183 let candidate = CandidateRouteHop::FirstHop { details };
1184 add_entry!(candidate, our_node_id, $node_id, $fee_to_target_msat,
1185 $next_hops_value_contribution,
1186 $next_hops_path_htlc_minimum_msat, $next_hops_path_penalty_msat,
1187 $next_hops_cltv_delta, $next_hops_path_length);
1191 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
1194 &default_node_features
1197 if !features.requires_unknown_bits() {
1198 for chan_id in $node.channels.iter() {
1199 let chan = network_channels.get(chan_id).unwrap();
1200 if !chan.features.requires_unknown_bits() {
1201 let (directed_channel, source) =
1202 chan.as_directed_to(&$node_id).expect("inconsistent NetworkGraph");
1203 if first_hops.is_none() || *source != our_node_id {
1204 if let Some(direction) = directed_channel.direction() {
1205 if direction.enabled {
1206 let candidate = CandidateRouteHop::PublicHop {
1207 info: directed_channel.with_update().unwrap(),
1208 short_channel_id: *chan_id,
1210 add_entry!(candidate, *source, $node_id,
1211 $fee_to_target_msat,
1212 $next_hops_value_contribution,
1213 $next_hops_path_htlc_minimum_msat,
1214 $next_hops_path_penalty_msat,
1215 $next_hops_cltv_delta, $next_hops_path_length);
1226 let mut payment_paths = Vec::<PaymentPath>::new();
1228 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
1229 'paths_collection: loop {
1230 // For every new path, start from scratch, except for used_channel_liquidities, which
1231 // helps to avoid reusing previously selected paths in future iterations.
1234 hit_minimum_limit = false;
1236 // If first hop is a private channel and the only way to reach the payee, this is the only
1237 // place where it could be added.
1238 if let Some(first_channels) = first_hop_targets.get(&payee_node_id) {
1239 for details in first_channels {
1240 let candidate = CandidateRouteHop::FirstHop { details };
1241 let added = add_entry!(candidate, our_node_id, payee_node_id, 0, path_value_msat,
1243 log_trace!(logger, "{} direct route to payee via SCID {}",
1244 if added { "Added" } else { "Skipped" }, candidate.short_channel_id());
1248 // Add the payee as a target, so that the payee-to-payer
1249 // search algorithm knows what to start with.
1250 match network_nodes.get(&payee_node_id) {
1251 // The payee is not in our network graph, so nothing to add here.
1252 // There is still a chance of reaching them via last_hops though,
1253 // so don't yet fail the payment here.
1254 // If not, targets.pop() will not even let us enter the loop in step 2.
1257 add_entries_to_cheapest_to_target_node!(node, payee_node_id, 0, path_value_msat, 0, 0u64, 0, 0);
1262 // If a caller provided us with last hops, add them to routing targets. Since this happens
1263 // earlier than general path finding, they will be somewhat prioritized, although currently
1264 // it matters only if the fees are exactly the same.
1265 for route in payment_params.route_hints.iter().filter(|route| !route.0.is_empty()) {
1266 let first_hop_in_route = &(route.0)[0];
1267 let have_hop_src_in_graph =
1268 // Only add the hops in this route to our candidate set if either
1269 // we have a direct channel to the first hop or the first hop is
1270 // in the regular network graph.
1271 first_hop_targets.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some() ||
1272 network_nodes.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some();
1273 if have_hop_src_in_graph {
1274 // We start building the path from reverse, i.e., from payee
1275 // to the first RouteHintHop in the path.
1276 let hop_iter = route.0.iter().rev();
1277 let prev_hop_iter = core::iter::once(&payment_params.payee_pubkey).chain(
1278 route.0.iter().skip(1).rev().map(|hop| &hop.src_node_id));
1279 let mut hop_used = true;
1280 let mut aggregate_next_hops_fee_msat: u64 = 0;
1281 let mut aggregate_next_hops_path_htlc_minimum_msat: u64 = 0;
1282 let mut aggregate_next_hops_path_penalty_msat: u64 = 0;
1283 let mut aggregate_next_hops_cltv_delta: u32 = 0;
1284 let mut aggregate_next_hops_path_length: u8 = 0;
1286 for (idx, (hop, prev_hop_id)) in hop_iter.zip(prev_hop_iter).enumerate() {
1287 let source = NodeId::from_pubkey(&hop.src_node_id);
1288 let target = NodeId::from_pubkey(&prev_hop_id);
1289 let candidate = network_channels
1290 .get(&hop.short_channel_id)
1291 .and_then(|channel| channel.as_directed_to(&target))
1292 .and_then(|(channel, _)| channel.with_update())
1293 .map(|info| CandidateRouteHop::PublicHop {
1295 short_channel_id: hop.short_channel_id,
1297 .unwrap_or_else(|| CandidateRouteHop::PrivateHop { hint: hop });
1298 let amount_to_transfer_msat = final_value_msat + aggregate_next_hops_fee_msat;
1299 let capacity_msat = candidate.effective_capacity().as_msat();
1300 aggregate_next_hops_path_penalty_msat = aggregate_next_hops_path_penalty_msat
1301 .saturating_add(scorer.channel_penalty_msat(hop.short_channel_id, amount_to_transfer_msat, capacity_msat, &source, &target));
1303 aggregate_next_hops_cltv_delta = aggregate_next_hops_cltv_delta
1304 .saturating_add(hop.cltv_expiry_delta as u32);
1306 aggregate_next_hops_path_length = aggregate_next_hops_path_length
1309 if !add_entry!(candidate, source, target, aggregate_next_hops_fee_msat,
1310 path_value_msat, aggregate_next_hops_path_htlc_minimum_msat,
1311 aggregate_next_hops_path_penalty_msat,
1312 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length) {
1313 // If this hop was not used then there is no use checking the preceding
1314 // hops in the RouteHint. We can break by just searching for a direct
1315 // channel between last checked hop and first_hop_targets.
1319 // Searching for a direct channel between last checked hop and first_hop_targets
1320 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&prev_hop_id)) {
1321 for details in first_channels {
1322 let candidate = CandidateRouteHop::FirstHop { details };
1323 add_entry!(candidate, our_node_id, NodeId::from_pubkey(&prev_hop_id),
1324 aggregate_next_hops_fee_msat, path_value_msat,
1325 aggregate_next_hops_path_htlc_minimum_msat,
1326 aggregate_next_hops_path_penalty_msat, aggregate_next_hops_cltv_delta,
1327 aggregate_next_hops_path_length);
1335 // In the next values of the iterator, the aggregate fees already reflects
1336 // the sum of value sent from payer (final_value_msat) and routing fees
1337 // for the last node in the RouteHint. We need to just add the fees to
1338 // route through the current node so that the preceding node (next iteration)
1340 let hops_fee = compute_fees(aggregate_next_hops_fee_msat + final_value_msat, hop.fees)
1341 .map_or(None, |inc| inc.checked_add(aggregate_next_hops_fee_msat));
1342 aggregate_next_hops_fee_msat = if let Some(val) = hops_fee { val } else { break; };
1344 let hop_htlc_minimum_msat = candidate.htlc_minimum_msat();
1345 let hop_htlc_minimum_msat_inc = if let Some(val) = compute_fees(aggregate_next_hops_path_htlc_minimum_msat, hop.fees) { val } else { break; };
1346 let hops_path_htlc_minimum = aggregate_next_hops_path_htlc_minimum_msat
1347 .checked_add(hop_htlc_minimum_msat_inc);
1348 aggregate_next_hops_path_htlc_minimum_msat = if let Some(val) = hops_path_htlc_minimum { cmp::max(hop_htlc_minimum_msat, val) } else { break; };
1350 if idx == route.0.len() - 1 {
1351 // The last hop in this iterator is the first hop in
1352 // overall RouteHint.
1353 // If this hop connects to a node with which we have a direct channel,
1354 // ignore the network graph and, if the last hop was added, add our
1355 // direct channel to the candidate set.
1357 // Note that we *must* check if the last hop was added as `add_entry`
1358 // always assumes that the third argument is a node to which we have a
1360 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&hop.src_node_id)) {
1361 for details in first_channels {
1362 let candidate = CandidateRouteHop::FirstHop { details };
1363 add_entry!(candidate, our_node_id,
1364 NodeId::from_pubkey(&hop.src_node_id),
1365 aggregate_next_hops_fee_msat, path_value_msat,
1366 aggregate_next_hops_path_htlc_minimum_msat,
1367 aggregate_next_hops_path_penalty_msat,
1368 aggregate_next_hops_cltv_delta,
1369 aggregate_next_hops_path_length);
1377 log_trace!(logger, "Starting main path collection loop with {} nodes pre-filled from first/last hops.", targets.len());
1379 // At this point, targets are filled with the data from first and
1380 // last hops communicated by the caller, and the payment receiver.
1381 let mut found_new_path = false;
1384 // If this loop terminates due the exhaustion of targets, two situations are possible:
1385 // - not enough outgoing liquidity:
1386 // 0 < already_collected_value_msat < final_value_msat
1387 // - enough outgoing liquidity:
1388 // final_value_msat <= already_collected_value_msat < recommended_value_msat
1389 // Both these cases (and other cases except reaching recommended_value_msat) mean that
1390 // paths_collection will be stopped because found_new_path==false.
1391 // This is not necessarily a routing failure.
1392 '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() {
1394 // Since we're going payee-to-payer, hitting our node as a target means we should stop
1395 // traversing the graph and arrange the path out of what we found.
1396 if node_id == our_node_id {
1397 let mut new_entry = dist.remove(&our_node_id).unwrap();
1398 let mut ordered_hops: Vec<(PathBuildingHop, NodeFeatures)> = vec!((new_entry.clone(), default_node_features.clone()));
1401 let mut features_set = false;
1402 if let Some(first_channels) = first_hop_targets.get(&ordered_hops.last().unwrap().0.node_id) {
1403 for details in first_channels {
1404 if details.short_channel_id.unwrap() == ordered_hops.last().unwrap().0.candidate.short_channel_id() {
1405 ordered_hops.last_mut().unwrap().1 = details.counterparty.features.to_context();
1406 features_set = true;
1412 if let Some(node) = network_nodes.get(&ordered_hops.last().unwrap().0.node_id) {
1413 if let Some(node_info) = node.announcement_info.as_ref() {
1414 ordered_hops.last_mut().unwrap().1 = node_info.features.clone();
1416 ordered_hops.last_mut().unwrap().1 = default_node_features.clone();
1419 // We can fill in features for everything except hops which were
1420 // provided via the invoice we're paying. We could guess based on the
1421 // recipient's features but for now we simply avoid guessing at all.
1425 // Means we succesfully traversed from the payer to the payee, now
1426 // save this path for the payment route. Also, update the liquidity
1427 // remaining on the used hops, so that we take them into account
1428 // while looking for more paths.
1429 if ordered_hops.last().unwrap().0.node_id == payee_node_id {
1433 new_entry = match dist.remove(&ordered_hops.last().unwrap().0.node_id) {
1434 Some(payment_hop) => payment_hop,
1435 // We can't arrive at None because, if we ever add an entry to targets,
1436 // we also fill in the entry in dist (see add_entry!).
1437 None => unreachable!(),
1439 // We "propagate" the fees one hop backward (topologically) here,
1440 // so that fees paid for a HTLC forwarding on the current channel are
1441 // associated with the previous channel (where they will be subtracted).
1442 ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
1443 ordered_hops.push((new_entry.clone(), default_node_features.clone()));
1445 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
1446 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
1448 log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: \n {:#?}",
1449 ordered_hops.len(), value_contribution_msat, ordered_hops.iter().map(|h| &(h.0)).collect::<Vec<&PathBuildingHop>>());
1451 let mut payment_path = PaymentPath {hops: ordered_hops};
1453 // We could have possibly constructed a slightly inconsistent path: since we reduce
1454 // value being transferred along the way, we could have violated htlc_minimum_msat
1455 // on some channels we already passed (assuming dest->source direction). Here, we
1456 // recompute the fees again, so that if that's the case, we match the currently
1457 // underpaid htlc_minimum_msat with fees.
1458 payment_path.update_value_and_recompute_fees(cmp::min(value_contribution_msat, final_value_msat));
1460 // Since a path allows to transfer as much value as
1461 // the smallest channel it has ("bottleneck"), we should recompute
1462 // the fees so sender HTLC don't overpay fees when traversing
1463 // larger channels than the bottleneck. This may happen because
1464 // when we were selecting those channels we were not aware how much value
1465 // this path will transfer, and the relative fee for them
1466 // might have been computed considering a larger value.
1467 // Remember that we used these channels so that we don't rely
1468 // on the same liquidity in future paths.
1469 let mut prevented_redundant_path_selection = false;
1470 let prev_hop_iter = core::iter::once(&our_node_id)
1471 .chain(payment_path.hops.iter().map(|(hop, _)| &hop.node_id));
1472 for (prev_hop, (hop, _)) in prev_hop_iter.zip(payment_path.hops.iter()) {
1473 let spent_on_hop_msat = value_contribution_msat + hop.next_hops_fee_msat;
1474 let used_liquidity_msat = used_channel_liquidities
1475 .entry((hop.candidate.short_channel_id(), *prev_hop < hop.node_id))
1476 .and_modify(|used_liquidity_msat| *used_liquidity_msat += spent_on_hop_msat)
1477 .or_insert(spent_on_hop_msat);
1478 if *used_liquidity_msat == hop.candidate.htlc_maximum_msat() {
1479 // If this path used all of this channel's available liquidity, we know
1480 // this path will not be selected again in the next loop iteration.
1481 prevented_redundant_path_selection = true;
1483 debug_assert!(*used_liquidity_msat <= hop.candidate.htlc_maximum_msat());
1485 if !prevented_redundant_path_selection {
1486 // If we weren't capped by hitting a liquidity limit on a channel in the path,
1487 // we'll probably end up picking the same path again on the next iteration.
1488 // Decrease the available liquidity of a hop in the middle of the path.
1489 let victim_scid = payment_path.hops[(payment_path.hops.len()) / 2].0.candidate.short_channel_id();
1490 let exhausted = u64::max_value();
1491 log_trace!(logger, "Disabling channel {} for future path building iterations to avoid duplicates.", victim_scid);
1492 *used_channel_liquidities.entry((victim_scid, false)).or_default() = exhausted;
1493 *used_channel_liquidities.entry((victim_scid, true)).or_default() = exhausted;
1496 // Track the total amount all our collected paths allow to send so that we:
1497 // - know when to stop looking for more paths
1498 // - know which of the hops are useless considering how much more sats we need
1499 // (contributes_sufficient_value)
1500 already_collected_value_msat += value_contribution_msat;
1502 payment_paths.push(payment_path);
1503 found_new_path = true;
1504 break 'path_construction;
1507 // If we found a path back to the payee, we shouldn't try to process it again. This is
1508 // the equivalent of the `elem.was_processed` check in
1509 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
1510 if node_id == payee_node_id { continue 'path_construction; }
1512 // Otherwise, since the current target node is not us,
1513 // keep "unrolling" the payment graph from payee to payer by
1514 // finding a way to reach the current target from the payer side.
1515 match network_nodes.get(&node_id) {
1518 add_entries_to_cheapest_to_target_node!(node, node_id, lowest_fee_to_node,
1519 value_contribution_msat, path_htlc_minimum_msat, path_penalty_msat,
1520 total_cltv_delta, path_length_to_node);
1526 // If we don't support MPP, no use trying to gather more value ever.
1527 break 'paths_collection;
1531 // Stop either when the recommended value is reached or if no new path was found in this
1533 // In the latter case, making another path finding attempt won't help,
1534 // because we deterministically terminated the search due to low liquidity.
1535 if already_collected_value_msat >= recommended_value_msat || !found_new_path {
1536 log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
1537 already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
1538 break 'paths_collection;
1539 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
1540 // Further, if this was our first walk of the graph, and we weren't limited by an
1541 // htlc_minimum_msat, return immediately because this path should suffice. If we were
1542 // limited by an htlc_minimum_msat value, find another path with a higher value,
1543 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
1544 // still keeping a lower total fee than this path.
1545 if !hit_minimum_limit {
1546 log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
1547 break 'paths_collection;
1549 log_trace!(logger, "Collected our payment amount on the first pass, but running again to collect extra paths with a potentially higher limit.");
1550 path_value_msat = recommended_value_msat;
1555 if payment_paths.len() == 0 {
1556 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1559 if already_collected_value_msat < final_value_msat {
1560 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1563 // Sort by total fees and take the best paths.
1564 payment_paths.sort_unstable_by_key(|path| path.get_total_fee_paid_msat());
1565 if payment_paths.len() > 50 {
1566 payment_paths.truncate(50);
1569 // Draw multiple sufficient routes by randomly combining the selected paths.
1570 let mut drawn_routes = Vec::new();
1571 let mut prng = ChaCha20::new(random_seed_bytes, &[0u8; 12]);
1572 let mut random_index_bytes = [0u8; ::core::mem::size_of::<usize>()];
1574 let num_permutations = payment_paths.len();
1575 for _ in 0..num_permutations {
1576 let mut cur_route = Vec::<PaymentPath>::new();
1577 let mut aggregate_route_value_msat = 0;
1580 // Do a Fisher-Yates shuffle to create a random permutation of the payment paths
1581 for cur_index in (1..payment_paths.len()).rev() {
1582 prng.process_in_place(&mut random_index_bytes);
1583 let random_index = usize::from_be_bytes(random_index_bytes).wrapping_rem(cur_index+1);
1584 payment_paths.swap(cur_index, random_index);
1588 for payment_path in &payment_paths {
1589 cur_route.push(payment_path.clone());
1590 aggregate_route_value_msat += payment_path.get_value_msat();
1591 if aggregate_route_value_msat > final_value_msat {
1592 // Last path likely overpaid. Substract it from the most expensive
1593 // (in terms of proportional fee) path in this route and recompute fees.
1594 // This might be not the most economically efficient way, but fewer paths
1595 // also makes routing more reliable.
1596 let mut overpaid_value_msat = aggregate_route_value_msat - final_value_msat;
1598 // First, we drop some expensive low-value paths entirely if possible, since fewer
1599 // paths is better: the payment is less likely to fail. In order to do so, we sort
1600 // by value and fall back to total fees paid, i.e., in case of equal values we
1601 // prefer lower cost paths.
1602 cur_route.sort_unstable_by(|a, b| {
1603 a.get_value_msat().cmp(&b.get_value_msat())
1604 // Reverse ordering for cost, so we drop higher-cost paths first
1605 .then_with(|| b.get_cost_msat().cmp(&a.get_cost_msat()))
1608 // We should make sure that at least 1 path left.
1609 let mut paths_left = cur_route.len();
1610 cur_route.retain(|path| {
1611 if paths_left == 1 {
1614 let mut keep = true;
1615 let path_value_msat = path.get_value_msat();
1616 if path_value_msat <= overpaid_value_msat {
1618 overpaid_value_msat -= path_value_msat;
1624 if overpaid_value_msat == 0 {
1628 assert!(cur_route.len() > 0);
1631 // Now, subtract the overpaid value from the most-expensive path.
1632 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1633 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1634 cur_route.sort_unstable_by_key(|path| { path.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>() });
1635 let expensive_payment_path = cur_route.first_mut().unwrap();
1637 // We already dropped all the small value paths above, meaning all the
1638 // remaining paths are larger than remaining overpaid_value_msat.
1639 // Thus, this can't be negative.
1640 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
1641 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
1645 drawn_routes.push(cur_route);
1649 // Select the best route by lowest total cost.
1650 drawn_routes.sort_unstable_by_key(|paths| paths.iter().map(|path| path.get_cost_msat()).sum::<u64>());
1651 let mut selected_paths = Vec::<Vec<Result<RouteHop, LightningError>>>::new();
1652 for payment_path in drawn_routes.first().unwrap() {
1653 let mut path = payment_path.hops.iter().map(|(payment_hop, node_features)| {
1655 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)})?,
1656 node_features: node_features.clone(),
1657 short_channel_id: payment_hop.candidate.short_channel_id(),
1658 channel_features: payment_hop.candidate.features(),
1659 fee_msat: payment_hop.fee_msat,
1660 cltv_expiry_delta: payment_hop.candidate.cltv_expiry_delta(),
1662 }).collect::<Vec<_>>();
1663 // Propagate the cltv_expiry_delta one hop backwards since the delta from the current hop is
1664 // applicable for the previous hop.
1665 path.iter_mut().rev().fold(final_cltv_expiry_delta, |prev_cltv_expiry_delta, hop| {
1666 core::mem::replace(&mut hop.as_mut().unwrap().cltv_expiry_delta, prev_cltv_expiry_delta)
1668 selected_paths.push(path);
1671 if let Some(features) = &payment_params.features {
1672 for path in selected_paths.iter_mut() {
1673 if let Ok(route_hop) = path.last_mut().unwrap() {
1674 route_hop.node_features = features.to_context();
1680 paths: selected_paths.into_iter().map(|path| path.into_iter().collect()).collect::<Result<Vec<_>, _>>()?,
1681 payment_params: Some(payment_params.clone()),
1683 log_info!(logger, "Got route to {}: {}", payment_params.payee_pubkey, log_route!(route));
1687 // When an adversarial intermediary node observes a payment, it may be able to infer its
1688 // destination, if the remaining CLTV expiry delta exactly matches a feasible path in the network
1689 // graph. In order to improve privacy, this method obfuscates the CLTV expiry deltas along the
1690 // payment path by adding a randomized 'shadow route' offset to the final hop.
1691 fn add_random_cltv_offset(route: &mut Route, payment_params: &PaymentParameters, network_graph: &ReadOnlyNetworkGraph, random_seed_bytes: &[u8; 32]) {
1692 let network_channels = network_graph.channels();
1693 let network_nodes = network_graph.nodes();
1695 for path in route.paths.iter_mut() {
1696 let mut shadow_ctlv_expiry_delta_offset: u32 = 0;
1698 // Remember the last three nodes of the random walk and avoid looping back on them.
1699 // Init with the last three nodes from the actual path, if possible.
1700 let mut nodes_to_avoid: [NodeId; 3] = [NodeId::from_pubkey(&path.last().unwrap().pubkey),
1701 NodeId::from_pubkey(&path.get(path.len().saturating_sub(2)).unwrap().pubkey),
1702 NodeId::from_pubkey(&path.get(path.len().saturating_sub(3)).unwrap().pubkey)];
1704 // Choose the last publicly known node as the starting point for the random walk.
1705 let mut cur_hop: Option<NodeId> = None;
1706 let mut path_nonce = [0u8; 12];
1707 if let Some(starting_hop) = path.iter().rev()
1708 .find(|h| network_nodes.contains_key(&NodeId::from_pubkey(&h.pubkey))) {
1709 cur_hop = Some(NodeId::from_pubkey(&starting_hop.pubkey));
1710 path_nonce.copy_from_slice(&cur_hop.unwrap().as_slice()[..12]);
1713 // Init PRNG with the path-dependant nonce, which is static for private paths.
1714 let mut prng = ChaCha20::new(random_seed_bytes, &path_nonce);
1715 let mut random_path_bytes = [0u8; ::core::mem::size_of::<usize>()];
1717 // Pick a random path length in [1 .. 3]
1718 prng.process_in_place(&mut random_path_bytes);
1719 let random_walk_length = usize::from_be_bytes(random_path_bytes).wrapping_rem(3).wrapping_add(1);
1721 for random_hop in 0..random_walk_length {
1722 // If we don't find a suitable offset in the public network graph, we default to
1723 // MEDIAN_HOP_CLTV_EXPIRY_DELTA.
1724 let mut random_hop_offset = MEDIAN_HOP_CLTV_EXPIRY_DELTA;
1726 if let Some(cur_node_id) = cur_hop {
1727 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
1728 // Randomly choose the next unvisited hop.
1729 prng.process_in_place(&mut random_path_bytes);
1730 if let Some(random_channel) = usize::from_be_bytes(random_path_bytes)
1731 .checked_rem(cur_node.channels.len())
1732 .and_then(|index| cur_node.channels.get(index))
1733 .and_then(|id| network_channels.get(id)) {
1734 random_channel.as_directed_from(&cur_node_id).map(|(dir_info, next_id)| {
1735 if !nodes_to_avoid.iter().any(|x| x == next_id) {
1736 nodes_to_avoid[random_hop] = *next_id;
1737 dir_info.direction().map(|channel_update_info| {
1738 random_hop_offset = channel_update_info.cltv_expiry_delta.into();
1739 cur_hop = Some(*next_id);
1747 shadow_ctlv_expiry_delta_offset = shadow_ctlv_expiry_delta_offset
1748 .checked_add(random_hop_offset)
1749 .unwrap_or(shadow_ctlv_expiry_delta_offset);
1752 // Limit the total offset to reduce the worst-case locked liquidity timevalue
1753 const MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET: u32 = 3*144;
1754 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET);
1756 // Limit the offset so we never exceed the max_total_cltv_expiry_delta. To improve plausibility,
1757 // we choose the limit to be the largest possible multiple of MEDIAN_HOP_CLTV_EXPIRY_DELTA.
1758 let path_total_cltv_expiry_delta: u32 = path.iter().map(|h| h.cltv_expiry_delta).sum();
1759 let mut max_path_offset = payment_params.max_total_cltv_expiry_delta - path_total_cltv_expiry_delta;
1760 max_path_offset = cmp::max(
1761 max_path_offset - (max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA),
1762 max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA);
1763 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, max_path_offset);
1765 // Add 'shadow' CLTV offset to the final hop
1766 if let Some(last_hop) = path.last_mut() {
1767 last_hop.cltv_expiry_delta = last_hop.cltv_expiry_delta
1768 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(last_hop.cltv_expiry_delta);
1775 use routing::network_graph::{NetworkGraph, NetGraphMsgHandler, NodeId};
1776 use routing::router::{get_route, add_random_cltv_offset, default_node_features,
1777 PaymentParameters, Route, RouteHint, RouteHintHop, RouteHop, RoutingFees,
1778 DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA, MAX_PATH_LENGTH_ESTIMATE};
1779 use routing::scoring::Score;
1780 use chain::transaction::OutPoint;
1781 use chain::keysinterface::KeysInterface;
1782 use ln::features::{ChannelFeatures, InitFeatures, InvoiceFeatures, NodeFeatures};
1783 use ln::msgs::{ErrorAction, LightningError, OptionalField, UnsignedChannelAnnouncement, ChannelAnnouncement, RoutingMessageHandler,
1784 NodeAnnouncement, UnsignedNodeAnnouncement, ChannelUpdate, UnsignedChannelUpdate};
1785 use ln::channelmanager;
1786 use util::test_utils;
1787 use util::chacha20::ChaCha20;
1788 use util::ser::Writeable;
1790 use util::ser::Writer;
1792 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
1793 use bitcoin::hashes::Hash;
1794 use bitcoin::network::constants::Network;
1795 use bitcoin::blockdata::constants::genesis_block;
1796 use bitcoin::blockdata::script::Builder;
1797 use bitcoin::blockdata::opcodes;
1798 use bitcoin::blockdata::transaction::TxOut;
1802 use bitcoin::secp256k1::{PublicKey,SecretKey};
1803 use bitcoin::secp256k1::{Secp256k1, All};
1806 use sync::{self, Arc};
1808 fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
1809 features: InitFeatures, outbound_capacity_msat: u64) -> channelmanager::ChannelDetails {
1810 channelmanager::ChannelDetails {
1811 channel_id: [0; 32],
1812 counterparty: channelmanager::ChannelCounterparty {
1815 unspendable_punishment_reserve: 0,
1816 forwarding_info: None,
1817 outbound_htlc_minimum_msat: None,
1818 outbound_htlc_maximum_msat: None,
1820 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
1823 inbound_scid_alias: None,
1824 channel_value_satoshis: 0,
1827 outbound_capacity_msat,
1828 next_outbound_htlc_limit_msat: outbound_capacity_msat,
1829 inbound_capacity_msat: 42,
1830 unspendable_punishment_reserve: None,
1831 confirmations_required: None,
1832 force_close_spend_delay: None,
1833 is_outbound: true, is_funding_locked: true,
1834 is_usable: true, is_public: true,
1835 inbound_htlc_minimum_msat: None,
1836 inbound_htlc_maximum_msat: None,
1840 // Using the same keys for LN and BTC ids
1842 net_graph_msg_handler: &NetGraphMsgHandler<Arc<NetworkGraph>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1843 secp_ctx: &Secp256k1<All>, node_1_privkey: &SecretKey, node_2_privkey: &SecretKey, features: ChannelFeatures, short_channel_id: u64
1845 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1846 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1848 let unsigned_announcement = UnsignedChannelAnnouncement {
1850 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1854 bitcoin_key_1: node_id_1,
1855 bitcoin_key_2: node_id_2,
1856 excess_data: Vec::new(),
1859 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1860 let valid_announcement = ChannelAnnouncement {
1861 node_signature_1: secp_ctx.sign_ecdsa(&msghash, node_1_privkey),
1862 node_signature_2: secp_ctx.sign_ecdsa(&msghash, node_2_privkey),
1863 bitcoin_signature_1: secp_ctx.sign_ecdsa(&msghash, node_1_privkey),
1864 bitcoin_signature_2: secp_ctx.sign_ecdsa(&msghash, node_2_privkey),
1865 contents: unsigned_announcement.clone(),
1867 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1868 Ok(res) => assert!(res),
1874 net_graph_msg_handler: &NetGraphMsgHandler<Arc<NetworkGraph>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1875 secp_ctx: &Secp256k1<All>, node_privkey: &SecretKey, update: UnsignedChannelUpdate
1877 let msghash = hash_to_message!(&Sha256dHash::hash(&update.encode()[..])[..]);
1878 let valid_channel_update = ChannelUpdate {
1879 signature: secp_ctx.sign_ecdsa(&msghash, node_privkey),
1880 contents: update.clone()
1883 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1884 Ok(res) => assert!(res),
1889 fn add_or_update_node(
1890 net_graph_msg_handler: &NetGraphMsgHandler<Arc<NetworkGraph>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1891 secp_ctx: &Secp256k1<All>, node_privkey: &SecretKey, features: NodeFeatures, timestamp: u32
1893 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
1894 let unsigned_announcement = UnsignedNodeAnnouncement {
1900 addresses: Vec::new(),
1901 excess_address_data: Vec::new(),
1902 excess_data: Vec::new(),
1904 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1905 let valid_announcement = NodeAnnouncement {
1906 signature: secp_ctx.sign_ecdsa(&msghash, node_privkey),
1907 contents: unsigned_announcement.clone()
1910 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1916 fn get_nodes(secp_ctx: &Secp256k1<All>) -> (SecretKey, PublicKey, Vec<SecretKey>, Vec<PublicKey>) {
1917 let privkeys: Vec<SecretKey> = (2..22).map(|i| {
1918 SecretKey::from_slice(&hex::decode(format!("{:02x}", i).repeat(32)).unwrap()[..]).unwrap()
1921 let pubkeys = privkeys.iter().map(|secret| PublicKey::from_secret_key(&secp_ctx, secret)).collect();
1923 let our_privkey = SecretKey::from_slice(&hex::decode("01".repeat(32)).unwrap()[..]).unwrap();
1924 let our_id = PublicKey::from_secret_key(&secp_ctx, &our_privkey);
1926 (our_privkey, our_id, privkeys, pubkeys)
1929 fn id_to_feature_flags(id: u8) -> Vec<u8> {
1930 // Set the feature flags to the id'th odd (ie non-required) feature bit so that we can
1931 // test for it later.
1932 let idx = (id - 1) * 2 + 1;
1934 vec![1 << (idx - 8*3), 0, 0, 0]
1935 } else if idx > 8*2 {
1936 vec![1 << (idx - 8*2), 0, 0]
1937 } else if idx > 8*1 {
1938 vec![1 << (idx - 8*1), 0]
1944 fn build_line_graph() -> (
1945 Secp256k1<All>, sync::Arc<NetworkGraph>, NetGraphMsgHandler<sync::Arc<NetworkGraph>,
1946 sync::Arc<test_utils::TestChainSource>, sync::Arc<crate::util::test_utils::TestLogger>>,
1947 sync::Arc<test_utils::TestChainSource>, sync::Arc<test_utils::TestLogger>,
1949 let secp_ctx = Secp256k1::new();
1950 let logger = Arc::new(test_utils::TestLogger::new());
1951 let chain_monitor = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1952 let network_graph = Arc::new(NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash()));
1953 let net_graph_msg_handler = NetGraphMsgHandler::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
1955 // Build network from our_id to node 19:
1956 // our_id -1(1)2- node0 -1(2)2- node1 - ... - node19
1957 let (our_privkey, _, privkeys, _) = get_nodes(&secp_ctx);
1959 for (idx, (cur_privkey, next_privkey)) in core::iter::once(&our_privkey)
1960 .chain(privkeys.iter()).zip(privkeys.iter()).enumerate() {
1961 let cur_short_channel_id = (idx as u64) + 1;
1962 add_channel(&net_graph_msg_handler, &secp_ctx, &cur_privkey, &next_privkey,
1963 ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), cur_short_channel_id);
1964 update_channel(&net_graph_msg_handler, &secp_ctx, &cur_privkey, UnsignedChannelUpdate {
1965 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1966 short_channel_id: cur_short_channel_id,
1967 timestamp: idx as u32,
1969 cltv_expiry_delta: 0,
1970 htlc_minimum_msat: 0,
1971 htlc_maximum_msat: OptionalField::Absent,
1973 fee_proportional_millionths: 0,
1974 excess_data: Vec::new()
1976 update_channel(&net_graph_msg_handler, &secp_ctx, &next_privkey, UnsignedChannelUpdate {
1977 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1978 short_channel_id: cur_short_channel_id,
1979 timestamp: (idx as u32)+1,
1981 cltv_expiry_delta: 0,
1982 htlc_minimum_msat: 0,
1983 htlc_maximum_msat: OptionalField::Absent,
1985 fee_proportional_millionths: 0,
1986 excess_data: Vec::new()
1988 add_or_update_node(&net_graph_msg_handler, &secp_ctx, next_privkey,
1989 NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
1992 (secp_ctx, network_graph, net_graph_msg_handler, chain_monitor, logger)
1995 fn build_graph() -> (
1997 sync::Arc<NetworkGraph>,
1998 NetGraphMsgHandler<sync::Arc<NetworkGraph>, sync::Arc<test_utils::TestChainSource>, sync::Arc<crate::util::test_utils::TestLogger>>,
1999 sync::Arc<test_utils::TestChainSource>,
2000 sync::Arc<test_utils::TestLogger>,
2002 let secp_ctx = Secp256k1::new();
2003 let logger = Arc::new(test_utils::TestLogger::new());
2004 let chain_monitor = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
2005 let network_graph = Arc::new(NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash()));
2006 let net_graph_msg_handler = NetGraphMsgHandler::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
2007 // Build network from our_id to node6:
2009 // -1(1)2- node0 -1(3)2-
2011 // our_id -1(12)2- node7 -1(13)2--- node2
2013 // -1(2)2- node1 -1(4)2-
2016 // chan1 1-to-2: disabled
2017 // chan1 2-to-1: enabled, 0 fee
2019 // chan2 1-to-2: enabled, ignored fee
2020 // chan2 2-to-1: enabled, 0 fee
2022 // chan3 1-to-2: enabled, 0 fee
2023 // chan3 2-to-1: enabled, 100 msat fee
2025 // chan4 1-to-2: enabled, 100% fee
2026 // chan4 2-to-1: enabled, 0 fee
2028 // chan12 1-to-2: enabled, ignored fee
2029 // chan12 2-to-1: enabled, 0 fee
2031 // chan13 1-to-2: enabled, 200% fee
2032 // chan13 2-to-1: enabled, 0 fee
2035 // -1(5)2- node3 -1(8)2--
2039 // node2--1(6)2- node4 -1(9)2--- node6 (not in global route map)
2041 // -1(7)2- node5 -1(10)2-
2043 // Channels 5, 8, 9 and 10 are private channels.
2045 // chan5 1-to-2: enabled, 100 msat fee
2046 // chan5 2-to-1: enabled, 0 fee
2048 // chan6 1-to-2: enabled, 0 fee
2049 // chan6 2-to-1: enabled, 0 fee
2051 // chan7 1-to-2: enabled, 100% fee
2052 // chan7 2-to-1: enabled, 0 fee
2054 // chan8 1-to-2: enabled, variable fee (0 then 1000 msat)
2055 // chan8 2-to-1: enabled, 0 fee
2057 // chan9 1-to-2: enabled, 1001 msat fee
2058 // chan9 2-to-1: enabled, 0 fee
2060 // chan10 1-to-2: enabled, 0 fee
2061 // chan10 2-to-1: enabled, 0 fee
2063 // chan11 1-to-2: enabled, 0 fee
2064 // chan11 2-to-1: enabled, 0 fee
2066 let (our_privkey, _, privkeys, _) = get_nodes(&secp_ctx);
2068 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[0], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
2069 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2070 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2071 short_channel_id: 1,
2074 cltv_expiry_delta: 0,
2075 htlc_minimum_msat: 0,
2076 htlc_maximum_msat: OptionalField::Absent,
2078 fee_proportional_millionths: 0,
2079 excess_data: Vec::new()
2082 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
2084 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
2085 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2086 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2087 short_channel_id: 2,
2090 cltv_expiry_delta: (5 << 4) | 3,
2091 htlc_minimum_msat: 0,
2092 htlc_maximum_msat: OptionalField::Absent,
2093 fee_base_msat: u32::max_value(),
2094 fee_proportional_millionths: u32::max_value(),
2095 excess_data: Vec::new()
2097 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2098 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2099 short_channel_id: 2,
2102 cltv_expiry_delta: 0,
2103 htlc_minimum_msat: 0,
2104 htlc_maximum_msat: OptionalField::Absent,
2106 fee_proportional_millionths: 0,
2107 excess_data: Vec::new()
2110 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
2112 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[7], ChannelFeatures::from_le_bytes(id_to_feature_flags(12)), 12);
2113 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2114 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2115 short_channel_id: 12,
2118 cltv_expiry_delta: (5 << 4) | 3,
2119 htlc_minimum_msat: 0,
2120 htlc_maximum_msat: OptionalField::Absent,
2121 fee_base_msat: u32::max_value(),
2122 fee_proportional_millionths: u32::max_value(),
2123 excess_data: Vec::new()
2125 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2126 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2127 short_channel_id: 12,
2130 cltv_expiry_delta: 0,
2131 htlc_minimum_msat: 0,
2132 htlc_maximum_msat: OptionalField::Absent,
2134 fee_proportional_millionths: 0,
2135 excess_data: Vec::new()
2138 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], NodeFeatures::from_le_bytes(id_to_feature_flags(8)), 0);
2140 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
2141 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2142 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2143 short_channel_id: 3,
2146 cltv_expiry_delta: (3 << 4) | 1,
2147 htlc_minimum_msat: 0,
2148 htlc_maximum_msat: OptionalField::Absent,
2150 fee_proportional_millionths: 0,
2151 excess_data: Vec::new()
2153 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2154 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2155 short_channel_id: 3,
2158 cltv_expiry_delta: (3 << 4) | 2,
2159 htlc_minimum_msat: 0,
2160 htlc_maximum_msat: OptionalField::Absent,
2162 fee_proportional_millionths: 0,
2163 excess_data: Vec::new()
2166 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
2167 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2168 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2169 short_channel_id: 4,
2172 cltv_expiry_delta: (4 << 4) | 1,
2173 htlc_minimum_msat: 0,
2174 htlc_maximum_msat: OptionalField::Absent,
2176 fee_proportional_millionths: 1000000,
2177 excess_data: Vec::new()
2179 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2180 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2181 short_channel_id: 4,
2184 cltv_expiry_delta: (4 << 4) | 2,
2185 htlc_minimum_msat: 0,
2186 htlc_maximum_msat: OptionalField::Absent,
2188 fee_proportional_millionths: 0,
2189 excess_data: Vec::new()
2192 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(13)), 13);
2193 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2194 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2195 short_channel_id: 13,
2198 cltv_expiry_delta: (13 << 4) | 1,
2199 htlc_minimum_msat: 0,
2200 htlc_maximum_msat: OptionalField::Absent,
2202 fee_proportional_millionths: 2000000,
2203 excess_data: Vec::new()
2205 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2206 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2207 short_channel_id: 13,
2210 cltv_expiry_delta: (13 << 4) | 2,
2211 htlc_minimum_msat: 0,
2212 htlc_maximum_msat: OptionalField::Absent,
2214 fee_proportional_millionths: 0,
2215 excess_data: Vec::new()
2218 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
2220 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
2221 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2222 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2223 short_channel_id: 6,
2226 cltv_expiry_delta: (6 << 4) | 1,
2227 htlc_minimum_msat: 0,
2228 htlc_maximum_msat: OptionalField::Absent,
2230 fee_proportional_millionths: 0,
2231 excess_data: Vec::new()
2233 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
2234 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2235 short_channel_id: 6,
2238 cltv_expiry_delta: (6 << 4) | 2,
2239 htlc_minimum_msat: 0,
2240 htlc_maximum_msat: OptionalField::Absent,
2242 fee_proportional_millionths: 0,
2243 excess_data: Vec::new(),
2246 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(11)), 11);
2247 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
2248 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2249 short_channel_id: 11,
2252 cltv_expiry_delta: (11 << 4) | 1,
2253 htlc_minimum_msat: 0,
2254 htlc_maximum_msat: OptionalField::Absent,
2256 fee_proportional_millionths: 0,
2257 excess_data: Vec::new()
2259 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
2260 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2261 short_channel_id: 11,
2264 cltv_expiry_delta: (11 << 4) | 2,
2265 htlc_minimum_msat: 0,
2266 htlc_maximum_msat: OptionalField::Absent,
2268 fee_proportional_millionths: 0,
2269 excess_data: Vec::new()
2272 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(5)), 0);
2274 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
2276 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[5], ChannelFeatures::from_le_bytes(id_to_feature_flags(7)), 7);
2277 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2278 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2279 short_channel_id: 7,
2282 cltv_expiry_delta: (7 << 4) | 1,
2283 htlc_minimum_msat: 0,
2284 htlc_maximum_msat: OptionalField::Absent,
2286 fee_proportional_millionths: 1000000,
2287 excess_data: Vec::new()
2289 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[5], UnsignedChannelUpdate {
2290 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2291 short_channel_id: 7,
2294 cltv_expiry_delta: (7 << 4) | 2,
2295 htlc_minimum_msat: 0,
2296 htlc_maximum_msat: OptionalField::Absent,
2298 fee_proportional_millionths: 0,
2299 excess_data: Vec::new()
2302 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[5], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
2304 (secp_ctx, network_graph, net_graph_msg_handler, chain_monitor, logger)
2308 fn simple_route_test() {
2309 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2310 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2311 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2312 let scorer = test_utils::TestScorer::with_penalty(0);
2313 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2314 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2316 // Simple route to 2 via 1
2318 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) {
2319 assert_eq!(err, "Cannot send a payment of 0 msat");
2320 } else { panic!(); }
2322 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2323 assert_eq!(route.paths[0].len(), 2);
2325 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2326 assert_eq!(route.paths[0][0].short_channel_id, 2);
2327 assert_eq!(route.paths[0][0].fee_msat, 100);
2328 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2329 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2330 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2332 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2333 assert_eq!(route.paths[0][1].short_channel_id, 4);
2334 assert_eq!(route.paths[0][1].fee_msat, 100);
2335 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2336 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2337 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2341 fn invalid_first_hop_test() {
2342 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2343 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2344 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2345 let scorer = test_utils::TestScorer::with_penalty(0);
2346 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2347 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2349 // Simple route to 2 via 1
2351 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
2353 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) =
2354 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) {
2355 assert_eq!(err, "First hop cannot have our_node_pubkey as a destination.");
2356 } else { panic!(); }
2358 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2359 assert_eq!(route.paths[0].len(), 2);
2363 fn htlc_minimum_test() {
2364 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2365 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2366 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2367 let scorer = test_utils::TestScorer::with_penalty(0);
2368 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2369 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2371 // Simple route to 2 via 1
2373 // Disable other paths
2374 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2375 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2376 short_channel_id: 12,
2378 flags: 2, // to disable
2379 cltv_expiry_delta: 0,
2380 htlc_minimum_msat: 0,
2381 htlc_maximum_msat: OptionalField::Absent,
2383 fee_proportional_millionths: 0,
2384 excess_data: Vec::new()
2386 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2387 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2388 short_channel_id: 3,
2390 flags: 2, // to disable
2391 cltv_expiry_delta: 0,
2392 htlc_minimum_msat: 0,
2393 htlc_maximum_msat: OptionalField::Absent,
2395 fee_proportional_millionths: 0,
2396 excess_data: Vec::new()
2398 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2399 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2400 short_channel_id: 13,
2402 flags: 2, // to disable
2403 cltv_expiry_delta: 0,
2404 htlc_minimum_msat: 0,
2405 htlc_maximum_msat: OptionalField::Absent,
2407 fee_proportional_millionths: 0,
2408 excess_data: Vec::new()
2410 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2411 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2412 short_channel_id: 6,
2414 flags: 2, // to disable
2415 cltv_expiry_delta: 0,
2416 htlc_minimum_msat: 0,
2417 htlc_maximum_msat: OptionalField::Absent,
2419 fee_proportional_millionths: 0,
2420 excess_data: Vec::new()
2422 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2423 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2424 short_channel_id: 7,
2426 flags: 2, // to disable
2427 cltv_expiry_delta: 0,
2428 htlc_minimum_msat: 0,
2429 htlc_maximum_msat: OptionalField::Absent,
2431 fee_proportional_millionths: 0,
2432 excess_data: Vec::new()
2435 // Check against amount_to_transfer_over_msat.
2436 // Set minimal HTLC of 200_000_000 msat.
2437 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2438 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2439 short_channel_id: 2,
2442 cltv_expiry_delta: 0,
2443 htlc_minimum_msat: 200_000_000,
2444 htlc_maximum_msat: OptionalField::Absent,
2446 fee_proportional_millionths: 0,
2447 excess_data: Vec::new()
2450 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
2452 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2453 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2454 short_channel_id: 4,
2457 cltv_expiry_delta: 0,
2458 htlc_minimum_msat: 0,
2459 htlc_maximum_msat: OptionalField::Present(199_999_999),
2461 fee_proportional_millionths: 0,
2462 excess_data: Vec::new()
2465 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
2466 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) {
2467 assert_eq!(err, "Failed to find a path to the given destination");
2468 } else { panic!(); }
2470 // Lift the restriction on the first hop.
2471 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2472 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2473 short_channel_id: 2,
2476 cltv_expiry_delta: 0,
2477 htlc_minimum_msat: 0,
2478 htlc_maximum_msat: OptionalField::Absent,
2480 fee_proportional_millionths: 0,
2481 excess_data: Vec::new()
2484 // A payment above the minimum should pass
2485 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();
2486 assert_eq!(route.paths[0].len(), 2);
2490 fn htlc_minimum_overpay_test() {
2491 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2492 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2493 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
2494 let scorer = test_utils::TestScorer::with_penalty(0);
2495 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2496 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2498 // A route to node#2 via two paths.
2499 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
2500 // Thus, they can't send 60 without overpaying.
2501 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2502 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2503 short_channel_id: 2,
2506 cltv_expiry_delta: 0,
2507 htlc_minimum_msat: 35_000,
2508 htlc_maximum_msat: OptionalField::Present(40_000),
2510 fee_proportional_millionths: 0,
2511 excess_data: Vec::new()
2513 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2514 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2515 short_channel_id: 12,
2518 cltv_expiry_delta: 0,
2519 htlc_minimum_msat: 35_000,
2520 htlc_maximum_msat: OptionalField::Present(40_000),
2522 fee_proportional_millionths: 0,
2523 excess_data: Vec::new()
2527 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2528 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2529 short_channel_id: 13,
2532 cltv_expiry_delta: 0,
2533 htlc_minimum_msat: 0,
2534 htlc_maximum_msat: OptionalField::Absent,
2536 fee_proportional_millionths: 0,
2537 excess_data: Vec::new()
2539 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2540 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2541 short_channel_id: 4,
2544 cltv_expiry_delta: 0,
2545 htlc_minimum_msat: 0,
2546 htlc_maximum_msat: OptionalField::Absent,
2548 fee_proportional_millionths: 0,
2549 excess_data: Vec::new()
2552 // Disable other paths
2553 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2554 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2555 short_channel_id: 1,
2557 flags: 2, // to disable
2558 cltv_expiry_delta: 0,
2559 htlc_minimum_msat: 0,
2560 htlc_maximum_msat: OptionalField::Absent,
2562 fee_proportional_millionths: 0,
2563 excess_data: Vec::new()
2566 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 60_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2567 // Overpay fees to hit htlc_minimum_msat.
2568 let overpaid_fees = route.paths[0][0].fee_msat + route.paths[1][0].fee_msat;
2569 // TODO: this could be better balanced to overpay 10k and not 15k.
2570 assert_eq!(overpaid_fees, 15_000);
2572 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
2573 // while taking even more fee to match htlc_minimum_msat.
2574 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2575 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2576 short_channel_id: 12,
2579 cltv_expiry_delta: 0,
2580 htlc_minimum_msat: 65_000,
2581 htlc_maximum_msat: OptionalField::Present(80_000),
2583 fee_proportional_millionths: 0,
2584 excess_data: Vec::new()
2586 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2587 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2588 short_channel_id: 2,
2591 cltv_expiry_delta: 0,
2592 htlc_minimum_msat: 0,
2593 htlc_maximum_msat: OptionalField::Absent,
2595 fee_proportional_millionths: 0,
2596 excess_data: Vec::new()
2598 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2599 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2600 short_channel_id: 4,
2603 cltv_expiry_delta: 0,
2604 htlc_minimum_msat: 0,
2605 htlc_maximum_msat: OptionalField::Absent,
2607 fee_proportional_millionths: 100_000,
2608 excess_data: Vec::new()
2611 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 60_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2612 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
2613 assert_eq!(route.paths.len(), 1);
2614 assert_eq!(route.paths[0][0].short_channel_id, 12);
2615 let fees = route.paths[0][0].fee_msat;
2616 assert_eq!(fees, 5_000);
2618 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2619 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
2620 // the other channel.
2621 assert_eq!(route.paths.len(), 1);
2622 assert_eq!(route.paths[0][0].short_channel_id, 2);
2623 let fees = route.paths[0][0].fee_msat;
2624 assert_eq!(fees, 5_000);
2628 fn disable_channels_test() {
2629 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2630 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2631 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2632 let scorer = test_utils::TestScorer::with_penalty(0);
2633 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2634 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2636 // // Disable channels 4 and 12 by flags=2
2637 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2638 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2639 short_channel_id: 4,
2641 flags: 2, // to disable
2642 cltv_expiry_delta: 0,
2643 htlc_minimum_msat: 0,
2644 htlc_maximum_msat: OptionalField::Absent,
2646 fee_proportional_millionths: 0,
2647 excess_data: Vec::new()
2649 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2650 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2651 short_channel_id: 12,
2653 flags: 2, // to disable
2654 cltv_expiry_delta: 0,
2655 htlc_minimum_msat: 0,
2656 htlc_maximum_msat: OptionalField::Absent,
2658 fee_proportional_millionths: 0,
2659 excess_data: Vec::new()
2662 // If all the channels require some features we don't understand, route should fail
2663 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) {
2664 assert_eq!(err, "Failed to find a path to the given destination");
2665 } else { panic!(); }
2667 // If we specify a channel to node7, that overrides our local channel view and that gets used
2668 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2669 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();
2670 assert_eq!(route.paths[0].len(), 2);
2672 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2673 assert_eq!(route.paths[0][0].short_channel_id, 42);
2674 assert_eq!(route.paths[0][0].fee_msat, 200);
2675 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2676 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2677 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2679 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2680 assert_eq!(route.paths[0][1].short_channel_id, 13);
2681 assert_eq!(route.paths[0][1].fee_msat, 100);
2682 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2683 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2684 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2688 fn disable_node_test() {
2689 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2690 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2691 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2692 let scorer = test_utils::TestScorer::with_penalty(0);
2693 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2694 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2696 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
2697 let mut unknown_features = NodeFeatures::known();
2698 unknown_features.set_unknown_feature_required();
2699 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
2700 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
2701 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
2703 // If all nodes require some features we don't understand, route should fail
2704 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) {
2705 assert_eq!(err, "Failed to find a path to the given destination");
2706 } else { panic!(); }
2708 // If we specify a channel to node7, that overrides our local channel view and that gets used
2709 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2710 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();
2711 assert_eq!(route.paths[0].len(), 2);
2713 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2714 assert_eq!(route.paths[0][0].short_channel_id, 42);
2715 assert_eq!(route.paths[0][0].fee_msat, 200);
2716 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2717 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2718 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2720 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2721 assert_eq!(route.paths[0][1].short_channel_id, 13);
2722 assert_eq!(route.paths[0][1].fee_msat, 100);
2723 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2724 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2725 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2727 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
2728 // naively) assume that the user checked the feature bits on the invoice, which override
2729 // the node_announcement.
2733 fn our_chans_test() {
2734 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2735 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2736 let scorer = test_utils::TestScorer::with_penalty(0);
2737 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2738 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2740 // Route to 1 via 2 and 3 because our channel to 1 is disabled
2741 let payment_params = PaymentParameters::from_node_id(nodes[0]);
2742 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2743 assert_eq!(route.paths[0].len(), 3);
2745 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2746 assert_eq!(route.paths[0][0].short_channel_id, 2);
2747 assert_eq!(route.paths[0][0].fee_msat, 200);
2748 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2749 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2750 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2752 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2753 assert_eq!(route.paths[0][1].short_channel_id, 4);
2754 assert_eq!(route.paths[0][1].fee_msat, 100);
2755 assert_eq!(route.paths[0][1].cltv_expiry_delta, (3 << 4) | 2);
2756 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2757 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2759 assert_eq!(route.paths[0][2].pubkey, nodes[0]);
2760 assert_eq!(route.paths[0][2].short_channel_id, 3);
2761 assert_eq!(route.paths[0][2].fee_msat, 100);
2762 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
2763 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(1));
2764 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(3));
2766 // If we specify a channel to node7, that overrides our local channel view and that gets used
2767 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2768 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2769 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();
2770 assert_eq!(route.paths[0].len(), 2);
2772 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2773 assert_eq!(route.paths[0][0].short_channel_id, 42);
2774 assert_eq!(route.paths[0][0].fee_msat, 200);
2775 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2776 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2777 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2779 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2780 assert_eq!(route.paths[0][1].short_channel_id, 13);
2781 assert_eq!(route.paths[0][1].fee_msat, 100);
2782 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2783 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2784 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2787 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2788 let zero_fees = RoutingFees {
2790 proportional_millionths: 0,
2792 vec![RouteHint(vec![RouteHintHop {
2793 src_node_id: nodes[3],
2794 short_channel_id: 8,
2796 cltv_expiry_delta: (8 << 4) | 1,
2797 htlc_minimum_msat: None,
2798 htlc_maximum_msat: None,
2800 ]), RouteHint(vec![RouteHintHop {
2801 src_node_id: nodes[4],
2802 short_channel_id: 9,
2805 proportional_millionths: 0,
2807 cltv_expiry_delta: (9 << 4) | 1,
2808 htlc_minimum_msat: None,
2809 htlc_maximum_msat: None,
2810 }]), RouteHint(vec![RouteHintHop {
2811 src_node_id: nodes[5],
2812 short_channel_id: 10,
2814 cltv_expiry_delta: (10 << 4) | 1,
2815 htlc_minimum_msat: None,
2816 htlc_maximum_msat: None,
2820 fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2821 let zero_fees = RoutingFees {
2823 proportional_millionths: 0,
2825 vec![RouteHint(vec![RouteHintHop {
2826 src_node_id: nodes[2],
2827 short_channel_id: 5,
2830 proportional_millionths: 0,
2832 cltv_expiry_delta: (5 << 4) | 1,
2833 htlc_minimum_msat: None,
2834 htlc_maximum_msat: None,
2836 src_node_id: nodes[3],
2837 short_channel_id: 8,
2839 cltv_expiry_delta: (8 << 4) | 1,
2840 htlc_minimum_msat: None,
2841 htlc_maximum_msat: None,
2843 ]), RouteHint(vec![RouteHintHop {
2844 src_node_id: nodes[4],
2845 short_channel_id: 9,
2848 proportional_millionths: 0,
2850 cltv_expiry_delta: (9 << 4) | 1,
2851 htlc_minimum_msat: None,
2852 htlc_maximum_msat: None,
2853 }]), RouteHint(vec![RouteHintHop {
2854 src_node_id: nodes[5],
2855 short_channel_id: 10,
2857 cltv_expiry_delta: (10 << 4) | 1,
2858 htlc_minimum_msat: None,
2859 htlc_maximum_msat: None,
2864 fn partial_route_hint_test() {
2865 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2866 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2867 let scorer = test_utils::TestScorer::with_penalty(0);
2868 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2869 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2871 // Simple test across 2, 3, 5, and 4 via a last_hop channel
2872 // Tests the behaviour when the RouteHint contains a suboptimal hop.
2873 // RouteHint may be partially used by the algo to build the best path.
2875 // First check that last hop can't have its source as the payee.
2876 let invalid_last_hop = RouteHint(vec![RouteHintHop {
2877 src_node_id: nodes[6],
2878 short_channel_id: 8,
2881 proportional_millionths: 0,
2883 cltv_expiry_delta: (8 << 4) | 1,
2884 htlc_minimum_msat: None,
2885 htlc_maximum_msat: None,
2888 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
2889 invalid_last_hops.push(invalid_last_hop);
2891 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(invalid_last_hops);
2892 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) {
2893 assert_eq!(err, "Route hint cannot have the payee as the source.");
2894 } else { panic!(); }
2897 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops_multi_private_channels(&nodes));
2898 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2899 assert_eq!(route.paths[0].len(), 5);
2901 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2902 assert_eq!(route.paths[0][0].short_channel_id, 2);
2903 assert_eq!(route.paths[0][0].fee_msat, 100);
2904 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2905 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2906 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2908 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2909 assert_eq!(route.paths[0][1].short_channel_id, 4);
2910 assert_eq!(route.paths[0][1].fee_msat, 0);
2911 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
2912 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2913 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2915 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2916 assert_eq!(route.paths[0][2].short_channel_id, 6);
2917 assert_eq!(route.paths[0][2].fee_msat, 0);
2918 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
2919 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2920 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2922 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2923 assert_eq!(route.paths[0][3].short_channel_id, 11);
2924 assert_eq!(route.paths[0][3].fee_msat, 0);
2925 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
2926 // If we have a peer in the node map, we'll use their features here since we don't have
2927 // a way of figuring out their features from the invoice:
2928 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2929 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2931 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2932 assert_eq!(route.paths[0][4].short_channel_id, 8);
2933 assert_eq!(route.paths[0][4].fee_msat, 100);
2934 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2935 assert_eq!(route.paths[0][4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
2936 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2939 fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2940 let zero_fees = RoutingFees {
2942 proportional_millionths: 0,
2944 vec![RouteHint(vec![RouteHintHop {
2945 src_node_id: nodes[3],
2946 short_channel_id: 8,
2948 cltv_expiry_delta: (8 << 4) | 1,
2949 htlc_minimum_msat: None,
2950 htlc_maximum_msat: None,
2951 }]), RouteHint(vec![
2953 ]), RouteHint(vec![RouteHintHop {
2954 src_node_id: nodes[5],
2955 short_channel_id: 10,
2957 cltv_expiry_delta: (10 << 4) | 1,
2958 htlc_minimum_msat: None,
2959 htlc_maximum_msat: None,
2964 fn ignores_empty_last_hops_test() {
2965 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2966 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2967 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(empty_last_hop(&nodes));
2968 let scorer = test_utils::TestScorer::with_penalty(0);
2969 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2970 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2972 // Test handling of an empty RouteHint passed in Invoice.
2974 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2975 assert_eq!(route.paths[0].len(), 5);
2977 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2978 assert_eq!(route.paths[0][0].short_channel_id, 2);
2979 assert_eq!(route.paths[0][0].fee_msat, 100);
2980 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2981 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2982 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2984 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2985 assert_eq!(route.paths[0][1].short_channel_id, 4);
2986 assert_eq!(route.paths[0][1].fee_msat, 0);
2987 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
2988 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2989 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2991 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2992 assert_eq!(route.paths[0][2].short_channel_id, 6);
2993 assert_eq!(route.paths[0][2].fee_msat, 0);
2994 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
2995 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2996 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2998 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2999 assert_eq!(route.paths[0][3].short_channel_id, 11);
3000 assert_eq!(route.paths[0][3].fee_msat, 0);
3001 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
3002 // If we have a peer in the node map, we'll use their features here since we don't have
3003 // a way of figuring out their features from the invoice:
3004 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
3005 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
3007 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
3008 assert_eq!(route.paths[0][4].short_channel_id, 8);
3009 assert_eq!(route.paths[0][4].fee_msat, 100);
3010 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
3011 assert_eq!(route.paths[0][4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3012 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3015 /// Builds a trivial last-hop hint that passes through the two nodes given, with channel 0xff00
3017 fn multi_hop_last_hops_hint(hint_hops: [PublicKey; 2]) -> Vec<RouteHint> {
3018 let zero_fees = RoutingFees {
3020 proportional_millionths: 0,
3022 vec![RouteHint(vec![RouteHintHop {
3023 src_node_id: hint_hops[0],
3024 short_channel_id: 0xff00,
3027 proportional_millionths: 0,
3029 cltv_expiry_delta: (5 << 4) | 1,
3030 htlc_minimum_msat: None,
3031 htlc_maximum_msat: None,
3033 src_node_id: hint_hops[1],
3034 short_channel_id: 0xff01,
3036 cltv_expiry_delta: (8 << 4) | 1,
3037 htlc_minimum_msat: None,
3038 htlc_maximum_msat: None,
3043 fn multi_hint_last_hops_test() {
3044 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3045 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3046 let last_hops = multi_hop_last_hops_hint([nodes[2], nodes[3]]);
3047 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops.clone());
3048 let scorer = test_utils::TestScorer::with_penalty(0);
3049 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3050 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3051 // Test through channels 2, 3, 0xff00, 0xff01.
3052 // Test shows that multiple hop hints are considered.
3054 // Disabling channels 6 & 7 by flags=2
3055 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3056 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3057 short_channel_id: 6,
3059 flags: 2, // to disable
3060 cltv_expiry_delta: 0,
3061 htlc_minimum_msat: 0,
3062 htlc_maximum_msat: OptionalField::Absent,
3064 fee_proportional_millionths: 0,
3065 excess_data: Vec::new()
3067 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3068 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3069 short_channel_id: 7,
3071 flags: 2, // to disable
3072 cltv_expiry_delta: 0,
3073 htlc_minimum_msat: 0,
3074 htlc_maximum_msat: OptionalField::Absent,
3076 fee_proportional_millionths: 0,
3077 excess_data: Vec::new()
3080 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3081 assert_eq!(route.paths[0].len(), 4);
3083 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3084 assert_eq!(route.paths[0][0].short_channel_id, 2);
3085 assert_eq!(route.paths[0][0].fee_msat, 200);
3086 assert_eq!(route.paths[0][0].cltv_expiry_delta, 65);
3087 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3088 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3090 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3091 assert_eq!(route.paths[0][1].short_channel_id, 4);
3092 assert_eq!(route.paths[0][1].fee_msat, 100);
3093 assert_eq!(route.paths[0][1].cltv_expiry_delta, 81);
3094 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3095 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3097 assert_eq!(route.paths[0][2].pubkey, nodes[3]);
3098 assert_eq!(route.paths[0][2].short_channel_id, last_hops[0].0[0].short_channel_id);
3099 assert_eq!(route.paths[0][2].fee_msat, 0);
3100 assert_eq!(route.paths[0][2].cltv_expiry_delta, 129);
3101 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(4));
3102 assert_eq!(route.paths[0][2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3104 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
3105 assert_eq!(route.paths[0][3].short_channel_id, last_hops[0].0[1].short_channel_id);
3106 assert_eq!(route.paths[0][3].fee_msat, 100);
3107 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
3108 assert_eq!(route.paths[0][3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3109 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3113 fn private_multi_hint_last_hops_test() {
3114 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3115 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3117 let non_announced_privkey = SecretKey::from_slice(&hex::decode(format!("{:02x}", 0xf0).repeat(32)).unwrap()[..]).unwrap();
3118 let non_announced_pubkey = PublicKey::from_secret_key(&secp_ctx, &non_announced_privkey);
3120 let last_hops = multi_hop_last_hops_hint([nodes[2], non_announced_pubkey]);
3121 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops.clone());
3122 let scorer = test_utils::TestScorer::with_penalty(0);
3123 // Test through channels 2, 3, 0xff00, 0xff01.
3124 // Test shows that multiple hop hints are considered.
3126 // Disabling channels 6 & 7 by flags=2
3127 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3128 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3129 short_channel_id: 6,
3131 flags: 2, // to disable
3132 cltv_expiry_delta: 0,
3133 htlc_minimum_msat: 0,
3134 htlc_maximum_msat: OptionalField::Absent,
3136 fee_proportional_millionths: 0,
3137 excess_data: Vec::new()
3139 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3140 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3141 short_channel_id: 7,
3143 flags: 2, // to disable
3144 cltv_expiry_delta: 0,
3145 htlc_minimum_msat: 0,
3146 htlc_maximum_msat: OptionalField::Absent,
3148 fee_proportional_millionths: 0,
3149 excess_data: Vec::new()
3152 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &[42u8; 32]).unwrap();
3153 assert_eq!(route.paths[0].len(), 4);
3155 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3156 assert_eq!(route.paths[0][0].short_channel_id, 2);
3157 assert_eq!(route.paths[0][0].fee_msat, 200);
3158 assert_eq!(route.paths[0][0].cltv_expiry_delta, 65);
3159 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3160 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3162 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3163 assert_eq!(route.paths[0][1].short_channel_id, 4);
3164 assert_eq!(route.paths[0][1].fee_msat, 100);
3165 assert_eq!(route.paths[0][1].cltv_expiry_delta, 81);
3166 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3167 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3169 assert_eq!(route.paths[0][2].pubkey, non_announced_pubkey);
3170 assert_eq!(route.paths[0][2].short_channel_id, last_hops[0].0[0].short_channel_id);
3171 assert_eq!(route.paths[0][2].fee_msat, 0);
3172 assert_eq!(route.paths[0][2].cltv_expiry_delta, 129);
3173 assert_eq!(route.paths[0][2].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3174 assert_eq!(route.paths[0][2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3176 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
3177 assert_eq!(route.paths[0][3].short_channel_id, last_hops[0].0[1].short_channel_id);
3178 assert_eq!(route.paths[0][3].fee_msat, 100);
3179 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
3180 assert_eq!(route.paths[0][3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3181 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3184 fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3185 let zero_fees = RoutingFees {
3187 proportional_millionths: 0,
3189 vec![RouteHint(vec![RouteHintHop {
3190 src_node_id: nodes[4],
3191 short_channel_id: 11,
3193 cltv_expiry_delta: (11 << 4) | 1,
3194 htlc_minimum_msat: None,
3195 htlc_maximum_msat: None,
3197 src_node_id: nodes[3],
3198 short_channel_id: 8,
3200 cltv_expiry_delta: (8 << 4) | 1,
3201 htlc_minimum_msat: None,
3202 htlc_maximum_msat: None,
3203 }]), RouteHint(vec![RouteHintHop {
3204 src_node_id: nodes[4],
3205 short_channel_id: 9,
3208 proportional_millionths: 0,
3210 cltv_expiry_delta: (9 << 4) | 1,
3211 htlc_minimum_msat: None,
3212 htlc_maximum_msat: None,
3213 }]), RouteHint(vec![RouteHintHop {
3214 src_node_id: nodes[5],
3215 short_channel_id: 10,
3217 cltv_expiry_delta: (10 << 4) | 1,
3218 htlc_minimum_msat: None,
3219 htlc_maximum_msat: None,
3224 fn last_hops_with_public_channel_test() {
3225 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3226 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3227 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops_with_public_channel(&nodes));
3228 let scorer = test_utils::TestScorer::with_penalty(0);
3229 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3230 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3231 // This test shows that public routes can be present in the invoice
3232 // which would be handled in the same manner.
3234 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3235 assert_eq!(route.paths[0].len(), 5);
3237 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3238 assert_eq!(route.paths[0][0].short_channel_id, 2);
3239 assert_eq!(route.paths[0][0].fee_msat, 100);
3240 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
3241 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3242 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3244 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3245 assert_eq!(route.paths[0][1].short_channel_id, 4);
3246 assert_eq!(route.paths[0][1].fee_msat, 0);
3247 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
3248 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3249 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3251 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
3252 assert_eq!(route.paths[0][2].short_channel_id, 6);
3253 assert_eq!(route.paths[0][2].fee_msat, 0);
3254 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
3255 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
3256 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
3258 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
3259 assert_eq!(route.paths[0][3].short_channel_id, 11);
3260 assert_eq!(route.paths[0][3].fee_msat, 0);
3261 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
3262 // If we have a peer in the node map, we'll use their features here since we don't have
3263 // a way of figuring out their features from the invoice:
3264 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
3265 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
3267 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
3268 assert_eq!(route.paths[0][4].short_channel_id, 8);
3269 assert_eq!(route.paths[0][4].fee_msat, 100);
3270 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
3271 assert_eq!(route.paths[0][4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3272 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3276 fn our_chans_last_hop_connect_test() {
3277 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3278 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3279 let scorer = test_utils::TestScorer::with_penalty(0);
3280 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3281 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3283 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
3284 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3285 let mut last_hops = last_hops(&nodes);
3286 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops.clone());
3287 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();
3288 assert_eq!(route.paths[0].len(), 2);
3290 assert_eq!(route.paths[0][0].pubkey, nodes[3]);
3291 assert_eq!(route.paths[0][0].short_channel_id, 42);
3292 assert_eq!(route.paths[0][0].fee_msat, 0);
3293 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 4) | 1);
3294 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
3295 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3297 assert_eq!(route.paths[0][1].pubkey, nodes[6]);
3298 assert_eq!(route.paths[0][1].short_channel_id, 8);
3299 assert_eq!(route.paths[0][1].fee_msat, 100);
3300 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
3301 assert_eq!(route.paths[0][1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3302 assert_eq!(route.paths[0][1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3304 last_hops[0].0[0].fees.base_msat = 1000;
3306 // Revert to via 6 as the fee on 8 goes up
3307 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops);
3308 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3309 assert_eq!(route.paths[0].len(), 4);
3311 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3312 assert_eq!(route.paths[0][0].short_channel_id, 2);
3313 assert_eq!(route.paths[0][0].fee_msat, 200); // fee increased as its % of value transferred across node
3314 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
3315 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3316 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3318 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3319 assert_eq!(route.paths[0][1].short_channel_id, 4);
3320 assert_eq!(route.paths[0][1].fee_msat, 100);
3321 assert_eq!(route.paths[0][1].cltv_expiry_delta, (7 << 4) | 1);
3322 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3323 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3325 assert_eq!(route.paths[0][2].pubkey, nodes[5]);
3326 assert_eq!(route.paths[0][2].short_channel_id, 7);
3327 assert_eq!(route.paths[0][2].fee_msat, 0);
3328 assert_eq!(route.paths[0][2].cltv_expiry_delta, (10 << 4) | 1);
3329 // If we have a peer in the node map, we'll use their features here since we don't have
3330 // a way of figuring out their features from the invoice:
3331 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
3332 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(7));
3334 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
3335 assert_eq!(route.paths[0][3].short_channel_id, 10);
3336 assert_eq!(route.paths[0][3].fee_msat, 100);
3337 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
3338 assert_eq!(route.paths[0][3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3339 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3341 // ...but still use 8 for larger payments as 6 has a variable feerate
3342 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 2000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3343 assert_eq!(route.paths[0].len(), 5);
3345 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3346 assert_eq!(route.paths[0][0].short_channel_id, 2);
3347 assert_eq!(route.paths[0][0].fee_msat, 3000);
3348 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
3349 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3350 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3352 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3353 assert_eq!(route.paths[0][1].short_channel_id, 4);
3354 assert_eq!(route.paths[0][1].fee_msat, 0);
3355 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
3356 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3357 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3359 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
3360 assert_eq!(route.paths[0][2].short_channel_id, 6);
3361 assert_eq!(route.paths[0][2].fee_msat, 0);
3362 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
3363 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
3364 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
3366 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
3367 assert_eq!(route.paths[0][3].short_channel_id, 11);
3368 assert_eq!(route.paths[0][3].fee_msat, 1000);
3369 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
3370 // If we have a peer in the node map, we'll use their features here since we don't have
3371 // a way of figuring out their features from the invoice:
3372 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
3373 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
3375 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
3376 assert_eq!(route.paths[0][4].short_channel_id, 8);
3377 assert_eq!(route.paths[0][4].fee_msat, 2000);
3378 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
3379 assert_eq!(route.paths[0][4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3380 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3383 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> {
3384 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
3385 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3386 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3388 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
3389 let last_hops = RouteHint(vec![RouteHintHop {
3390 src_node_id: middle_node_id,
3391 short_channel_id: 8,
3394 proportional_millionths: last_hop_fee_prop,
3396 cltv_expiry_delta: (8 << 4) | 1,
3397 htlc_minimum_msat: None,
3398 htlc_maximum_msat: last_hop_htlc_max,
3400 let payment_params = PaymentParameters::from_node_id(target_node_id).with_route_hints(vec![last_hops]);
3401 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
3402 let scorer = test_utils::TestScorer::with_penalty(0);
3403 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3404 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3405 get_route(&source_node_id, &payment_params, &NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash()).read_only(),
3406 Some(&our_chans.iter().collect::<Vec<_>>()), route_val, 42, &test_utils::TestLogger::new(), &scorer, &random_seed_bytes)
3410 fn unannounced_path_test() {
3411 // We should be able to send a payment to a destination without any help of a routing graph
3412 // if we have a channel with a common counterparty that appears in the first and last hop
3414 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
3416 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3417 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3418 assert_eq!(route.paths[0].len(), 2);
3420 assert_eq!(route.paths[0][0].pubkey, middle_node_id);
3421 assert_eq!(route.paths[0][0].short_channel_id, 42);
3422 assert_eq!(route.paths[0][0].fee_msat, 1001);
3423 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 4) | 1);
3424 assert_eq!(route.paths[0][0].node_features.le_flags(), &[0b11]);
3425 assert_eq!(route.paths[0][0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3427 assert_eq!(route.paths[0][1].pubkey, target_node_id);
3428 assert_eq!(route.paths[0][1].short_channel_id, 8);
3429 assert_eq!(route.paths[0][1].fee_msat, 1000000);
3430 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
3431 assert_eq!(route.paths[0][1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3432 assert_eq!(route.paths[0][1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3436 fn overflow_unannounced_path_test_liquidity_underflow() {
3437 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
3438 // the last-hop had a fee which overflowed a u64, we'd panic.
3439 // This was due to us adding the first-hop from us unconditionally, causing us to think
3440 // we'd built a path (as our node is in the "best candidate" set), when we had not.
3441 // In this test, we previously hit a subtraction underflow due to having less available
3442 // liquidity at the last hop than 0.
3443 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());
3447 fn overflow_unannounced_path_test_feerate_overflow() {
3448 // This tests for the same case as above, except instead of hitting a subtraction
3449 // underflow, we hit a case where the fee charged at a hop overflowed.
3450 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());
3454 fn available_amount_while_routing_test() {
3455 // Tests whether we choose the correct available channel amount while routing.
3457 let (secp_ctx, network_graph, mut net_graph_msg_handler, chain_monitor, logger) = build_graph();
3458 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3459 let scorer = test_utils::TestScorer::with_penalty(0);
3460 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3461 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3462 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
3464 // We will use a simple single-path route from
3465 // our node to node2 via node0: channels {1, 3}.
3467 // First disable all other paths.
3468 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3469 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3470 short_channel_id: 2,
3473 cltv_expiry_delta: 0,
3474 htlc_minimum_msat: 0,
3475 htlc_maximum_msat: OptionalField::Present(100_000),
3477 fee_proportional_millionths: 0,
3478 excess_data: Vec::new()
3480 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3481 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3482 short_channel_id: 12,
3485 cltv_expiry_delta: 0,
3486 htlc_minimum_msat: 0,
3487 htlc_maximum_msat: OptionalField::Present(100_000),
3489 fee_proportional_millionths: 0,
3490 excess_data: Vec::new()
3493 // Make the first channel (#1) very permissive,
3494 // and we will be testing all limits on the second channel.
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: 1,
3500 cltv_expiry_delta: 0,
3501 htlc_minimum_msat: 0,
3502 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3504 fee_proportional_millionths: 0,
3505 excess_data: Vec::new()
3508 // First, let's see if routing works if we have absolutely no idea about the available amount.
3509 // In this case, it should be set to 250_000 sats.
3510 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3511 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3512 short_channel_id: 3,
3515 cltv_expiry_delta: 0,
3516 htlc_minimum_msat: 0,
3517 htlc_maximum_msat: OptionalField::Absent,
3519 fee_proportional_millionths: 0,
3520 excess_data: Vec::new()
3524 // Attempt to route more than available results in a failure.
3525 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3526 &our_id, &payment_params, &network_graph.read_only(), None, 250_000_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3527 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3528 } else { panic!(); }
3532 // Now, attempt to route an exact amount we have should be fine.
3533 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 250_000_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3534 assert_eq!(route.paths.len(), 1);
3535 let path = route.paths.last().unwrap();
3536 assert_eq!(path.len(), 2);
3537 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3538 assert_eq!(path.last().unwrap().fee_msat, 250_000_000);
3541 // Check that setting next_outbound_htlc_limit_msat in first_hops limits the channels.
3542 // Disable channel #1 and use another first hop.
3543 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3544 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3545 short_channel_id: 1,
3548 cltv_expiry_delta: 0,
3549 htlc_minimum_msat: 0,
3550 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3552 fee_proportional_millionths: 0,
3553 excess_data: Vec::new()
3556 // Now, limit the first_hop by the next_outbound_htlc_limit_msat of 200_000 sats.
3557 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
3560 // Attempt to route more than available results in a failure.
3561 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3562 &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) {
3563 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3564 } else { panic!(); }
3568 // Now, attempt to route an exact amount we have should be fine.
3569 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();
3570 assert_eq!(route.paths.len(), 1);
3571 let path = route.paths.last().unwrap();
3572 assert_eq!(path.len(), 2);
3573 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3574 assert_eq!(path.last().unwrap().fee_msat, 200_000_000);
3577 // Enable channel #1 back.
3578 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3579 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3580 short_channel_id: 1,
3583 cltv_expiry_delta: 0,
3584 htlc_minimum_msat: 0,
3585 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3587 fee_proportional_millionths: 0,
3588 excess_data: Vec::new()
3592 // Now let's see if routing works if we know only htlc_maximum_msat.
3593 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3594 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3595 short_channel_id: 3,
3598 cltv_expiry_delta: 0,
3599 htlc_minimum_msat: 0,
3600 htlc_maximum_msat: OptionalField::Present(15_000),
3602 fee_proportional_millionths: 0,
3603 excess_data: Vec::new()
3607 // Attempt to route more than available results in a failure.
3608 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3609 &our_id, &payment_params, &network_graph.read_only(), None, 15_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3610 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3611 } else { panic!(); }
3615 // Now, attempt to route an exact amount we have should be fine.
3616 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 15_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3617 assert_eq!(route.paths.len(), 1);
3618 let path = route.paths.last().unwrap();
3619 assert_eq!(path.len(), 2);
3620 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3621 assert_eq!(path.last().unwrap().fee_msat, 15_000);
3624 // Now let's see if routing works if we know only capacity from the UTXO.
3626 // We can't change UTXO capacity on the fly, so we'll disable
3627 // the existing channel and add another one with the capacity we need.
3628 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3629 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3630 short_channel_id: 3,
3633 cltv_expiry_delta: 0,
3634 htlc_minimum_msat: 0,
3635 htlc_maximum_msat: OptionalField::Absent,
3637 fee_proportional_millionths: 0,
3638 excess_data: Vec::new()
3641 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
3642 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
3643 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
3644 .push_opcode(opcodes::all::OP_PUSHNUM_2)
3645 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
3647 *chain_monitor.utxo_ret.lock().unwrap() = Ok(TxOut { value: 15, script_pubkey: good_script.clone() });
3648 net_graph_msg_handler.add_chain_access(Some(chain_monitor));
3650 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
3651 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3652 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3653 short_channel_id: 333,
3656 cltv_expiry_delta: (3 << 4) | 1,
3657 htlc_minimum_msat: 0,
3658 htlc_maximum_msat: OptionalField::Absent,
3660 fee_proportional_millionths: 0,
3661 excess_data: Vec::new()
3663 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3664 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3665 short_channel_id: 333,
3668 cltv_expiry_delta: (3 << 4) | 2,
3669 htlc_minimum_msat: 0,
3670 htlc_maximum_msat: OptionalField::Absent,
3672 fee_proportional_millionths: 0,
3673 excess_data: Vec::new()
3677 // Attempt to route more than available results in a failure.
3678 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3679 &our_id, &payment_params, &network_graph.read_only(), None, 15_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3680 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3681 } else { panic!(); }
3685 // Now, attempt to route an exact amount we have should be fine.
3686 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 15_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3687 assert_eq!(route.paths.len(), 1);
3688 let path = route.paths.last().unwrap();
3689 assert_eq!(path.len(), 2);
3690 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3691 assert_eq!(path.last().unwrap().fee_msat, 15_000);
3694 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
3695 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3696 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3697 short_channel_id: 333,
3700 cltv_expiry_delta: 0,
3701 htlc_minimum_msat: 0,
3702 htlc_maximum_msat: OptionalField::Present(10_000),
3704 fee_proportional_millionths: 0,
3705 excess_data: Vec::new()
3709 // Attempt to route more than available results in a failure.
3710 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3711 &our_id, &payment_params, &network_graph.read_only(), None, 10_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3712 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3713 } else { panic!(); }
3717 // Now, attempt to route an exact amount we have should be fine.
3718 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 10_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3719 assert_eq!(route.paths.len(), 1);
3720 let path = route.paths.last().unwrap();
3721 assert_eq!(path.len(), 2);
3722 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3723 assert_eq!(path.last().unwrap().fee_msat, 10_000);
3728 fn available_liquidity_last_hop_test() {
3729 // Check that available liquidity properly limits the path even when only
3730 // one of the latter hops is limited.
3731 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3732 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3733 let scorer = test_utils::TestScorer::with_penalty(0);
3734 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3735 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3736 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
3738 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3739 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
3740 // Total capacity: 50 sats.
3742 // Disable other potential paths.
3743 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3744 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3745 short_channel_id: 2,
3748 cltv_expiry_delta: 0,
3749 htlc_minimum_msat: 0,
3750 htlc_maximum_msat: OptionalField::Present(100_000),
3752 fee_proportional_millionths: 0,
3753 excess_data: Vec::new()
3755 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3756 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3757 short_channel_id: 7,
3760 cltv_expiry_delta: 0,
3761 htlc_minimum_msat: 0,
3762 htlc_maximum_msat: OptionalField::Present(100_000),
3764 fee_proportional_millionths: 0,
3765 excess_data: Vec::new()
3770 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3771 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3772 short_channel_id: 12,
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()
3782 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3783 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3784 short_channel_id: 13,
3787 cltv_expiry_delta: 0,
3788 htlc_minimum_msat: 0,
3789 htlc_maximum_msat: OptionalField::Present(100_000),
3791 fee_proportional_millionths: 0,
3792 excess_data: Vec::new()
3795 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3796 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3797 short_channel_id: 6,
3800 cltv_expiry_delta: 0,
3801 htlc_minimum_msat: 0,
3802 htlc_maximum_msat: OptionalField::Present(50_000),
3804 fee_proportional_millionths: 0,
3805 excess_data: Vec::new()
3807 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3808 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3809 short_channel_id: 11,
3812 cltv_expiry_delta: 0,
3813 htlc_minimum_msat: 0,
3814 htlc_maximum_msat: OptionalField::Present(100_000),
3816 fee_proportional_millionths: 0,
3817 excess_data: Vec::new()
3820 // Attempt to route more than available results in a failure.
3821 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3822 &our_id, &payment_params, &network_graph.read_only(), None, 60_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3823 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3824 } else { panic!(); }
3828 // Now, attempt to route 49 sats (just a bit below the capacity).
3829 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 49_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3830 assert_eq!(route.paths.len(), 1);
3831 let mut total_amount_paid_msat = 0;
3832 for path in &route.paths {
3833 assert_eq!(path.len(), 4);
3834 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3835 total_amount_paid_msat += path.last().unwrap().fee_msat;
3837 assert_eq!(total_amount_paid_msat, 49_000);
3841 // Attempt to route an exact amount is also fine
3842 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3843 assert_eq!(route.paths.len(), 1);
3844 let mut total_amount_paid_msat = 0;
3845 for path in &route.paths {
3846 assert_eq!(path.len(), 4);
3847 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3848 total_amount_paid_msat += path.last().unwrap().fee_msat;
3850 assert_eq!(total_amount_paid_msat, 50_000);
3855 fn ignore_fee_first_hop_test() {
3856 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3857 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3858 let scorer = test_utils::TestScorer::with_penalty(0);
3859 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3860 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3861 let payment_params = PaymentParameters::from_node_id(nodes[2]);
3863 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3864 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3865 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3866 short_channel_id: 1,
3869 cltv_expiry_delta: 0,
3870 htlc_minimum_msat: 0,
3871 htlc_maximum_msat: OptionalField::Present(100_000),
3872 fee_base_msat: 1_000_000,
3873 fee_proportional_millionths: 0,
3874 excess_data: Vec::new()
3876 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3877 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3878 short_channel_id: 3,
3881 cltv_expiry_delta: 0,
3882 htlc_minimum_msat: 0,
3883 htlc_maximum_msat: OptionalField::Present(50_000),
3885 fee_proportional_millionths: 0,
3886 excess_data: Vec::new()
3890 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3891 assert_eq!(route.paths.len(), 1);
3892 let mut total_amount_paid_msat = 0;
3893 for path in &route.paths {
3894 assert_eq!(path.len(), 2);
3895 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3896 total_amount_paid_msat += path.last().unwrap().fee_msat;
3898 assert_eq!(total_amount_paid_msat, 50_000);
3903 fn simple_mpp_route_test() {
3904 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3905 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3906 let scorer = test_utils::TestScorer::with_penalty(0);
3907 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3908 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3909 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
3911 // We need a route consisting of 3 paths:
3912 // From our node to node2 via node0, node7, node1 (three paths one hop each).
3913 // To achieve this, the amount being transferred should be around
3914 // the total capacity of these 3 paths.
3916 // First, we set limits on these (previously unlimited) channels.
3917 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
3919 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3920 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3921 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3922 short_channel_id: 1,
3925 cltv_expiry_delta: 0,
3926 htlc_minimum_msat: 0,
3927 htlc_maximum_msat: OptionalField::Present(100_000),
3929 fee_proportional_millionths: 0,
3930 excess_data: Vec::new()
3932 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3933 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3934 short_channel_id: 3,
3937 cltv_expiry_delta: 0,
3938 htlc_minimum_msat: 0,
3939 htlc_maximum_msat: OptionalField::Present(50_000),
3941 fee_proportional_millionths: 0,
3942 excess_data: Vec::new()
3945 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
3946 // (total limit 60).
3947 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3948 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3949 short_channel_id: 12,
3952 cltv_expiry_delta: 0,
3953 htlc_minimum_msat: 0,
3954 htlc_maximum_msat: OptionalField::Present(60_000),
3956 fee_proportional_millionths: 0,
3957 excess_data: Vec::new()
3959 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3960 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3961 short_channel_id: 13,
3964 cltv_expiry_delta: 0,
3965 htlc_minimum_msat: 0,
3966 htlc_maximum_msat: OptionalField::Present(60_000),
3968 fee_proportional_millionths: 0,
3969 excess_data: Vec::new()
3972 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
3973 // (total capacity 180 sats).
3974 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3975 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3976 short_channel_id: 2,
3979 cltv_expiry_delta: 0,
3980 htlc_minimum_msat: 0,
3981 htlc_maximum_msat: OptionalField::Present(200_000),
3983 fee_proportional_millionths: 0,
3984 excess_data: Vec::new()
3986 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3987 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3988 short_channel_id: 4,
3991 cltv_expiry_delta: 0,
3992 htlc_minimum_msat: 0,
3993 htlc_maximum_msat: OptionalField::Present(180_000),
3995 fee_proportional_millionths: 0,
3996 excess_data: Vec::new()
4000 // Attempt to route more than available results in a failure.
4001 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4002 &our_id, &payment_params, &network_graph.read_only(), None, 300_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
4003 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4004 } else { panic!(); }
4008 // Now, attempt to route 250 sats (just a bit below the capacity).
4009 // Our algorithm should provide us with these 3 paths.
4010 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 250_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4011 assert_eq!(route.paths.len(), 3);
4012 let mut total_amount_paid_msat = 0;
4013 for path in &route.paths {
4014 assert_eq!(path.len(), 2);
4015 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4016 total_amount_paid_msat += path.last().unwrap().fee_msat;
4018 assert_eq!(total_amount_paid_msat, 250_000);
4022 // Attempt to route an exact amount is also fine
4023 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 290_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4024 assert_eq!(route.paths.len(), 3);
4025 let mut total_amount_paid_msat = 0;
4026 for path in &route.paths {
4027 assert_eq!(path.len(), 2);
4028 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4029 total_amount_paid_msat += path.last().unwrap().fee_msat;
4031 assert_eq!(total_amount_paid_msat, 290_000);
4036 fn long_mpp_route_test() {
4037 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4038 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4039 let scorer = test_utils::TestScorer::with_penalty(0);
4040 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4041 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4042 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
4044 // We need a route consisting of 3 paths:
4045 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
4046 // Note that these paths overlap (channels 5, 12, 13).
4047 // We will route 300 sats.
4048 // Each path will have 100 sats capacity, those channels which
4049 // are used twice will have 200 sats capacity.
4051 // Disable other potential paths.
4052 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4053 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4054 short_channel_id: 2,
4057 cltv_expiry_delta: 0,
4058 htlc_minimum_msat: 0,
4059 htlc_maximum_msat: OptionalField::Present(100_000),
4061 fee_proportional_millionths: 0,
4062 excess_data: Vec::new()
4064 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4065 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4066 short_channel_id: 7,
4069 cltv_expiry_delta: 0,
4070 htlc_minimum_msat: 0,
4071 htlc_maximum_msat: OptionalField::Present(100_000),
4073 fee_proportional_millionths: 0,
4074 excess_data: Vec::new()
4077 // Path via {node0, node2} is channels {1, 3, 5}.
4078 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4079 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4080 short_channel_id: 1,
4083 cltv_expiry_delta: 0,
4084 htlc_minimum_msat: 0,
4085 htlc_maximum_msat: OptionalField::Present(100_000),
4087 fee_proportional_millionths: 0,
4088 excess_data: Vec::new()
4090 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4091 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4092 short_channel_id: 3,
4095 cltv_expiry_delta: 0,
4096 htlc_minimum_msat: 0,
4097 htlc_maximum_msat: OptionalField::Present(100_000),
4099 fee_proportional_millionths: 0,
4100 excess_data: Vec::new()
4103 // Capacity of 200 sats because this channel will be used by 3rd path as well.
4104 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4105 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4106 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4107 short_channel_id: 5,
4110 cltv_expiry_delta: 0,
4111 htlc_minimum_msat: 0,
4112 htlc_maximum_msat: OptionalField::Present(200_000),
4114 fee_proportional_millionths: 0,
4115 excess_data: Vec::new()
4118 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4119 // Add 100 sats to the capacities of {12, 13}, because these channels
4120 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
4121 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4122 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4123 short_channel_id: 12,
4126 cltv_expiry_delta: 0,
4127 htlc_minimum_msat: 0,
4128 htlc_maximum_msat: OptionalField::Present(200_000),
4130 fee_proportional_millionths: 0,
4131 excess_data: Vec::new()
4133 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4134 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4135 short_channel_id: 13,
4138 cltv_expiry_delta: 0,
4139 htlc_minimum_msat: 0,
4140 htlc_maximum_msat: OptionalField::Present(200_000),
4142 fee_proportional_millionths: 0,
4143 excess_data: Vec::new()
4146 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4147 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4148 short_channel_id: 6,
4151 cltv_expiry_delta: 0,
4152 htlc_minimum_msat: 0,
4153 htlc_maximum_msat: OptionalField::Present(100_000),
4155 fee_proportional_millionths: 0,
4156 excess_data: Vec::new()
4158 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4159 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4160 short_channel_id: 11,
4163 cltv_expiry_delta: 0,
4164 htlc_minimum_msat: 0,
4165 htlc_maximum_msat: OptionalField::Present(100_000),
4167 fee_proportional_millionths: 0,
4168 excess_data: Vec::new()
4171 // Path via {node7, node2} is channels {12, 13, 5}.
4172 // We already limited them to 200 sats (they are used twice for 100 sats).
4173 // Nothing to do here.
4176 // Attempt to route more than available results in a failure.
4177 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4178 &our_id, &payment_params, &network_graph.read_only(), None, 350_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
4179 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4180 } else { panic!(); }
4184 // Now, attempt to route 300 sats (exact amount we can route).
4185 // Our algorithm should provide us with these 3 paths, 100 sats each.
4186 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 300_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4187 assert_eq!(route.paths.len(), 3);
4189 let mut total_amount_paid_msat = 0;
4190 for path in &route.paths {
4191 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
4192 total_amount_paid_msat += path.last().unwrap().fee_msat;
4194 assert_eq!(total_amount_paid_msat, 300_000);
4200 fn mpp_cheaper_route_test() {
4201 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4202 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4203 let scorer = test_utils::TestScorer::with_penalty(0);
4204 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4205 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4206 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
4208 // This test checks that if we have two cheaper paths and one more expensive path,
4209 // so that liquidity-wise any 2 of 3 combination is sufficient,
4210 // two cheaper paths will be taken.
4211 // These paths have equal available liquidity.
4213 // We need a combination of 3 paths:
4214 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
4215 // Note that these paths overlap (channels 5, 12, 13).
4216 // Each path will have 100 sats capacity, those channels which
4217 // are used twice will have 200 sats capacity.
4219 // Disable other potential paths.
4220 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4221 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4222 short_channel_id: 2,
4225 cltv_expiry_delta: 0,
4226 htlc_minimum_msat: 0,
4227 htlc_maximum_msat: OptionalField::Present(100_000),
4229 fee_proportional_millionths: 0,
4230 excess_data: Vec::new()
4232 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4233 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4234 short_channel_id: 7,
4237 cltv_expiry_delta: 0,
4238 htlc_minimum_msat: 0,
4239 htlc_maximum_msat: OptionalField::Present(100_000),
4241 fee_proportional_millionths: 0,
4242 excess_data: Vec::new()
4245 // Path via {node0, node2} is channels {1, 3, 5}.
4246 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4247 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4248 short_channel_id: 1,
4251 cltv_expiry_delta: 0,
4252 htlc_minimum_msat: 0,
4253 htlc_maximum_msat: OptionalField::Present(100_000),
4255 fee_proportional_millionths: 0,
4256 excess_data: Vec::new()
4258 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4259 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4260 short_channel_id: 3,
4263 cltv_expiry_delta: 0,
4264 htlc_minimum_msat: 0,
4265 htlc_maximum_msat: OptionalField::Present(100_000),
4267 fee_proportional_millionths: 0,
4268 excess_data: Vec::new()
4271 // Capacity of 200 sats because this channel will be used by 3rd path as well.
4272 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4273 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4274 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4275 short_channel_id: 5,
4278 cltv_expiry_delta: 0,
4279 htlc_minimum_msat: 0,
4280 htlc_maximum_msat: OptionalField::Present(200_000),
4282 fee_proportional_millionths: 0,
4283 excess_data: Vec::new()
4286 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4287 // Add 100 sats to the capacities of {12, 13}, because these channels
4288 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
4289 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4290 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4291 short_channel_id: 12,
4294 cltv_expiry_delta: 0,
4295 htlc_minimum_msat: 0,
4296 htlc_maximum_msat: OptionalField::Present(200_000),
4298 fee_proportional_millionths: 0,
4299 excess_data: Vec::new()
4301 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4302 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4303 short_channel_id: 13,
4306 cltv_expiry_delta: 0,
4307 htlc_minimum_msat: 0,
4308 htlc_maximum_msat: OptionalField::Present(200_000),
4310 fee_proportional_millionths: 0,
4311 excess_data: Vec::new()
4314 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4315 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4316 short_channel_id: 6,
4319 cltv_expiry_delta: 0,
4320 htlc_minimum_msat: 0,
4321 htlc_maximum_msat: OptionalField::Present(100_000),
4322 fee_base_msat: 1_000,
4323 fee_proportional_millionths: 0,
4324 excess_data: Vec::new()
4326 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4327 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4328 short_channel_id: 11,
4331 cltv_expiry_delta: 0,
4332 htlc_minimum_msat: 0,
4333 htlc_maximum_msat: OptionalField::Present(100_000),
4335 fee_proportional_millionths: 0,
4336 excess_data: Vec::new()
4339 // Path via {node7, node2} is channels {12, 13, 5}.
4340 // We already limited them to 200 sats (they are used twice for 100 sats).
4341 // Nothing to do here.
4344 // Now, attempt to route 180 sats.
4345 // Our algorithm should provide us with these 2 paths.
4346 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 180_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4347 assert_eq!(route.paths.len(), 2);
4349 let mut total_value_transferred_msat = 0;
4350 let mut total_paid_msat = 0;
4351 for path in &route.paths {
4352 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
4353 total_value_transferred_msat += path.last().unwrap().fee_msat;
4355 total_paid_msat += hop.fee_msat;
4358 // If we paid fee, this would be higher.
4359 assert_eq!(total_value_transferred_msat, 180_000);
4360 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
4361 assert_eq!(total_fees_paid, 0);
4366 fn fees_on_mpp_route_test() {
4367 // This test makes sure that MPP algorithm properly takes into account
4368 // fees charged on the channels, by making the fees impactful:
4369 // if the fee is not properly accounted for, the behavior is different.
4370 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4371 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4372 let scorer = test_utils::TestScorer::with_penalty(0);
4373 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4374 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4375 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
4377 // We need a route consisting of 2 paths:
4378 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
4379 // We will route 200 sats, Each path will have 100 sats capacity.
4381 // This test is not particularly stable: e.g.,
4382 // there's a way to route via {node0, node2, node4}.
4383 // It works while pathfinding is deterministic, but can be broken otherwise.
4384 // It's fine to ignore this concern for now.
4386 // Disable other potential paths.
4387 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4388 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4389 short_channel_id: 2,
4392 cltv_expiry_delta: 0,
4393 htlc_minimum_msat: 0,
4394 htlc_maximum_msat: OptionalField::Present(100_000),
4396 fee_proportional_millionths: 0,
4397 excess_data: Vec::new()
4400 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4401 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4402 short_channel_id: 7,
4405 cltv_expiry_delta: 0,
4406 htlc_minimum_msat: 0,
4407 htlc_maximum_msat: OptionalField::Present(100_000),
4409 fee_proportional_millionths: 0,
4410 excess_data: Vec::new()
4413 // Path via {node0, node2} is channels {1, 3, 5}.
4414 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4415 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4416 short_channel_id: 1,
4419 cltv_expiry_delta: 0,
4420 htlc_minimum_msat: 0,
4421 htlc_maximum_msat: OptionalField::Present(100_000),
4423 fee_proportional_millionths: 0,
4424 excess_data: Vec::new()
4426 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4427 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4428 short_channel_id: 3,
4431 cltv_expiry_delta: 0,
4432 htlc_minimum_msat: 0,
4433 htlc_maximum_msat: OptionalField::Present(100_000),
4435 fee_proportional_millionths: 0,
4436 excess_data: Vec::new()
4439 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4440 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4441 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4442 short_channel_id: 5,
4445 cltv_expiry_delta: 0,
4446 htlc_minimum_msat: 0,
4447 htlc_maximum_msat: OptionalField::Present(100_000),
4449 fee_proportional_millionths: 0,
4450 excess_data: Vec::new()
4453 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4454 // All channels should be 100 sats capacity. But for the fee experiment,
4455 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
4456 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
4457 // 100 sats (and pay 150 sats in fees for the use of channel 6),
4458 // so no matter how large are other channels,
4459 // the whole path will be limited by 100 sats with just these 2 conditions:
4460 // - channel 12 capacity is 250 sats
4461 // - fee for channel 6 is 150 sats
4462 // Let's test this by enforcing these 2 conditions and removing other limits.
4463 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4464 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4465 short_channel_id: 12,
4468 cltv_expiry_delta: 0,
4469 htlc_minimum_msat: 0,
4470 htlc_maximum_msat: OptionalField::Present(250_000),
4472 fee_proportional_millionths: 0,
4473 excess_data: Vec::new()
4475 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4476 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4477 short_channel_id: 13,
4480 cltv_expiry_delta: 0,
4481 htlc_minimum_msat: 0,
4482 htlc_maximum_msat: OptionalField::Absent,
4484 fee_proportional_millionths: 0,
4485 excess_data: Vec::new()
4488 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4489 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4490 short_channel_id: 6,
4493 cltv_expiry_delta: 0,
4494 htlc_minimum_msat: 0,
4495 htlc_maximum_msat: OptionalField::Absent,
4496 fee_base_msat: 150_000,
4497 fee_proportional_millionths: 0,
4498 excess_data: Vec::new()
4500 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4501 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4502 short_channel_id: 11,
4505 cltv_expiry_delta: 0,
4506 htlc_minimum_msat: 0,
4507 htlc_maximum_msat: OptionalField::Absent,
4509 fee_proportional_millionths: 0,
4510 excess_data: Vec::new()
4514 // Attempt to route more than available results in a failure.
4515 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4516 &our_id, &payment_params, &network_graph.read_only(), None, 210_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
4517 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4518 } else { panic!(); }
4522 // Now, attempt to route 200 sats (exact amount we can route).
4523 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 200_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4524 assert_eq!(route.paths.len(), 2);
4526 let mut total_amount_paid_msat = 0;
4527 for path in &route.paths {
4528 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
4529 total_amount_paid_msat += path.last().unwrap().fee_msat;
4531 assert_eq!(total_amount_paid_msat, 200_000);
4532 assert_eq!(route.get_total_fees(), 150_000);
4537 fn mpp_with_last_hops() {
4538 // Previously, if we tried to send an MPP payment to a destination which was only reachable
4539 // via a single last-hop route hint, we'd fail to route if we first collected routes
4540 // totaling close but not quite enough to fund the full payment.
4542 // This was because we considered last-hop hints to have exactly the sought payment amount
4543 // instead of the amount we were trying to collect, needlessly limiting our path searching
4544 // at the very first hop.
4546 // Specifically, this interacted with our "all paths must fund at least 5% of total target"
4547 // criterion to cause us to refuse all routes at the last hop hint which would be considered
4548 // to only have the remaining to-collect amount in available liquidity.
4550 // This bug appeared in production in some specific channel configurations.
4551 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4552 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4553 let scorer = test_utils::TestScorer::with_penalty(0);
4554 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4555 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4556 let payment_params = PaymentParameters::from_node_id(PublicKey::from_slice(&[02; 33]).unwrap()).with_features(InvoiceFeatures::known())
4557 .with_route_hints(vec![RouteHint(vec![RouteHintHop {
4558 src_node_id: nodes[2],
4559 short_channel_id: 42,
4560 fees: RoutingFees { base_msat: 0, proportional_millionths: 0 },
4561 cltv_expiry_delta: 42,
4562 htlc_minimum_msat: None,
4563 htlc_maximum_msat: None,
4566 // Keep only two paths from us to nodes[2], both with a 99sat HTLC maximum, with one with
4567 // no fee and one with a 1msat fee. Previously, trying to route 100 sats to nodes[2] here
4568 // would first use the no-fee route and then fail to find a path along the second route as
4569 // we think we can only send up to 1 additional sat over the last-hop but refuse to as its
4570 // under 5% of our payment amount.
4571 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4572 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4573 short_channel_id: 1,
4576 cltv_expiry_delta: (5 << 4) | 5,
4577 htlc_minimum_msat: 0,
4578 htlc_maximum_msat: OptionalField::Present(99_000),
4579 fee_base_msat: u32::max_value(),
4580 fee_proportional_millionths: u32::max_value(),
4581 excess_data: Vec::new()
4583 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4584 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4585 short_channel_id: 2,
4588 cltv_expiry_delta: (5 << 4) | 3,
4589 htlc_minimum_msat: 0,
4590 htlc_maximum_msat: OptionalField::Present(99_000),
4591 fee_base_msat: u32::max_value(),
4592 fee_proportional_millionths: u32::max_value(),
4593 excess_data: Vec::new()
4595 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4596 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4597 short_channel_id: 4,
4600 cltv_expiry_delta: (4 << 4) | 1,
4601 htlc_minimum_msat: 0,
4602 htlc_maximum_msat: OptionalField::Absent,
4604 fee_proportional_millionths: 0,
4605 excess_data: Vec::new()
4607 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4608 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4609 short_channel_id: 13,
4611 flags: 0|2, // Channel disabled
4612 cltv_expiry_delta: (13 << 4) | 1,
4613 htlc_minimum_msat: 0,
4614 htlc_maximum_msat: OptionalField::Absent,
4616 fee_proportional_millionths: 2000000,
4617 excess_data: Vec::new()
4620 // Get a route for 100 sats and check that we found the MPP route no problem and didn't
4622 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4623 assert_eq!(route.paths.len(), 2);
4624 // Paths are somewhat randomly ordered, but:
4625 // * the first is channel 2 (1 msat fee) -> channel 4 -> channel 42
4626 // * the second is channel 1 (0 fee, but 99 sat maximum) -> channel 3 -> channel 42
4627 assert_eq!(route.paths[0][0].short_channel_id, 2);
4628 assert_eq!(route.paths[0][0].fee_msat, 1);
4629 assert_eq!(route.paths[0][2].fee_msat, 1_000);
4630 assert_eq!(route.paths[1][0].short_channel_id, 1);
4631 assert_eq!(route.paths[1][0].fee_msat, 0);
4632 assert_eq!(route.paths[1][2].fee_msat, 99_000);
4633 assert_eq!(route.get_total_fees(), 1);
4634 assert_eq!(route.get_total_amount(), 100_000);
4638 fn drop_lowest_channel_mpp_route_test() {
4639 // This test checks that low-capacity channel is dropped when after
4640 // path finding we realize that we found more capacity than we need.
4641 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4642 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4643 let scorer = test_utils::TestScorer::with_penalty(0);
4644 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4645 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4646 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
4648 // We need a route consisting of 3 paths:
4649 // From our node to node2 via node0, node7, node1 (three paths one hop each).
4651 // The first and the second paths should be sufficient, but the third should be
4652 // cheaper, so that we select it but drop later.
4654 // First, we set limits on these (previously unlimited) channels.
4655 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
4657 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
4658 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4659 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4660 short_channel_id: 1,
4663 cltv_expiry_delta: 0,
4664 htlc_minimum_msat: 0,
4665 htlc_maximum_msat: OptionalField::Present(100_000),
4667 fee_proportional_millionths: 0,
4668 excess_data: Vec::new()
4670 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4671 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4672 short_channel_id: 3,
4675 cltv_expiry_delta: 0,
4676 htlc_minimum_msat: 0,
4677 htlc_maximum_msat: OptionalField::Present(50_000),
4679 fee_proportional_millionths: 0,
4680 excess_data: Vec::new()
4683 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
4684 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4685 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4686 short_channel_id: 12,
4689 cltv_expiry_delta: 0,
4690 htlc_minimum_msat: 0,
4691 htlc_maximum_msat: OptionalField::Present(60_000),
4693 fee_proportional_millionths: 0,
4694 excess_data: Vec::new()
4696 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4697 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4698 short_channel_id: 13,
4701 cltv_expiry_delta: 0,
4702 htlc_minimum_msat: 0,
4703 htlc_maximum_msat: OptionalField::Present(60_000),
4705 fee_proportional_millionths: 0,
4706 excess_data: Vec::new()
4709 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
4710 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4711 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4712 short_channel_id: 2,
4715 cltv_expiry_delta: 0,
4716 htlc_minimum_msat: 0,
4717 htlc_maximum_msat: OptionalField::Present(20_000),
4719 fee_proportional_millionths: 0,
4720 excess_data: Vec::new()
4722 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4723 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4724 short_channel_id: 4,
4727 cltv_expiry_delta: 0,
4728 htlc_minimum_msat: 0,
4729 htlc_maximum_msat: OptionalField::Present(20_000),
4731 fee_proportional_millionths: 0,
4732 excess_data: Vec::new()
4736 // Attempt to route more than available results in a failure.
4737 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4738 &our_id, &payment_params, &network_graph.read_only(), None, 150_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
4739 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4740 } else { panic!(); }
4744 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
4745 // Our algorithm should provide us with these 3 paths.
4746 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 125_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4747 assert_eq!(route.paths.len(), 3);
4748 let mut total_amount_paid_msat = 0;
4749 for path in &route.paths {
4750 assert_eq!(path.len(), 2);
4751 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4752 total_amount_paid_msat += path.last().unwrap().fee_msat;
4754 assert_eq!(total_amount_paid_msat, 125_000);
4758 // Attempt to route without the last small cheap channel
4759 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4760 assert_eq!(route.paths.len(), 2);
4761 let mut total_amount_paid_msat = 0;
4762 for path in &route.paths {
4763 assert_eq!(path.len(), 2);
4764 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4765 total_amount_paid_msat += path.last().unwrap().fee_msat;
4767 assert_eq!(total_amount_paid_msat, 90_000);
4772 fn min_criteria_consistency() {
4773 // Test that we don't use an inconsistent metric between updating and walking nodes during
4774 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
4775 // was updated with a different criterion from the heap sorting, resulting in loops in
4776 // calculated paths. We test for that specific case here.
4778 // We construct a network that looks like this:
4780 // node2 -1(3)2- node3
4784 // node1 -1(5)2- node4 -1(1)2- node6
4790 // We create a loop on the side of our real path - our destination is node 6, with a
4791 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
4792 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
4793 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
4794 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
4795 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
4796 // "previous hop" being set to node 3, creating a loop in the path.
4797 let secp_ctx = Secp256k1::new();
4798 let logger = Arc::new(test_utils::TestLogger::new());
4799 let network = Arc::new(NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash()));
4800 let net_graph_msg_handler = NetGraphMsgHandler::new(Arc::clone(&network), None, Arc::clone(&logger));
4801 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4802 let scorer = test_utils::TestScorer::with_penalty(0);
4803 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4804 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4805 let payment_params = PaymentParameters::from_node_id(nodes[6]);
4807 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
4808 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4809 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4810 short_channel_id: 6,
4813 cltv_expiry_delta: (6 << 4) | 0,
4814 htlc_minimum_msat: 0,
4815 htlc_maximum_msat: OptionalField::Absent,
4817 fee_proportional_millionths: 0,
4818 excess_data: Vec::new()
4820 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
4822 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4823 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4824 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4825 short_channel_id: 5,
4828 cltv_expiry_delta: (5 << 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[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
4837 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
4838 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4839 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4840 short_channel_id: 4,
4843 cltv_expiry_delta: (4 << 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[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
4852 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
4853 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
4854 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4855 short_channel_id: 3,
4858 cltv_expiry_delta: (3 << 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[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
4867 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
4868 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4869 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4870 short_channel_id: 2,
4873 cltv_expiry_delta: (2 << 4) | 0,
4874 htlc_minimum_msat: 0,
4875 htlc_maximum_msat: OptionalField::Absent,
4877 fee_proportional_millionths: 0,
4878 excess_data: Vec::new()
4881 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
4882 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4883 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4884 short_channel_id: 1,
4887 cltv_expiry_delta: (1 << 4) | 0,
4888 htlc_minimum_msat: 100,
4889 htlc_maximum_msat: OptionalField::Absent,
4891 fee_proportional_millionths: 0,
4892 excess_data: Vec::new()
4894 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
4897 // Now ensure the route flows simply over nodes 1 and 4 to 6.
4898 let route = get_route(&our_id, &payment_params, &network.read_only(), None, 10_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4899 assert_eq!(route.paths.len(), 1);
4900 assert_eq!(route.paths[0].len(), 3);
4902 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
4903 assert_eq!(route.paths[0][0].short_channel_id, 6);
4904 assert_eq!(route.paths[0][0].fee_msat, 100);
4905 assert_eq!(route.paths[0][0].cltv_expiry_delta, (5 << 4) | 0);
4906 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(1));
4907 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(6));
4909 assert_eq!(route.paths[0][1].pubkey, nodes[4]);
4910 assert_eq!(route.paths[0][1].short_channel_id, 5);
4911 assert_eq!(route.paths[0][1].fee_msat, 0);
4912 assert_eq!(route.paths[0][1].cltv_expiry_delta, (1 << 4) | 0);
4913 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(4));
4914 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(5));
4916 assert_eq!(route.paths[0][2].pubkey, nodes[6]);
4917 assert_eq!(route.paths[0][2].short_channel_id, 1);
4918 assert_eq!(route.paths[0][2].fee_msat, 10_000);
4919 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
4920 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
4921 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(1));
4927 fn exact_fee_liquidity_limit() {
4928 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
4929 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
4930 // we calculated fees on a higher value, resulting in us ignoring such paths.
4931 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4932 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
4933 let scorer = test_utils::TestScorer::with_penalty(0);
4934 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4935 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4936 let payment_params = PaymentParameters::from_node_id(nodes[2]);
4938 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
4940 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4941 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4942 short_channel_id: 2,
4945 cltv_expiry_delta: 0,
4946 htlc_minimum_msat: 0,
4947 htlc_maximum_msat: OptionalField::Present(85_000),
4949 fee_proportional_millionths: 0,
4950 excess_data: Vec::new()
4953 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4954 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4955 short_channel_id: 12,
4958 cltv_expiry_delta: (4 << 4) | 1,
4959 htlc_minimum_msat: 0,
4960 htlc_maximum_msat: OptionalField::Present(270_000),
4962 fee_proportional_millionths: 1000000,
4963 excess_data: Vec::new()
4967 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
4968 // 200% fee charged channel 13 in the 1-to-2 direction.
4969 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4970 assert_eq!(route.paths.len(), 1);
4971 assert_eq!(route.paths[0].len(), 2);
4973 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
4974 assert_eq!(route.paths[0][0].short_channel_id, 12);
4975 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
4976 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
4977 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
4978 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
4980 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
4981 assert_eq!(route.paths[0][1].short_channel_id, 13);
4982 assert_eq!(route.paths[0][1].fee_msat, 90_000);
4983 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
4984 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
4985 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
4990 fn htlc_max_reduction_below_min() {
4991 // Test that if, while walking the graph, we reduce the value being sent to meet an
4992 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
4993 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
4994 // resulting in us thinking there is no possible path, even if other paths exist.
4995 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4996 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4997 let scorer = test_utils::TestScorer::with_penalty(0);
4998 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4999 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5000 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
5002 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
5003 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
5004 // then try to send 90_000.
5005 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5006 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5007 short_channel_id: 2,
5010 cltv_expiry_delta: 0,
5011 htlc_minimum_msat: 0,
5012 htlc_maximum_msat: OptionalField::Present(80_000),
5014 fee_proportional_millionths: 0,
5015 excess_data: Vec::new()
5017 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5018 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5019 short_channel_id: 4,
5022 cltv_expiry_delta: (4 << 4) | 1,
5023 htlc_minimum_msat: 90_000,
5024 htlc_maximum_msat: OptionalField::Absent,
5026 fee_proportional_millionths: 0,
5027 excess_data: Vec::new()
5031 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
5032 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
5033 // expensive) channels 12-13 path.
5034 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5035 assert_eq!(route.paths.len(), 1);
5036 assert_eq!(route.paths[0].len(), 2);
5038 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
5039 assert_eq!(route.paths[0][0].short_channel_id, 12);
5040 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
5041 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
5042 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
5043 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
5045 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
5046 assert_eq!(route.paths[0][1].short_channel_id, 13);
5047 assert_eq!(route.paths[0][1].fee_msat, 90_000);
5048 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
5049 assert_eq!(route.paths[0][1].node_features.le_flags(), InvoiceFeatures::known().le_flags());
5050 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
5055 fn multiple_direct_first_hops() {
5056 // Previously we'd only ever considered one first hop path per counterparty.
5057 // However, as we don't restrict users to one channel per peer, we really need to support
5058 // looking at all first hop paths.
5059 // Here we test that we do not ignore all-but-the-last first hop paths per counterparty (as
5060 // we used to do by overwriting the `first_hop_targets` hashmap entry) and that we can MPP
5061 // route over multiple channels with the same first hop.
5062 let secp_ctx = Secp256k1::new();
5063 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5064 let logger = Arc::new(test_utils::TestLogger::new());
5065 let network_graph = NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash());
5066 let scorer = test_utils::TestScorer::with_penalty(0);
5067 let payment_params = PaymentParameters::from_node_id(nodes[0]).with_features(InvoiceFeatures::known());
5068 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5069 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5072 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
5073 &get_channel_details(Some(3), nodes[0], InitFeatures::known(), 200_000),
5074 &get_channel_details(Some(2), nodes[0], InitFeatures::known(), 10_000),
5075 ]), 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5076 assert_eq!(route.paths.len(), 1);
5077 assert_eq!(route.paths[0].len(), 1);
5079 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
5080 assert_eq!(route.paths[0][0].short_channel_id, 3);
5081 assert_eq!(route.paths[0][0].fee_msat, 100_000);
5084 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
5085 &get_channel_details(Some(3), nodes[0], InitFeatures::known(), 50_000),
5086 &get_channel_details(Some(2), nodes[0], InitFeatures::known(), 50_000),
5087 ]), 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5088 assert_eq!(route.paths.len(), 2);
5089 assert_eq!(route.paths[0].len(), 1);
5090 assert_eq!(route.paths[1].len(), 1);
5092 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
5093 assert_eq!(route.paths[0][0].short_channel_id, 3);
5094 assert_eq!(route.paths[0][0].fee_msat, 50_000);
5096 assert_eq!(route.paths[1][0].pubkey, nodes[0]);
5097 assert_eq!(route.paths[1][0].short_channel_id, 2);
5098 assert_eq!(route.paths[1][0].fee_msat, 50_000);
5102 // If we have a bunch of outbound channels to the same node, where most are not
5103 // sufficient to pay the full payment, but one is, we should default to just using the
5104 // one single channel that has sufficient balance, avoiding MPP.
5106 // If we have several options above the 3xpayment value threshold, we should pick the
5107 // smallest of them, avoiding further fragmenting our available outbound balance to
5109 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
5110 &get_channel_details(Some(2), nodes[0], InitFeatures::known(), 50_000),
5111 &get_channel_details(Some(3), nodes[0], InitFeatures::known(), 50_000),
5112 &get_channel_details(Some(5), nodes[0], InitFeatures::known(), 50_000),
5113 &get_channel_details(Some(6), nodes[0], InitFeatures::known(), 300_000),
5114 &get_channel_details(Some(7), nodes[0], InitFeatures::known(), 50_000),
5115 &get_channel_details(Some(8), nodes[0], InitFeatures::known(), 50_000),
5116 &get_channel_details(Some(9), nodes[0], InitFeatures::known(), 50_000),
5117 &get_channel_details(Some(4), nodes[0], InitFeatures::known(), 1_000_000),
5118 ]), 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5119 assert_eq!(route.paths.len(), 1);
5120 assert_eq!(route.paths[0].len(), 1);
5122 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
5123 assert_eq!(route.paths[0][0].short_channel_id, 6);
5124 assert_eq!(route.paths[0][0].fee_msat, 100_000);
5129 fn prefers_shorter_route_with_higher_fees() {
5130 let (secp_ctx, network_graph, _, _, logger) = build_graph();
5131 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5132 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
5134 // Without penalizing each hop 100 msats, a longer path with lower fees is chosen.
5135 let scorer = test_utils::TestScorer::with_penalty(0);
5136 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5137 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5138 let route = get_route(
5139 &our_id, &payment_params, &network_graph.read_only(), None, 100, 42,
5140 Arc::clone(&logger), &scorer, &random_seed_bytes
5142 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5144 assert_eq!(route.get_total_fees(), 100);
5145 assert_eq!(route.get_total_amount(), 100);
5146 assert_eq!(path, vec![2, 4, 6, 11, 8]);
5148 // Applying a 100 msat penalty to each hop results in taking channels 7 and 10 to nodes[6]
5149 // from nodes[2] rather than channel 6, 11, and 8, even though the longer path is cheaper.
5150 let scorer = test_utils::TestScorer::with_penalty(100);
5151 let route = get_route(
5152 &our_id, &payment_params, &network_graph.read_only(), None, 100, 42,
5153 Arc::clone(&logger), &scorer, &random_seed_bytes
5155 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5157 assert_eq!(route.get_total_fees(), 300);
5158 assert_eq!(route.get_total_amount(), 100);
5159 assert_eq!(path, vec![2, 4, 7, 10]);
5162 struct BadChannelScorer {
5163 short_channel_id: u64,
5167 impl Writeable for BadChannelScorer {
5168 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), ::io::Error> { unimplemented!() }
5170 impl Score for BadChannelScorer {
5171 fn channel_penalty_msat(&self, short_channel_id: u64, _send_amt: u64, _capacity_msat: u64, _source: &NodeId, _target: &NodeId) -> u64 {
5172 if short_channel_id == self.short_channel_id { u64::max_value() } else { 0 }
5175 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
5176 fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
5179 struct BadNodeScorer {
5184 impl Writeable for BadNodeScorer {
5185 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), ::io::Error> { unimplemented!() }
5188 impl Score for BadNodeScorer {
5189 fn channel_penalty_msat(&self, _short_channel_id: u64, _send_amt: u64, _capacity_msat: u64, _source: &NodeId, target: &NodeId) -> u64 {
5190 if *target == self.node_id { u64::max_value() } else { 0 }
5193 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
5194 fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
5198 fn avoids_routing_through_bad_channels_and_nodes() {
5199 let (secp_ctx, network, _, _, logger) = build_graph();
5200 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5201 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
5202 let network_graph = network.read_only();
5204 // A path to nodes[6] exists when no penalties are applied to any channel.
5205 let scorer = test_utils::TestScorer::with_penalty(0);
5206 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5207 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5208 let route = get_route(
5209 &our_id, &payment_params, &network_graph, None, 100, 42,
5210 Arc::clone(&logger), &scorer, &random_seed_bytes
5212 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5214 assert_eq!(route.get_total_fees(), 100);
5215 assert_eq!(route.get_total_amount(), 100);
5216 assert_eq!(path, vec![2, 4, 6, 11, 8]);
5218 // A different path to nodes[6] exists if channel 6 cannot be routed over.
5219 let scorer = BadChannelScorer { short_channel_id: 6 };
5220 let route = get_route(
5221 &our_id, &payment_params, &network_graph, None, 100, 42,
5222 Arc::clone(&logger), &scorer, &random_seed_bytes
5224 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5226 assert_eq!(route.get_total_fees(), 300);
5227 assert_eq!(route.get_total_amount(), 100);
5228 assert_eq!(path, vec![2, 4, 7, 10]);
5230 // A path to nodes[6] does not exist if nodes[2] cannot be routed through.
5231 let scorer = BadNodeScorer { node_id: NodeId::from_pubkey(&nodes[2]) };
5233 &our_id, &payment_params, &network_graph, None, 100, 42,
5234 Arc::clone(&logger), &scorer, &random_seed_bytes
5236 Err(LightningError { err, .. } ) => {
5237 assert_eq!(err, "Failed to find a path to the given destination");
5239 Ok(_) => panic!("Expected error"),
5244 fn total_fees_single_path() {
5248 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5249 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5250 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5253 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5254 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5255 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5258 pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
5259 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5260 short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0
5263 payment_params: None,
5266 assert_eq!(route.get_total_fees(), 250);
5267 assert_eq!(route.get_total_amount(), 225);
5271 fn total_fees_multi_path() {
5275 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5276 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5277 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5280 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5281 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5282 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5286 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5287 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5288 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5291 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5292 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5293 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5296 payment_params: None,
5299 assert_eq!(route.get_total_fees(), 200);
5300 assert_eq!(route.get_total_amount(), 300);
5304 fn total_empty_route_no_panic() {
5305 // In an earlier version of `Route::get_total_fees` and `Route::get_total_amount`, they
5306 // would both panic if the route was completely empty. We test to ensure they return 0
5307 // here, even though its somewhat nonsensical as a route.
5308 let route = Route { paths: Vec::new(), payment_params: None };
5310 assert_eq!(route.get_total_fees(), 0);
5311 assert_eq!(route.get_total_amount(), 0);
5315 fn limits_total_cltv_delta() {
5316 let (secp_ctx, network, _, _, logger) = build_graph();
5317 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5318 let network_graph = network.read_only();
5320 let scorer = test_utils::TestScorer::with_penalty(0);
5322 // Make sure that generally there is at least one route available
5323 let feasible_max_total_cltv_delta = 1008;
5324 let feasible_payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes))
5325 .with_max_total_cltv_expiry_delta(feasible_max_total_cltv_delta);
5326 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5327 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5328 let route = get_route(&our_id, &feasible_payment_params, &network_graph, None, 100, 0, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5329 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5330 assert_ne!(path.len(), 0);
5332 // But not if we exclude all paths on the basis of their accumulated CLTV delta
5333 let fail_max_total_cltv_delta = 23;
5334 let fail_payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes))
5335 .with_max_total_cltv_expiry_delta(fail_max_total_cltv_delta);
5336 match get_route(&our_id, &fail_payment_params, &network_graph, None, 100, 0, Arc::clone(&logger), &scorer, &random_seed_bytes)
5338 Err(LightningError { err, .. } ) => {
5339 assert_eq!(err, "Failed to find a path to the given destination");
5341 Ok(_) => panic!("Expected error"),
5346 fn limits_path_length() {
5347 let (secp_ctx, network, _, _, logger) = build_line_graph();
5348 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5349 let network_graph = network.read_only();
5351 let scorer = test_utils::TestScorer::with_penalty(0);
5352 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5353 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5355 // First check we can actually create a long route on this graph.
5356 let feasible_payment_params = PaymentParameters::from_node_id(nodes[18]);
5357 let route = get_route(&our_id, &feasible_payment_params, &network_graph, None, 100, 0,
5358 Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5359 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5360 assert!(path.len() == MAX_PATH_LENGTH_ESTIMATE.into());
5362 // But we can't create a path surpassing the MAX_PATH_LENGTH_ESTIMATE limit.
5363 let fail_payment_params = PaymentParameters::from_node_id(nodes[19]);
5364 match get_route(&our_id, &fail_payment_params, &network_graph, None, 100, 0,
5365 Arc::clone(&logger), &scorer, &random_seed_bytes)
5367 Err(LightningError { err, .. } ) => {
5368 assert_eq!(err, "Failed to find a path to the given destination");
5370 Ok(_) => panic!("Expected error"),
5375 fn adds_and_limits_cltv_offset() {
5376 let (secp_ctx, network_graph, _, _, logger) = build_graph();
5377 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5379 let scorer = test_utils::TestScorer::with_penalty(0);
5381 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
5382 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5383 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5384 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5385 assert_eq!(route.paths.len(), 1);
5387 let cltv_expiry_deltas_before = route.paths[0].iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5389 // Check whether the offset added to the last hop by default is in [1 .. DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA]
5390 let mut route_default = route.clone();
5391 add_random_cltv_offset(&mut route_default, &payment_params, &network_graph.read_only(), &random_seed_bytes);
5392 let cltv_expiry_deltas_default = route_default.paths[0].iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5393 assert_eq!(cltv_expiry_deltas_before.split_last().unwrap().1, cltv_expiry_deltas_default.split_last().unwrap().1);
5394 assert!(cltv_expiry_deltas_default.last() > cltv_expiry_deltas_before.last());
5395 assert!(cltv_expiry_deltas_default.last().unwrap() <= &DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA);
5397 // Check that no offset is added when we restrict the max_total_cltv_expiry_delta
5398 let mut route_limited = route.clone();
5399 let limited_max_total_cltv_expiry_delta = cltv_expiry_deltas_before.iter().sum();
5400 let limited_payment_params = payment_params.with_max_total_cltv_expiry_delta(limited_max_total_cltv_expiry_delta);
5401 add_random_cltv_offset(&mut route_limited, &limited_payment_params, &network_graph.read_only(), &random_seed_bytes);
5402 let cltv_expiry_deltas_limited = route_limited.paths[0].iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5403 assert_eq!(cltv_expiry_deltas_before, cltv_expiry_deltas_limited);
5407 fn adds_plausible_cltv_offset() {
5408 let (secp_ctx, network, _, _, logger) = build_graph();
5409 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5410 let network_graph = network.read_only();
5411 let network_nodes = network_graph.nodes();
5412 let network_channels = network_graph.channels();
5413 let scorer = test_utils::TestScorer::with_penalty(0);
5414 let payment_params = PaymentParameters::from_node_id(nodes[3]);
5415 let keys_manager = test_utils::TestKeysInterface::new(&[4u8; 32], Network::Testnet);
5416 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5418 let mut route = get_route(&our_id, &payment_params, &network_graph, None, 100, 0,
5419 Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5420 add_random_cltv_offset(&mut route, &payment_params, &network_graph, &random_seed_bytes);
5422 let mut path_plausibility = vec![];
5424 for p in route.paths {
5425 // 1. Select random observation point
5426 let mut prng = ChaCha20::new(&random_seed_bytes, &[0u8; 12]);
5427 let mut random_bytes = [0u8; ::core::mem::size_of::<usize>()];
5429 prng.process_in_place(&mut random_bytes);
5430 let random_path_index = usize::from_be_bytes(random_bytes).wrapping_rem(p.len());
5431 let observation_point = NodeId::from_pubkey(&p.get(random_path_index).unwrap().pubkey);
5433 // 2. Calculate what CLTV expiry delta we would observe there
5434 let observed_cltv_expiry_delta: u32 = p[random_path_index..].iter().map(|h| h.cltv_expiry_delta).sum();
5436 // 3. Starting from the observation point, find candidate paths
5437 let mut candidates: VecDeque<(NodeId, Vec<u32>)> = VecDeque::new();
5438 candidates.push_back((observation_point, vec![]));
5440 let mut found_plausible_candidate = false;
5442 'candidate_loop: while let Some((cur_node_id, cur_path_cltv_deltas)) = candidates.pop_front() {
5443 if let Some(remaining) = observed_cltv_expiry_delta.checked_sub(cur_path_cltv_deltas.iter().sum::<u32>()) {
5444 if remaining == 0 || remaining.wrapping_rem(40) == 0 || remaining.wrapping_rem(144) == 0 {
5445 found_plausible_candidate = true;
5446 break 'candidate_loop;
5450 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
5451 for channel_id in &cur_node.channels {
5452 if let Some(channel_info) = network_channels.get(&channel_id) {
5453 if let Some((dir_info, next_id)) = channel_info.as_directed_from(&cur_node_id) {
5454 if let Some(channel_update_info) = dir_info.direction() {
5455 let next_cltv_expiry_delta = channel_update_info.cltv_expiry_delta as u32;
5456 if cur_path_cltv_deltas.iter().sum::<u32>()
5457 .saturating_add(next_cltv_expiry_delta) <= observed_cltv_expiry_delta {
5458 let mut new_path_cltv_deltas = cur_path_cltv_deltas.clone();
5459 new_path_cltv_deltas.push(next_cltv_expiry_delta);
5460 candidates.push_back((*next_id, new_path_cltv_deltas));
5469 path_plausibility.push(found_plausible_candidate);
5471 assert!(path_plausibility.iter().all(|x| *x));
5474 #[cfg(not(feature = "no-std"))]
5475 pub(super) fn random_init_seed() -> u64 {
5476 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
5477 use core::hash::{BuildHasher, Hasher};
5478 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
5479 println!("Using seed of {}", seed);
5482 #[cfg(not(feature = "no-std"))]
5483 use util::ser::Readable;
5486 #[cfg(not(feature = "no-std"))]
5487 fn generate_routes() {
5488 use routing::scoring::{ProbabilisticScorer, ProbabilisticScoringParameters};
5490 let mut d = match super::test_utils::get_route_file() {
5497 let graph = NetworkGraph::read(&mut d).unwrap();
5498 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5499 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5501 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
5502 let mut seed = random_init_seed() as usize;
5503 let nodes = graph.read_only().nodes().clone();
5504 'load_endpoints: for _ in 0..10 {
5506 seed = seed.overflowing_mul(0xdeadbeef).0;
5507 let src = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5508 seed = seed.overflowing_mul(0xdeadbeef).0;
5509 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5510 let payment_params = PaymentParameters::from_node_id(dst);
5511 let amt = seed as u64 % 200_000_000;
5512 let params = ProbabilisticScoringParameters::default();
5513 let logger = test_utils::TestLogger::new();
5514 let scorer = ProbabilisticScorer::new(params, &graph, &logger);
5515 if get_route(src, &payment_params, &graph.read_only(), None, amt, 42, &logger, &scorer, &random_seed_bytes).is_ok() {
5516 continue 'load_endpoints;
5523 #[cfg(not(feature = "no-std"))]
5524 fn generate_routes_mpp() {
5525 use routing::scoring::{ProbabilisticScorer, ProbabilisticScoringParameters};
5527 let mut d = match super::test_utils::get_route_file() {
5534 let graph = NetworkGraph::read(&mut d).unwrap();
5535 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5536 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5538 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
5539 let mut seed = random_init_seed() as usize;
5540 let nodes = graph.read_only().nodes().clone();
5541 'load_endpoints: for _ in 0..10 {
5543 seed = seed.overflowing_mul(0xdeadbeef).0;
5544 let src = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5545 seed = seed.overflowing_mul(0xdeadbeef).0;
5546 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5547 let payment_params = PaymentParameters::from_node_id(dst).with_features(InvoiceFeatures::known());
5548 let amt = seed as u64 % 200_000_000;
5549 let params = ProbabilisticScoringParameters::default();
5550 let logger = test_utils::TestLogger::new();
5551 let scorer = ProbabilisticScorer::new(params, &graph, &logger);
5552 if get_route(src, &payment_params, &graph.read_only(), None, amt, 42, &logger, &scorer, &random_seed_bytes).is_ok() {
5553 continue 'load_endpoints;
5560 #[cfg(all(test, not(feature = "no-std")))]
5561 pub(crate) mod test_utils {
5563 /// Tries to open a network graph file, or panics with a URL to fetch it.
5564 pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
5565 let res = File::open("net_graph-2021-05-31.bin") // By default we're run in RL/lightning
5566 .or_else(|_| File::open("lightning/net_graph-2021-05-31.bin")) // We may be run manually in RL/
5567 .or_else(|_| { // Fall back to guessing based on the binary location
5568 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
5569 let mut path = std::env::current_exe().unwrap();
5570 path.pop(); // lightning-...
5572 path.pop(); // debug
5573 path.pop(); // target
5574 path.push("lightning");
5575 path.push("net_graph-2021-05-31.bin");
5576 eprintln!("{}", path.to_str().unwrap());
5579 .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");
5580 #[cfg(require_route_graph_test)]
5581 return Ok(res.unwrap());
5582 #[cfg(not(require_route_graph_test))]
5587 #[cfg(all(test, feature = "_bench_unstable", not(feature = "no-std")))]
5590 use bitcoin::hashes::Hash;
5591 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
5592 use chain::transaction::OutPoint;
5593 use chain::keysinterface::{KeysManager,KeysInterface};
5594 use ln::channelmanager::{ChannelCounterparty, ChannelDetails};
5595 use ln::features::{InitFeatures, InvoiceFeatures};
5596 use routing::scoring::{FixedPenaltyScorer, ProbabilisticScorer, ProbabilisticScoringParameters, Scorer};
5597 use util::logger::{Logger, Record};
5598 use util::test_utils::TestLogger;
5602 struct DummyLogger {}
5603 impl Logger for DummyLogger {
5604 fn log(&self, _record: &Record) {}
5607 fn read_network_graph() -> NetworkGraph {
5608 let mut d = test_utils::get_route_file().unwrap();
5609 NetworkGraph::read(&mut d).unwrap()
5612 fn payer_pubkey() -> PublicKey {
5613 let secp_ctx = Secp256k1::new();
5614 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
5618 fn first_hop(node_id: PublicKey) -> ChannelDetails {
5620 channel_id: [0; 32],
5621 counterparty: ChannelCounterparty {
5622 features: InitFeatures::known(),
5624 unspendable_punishment_reserve: 0,
5625 forwarding_info: None,
5626 outbound_htlc_minimum_msat: None,
5627 outbound_htlc_maximum_msat: None,
5629 funding_txo: Some(OutPoint {
5630 txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0
5633 short_channel_id: Some(1),
5634 inbound_scid_alias: None,
5635 channel_value_satoshis: 10_000_000,
5637 balance_msat: 10_000_000,
5638 outbound_capacity_msat: 10_000_000,
5639 next_outbound_htlc_limit_msat: 10_000_000,
5640 inbound_capacity_msat: 0,
5641 unspendable_punishment_reserve: None,
5642 confirmations_required: None,
5643 force_close_spend_delay: None,
5645 is_funding_locked: true,
5648 inbound_htlc_minimum_msat: None,
5649 inbound_htlc_maximum_msat: None,
5654 fn generate_routes_with_zero_penalty_scorer(bench: &mut Bencher) {
5655 let network_graph = read_network_graph();
5656 let scorer = FixedPenaltyScorer::with_penalty(0);
5657 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::empty());
5661 fn generate_mpp_routes_with_zero_penalty_scorer(bench: &mut Bencher) {
5662 let network_graph = read_network_graph();
5663 let scorer = FixedPenaltyScorer::with_penalty(0);
5664 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::known());
5668 fn generate_routes_with_default_scorer(bench: &mut Bencher) {
5669 let network_graph = read_network_graph();
5670 let scorer = Scorer::default();
5671 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::empty());
5675 fn generate_mpp_routes_with_default_scorer(bench: &mut Bencher) {
5676 let network_graph = read_network_graph();
5677 let scorer = Scorer::default();
5678 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::known());
5682 fn generate_routes_with_probabilistic_scorer(bench: &mut Bencher) {
5683 let logger = TestLogger::new();
5684 let network_graph = read_network_graph();
5685 let params = ProbabilisticScoringParameters::default();
5686 let scorer = ProbabilisticScorer::new(params, &network_graph, &logger);
5687 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::empty());
5691 fn generate_mpp_routes_with_probabilistic_scorer(bench: &mut Bencher) {
5692 let logger = TestLogger::new();
5693 let network_graph = read_network_graph();
5694 let params = ProbabilisticScoringParameters::default();
5695 let scorer = ProbabilisticScorer::new(params, &network_graph, &logger);
5696 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::known());
5699 fn generate_routes<S: Score>(
5700 bench: &mut Bencher, graph: &NetworkGraph, mut scorer: S, features: InvoiceFeatures
5702 let nodes = graph.read_only().nodes().clone();
5703 let payer = payer_pubkey();
5704 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
5705 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5707 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
5708 let mut routes = Vec::new();
5709 let mut route_endpoints = Vec::new();
5710 let mut seed: usize = 0xdeadbeef;
5711 'load_endpoints: for _ in 0..150 {
5714 let src = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5716 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5717 let params = PaymentParameters::from_node_id(dst).with_features(features.clone());
5718 let first_hop = first_hop(src);
5719 let amt = seed as u64 % 1_000_000;
5720 if let Ok(route) = get_route(&payer, ¶ms, &graph.read_only(), Some(&[&first_hop]), amt, 42, &DummyLogger{}, &scorer, &random_seed_bytes) {
5722 route_endpoints.push((first_hop, params, amt));
5723 continue 'load_endpoints;
5728 // ...and seed the scorer with success and failure data...
5729 for route in routes {
5730 let amount = route.get_total_amount();
5731 if amount < 250_000 {
5732 for path in route.paths {
5733 scorer.payment_path_successful(&path.iter().collect::<Vec<_>>());
5735 } else if amount > 750_000 {
5736 for path in route.paths {
5737 let short_channel_id = path[path.len() / 2].short_channel_id;
5738 scorer.payment_path_failed(&path.iter().collect::<Vec<_>>(), short_channel_id);
5743 // Because we've changed channel scores, its possible we'll take different routes to the
5744 // selected destinations, possibly causing us to fail because, eg, the newly-selected path
5745 // requires a too-high CLTV delta.
5746 route_endpoints.retain(|(first_hop, params, amt)| {
5747 get_route(&payer, params, &graph.read_only(), Some(&[first_hop]), *amt, 42, &DummyLogger{}, &scorer, &random_seed_bytes).is_ok()
5749 route_endpoints.truncate(100);
5750 assert_eq!(route_endpoints.len(), 100);
5752 // ...then benchmark finding paths between the nodes we learned.
5755 let (first_hop, params, amt) = &route_endpoints[idx % route_endpoints.len()];
5756 assert!(get_route(&payer, params, &graph.read_only(), Some(&[first_hop]), *amt, 42, &DummyLogger{}, &scorer, &random_seed_bytes).is_ok());