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 fees(&self) -> RoutingFees {
419 CandidateRouteHop::FirstHop { .. } => RoutingFees {
420 base_msat: 0, proportional_millionths: 0,
422 CandidateRouteHop::PublicHop { info, .. } => info.direction().fees,
423 CandidateRouteHop::PrivateHop { hint } => hint.fees,
427 fn effective_capacity(&self) -> EffectiveCapacity {
429 CandidateRouteHop::FirstHop { details } => EffectiveCapacity::ExactLiquidity {
430 liquidity_msat: details.next_outbound_htlc_limit_msat,
432 CandidateRouteHop::PublicHop { info, .. } => info.effective_capacity(),
433 CandidateRouteHop::PrivateHop { .. } => EffectiveCapacity::Infinite,
438 /// It's useful to keep track of the hops associated with the fees required to use them,
439 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
440 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
441 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
443 struct PathBuildingHop<'a> {
444 // Note that this should be dropped in favor of loading it from CandidateRouteHop, but doing so
445 // is a larger refactor and will require careful performance analysis.
447 candidate: CandidateRouteHop<'a>,
450 /// Minimal fees required to route to the source node of the current hop via any of its inbound channels.
451 src_lowest_inbound_fees: RoutingFees,
452 /// All the fees paid *after* this channel on the way to the destination
453 next_hops_fee_msat: u64,
454 /// Fee paid for the use of the current channel (see candidate.fees()).
455 /// The value will be actually deducted from the counterparty balance on the previous link.
456 hop_use_fee_msat: u64,
457 /// Used to compare channels when choosing the for routing.
458 /// Includes paying for the use of a hop and the following hops, as well as
459 /// an estimated cost of reaching this hop.
460 /// Might get stale when fees are recomputed. Primarily for internal use.
462 /// A mirror of the same field in RouteGraphNode. Note that this is only used during the graph
463 /// walk and may be invalid thereafter.
464 path_htlc_minimum_msat: u64,
465 /// All penalties incurred from this channel on the way to the destination, as calculated using
467 path_penalty_msat: u64,
468 /// If we've already processed a node as the best node, we shouldn't process it again. Normally
469 /// we'd just ignore it if we did as all channels would have a higher new fee, but because we
470 /// may decrease the amounts in use as we walk the graph, the actual calculated fee may
471 /// decrease as well. Thus, we have to explicitly track which nodes have been processed and
472 /// avoid processing them again.
474 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
475 // In tests, we apply further sanity checks on cases where we skip nodes we already processed
476 // to ensure it is specifically in cases where the fee has gone down because of a decrease in
477 // value_contribution_msat, which requires tracking it here. See comments below where it is
478 // used for more info.
479 value_contribution_msat: u64,
482 impl<'a> core::fmt::Debug for PathBuildingHop<'a> {
483 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
484 f.debug_struct("PathBuildingHop")
485 .field("node_id", &self.node_id)
486 .field("short_channel_id", &self.candidate.short_channel_id())
487 .field("total_fee_msat", &self.total_fee_msat)
488 .field("next_hops_fee_msat", &self.next_hops_fee_msat)
489 .field("hop_use_fee_msat", &self.hop_use_fee_msat)
490 .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)))
491 .field("path_penalty_msat", &self.path_penalty_msat)
492 .field("path_htlc_minimum_msat", &self.path_htlc_minimum_msat)
493 .field("cltv_expiry_delta", &self.candidate.cltv_expiry_delta())
498 // Instantiated with a list of hops with correct data in them collected during path finding,
499 // an instance of this struct should be further modified only via given methods.
501 struct PaymentPath<'a> {
502 hops: Vec<(PathBuildingHop<'a>, NodeFeatures)>,
505 impl<'a> PaymentPath<'a> {
506 // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
507 fn get_value_msat(&self) -> u64 {
508 self.hops.last().unwrap().0.fee_msat
511 fn get_path_penalty_msat(&self) -> u64 {
512 self.hops.first().map(|h| h.0.path_penalty_msat).unwrap_or(u64::max_value())
515 fn get_total_fee_paid_msat(&self) -> u64 {
516 if self.hops.len() < 1 {
520 // Can't use next_hops_fee_msat because it gets outdated.
521 for (i, (hop, _)) in self.hops.iter().enumerate() {
522 if i != self.hops.len() - 1 {
523 result += hop.fee_msat;
529 fn get_cost_msat(&self) -> u64 {
530 self.get_total_fee_paid_msat().saturating_add(self.get_path_penalty_msat())
533 // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
534 // to change fees may result in an inconsistency.
536 // Sometimes we call this function right after constructing a path which is inconsistent in
537 // that it the value being transferred has decreased while we were doing path finding, leading
538 // to the fees being paid not lining up with the actual limits.
540 // Note that this function is not aware of the available_liquidity limit, and thus does not
541 // support increasing the value being transferred.
542 fn update_value_and_recompute_fees(&mut self, value_msat: u64) {
543 assert!(value_msat <= self.hops.last().unwrap().0.fee_msat);
545 let mut total_fee_paid_msat = 0 as u64;
546 for i in (0..self.hops.len()).rev() {
547 let last_hop = i == self.hops.len() - 1;
549 // For non-last-hop, this value will represent the fees paid on the current hop. It
550 // will consist of the fees for the use of the next hop, and extra fees to match
551 // htlc_minimum_msat of the current channel. Last hop is handled separately.
552 let mut cur_hop_fees_msat = 0;
554 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().0.hop_use_fee_msat;
557 let mut cur_hop = &mut self.hops.get_mut(i).unwrap().0;
558 cur_hop.next_hops_fee_msat = total_fee_paid_msat;
559 // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
560 // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
561 // set it too high just to maliciously take more fees by exploiting this
562 // match htlc_minimum_msat logic.
563 let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
564 if let Some(extra_fees_msat) = cur_hop.candidate.htlc_minimum_msat().checked_sub(cur_hop_transferred_amount_msat) {
565 // Note that there is a risk that *previous hops* (those closer to us, as we go
566 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
568 // This might make us end up with a broken route, although this should be super-rare
569 // in practice, both because of how healthy channels look like, and how we pick
570 // channels in add_entry.
571 // Also, this can't be exploited more heavily than *announce a free path and fail
573 cur_hop_transferred_amount_msat += extra_fees_msat;
574 total_fee_paid_msat += extra_fees_msat;
575 cur_hop_fees_msat += extra_fees_msat;
579 // Final hop is a special case: it usually has just value_msat (by design), but also
580 // it still could overpay for the htlc_minimum_msat.
581 cur_hop.fee_msat = cur_hop_transferred_amount_msat;
583 // Propagate updated fees for the use of the channels to one hop back, where they
584 // will be actually paid (fee_msat). The last hop is handled above separately.
585 cur_hop.fee_msat = cur_hop_fees_msat;
588 // Fee for the use of the current hop which will be deducted on the previous hop.
589 // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
590 // this channel is free for us.
592 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.candidate.fees()) {
593 cur_hop.hop_use_fee_msat = new_fee;
594 total_fee_paid_msat += new_fee;
596 // It should not be possible because this function is called only to reduce the
597 // value. In that case, compute_fee was already called with the same fees for
598 // larger amount and there was no overflow.
606 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
607 let proportional_fee_millions =
608 amount_msat.checked_mul(channel_fees.proportional_millionths as u64);
609 if let Some(new_fee) = proportional_fee_millions.and_then(|part| {
610 (channel_fees.base_msat as u64).checked_add(part / 1_000_000) }) {
614 // This function may be (indirectly) called without any verification,
615 // with channel_fees provided by a caller. We should handle it gracefully.
620 /// The default `features` we assume for a node in a route, when no `features` are known about that
623 /// Default features are:
624 /// * variable_length_onion_optional
625 fn default_node_features() -> NodeFeatures {
626 let mut features = NodeFeatures::empty();
627 features.set_variable_length_onion_optional();
631 /// Finds a route from us (payer) to the given target node (payee).
633 /// If the payee provided features in their invoice, they should be provided via `params.payee`.
634 /// Without this, MPP will only be used if the payee's features are available in the network graph.
636 /// Private routing paths between a public node and the target may be included in `params.payee`.
638 /// If some channels aren't announced, it may be useful to fill in `first_hops` with the results
639 /// from [`ChannelManager::list_usable_channels`]. If it is filled in, the view of our local
640 /// channels from [`NetworkGraph`] will be ignored, and only those in `first_hops` will be used.
642 /// The fees on channels from us to the next hop are ignored as they are assumed to all be equal.
643 /// However, the enabled/disabled bit on such channels as well as the `htlc_minimum_msat` /
644 /// `htlc_maximum_msat` *are* checked as they may change based on the receiving node.
648 /// May be used to re-compute a [`Route`] when handling a [`Event::PaymentPathFailed`]. Any
649 /// adjustments to the [`NetworkGraph`] and channel scores should be made prior to calling this
654 /// Panics if first_hops contains channels without short_channel_ids;
655 /// [`ChannelManager::list_usable_channels`] will never include such channels.
657 /// [`ChannelManager::list_usable_channels`]: crate::ln::channelmanager::ChannelManager::list_usable_channels
658 /// [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed
659 pub fn find_route<L: Deref, S: Score>(
660 our_node_pubkey: &PublicKey, route_params: &RouteParameters, network: &NetworkGraph,
661 first_hops: Option<&[&ChannelDetails]>, logger: L, scorer: &S, random_seed_bytes: &[u8; 32]
662 ) -> Result<Route, LightningError>
663 where L::Target: Logger {
664 let network_graph = network.read_only();
666 our_node_pubkey, &route_params.payment_params, &network_graph, first_hops, route_params.final_value_msat,
667 route_params.final_cltv_expiry_delta, logger, scorer, random_seed_bytes
670 add_random_cltv_offset(&mut route, &route_params.payment_params, &network_graph, random_seed_bytes);
673 Err(err) => Err(err),
677 pub(crate) fn get_route<L: Deref, S: Score>(
678 our_node_pubkey: &PublicKey, payment_params: &PaymentParameters, network_graph: &ReadOnlyNetworkGraph,
679 first_hops: Option<&[&ChannelDetails]>, final_value_msat: u64, final_cltv_expiry_delta: u32,
680 logger: L, scorer: &S, random_seed_bytes: &[u8; 32]
681 ) -> Result<Route, LightningError>
682 where L::Target: Logger {
683 let payee_node_id = NodeId::from_pubkey(&payment_params.payee_pubkey);
684 let our_node_id = NodeId::from_pubkey(&our_node_pubkey);
686 if payee_node_id == our_node_id {
687 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
690 if final_value_msat > MAX_VALUE_MSAT {
691 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
694 if final_value_msat == 0 {
695 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
698 for route in payment_params.route_hints.iter() {
699 for hop in &route.0 {
700 if hop.src_node_id == payment_params.payee_pubkey {
701 return Err(LightningError{err: "Route hint cannot have the payee as the source.".to_owned(), action: ErrorAction::IgnoreError});
705 if payment_params.max_total_cltv_expiry_delta <= final_cltv_expiry_delta {
706 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});
709 // The general routing idea is the following:
710 // 1. Fill first/last hops communicated by the caller.
711 // 2. Attempt to construct a path from payer to payee for transferring
712 // any ~sufficient (described later) value.
713 // If succeed, remember which channels were used and how much liquidity they have available,
714 // so that future paths don't rely on the same liquidity.
715 // 3. Proceed to the next step if:
716 // - we hit the recommended target value;
717 // - OR if we could not construct a new path. Any next attempt will fail too.
718 // Otherwise, repeat step 2.
719 // 4. See if we managed to collect paths which aggregately are able to transfer target value
720 // (not recommended value).
721 // 5. If yes, proceed. If not, fail routing.
722 // 6. Randomly combine paths into routes having enough to fulfill the payment. (TODO: knapsack)
723 // 7. Of all the found paths, select only those with the lowest total fee.
724 // 8. The last path in every selected route is likely to be more than we need.
725 // Reduce its value-to-transfer and recompute fees.
726 // 9. Choose the best route by the lowest total fee.
728 // As for the actual search algorithm,
729 // we do a payee-to-payer pseudo-Dijkstra's sorting by each node's distance from the payee
730 // plus the minimum per-HTLC fee to get from it to another node (aka "shitty pseudo-A*").
732 // We are not a faithful Dijkstra's implementation because we can change values which impact
733 // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
734 // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) than
735 // the value we are currently attempting to send over a path, we simply reduce the value being
736 // sent along the path for any hops after that channel. This may imply that later fees (which
737 // we've already tabulated) are lower because a smaller value is passing through the channels
738 // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
739 // channels which were selected earlier (and which may still be used for other paths without a
740 // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
743 // One potentially problematic case for this algorithm would be if there are many
744 // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
745 // graph walking), we may never find a path which is not liquidity-limited and has lower
746 // proportional fee (and only lower absolute fee when considering the ultimate value sent).
747 // Because we only consider paths with at least 5% of the total value being sent, the damage
748 // from such a case should be limited, however this could be further reduced in the future by
749 // calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
750 // limits for the purposes of fee calculation.
752 // Alternatively, we could store more detailed path information in the heap (targets, below)
753 // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
754 // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
755 // and practically (as we would need to store dynamically-allocated path information in heap
756 // objects, increasing malloc traffic and indirect memory access significantly). Further, the
757 // results of such an algorithm would likely be biased towards lower-value paths.
759 // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
760 // outside of our current search value, running a path search more times to gather candidate
761 // paths at different values. While this may be acceptable, further path searches may increase
762 // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
763 // graph for candidate paths, calculating the maximum value which can realistically be sent at
764 // the same time, remaining generic across different payment values.
766 // TODO: There are a few tweaks we could do, including possibly pre-calculating more stuff
767 // to use as the A* heuristic beyond just the cost to get one node further than the current
770 let network_channels = network_graph.channels();
771 let network_nodes = network_graph.nodes();
773 // Allow MPP only if we have a features set from somewhere that indicates the payee supports
774 // it. If the payee supports it they're supposed to include it in the invoice, so that should
776 let allow_mpp = if let Some(features) = &payment_params.features {
777 features.supports_basic_mpp()
778 } else if let Some(node) = network_nodes.get(&payee_node_id) {
779 if let Some(node_info) = node.announcement_info.as_ref() {
780 node_info.features.supports_basic_mpp()
783 log_trace!(logger, "Searching for a route from payer {} to payee {} {} MPP and {} first hops {}overriding the network graph", our_node_pubkey,
784 payment_params.payee_pubkey, if allow_mpp { "with" } else { "without" },
785 first_hops.map(|hops| hops.len()).unwrap_or(0), if first_hops.is_some() { "" } else { "not " });
788 // Prepare the data we'll use for payee-to-payer search by
789 // inserting first hops suggested by the caller as targets.
790 // Our search will then attempt to reach them while traversing from the payee node.
791 let mut first_hop_targets: HashMap<_, Vec<&ChannelDetails>> =
792 HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
793 if let Some(hops) = first_hops {
795 if chan.short_channel_id.is_none() {
796 panic!("first_hops should be filled in with usable channels, not pending ones");
798 if chan.counterparty.node_id == *our_node_pubkey {
799 return Err(LightningError{err: "First hop cannot have our_node_pubkey as a destination.".to_owned(), action: ErrorAction::IgnoreError});
802 .entry(NodeId::from_pubkey(&chan.counterparty.node_id))
803 .or_insert(Vec::new())
806 if first_hop_targets.is_empty() {
807 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
811 // The main heap containing all candidate next-hops sorted by their score (max(A* fee,
812 // htlc_minimum)). Ideally this would be a heap which allowed cheap score reduction instead of
813 // adding duplicate entries when we find a better path to a given node.
814 let mut targets: BinaryHeap<RouteGraphNode> = BinaryHeap::new();
816 // Map from node_id to information about the best current path to that node, including feerate
818 let mut dist: HashMap<NodeId, PathBuildingHop> = HashMap::with_capacity(network_nodes.len());
820 // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
821 // indicating that we may wish to try again with a higher value, potentially paying to meet an
822 // htlc_minimum with extra fees while still finding a cheaper path.
823 let mut hit_minimum_limit;
825 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
826 // We start with a path_value of the exact amount we want, and if that generates a route we may
827 // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
828 // amount we want in total across paths, selecting the best subset at the end.
829 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
830 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
831 let mut path_value_msat = final_value_msat;
833 // We don't want multiple paths (as per MPP) share liquidity of the same channels.
834 // This map allows paths to be aware of the channel use by other paths in the same call.
835 // This would help to make a better path finding decisions and not "overbook" channels.
836 // It is unaware of the directions (except for `next_outbound_htlc_limit_msat` in
838 let mut bookkept_channels_liquidity_available_msat = HashMap::with_capacity(network_nodes.len());
840 // Keeping track of how much value we already collected across other paths. Helps to decide:
841 // - how much a new path should be transferring (upper bound);
842 // - whether a channel should be disregarded because
843 // it's available liquidity is too small comparing to how much more we need to collect;
844 // - when we want to stop looking for new paths.
845 let mut already_collected_value_msat = 0;
847 for (_, channels) in first_hop_targets.iter_mut() {
848 // Sort the first_hops channels to the same node(s) in priority order of which channel we'd
851 // First, if channels are below `recommended_value_msat`, sort them in descending order,
852 // preferring larger channels to avoid splitting the payment into more MPP parts than is
855 // Second, because simply always sorting in descending order would always use our largest
856 // available outbound capacity, needlessly fragmenting our available channel capacities,
857 // sort channels above `recommended_value_msat` in ascending order, preferring channels
858 // which have enough, but not too much, capacity for the payment.
859 channels.sort_unstable_by(|chan_a, chan_b| {
860 if chan_b.next_outbound_htlc_limit_msat < recommended_value_msat || chan_a.next_outbound_htlc_limit_msat < recommended_value_msat {
861 // Sort in descending order
862 chan_b.next_outbound_htlc_limit_msat.cmp(&chan_a.next_outbound_htlc_limit_msat)
864 // Sort in ascending order
865 chan_a.next_outbound_htlc_limit_msat.cmp(&chan_b.next_outbound_htlc_limit_msat)
870 log_trace!(logger, "Building path from {} (payee) to {} (us/payer) for value {} msat.", payment_params.payee_pubkey, our_node_pubkey, final_value_msat);
872 macro_rules! add_entry {
873 // Adds entry which goes from $src_node_id to $dest_node_id over the $candidate hop.
874 // $next_hops_fee_msat represents the fees paid for using all the channels *after* this one,
875 // since that value has to be transferred over this channel.
876 // Returns whether this channel caused an update to `targets`.
877 ( $candidate: expr, $src_node_id: expr, $dest_node_id: expr, $next_hops_fee_msat: expr,
878 $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr,
879 $next_hops_path_penalty_msat: expr, $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => { {
880 // We "return" whether we updated the path at the end, via this:
881 let mut did_add_update_path_to_src_node = false;
882 // Channels to self should not be used. This is more of belt-and-suspenders, because in
883 // practice these cases should be caught earlier:
884 // - for regular channels at channel announcement (TODO)
885 // - for first and last hops early in get_route
886 if $src_node_id != $dest_node_id {
887 let short_channel_id = $candidate.short_channel_id();
888 let available_liquidity_msat = bookkept_channels_liquidity_available_msat
889 .entry(short_channel_id)
890 .or_insert_with(|| $candidate.effective_capacity().as_msat());
892 // It is tricky to subtract $next_hops_fee_msat from available liquidity here.
893 // It may be misleading because we might later choose to reduce the value transferred
894 // over these channels, and the channel which was insufficient might become sufficient.
895 // Worst case: we drop a good channel here because it can't cover the high following
896 // fees caused by one expensive channel, but then this channel could have been used
897 // if the amount being transferred over this path is lower.
898 // We do this for now, but this is a subject for removal.
899 if let Some(available_value_contribution_msat) = available_liquidity_msat.checked_sub($next_hops_fee_msat) {
901 // Routing Fragmentation Mitigation heuristic:
903 // Routing fragmentation across many payment paths increases the overall routing
904 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
905 // Taking too many smaller paths also increases the chance of payment failure.
906 // Thus to avoid this effect, we require from our collected links to provide
907 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
909 // This requirement is currently 5% of the remaining-to-be-collected value.
910 // This means as we successfully advance in our collection,
911 // the absolute liquidity contribution is lowered,
912 // thus increasing the number of potential channels to be selected.
914 // Derive the minimal liquidity contribution with a ratio of 20 (5%, rounded up)
915 // or 100% if we're not allowed to do multipath payments.
916 let minimal_value_contribution_msat: u64 = if allow_mpp {
917 (recommended_value_msat - already_collected_value_msat + 19) / 20
921 // Verify the liquidity offered by this channel complies to the minimal contribution.
922 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
923 // Do not consider candidate hops that would exceed the maximum path length.
924 let path_length_to_node = $next_hops_path_length + 1;
925 let doesnt_exceed_max_path_length = path_length_to_node <= MAX_PATH_LENGTH_ESTIMATE;
927 // Do not consider candidates that exceed the maximum total cltv expiry limit.
928 // In order to already account for some of the privacy enhancing random CLTV
929 // expiry delta offset we add on top later, we subtract a rough estimate
930 // (2*MEDIAN_HOP_CLTV_EXPIRY_DELTA) here.
931 let max_total_cltv_expiry_delta = (payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta)
932 .checked_sub(2*MEDIAN_HOP_CLTV_EXPIRY_DELTA)
933 .unwrap_or(payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta);
934 let hop_total_cltv_delta = ($next_hops_cltv_delta as u32)
935 .saturating_add($candidate.cltv_expiry_delta());
936 let doesnt_exceed_cltv_delta_limit = hop_total_cltv_delta <= max_total_cltv_expiry_delta;
938 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
939 // Includes paying fees for the use of the following channels.
940 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
941 Some(result) => result,
942 // Can't overflow due to how the values were computed right above.
943 None => unreachable!(),
945 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
946 let over_path_minimum_msat = amount_to_transfer_over_msat >= $candidate.htlc_minimum_msat() &&
947 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
949 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
950 let may_overpay_to_meet_path_minimum_msat =
951 ((amount_to_transfer_over_msat < $candidate.htlc_minimum_msat() &&
952 recommended_value_msat > $candidate.htlc_minimum_msat()) ||
953 (amount_to_transfer_over_msat < $next_hops_path_htlc_minimum_msat &&
954 recommended_value_msat > $next_hops_path_htlc_minimum_msat));
956 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
957 // bother considering this channel. If retrying with recommended_value_msat may
958 // allow us to hit the HTLC minimum limit, set htlc_minimum_limit so that we go
959 // around again with a higher amount.
960 if contributes_sufficient_value && doesnt_exceed_max_path_length &&
961 doesnt_exceed_cltv_delta_limit && may_overpay_to_meet_path_minimum_msat {
962 hit_minimum_limit = true;
963 } else if contributes_sufficient_value && doesnt_exceed_max_path_length &&
964 doesnt_exceed_cltv_delta_limit && over_path_minimum_msat {
965 // Note that low contribution here (limited by available_liquidity_msat)
966 // might violate htlc_minimum_msat on the hops which are next along the
967 // payment path (upstream to the payee). To avoid that, we recompute
968 // path fees knowing the final path contribution after constructing it.
969 let path_htlc_minimum_msat = compute_fees($next_hops_path_htlc_minimum_msat, $candidate.fees())
970 .and_then(|fee_msat| fee_msat.checked_add($next_hops_path_htlc_minimum_msat))
971 .map(|fee_msat| cmp::max(fee_msat, $candidate.htlc_minimum_msat()))
972 .unwrap_or_else(|| u64::max_value());
973 let hm_entry = dist.entry($src_node_id);
974 let old_entry = hm_entry.or_insert_with(|| {
975 // If there was previously no known way to access the source node
976 // (recall it goes payee-to-payer) of short_channel_id, first add a
977 // semi-dummy record just to compute the fees to reach the source node.
978 // This will affect our decision on selecting short_channel_id
979 // as a way to reach the $dest_node_id.
980 let mut fee_base_msat = 0;
981 let mut fee_proportional_millionths = 0;
982 if let Some(Some(fees)) = network_nodes.get(&$src_node_id).map(|node| node.lowest_inbound_channel_fees) {
983 fee_base_msat = fees.base_msat;
984 fee_proportional_millionths = fees.proportional_millionths;
987 node_id: $dest_node_id.clone(),
988 candidate: $candidate.clone(),
990 src_lowest_inbound_fees: RoutingFees {
991 base_msat: fee_base_msat,
992 proportional_millionths: fee_proportional_millionths,
994 next_hops_fee_msat: u64::max_value(),
995 hop_use_fee_msat: u64::max_value(),
996 total_fee_msat: u64::max_value(),
997 path_htlc_minimum_msat,
998 path_penalty_msat: u64::max_value(),
999 was_processed: false,
1000 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
1001 value_contribution_msat,
1005 #[allow(unused_mut)] // We only use the mut in cfg(test)
1006 let mut should_process = !old_entry.was_processed;
1007 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
1009 // In test/fuzzing builds, we do extra checks to make sure the skipping
1010 // of already-seen nodes only happens in cases we expect (see below).
1011 if !should_process { should_process = true; }
1015 let mut hop_use_fee_msat = 0;
1016 let mut total_fee_msat = $next_hops_fee_msat;
1018 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
1019 // will have the same effective-fee
1020 if $src_node_id != our_node_id {
1021 match compute_fees(amount_to_transfer_over_msat, $candidate.fees()) {
1022 // max_value means we'll always fail
1023 // the old_entry.total_fee_msat > total_fee_msat check
1024 None => total_fee_msat = u64::max_value(),
1026 hop_use_fee_msat = fee_msat;
1027 total_fee_msat += hop_use_fee_msat;
1028 // When calculating the lowest inbound fees to a node, we
1029 // calculate fees here not based on the actual value we think
1030 // will flow over this channel, but on the minimum value that
1031 // we'll accept flowing over it. The minimum accepted value
1032 // is a constant through each path collection run, ensuring
1033 // consistent basis. Otherwise we may later find a
1034 // different path to the source node that is more expensive,
1035 // but which we consider to be cheaper because we are capacity
1036 // constrained and the relative fee becomes lower.
1037 match compute_fees(minimal_value_contribution_msat, old_entry.src_lowest_inbound_fees)
1038 .map(|a| a.checked_add(total_fee_msat)) {
1043 total_fee_msat = u64::max_value();
1050 let path_penalty_msat = $next_hops_path_penalty_msat.saturating_add(
1051 scorer.channel_penalty_msat(short_channel_id, amount_to_transfer_over_msat,
1052 *available_liquidity_msat, &$src_node_id, &$dest_node_id));
1053 let new_graph_node = RouteGraphNode {
1054 node_id: $src_node_id,
1055 lowest_fee_to_peer_through_node: total_fee_msat,
1056 lowest_fee_to_node: $next_hops_fee_msat as u64 + hop_use_fee_msat,
1057 total_cltv_delta: hop_total_cltv_delta,
1058 value_contribution_msat: value_contribution_msat,
1059 path_htlc_minimum_msat,
1061 path_length_to_node,
1064 // Update the way of reaching $src_node_id with the given short_channel_id (from $dest_node_id),
1065 // if this way is cheaper than the already known
1066 // (considering the cost to "reach" this channel from the route destination,
1067 // the cost of using this channel,
1068 // and the cost of routing to the source node of this channel).
1069 // Also, consider that htlc_minimum_msat_difference, because we might end up
1070 // paying it. Consider the following exploit:
1071 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
1072 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
1073 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
1074 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
1076 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
1077 // but it may require additional tracking - we don't want to double-count
1078 // the fees included in $next_hops_path_htlc_minimum_msat, but also
1079 // can't use something that may decrease on future hops.
1080 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat)
1081 .saturating_add(old_entry.path_penalty_msat);
1082 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat)
1083 .saturating_add(path_penalty_msat);
1085 if !old_entry.was_processed && new_cost < old_cost {
1086 targets.push(new_graph_node);
1087 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
1088 old_entry.hop_use_fee_msat = hop_use_fee_msat;
1089 old_entry.total_fee_msat = total_fee_msat;
1090 old_entry.node_id = $dest_node_id.clone();
1091 old_entry.candidate = $candidate.clone();
1092 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
1093 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
1094 old_entry.path_penalty_msat = path_penalty_msat;
1095 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
1097 old_entry.value_contribution_msat = value_contribution_msat;
1099 did_add_update_path_to_src_node = true;
1100 } else if old_entry.was_processed && new_cost < old_cost {
1101 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
1103 // If we're skipping processing a node which was previously
1104 // processed even though we found another path to it with a
1105 // cheaper fee, check that it was because the second path we
1106 // found (which we are processing now) has a lower value
1107 // contribution due to an HTLC minimum limit.
1109 // e.g. take a graph with two paths from node 1 to node 2, one
1110 // through channel A, and one through channel B. Channel A and
1111 // B are both in the to-process heap, with their scores set by
1112 // a higher htlc_minimum than fee.
1113 // Channel A is processed first, and the channels onwards from
1114 // node 1 are added to the to-process heap. Thereafter, we pop
1115 // Channel B off of the heap, note that it has a much more
1116 // restrictive htlc_maximum_msat, and recalculate the fees for
1117 // all of node 1's channels using the new, reduced, amount.
1119 // This would be bogus - we'd be selecting a higher-fee path
1120 // with a lower htlc_maximum_msat instead of the one we'd
1121 // already decided to use.
1122 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
1124 value_contribution_msat + path_penalty_msat <
1125 old_entry.value_contribution_msat + old_entry.path_penalty_msat
1133 did_add_update_path_to_src_node
1137 let default_node_features = default_node_features();
1139 // Find ways (channels with destination) to reach a given node and store them
1140 // in the corresponding data structures (routing graph etc).
1141 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
1142 // meaning how much will be paid in fees after this node (to the best of our knowledge).
1143 // This data can later be helpful to optimize routing (pay lower fees).
1144 macro_rules! add_entries_to_cheapest_to_target_node {
1145 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr, $next_hops_value_contribution: expr,
1146 $next_hops_path_htlc_minimum_msat: expr, $next_hops_path_penalty_msat: expr,
1147 $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => {
1148 let skip_node = if let Some(elem) = dist.get_mut(&$node_id) {
1149 let was_processed = elem.was_processed;
1150 elem.was_processed = true;
1153 // Entries are added to dist in add_entry!() when there is a channel from a node.
1154 // Because there are no channels from payee, it will not have a dist entry at this point.
1155 // If we're processing any other node, it is always be the result of a channel from it.
1156 assert_eq!($node_id, payee_node_id);
1161 if let Some(first_channels) = first_hop_targets.get(&$node_id) {
1162 for details in first_channels {
1163 let candidate = CandidateRouteHop::FirstHop { details };
1164 add_entry!(candidate, our_node_id, $node_id, $fee_to_target_msat,
1165 $next_hops_value_contribution,
1166 $next_hops_path_htlc_minimum_msat, $next_hops_path_penalty_msat,
1167 $next_hops_cltv_delta, $next_hops_path_length);
1171 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
1174 &default_node_features
1177 if !features.requires_unknown_bits() {
1178 for chan_id in $node.channels.iter() {
1179 let chan = network_channels.get(chan_id).unwrap();
1180 if !chan.features.requires_unknown_bits() {
1181 let (directed_channel, source) =
1182 chan.as_directed_to(&$node_id).expect("inconsistent NetworkGraph");
1183 if first_hops.is_none() || *source != our_node_id {
1184 if let Some(direction) = directed_channel.direction() {
1185 if direction.enabled {
1186 let candidate = CandidateRouteHop::PublicHop {
1187 info: directed_channel.with_update().unwrap(),
1188 short_channel_id: *chan_id,
1190 add_entry!(candidate, *source, $node_id,
1191 $fee_to_target_msat,
1192 $next_hops_value_contribution,
1193 $next_hops_path_htlc_minimum_msat,
1194 $next_hops_path_penalty_msat,
1195 $next_hops_cltv_delta, $next_hops_path_length);
1206 let mut payment_paths = Vec::<PaymentPath>::new();
1208 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
1209 'paths_collection: loop {
1210 // For every new path, start from scratch, except
1211 // bookkept_channels_liquidity_available_msat, which will improve
1212 // the further iterations of path finding. Also don't erase first_hop_targets.
1215 hit_minimum_limit = false;
1217 // If first hop is a private channel and the only way to reach the payee, this is the only
1218 // place where it could be added.
1219 if let Some(first_channels) = first_hop_targets.get(&payee_node_id) {
1220 for details in first_channels {
1221 let candidate = CandidateRouteHop::FirstHop { details };
1222 let added = add_entry!(candidate, our_node_id, payee_node_id, 0, path_value_msat,
1224 log_trace!(logger, "{} direct route to payee via SCID {}",
1225 if added { "Added" } else { "Skipped" }, candidate.short_channel_id());
1229 // Add the payee as a target, so that the payee-to-payer
1230 // search algorithm knows what to start with.
1231 match network_nodes.get(&payee_node_id) {
1232 // The payee is not in our network graph, so nothing to add here.
1233 // There is still a chance of reaching them via last_hops though,
1234 // so don't yet fail the payment here.
1235 // If not, targets.pop() will not even let us enter the loop in step 2.
1238 add_entries_to_cheapest_to_target_node!(node, payee_node_id, 0, path_value_msat, 0, 0u64, 0, 0);
1243 // If a caller provided us with last hops, add them to routing targets. Since this happens
1244 // earlier than general path finding, they will be somewhat prioritized, although currently
1245 // it matters only if the fees are exactly the same.
1246 for route in payment_params.route_hints.iter().filter(|route| !route.0.is_empty()) {
1247 let first_hop_in_route = &(route.0)[0];
1248 let have_hop_src_in_graph =
1249 // Only add the hops in this route to our candidate set if either
1250 // we have a direct channel to the first hop or the first hop is
1251 // in the regular network graph.
1252 first_hop_targets.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some() ||
1253 network_nodes.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some();
1254 if have_hop_src_in_graph {
1255 // We start building the path from reverse, i.e., from payee
1256 // to the first RouteHintHop in the path.
1257 let hop_iter = route.0.iter().rev();
1258 let prev_hop_iter = core::iter::once(&payment_params.payee_pubkey).chain(
1259 route.0.iter().skip(1).rev().map(|hop| &hop.src_node_id));
1260 let mut hop_used = true;
1261 let mut aggregate_next_hops_fee_msat: u64 = 0;
1262 let mut aggregate_next_hops_path_htlc_minimum_msat: u64 = 0;
1263 let mut aggregate_next_hops_path_penalty_msat: u64 = 0;
1264 let mut aggregate_next_hops_cltv_delta: u32 = 0;
1265 let mut aggregate_next_hops_path_length: u8 = 0;
1267 for (idx, (hop, prev_hop_id)) in hop_iter.zip(prev_hop_iter).enumerate() {
1268 let source = NodeId::from_pubkey(&hop.src_node_id);
1269 let target = NodeId::from_pubkey(&prev_hop_id);
1270 let candidate = network_channels
1271 .get(&hop.short_channel_id)
1272 .and_then(|channel| channel.as_directed_to(&target))
1273 .and_then(|(channel, _)| channel.with_update())
1274 .map(|info| CandidateRouteHop::PublicHop {
1276 short_channel_id: hop.short_channel_id,
1278 .unwrap_or_else(|| CandidateRouteHop::PrivateHop { hint: hop });
1279 let capacity_msat = candidate.effective_capacity().as_msat();
1280 aggregate_next_hops_path_penalty_msat = aggregate_next_hops_path_penalty_msat
1281 .saturating_add(scorer.channel_penalty_msat(hop.short_channel_id,
1282 final_value_msat, capacity_msat, &source, &target));
1284 aggregate_next_hops_cltv_delta = aggregate_next_hops_cltv_delta
1285 .saturating_add(hop.cltv_expiry_delta as u32);
1287 aggregate_next_hops_path_length = aggregate_next_hops_path_length
1290 if !add_entry!(candidate, source, target, aggregate_next_hops_fee_msat,
1291 path_value_msat, aggregate_next_hops_path_htlc_minimum_msat,
1292 aggregate_next_hops_path_penalty_msat,
1293 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length) {
1294 // If this hop was not used then there is no use checking the preceding
1295 // hops in the RouteHint. We can break by just searching for a direct
1296 // channel between last checked hop and first_hop_targets.
1300 // Searching for a direct channel between last checked hop and first_hop_targets
1301 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&prev_hop_id)) {
1302 for details in first_channels {
1303 let candidate = CandidateRouteHop::FirstHop { details };
1304 add_entry!(candidate, our_node_id, NodeId::from_pubkey(&prev_hop_id),
1305 aggregate_next_hops_fee_msat, path_value_msat,
1306 aggregate_next_hops_path_htlc_minimum_msat,
1307 aggregate_next_hops_path_penalty_msat, aggregate_next_hops_cltv_delta,
1308 aggregate_next_hops_path_length);
1316 // In the next values of the iterator, the aggregate fees already reflects
1317 // the sum of value sent from payer (final_value_msat) and routing fees
1318 // for the last node in the RouteHint. We need to just add the fees to
1319 // route through the current node so that the preceding node (next iteration)
1321 let hops_fee = compute_fees(aggregate_next_hops_fee_msat + final_value_msat, hop.fees)
1322 .map_or(None, |inc| inc.checked_add(aggregate_next_hops_fee_msat));
1323 aggregate_next_hops_fee_msat = if let Some(val) = hops_fee { val } else { break; };
1325 let hop_htlc_minimum_msat = candidate.htlc_minimum_msat();
1326 let hop_htlc_minimum_msat_inc = if let Some(val) = compute_fees(aggregate_next_hops_path_htlc_minimum_msat, hop.fees) { val } else { break; };
1327 let hops_path_htlc_minimum = aggregate_next_hops_path_htlc_minimum_msat
1328 .checked_add(hop_htlc_minimum_msat_inc);
1329 aggregate_next_hops_path_htlc_minimum_msat = if let Some(val) = hops_path_htlc_minimum { cmp::max(hop_htlc_minimum_msat, val) } else { break; };
1331 if idx == route.0.len() - 1 {
1332 // The last hop in this iterator is the first hop in
1333 // overall RouteHint.
1334 // If this hop connects to a node with which we have a direct channel,
1335 // ignore the network graph and, if the last hop was added, add our
1336 // direct channel to the candidate set.
1338 // Note that we *must* check if the last hop was added as `add_entry`
1339 // always assumes that the third argument is a node to which we have a
1341 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&hop.src_node_id)) {
1342 for details in first_channels {
1343 let candidate = CandidateRouteHop::FirstHop { details };
1344 add_entry!(candidate, our_node_id,
1345 NodeId::from_pubkey(&hop.src_node_id),
1346 aggregate_next_hops_fee_msat, path_value_msat,
1347 aggregate_next_hops_path_htlc_minimum_msat,
1348 aggregate_next_hops_path_penalty_msat,
1349 aggregate_next_hops_cltv_delta,
1350 aggregate_next_hops_path_length);
1358 log_trace!(logger, "Starting main path collection loop with {} nodes pre-filled from first/last hops.", targets.len());
1360 // At this point, targets are filled with the data from first and
1361 // last hops communicated by the caller, and the payment receiver.
1362 let mut found_new_path = false;
1365 // If this loop terminates due the exhaustion of targets, two situations are possible:
1366 // - not enough outgoing liquidity:
1367 // 0 < already_collected_value_msat < final_value_msat
1368 // - enough outgoing liquidity:
1369 // final_value_msat <= already_collected_value_msat < recommended_value_msat
1370 // Both these cases (and other cases except reaching recommended_value_msat) mean that
1371 // paths_collection will be stopped because found_new_path==false.
1372 // This is not necessarily a routing failure.
1373 '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() {
1375 // Since we're going payee-to-payer, hitting our node as a target means we should stop
1376 // traversing the graph and arrange the path out of what we found.
1377 if node_id == our_node_id {
1378 let mut new_entry = dist.remove(&our_node_id).unwrap();
1379 let mut ordered_hops: Vec<(PathBuildingHop, NodeFeatures)> = vec!((new_entry.clone(), default_node_features.clone()));
1382 let mut features_set = false;
1383 if let Some(first_channels) = first_hop_targets.get(&ordered_hops.last().unwrap().0.node_id) {
1384 for details in first_channels {
1385 if details.short_channel_id.unwrap() == ordered_hops.last().unwrap().0.candidate.short_channel_id() {
1386 ordered_hops.last_mut().unwrap().1 = details.counterparty.features.to_context();
1387 features_set = true;
1393 if let Some(node) = network_nodes.get(&ordered_hops.last().unwrap().0.node_id) {
1394 if let Some(node_info) = node.announcement_info.as_ref() {
1395 ordered_hops.last_mut().unwrap().1 = node_info.features.clone();
1397 ordered_hops.last_mut().unwrap().1 = default_node_features.clone();
1400 // We can fill in features for everything except hops which were
1401 // provided via the invoice we're paying. We could guess based on the
1402 // recipient's features but for now we simply avoid guessing at all.
1406 // Means we succesfully traversed from the payer to the payee, now
1407 // save this path for the payment route. Also, update the liquidity
1408 // remaining on the used hops, so that we take them into account
1409 // while looking for more paths.
1410 if ordered_hops.last().unwrap().0.node_id == payee_node_id {
1414 new_entry = match dist.remove(&ordered_hops.last().unwrap().0.node_id) {
1415 Some(payment_hop) => payment_hop,
1416 // We can't arrive at None because, if we ever add an entry to targets,
1417 // we also fill in the entry in dist (see add_entry!).
1418 None => unreachable!(),
1420 // We "propagate" the fees one hop backward (topologically) here,
1421 // so that fees paid for a HTLC forwarding on the current channel are
1422 // associated with the previous channel (where they will be subtracted).
1423 ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
1424 ordered_hops.push((new_entry.clone(), default_node_features.clone()));
1426 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
1427 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
1429 log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: \n {:#?}",
1430 ordered_hops.len(), value_contribution_msat, ordered_hops.iter().map(|h| &(h.0)).collect::<Vec<&PathBuildingHop>>());
1432 let mut payment_path = PaymentPath {hops: ordered_hops};
1434 // We could have possibly constructed a slightly inconsistent path: since we reduce
1435 // value being transferred along the way, we could have violated htlc_minimum_msat
1436 // on some channels we already passed (assuming dest->source direction). Here, we
1437 // recompute the fees again, so that if that's the case, we match the currently
1438 // underpaid htlc_minimum_msat with fees.
1439 payment_path.update_value_and_recompute_fees(cmp::min(value_contribution_msat, final_value_msat));
1441 // Since a path allows to transfer as much value as
1442 // the smallest channel it has ("bottleneck"), we should recompute
1443 // the fees so sender HTLC don't overpay fees when traversing
1444 // larger channels than the bottleneck. This may happen because
1445 // when we were selecting those channels we were not aware how much value
1446 // this path will transfer, and the relative fee for them
1447 // might have been computed considering a larger value.
1448 // Remember that we used these channels so that we don't rely
1449 // on the same liquidity in future paths.
1450 let mut prevented_redundant_path_selection = false;
1451 for (payment_hop, _) in payment_path.hops.iter() {
1452 let channel_liquidity_available_msat = bookkept_channels_liquidity_available_msat.get_mut(&payment_hop.candidate.short_channel_id()).unwrap();
1453 let mut spent_on_hop_msat = value_contribution_msat;
1454 let next_hops_fee_msat = payment_hop.next_hops_fee_msat;
1455 spent_on_hop_msat += next_hops_fee_msat;
1456 if spent_on_hop_msat == *channel_liquidity_available_msat {
1457 // If this path used all of this channel's available liquidity, we know
1458 // this path will not be selected again in the next loop iteration.
1459 prevented_redundant_path_selection = true;
1461 *channel_liquidity_available_msat -= spent_on_hop_msat;
1463 if !prevented_redundant_path_selection {
1464 // If we weren't capped by hitting a liquidity limit on a channel in the path,
1465 // we'll probably end up picking the same path again on the next iteration.
1466 // Decrease the available liquidity of a hop in the middle of the path.
1467 let victim_scid = payment_path.hops[(payment_path.hops.len()) / 2].0.candidate.short_channel_id();
1468 log_trace!(logger, "Disabling channel {} for future path building iterations to avoid duplicates.", victim_scid);
1469 let victim_liquidity = bookkept_channels_liquidity_available_msat.get_mut(&victim_scid).unwrap();
1470 *victim_liquidity = 0;
1473 // Track the total amount all our collected paths allow to send so that we:
1474 // - know when to stop looking for more paths
1475 // - know which of the hops are useless considering how much more sats we need
1476 // (contributes_sufficient_value)
1477 already_collected_value_msat += value_contribution_msat;
1479 payment_paths.push(payment_path);
1480 found_new_path = true;
1481 break 'path_construction;
1484 // If we found a path back to the payee, we shouldn't try to process it again. This is
1485 // the equivalent of the `elem.was_processed` check in
1486 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
1487 if node_id == payee_node_id { continue 'path_construction; }
1489 // Otherwise, since the current target node is not us,
1490 // keep "unrolling" the payment graph from payee to payer by
1491 // finding a way to reach the current target from the payer side.
1492 match network_nodes.get(&node_id) {
1495 add_entries_to_cheapest_to_target_node!(node, node_id, lowest_fee_to_node,
1496 value_contribution_msat, path_htlc_minimum_msat, path_penalty_msat,
1497 total_cltv_delta, path_length_to_node);
1503 // If we don't support MPP, no use trying to gather more value ever.
1504 break 'paths_collection;
1508 // Stop either when the recommended value is reached or if no new path was found in this
1510 // In the latter case, making another path finding attempt won't help,
1511 // because we deterministically terminated the search due to low liquidity.
1512 if already_collected_value_msat >= recommended_value_msat || !found_new_path {
1513 log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
1514 already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
1515 break 'paths_collection;
1516 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
1517 // Further, if this was our first walk of the graph, and we weren't limited by an
1518 // htlc_minimum_msat, return immediately because this path should suffice. If we were
1519 // limited by an htlc_minimum_msat value, find another path with a higher value,
1520 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
1521 // still keeping a lower total fee than this path.
1522 if !hit_minimum_limit {
1523 log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
1524 break 'paths_collection;
1526 log_trace!(logger, "Collected our payment amount on the first pass, but running again to collect extra paths with a potentially higher limit.");
1527 path_value_msat = recommended_value_msat;
1532 if payment_paths.len() == 0 {
1533 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1536 if already_collected_value_msat < final_value_msat {
1537 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1540 // Sort by total fees and take the best paths.
1541 payment_paths.sort_unstable_by_key(|path| path.get_total_fee_paid_msat());
1542 if payment_paths.len() > 50 {
1543 payment_paths.truncate(50);
1546 // Draw multiple sufficient routes by randomly combining the selected paths.
1547 let mut drawn_routes = Vec::new();
1548 let mut prng = ChaCha20::new(random_seed_bytes, &[0u8; 12]);
1549 let mut random_index_bytes = [0u8; ::core::mem::size_of::<usize>()];
1551 let num_permutations = payment_paths.len();
1552 for _ in 0..num_permutations {
1553 let mut cur_route = Vec::<PaymentPath>::new();
1554 let mut aggregate_route_value_msat = 0;
1557 // Do a Fisher-Yates shuffle to create a random permutation of the payment paths
1558 for cur_index in (1..payment_paths.len()).rev() {
1559 prng.process_in_place(&mut random_index_bytes);
1560 let random_index = usize::from_be_bytes(random_index_bytes).wrapping_rem(cur_index+1);
1561 payment_paths.swap(cur_index, random_index);
1565 for payment_path in &payment_paths {
1566 cur_route.push(payment_path.clone());
1567 aggregate_route_value_msat += payment_path.get_value_msat();
1568 if aggregate_route_value_msat > final_value_msat {
1569 // Last path likely overpaid. Substract it from the most expensive
1570 // (in terms of proportional fee) path in this route and recompute fees.
1571 // This might be not the most economically efficient way, but fewer paths
1572 // also makes routing more reliable.
1573 let mut overpaid_value_msat = aggregate_route_value_msat - final_value_msat;
1575 // First, we drop some expensive low-value paths entirely if possible, since fewer
1576 // paths is better: the payment is less likely to fail. In order to do so, we sort
1577 // by value and fall back to total fees paid, i.e., in case of equal values we
1578 // prefer lower cost paths.
1579 cur_route.sort_unstable_by(|a, b| {
1580 a.get_value_msat().cmp(&b.get_value_msat())
1581 // Reverse ordering for cost, so we drop higher-cost paths first
1582 .then_with(|| b.get_cost_msat().cmp(&a.get_cost_msat()))
1585 // We should make sure that at least 1 path left.
1586 let mut paths_left = cur_route.len();
1587 cur_route.retain(|path| {
1588 if paths_left == 1 {
1591 let mut keep = true;
1592 let path_value_msat = path.get_value_msat();
1593 if path_value_msat <= overpaid_value_msat {
1595 overpaid_value_msat -= path_value_msat;
1601 if overpaid_value_msat == 0 {
1605 assert!(cur_route.len() > 0);
1608 // Now, subtract the overpaid value from the most-expensive path.
1609 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1610 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1611 cur_route.sort_unstable_by_key(|path| { path.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>() });
1612 let expensive_payment_path = cur_route.first_mut().unwrap();
1614 // We already dropped all the small value paths above, meaning all the
1615 // remaining paths are larger than remaining overpaid_value_msat.
1616 // Thus, this can't be negative.
1617 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
1618 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
1622 drawn_routes.push(cur_route);
1626 // Select the best route by lowest total cost.
1627 drawn_routes.sort_unstable_by_key(|paths| paths.iter().map(|path| path.get_cost_msat()).sum::<u64>());
1628 let mut selected_paths = Vec::<Vec<Result<RouteHop, LightningError>>>::new();
1629 for payment_path in drawn_routes.first().unwrap() {
1630 let mut path = payment_path.hops.iter().map(|(payment_hop, node_features)| {
1632 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)})?,
1633 node_features: node_features.clone(),
1634 short_channel_id: payment_hop.candidate.short_channel_id(),
1635 channel_features: payment_hop.candidate.features(),
1636 fee_msat: payment_hop.fee_msat,
1637 cltv_expiry_delta: payment_hop.candidate.cltv_expiry_delta(),
1639 }).collect::<Vec<_>>();
1640 // Propagate the cltv_expiry_delta one hop backwards since the delta from the current hop is
1641 // applicable for the previous hop.
1642 path.iter_mut().rev().fold(final_cltv_expiry_delta, |prev_cltv_expiry_delta, hop| {
1643 core::mem::replace(&mut hop.as_mut().unwrap().cltv_expiry_delta, prev_cltv_expiry_delta)
1645 selected_paths.push(path);
1648 if let Some(features) = &payment_params.features {
1649 for path in selected_paths.iter_mut() {
1650 if let Ok(route_hop) = path.last_mut().unwrap() {
1651 route_hop.node_features = features.to_context();
1657 paths: selected_paths.into_iter().map(|path| path.into_iter().collect()).collect::<Result<Vec<_>, _>>()?,
1658 payment_params: Some(payment_params.clone()),
1660 log_info!(logger, "Got route to {}: {}", payment_params.payee_pubkey, log_route!(route));
1664 // When an adversarial intermediary node observes a payment, it may be able to infer its
1665 // destination, if the remaining CLTV expiry delta exactly matches a feasible path in the network
1666 // graph. In order to improve privacy, this method obfuscates the CLTV expiry deltas along the
1667 // payment path by adding a randomized 'shadow route' offset to the final hop.
1668 fn add_random_cltv_offset(route: &mut Route, payment_params: &PaymentParameters, network_graph: &ReadOnlyNetworkGraph, random_seed_bytes: &[u8; 32]) {
1669 let network_channels = network_graph.channels();
1670 let network_nodes = network_graph.nodes();
1672 for path in route.paths.iter_mut() {
1673 let mut shadow_ctlv_expiry_delta_offset: u32 = 0;
1675 // Remember the last three nodes of the random walk and avoid looping back on them.
1676 // Init with the last three nodes from the actual path, if possible.
1677 let mut nodes_to_avoid: [NodeId; 3] = [NodeId::from_pubkey(&path.last().unwrap().pubkey),
1678 NodeId::from_pubkey(&path.get(path.len().saturating_sub(2)).unwrap().pubkey),
1679 NodeId::from_pubkey(&path.get(path.len().saturating_sub(3)).unwrap().pubkey)];
1681 // Choose the last publicly known node as the starting point for the random walk.
1682 let mut cur_hop: Option<NodeId> = None;
1683 let mut path_nonce = [0u8; 12];
1684 if let Some(starting_hop) = path.iter().rev()
1685 .find(|h| network_nodes.contains_key(&NodeId::from_pubkey(&h.pubkey))) {
1686 cur_hop = Some(NodeId::from_pubkey(&starting_hop.pubkey));
1687 path_nonce.copy_from_slice(&cur_hop.unwrap().as_slice()[..12]);
1690 // Init PRNG with the path-dependant nonce, which is static for private paths.
1691 let mut prng = ChaCha20::new(random_seed_bytes, &path_nonce);
1692 let mut random_path_bytes = [0u8; ::core::mem::size_of::<usize>()];
1694 // Pick a random path length in [1 .. 3]
1695 prng.process_in_place(&mut random_path_bytes);
1696 let random_walk_length = usize::from_be_bytes(random_path_bytes).wrapping_rem(3).wrapping_add(1);
1698 for random_hop in 0..random_walk_length {
1699 // If we don't find a suitable offset in the public network graph, we default to
1700 // MEDIAN_HOP_CLTV_EXPIRY_DELTA.
1701 let mut random_hop_offset = MEDIAN_HOP_CLTV_EXPIRY_DELTA;
1703 if let Some(cur_node_id) = cur_hop {
1704 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
1705 // Randomly choose the next unvisited hop.
1706 prng.process_in_place(&mut random_path_bytes);
1707 if let Some(random_channel) = usize::from_be_bytes(random_path_bytes)
1708 .checked_rem(cur_node.channels.len())
1709 .and_then(|index| cur_node.channels.get(index))
1710 .and_then(|id| network_channels.get(id)) {
1711 random_channel.as_directed_from(&cur_node_id).map(|(dir_info, next_id)| {
1712 if !nodes_to_avoid.iter().any(|x| x == next_id) {
1713 nodes_to_avoid[random_hop] = *next_id;
1714 dir_info.direction().map(|channel_update_info| {
1715 random_hop_offset = channel_update_info.cltv_expiry_delta.into();
1716 cur_hop = Some(*next_id);
1724 shadow_ctlv_expiry_delta_offset = shadow_ctlv_expiry_delta_offset
1725 .checked_add(random_hop_offset)
1726 .unwrap_or(shadow_ctlv_expiry_delta_offset);
1729 // Limit the total offset to reduce the worst-case locked liquidity timevalue
1730 const MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET: u32 = 3*144;
1731 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET);
1733 // Limit the offset so we never exceed the max_total_cltv_expiry_delta. To improve plausibility,
1734 // we choose the limit to be the largest possible multiple of MEDIAN_HOP_CLTV_EXPIRY_DELTA.
1735 let path_total_cltv_expiry_delta: u32 = path.iter().map(|h| h.cltv_expiry_delta).sum();
1736 let mut max_path_offset = payment_params.max_total_cltv_expiry_delta - path_total_cltv_expiry_delta;
1737 max_path_offset = cmp::max(
1738 max_path_offset - (max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA),
1739 max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA);
1740 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, max_path_offset);
1742 // Add 'shadow' CLTV offset to the final hop
1743 if let Some(last_hop) = path.last_mut() {
1744 last_hop.cltv_expiry_delta = last_hop.cltv_expiry_delta
1745 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(last_hop.cltv_expiry_delta);
1752 use routing::network_graph::{NetworkGraph, NetGraphMsgHandler, NodeId};
1753 use routing::router::{get_route, add_random_cltv_offset, default_node_features,
1754 PaymentParameters, Route, RouteHint, RouteHintHop, RouteHop, RoutingFees,
1755 DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA, MAX_PATH_LENGTH_ESTIMATE};
1756 use routing::scoring::Score;
1757 use chain::transaction::OutPoint;
1758 use chain::keysinterface::KeysInterface;
1759 use ln::features::{ChannelFeatures, InitFeatures, InvoiceFeatures, NodeFeatures};
1760 use ln::msgs::{ErrorAction, LightningError, OptionalField, UnsignedChannelAnnouncement, ChannelAnnouncement, RoutingMessageHandler,
1761 NodeAnnouncement, UnsignedNodeAnnouncement, ChannelUpdate, UnsignedChannelUpdate};
1762 use ln::channelmanager;
1763 use util::test_utils;
1764 use util::chacha20::ChaCha20;
1765 use util::ser::Writeable;
1767 use util::ser::Writer;
1769 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
1770 use bitcoin::hashes::Hash;
1771 use bitcoin::network::constants::Network;
1772 use bitcoin::blockdata::constants::genesis_block;
1773 use bitcoin::blockdata::script::Builder;
1774 use bitcoin::blockdata::opcodes;
1775 use bitcoin::blockdata::transaction::TxOut;
1779 use bitcoin::secp256k1::{PublicKey,SecretKey};
1780 use bitcoin::secp256k1::{Secp256k1, All};
1783 use sync::{self, Arc};
1785 fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
1786 features: InitFeatures, outbound_capacity_msat: u64) -> channelmanager::ChannelDetails {
1787 channelmanager::ChannelDetails {
1788 channel_id: [0; 32],
1789 counterparty: channelmanager::ChannelCounterparty {
1792 unspendable_punishment_reserve: 0,
1793 forwarding_info: None,
1794 outbound_htlc_minimum_msat: None,
1795 outbound_htlc_maximum_msat: None,
1797 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
1800 inbound_scid_alias: None,
1801 channel_value_satoshis: 0,
1804 outbound_capacity_msat,
1805 next_outbound_htlc_limit_msat: outbound_capacity_msat,
1806 inbound_capacity_msat: 42,
1807 unspendable_punishment_reserve: None,
1808 confirmations_required: None,
1809 force_close_spend_delay: None,
1810 is_outbound: true, is_funding_locked: true,
1811 is_usable: true, is_public: true,
1812 inbound_htlc_minimum_msat: None,
1813 inbound_htlc_maximum_msat: None,
1817 // Using the same keys for LN and BTC ids
1819 net_graph_msg_handler: &NetGraphMsgHandler<Arc<NetworkGraph>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1820 secp_ctx: &Secp256k1<All>, node_1_privkey: &SecretKey, node_2_privkey: &SecretKey, features: ChannelFeatures, short_channel_id: u64
1822 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1823 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1825 let unsigned_announcement = UnsignedChannelAnnouncement {
1827 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1831 bitcoin_key_1: node_id_1,
1832 bitcoin_key_2: node_id_2,
1833 excess_data: Vec::new(),
1836 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1837 let valid_announcement = ChannelAnnouncement {
1838 node_signature_1: secp_ctx.sign_ecdsa(&msghash, node_1_privkey),
1839 node_signature_2: secp_ctx.sign_ecdsa(&msghash, node_2_privkey),
1840 bitcoin_signature_1: secp_ctx.sign_ecdsa(&msghash, node_1_privkey),
1841 bitcoin_signature_2: secp_ctx.sign_ecdsa(&msghash, node_2_privkey),
1842 contents: unsigned_announcement.clone(),
1844 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1845 Ok(res) => assert!(res),
1851 net_graph_msg_handler: &NetGraphMsgHandler<Arc<NetworkGraph>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1852 secp_ctx: &Secp256k1<All>, node_privkey: &SecretKey, update: UnsignedChannelUpdate
1854 let msghash = hash_to_message!(&Sha256dHash::hash(&update.encode()[..])[..]);
1855 let valid_channel_update = ChannelUpdate {
1856 signature: secp_ctx.sign_ecdsa(&msghash, node_privkey),
1857 contents: update.clone()
1860 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1861 Ok(res) => assert!(res),
1866 fn add_or_update_node(
1867 net_graph_msg_handler: &NetGraphMsgHandler<Arc<NetworkGraph>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1868 secp_ctx: &Secp256k1<All>, node_privkey: &SecretKey, features: NodeFeatures, timestamp: u32
1870 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
1871 let unsigned_announcement = UnsignedNodeAnnouncement {
1877 addresses: Vec::new(),
1878 excess_address_data: Vec::new(),
1879 excess_data: Vec::new(),
1881 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1882 let valid_announcement = NodeAnnouncement {
1883 signature: secp_ctx.sign_ecdsa(&msghash, node_privkey),
1884 contents: unsigned_announcement.clone()
1887 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1893 fn get_nodes(secp_ctx: &Secp256k1<All>) -> (SecretKey, PublicKey, Vec<SecretKey>, Vec<PublicKey>) {
1894 let privkeys: Vec<SecretKey> = (2..22).map(|i| {
1895 SecretKey::from_slice(&hex::decode(format!("{:02x}", i).repeat(32)).unwrap()[..]).unwrap()
1898 let pubkeys = privkeys.iter().map(|secret| PublicKey::from_secret_key(&secp_ctx, secret)).collect();
1900 let our_privkey = SecretKey::from_slice(&hex::decode("01".repeat(32)).unwrap()[..]).unwrap();
1901 let our_id = PublicKey::from_secret_key(&secp_ctx, &our_privkey);
1903 (our_privkey, our_id, privkeys, pubkeys)
1906 fn id_to_feature_flags(id: u8) -> Vec<u8> {
1907 // Set the feature flags to the id'th odd (ie non-required) feature bit so that we can
1908 // test for it later.
1909 let idx = (id - 1) * 2 + 1;
1911 vec![1 << (idx - 8*3), 0, 0, 0]
1912 } else if idx > 8*2 {
1913 vec![1 << (idx - 8*2), 0, 0]
1914 } else if idx > 8*1 {
1915 vec![1 << (idx - 8*1), 0]
1921 fn build_line_graph() -> (
1922 Secp256k1<All>, sync::Arc<NetworkGraph>, NetGraphMsgHandler<sync::Arc<NetworkGraph>,
1923 sync::Arc<test_utils::TestChainSource>, sync::Arc<crate::util::test_utils::TestLogger>>,
1924 sync::Arc<test_utils::TestChainSource>, sync::Arc<test_utils::TestLogger>,
1926 let secp_ctx = Secp256k1::new();
1927 let logger = Arc::new(test_utils::TestLogger::new());
1928 let chain_monitor = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1929 let network_graph = Arc::new(NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash()));
1930 let net_graph_msg_handler = NetGraphMsgHandler::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
1932 // Build network from our_id to node 19:
1933 // our_id -1(1)2- node0 -1(2)2- node1 - ... - node19
1934 let (our_privkey, _, privkeys, _) = get_nodes(&secp_ctx);
1936 for (idx, (cur_privkey, next_privkey)) in core::iter::once(&our_privkey)
1937 .chain(privkeys.iter()).zip(privkeys.iter()).enumerate() {
1938 let cur_short_channel_id = (idx as u64) + 1;
1939 add_channel(&net_graph_msg_handler, &secp_ctx, &cur_privkey, &next_privkey,
1940 ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), cur_short_channel_id);
1941 update_channel(&net_graph_msg_handler, &secp_ctx, &cur_privkey, UnsignedChannelUpdate {
1942 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1943 short_channel_id: cur_short_channel_id,
1944 timestamp: idx as u32,
1946 cltv_expiry_delta: 0,
1947 htlc_minimum_msat: 0,
1948 htlc_maximum_msat: OptionalField::Absent,
1950 fee_proportional_millionths: 0,
1951 excess_data: Vec::new()
1953 update_channel(&net_graph_msg_handler, &secp_ctx, &next_privkey, UnsignedChannelUpdate {
1954 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1955 short_channel_id: cur_short_channel_id,
1956 timestamp: (idx as u32)+1,
1958 cltv_expiry_delta: 0,
1959 htlc_minimum_msat: 0,
1960 htlc_maximum_msat: OptionalField::Absent,
1962 fee_proportional_millionths: 0,
1963 excess_data: Vec::new()
1965 add_or_update_node(&net_graph_msg_handler, &secp_ctx, next_privkey,
1966 NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
1969 (secp_ctx, network_graph, net_graph_msg_handler, chain_monitor, logger)
1972 fn build_graph() -> (
1974 sync::Arc<NetworkGraph>,
1975 NetGraphMsgHandler<sync::Arc<NetworkGraph>, sync::Arc<test_utils::TestChainSource>, sync::Arc<crate::util::test_utils::TestLogger>>,
1976 sync::Arc<test_utils::TestChainSource>,
1977 sync::Arc<test_utils::TestLogger>,
1979 let secp_ctx = Secp256k1::new();
1980 let logger = Arc::new(test_utils::TestLogger::new());
1981 let chain_monitor = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1982 let network_graph = Arc::new(NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash()));
1983 let net_graph_msg_handler = NetGraphMsgHandler::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
1984 // Build network from our_id to node6:
1986 // -1(1)2- node0 -1(3)2-
1988 // our_id -1(12)2- node7 -1(13)2--- node2
1990 // -1(2)2- node1 -1(4)2-
1993 // chan1 1-to-2: disabled
1994 // chan1 2-to-1: enabled, 0 fee
1996 // chan2 1-to-2: enabled, ignored fee
1997 // chan2 2-to-1: enabled, 0 fee
1999 // chan3 1-to-2: enabled, 0 fee
2000 // chan3 2-to-1: enabled, 100 msat fee
2002 // chan4 1-to-2: enabled, 100% fee
2003 // chan4 2-to-1: enabled, 0 fee
2005 // chan12 1-to-2: enabled, ignored fee
2006 // chan12 2-to-1: enabled, 0 fee
2008 // chan13 1-to-2: enabled, 200% fee
2009 // chan13 2-to-1: enabled, 0 fee
2012 // -1(5)2- node3 -1(8)2--
2016 // node2--1(6)2- node4 -1(9)2--- node6 (not in global route map)
2018 // -1(7)2- node5 -1(10)2-
2020 // Channels 5, 8, 9 and 10 are private channels.
2022 // chan5 1-to-2: enabled, 100 msat fee
2023 // chan5 2-to-1: enabled, 0 fee
2025 // chan6 1-to-2: enabled, 0 fee
2026 // chan6 2-to-1: enabled, 0 fee
2028 // chan7 1-to-2: enabled, 100% fee
2029 // chan7 2-to-1: enabled, 0 fee
2031 // chan8 1-to-2: enabled, variable fee (0 then 1000 msat)
2032 // chan8 2-to-1: enabled, 0 fee
2034 // chan9 1-to-2: enabled, 1001 msat fee
2035 // chan9 2-to-1: enabled, 0 fee
2037 // chan10 1-to-2: enabled, 0 fee
2038 // chan10 2-to-1: enabled, 0 fee
2040 // chan11 1-to-2: enabled, 0 fee
2041 // chan11 2-to-1: enabled, 0 fee
2043 let (our_privkey, _, privkeys, _) = get_nodes(&secp_ctx);
2045 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[0], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
2046 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2047 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2048 short_channel_id: 1,
2051 cltv_expiry_delta: 0,
2052 htlc_minimum_msat: 0,
2053 htlc_maximum_msat: OptionalField::Absent,
2055 fee_proportional_millionths: 0,
2056 excess_data: Vec::new()
2059 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
2061 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
2062 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2063 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2064 short_channel_id: 2,
2067 cltv_expiry_delta: (5 << 4) | 3,
2068 htlc_minimum_msat: 0,
2069 htlc_maximum_msat: OptionalField::Absent,
2070 fee_base_msat: u32::max_value(),
2071 fee_proportional_millionths: u32::max_value(),
2072 excess_data: Vec::new()
2074 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2075 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2076 short_channel_id: 2,
2079 cltv_expiry_delta: 0,
2080 htlc_minimum_msat: 0,
2081 htlc_maximum_msat: OptionalField::Absent,
2083 fee_proportional_millionths: 0,
2084 excess_data: Vec::new()
2087 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
2089 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[7], ChannelFeatures::from_le_bytes(id_to_feature_flags(12)), 12);
2090 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2091 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2092 short_channel_id: 12,
2095 cltv_expiry_delta: (5 << 4) | 3,
2096 htlc_minimum_msat: 0,
2097 htlc_maximum_msat: OptionalField::Absent,
2098 fee_base_msat: u32::max_value(),
2099 fee_proportional_millionths: u32::max_value(),
2100 excess_data: Vec::new()
2102 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2103 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2104 short_channel_id: 12,
2107 cltv_expiry_delta: 0,
2108 htlc_minimum_msat: 0,
2109 htlc_maximum_msat: OptionalField::Absent,
2111 fee_proportional_millionths: 0,
2112 excess_data: Vec::new()
2115 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], NodeFeatures::from_le_bytes(id_to_feature_flags(8)), 0);
2117 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
2118 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2119 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2120 short_channel_id: 3,
2123 cltv_expiry_delta: (3 << 4) | 1,
2124 htlc_minimum_msat: 0,
2125 htlc_maximum_msat: OptionalField::Absent,
2127 fee_proportional_millionths: 0,
2128 excess_data: Vec::new()
2130 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2131 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2132 short_channel_id: 3,
2135 cltv_expiry_delta: (3 << 4) | 2,
2136 htlc_minimum_msat: 0,
2137 htlc_maximum_msat: OptionalField::Absent,
2139 fee_proportional_millionths: 0,
2140 excess_data: Vec::new()
2143 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
2144 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2145 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2146 short_channel_id: 4,
2149 cltv_expiry_delta: (4 << 4) | 1,
2150 htlc_minimum_msat: 0,
2151 htlc_maximum_msat: OptionalField::Absent,
2153 fee_proportional_millionths: 1000000,
2154 excess_data: Vec::new()
2156 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2157 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2158 short_channel_id: 4,
2161 cltv_expiry_delta: (4 << 4) | 2,
2162 htlc_minimum_msat: 0,
2163 htlc_maximum_msat: OptionalField::Absent,
2165 fee_proportional_millionths: 0,
2166 excess_data: Vec::new()
2169 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(13)), 13);
2170 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2171 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2172 short_channel_id: 13,
2175 cltv_expiry_delta: (13 << 4) | 1,
2176 htlc_minimum_msat: 0,
2177 htlc_maximum_msat: OptionalField::Absent,
2179 fee_proportional_millionths: 2000000,
2180 excess_data: Vec::new()
2182 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2183 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2184 short_channel_id: 13,
2187 cltv_expiry_delta: (13 << 4) | 2,
2188 htlc_minimum_msat: 0,
2189 htlc_maximum_msat: OptionalField::Absent,
2191 fee_proportional_millionths: 0,
2192 excess_data: Vec::new()
2195 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
2197 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
2198 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2199 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2200 short_channel_id: 6,
2203 cltv_expiry_delta: (6 << 4) | 1,
2204 htlc_minimum_msat: 0,
2205 htlc_maximum_msat: OptionalField::Absent,
2207 fee_proportional_millionths: 0,
2208 excess_data: Vec::new()
2210 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
2211 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2212 short_channel_id: 6,
2215 cltv_expiry_delta: (6 << 4) | 2,
2216 htlc_minimum_msat: 0,
2217 htlc_maximum_msat: OptionalField::Absent,
2219 fee_proportional_millionths: 0,
2220 excess_data: Vec::new(),
2223 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(11)), 11);
2224 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
2225 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2226 short_channel_id: 11,
2229 cltv_expiry_delta: (11 << 4) | 1,
2230 htlc_minimum_msat: 0,
2231 htlc_maximum_msat: OptionalField::Absent,
2233 fee_proportional_millionths: 0,
2234 excess_data: Vec::new()
2236 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
2237 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2238 short_channel_id: 11,
2241 cltv_expiry_delta: (11 << 4) | 2,
2242 htlc_minimum_msat: 0,
2243 htlc_maximum_msat: OptionalField::Absent,
2245 fee_proportional_millionths: 0,
2246 excess_data: Vec::new()
2249 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(5)), 0);
2251 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
2253 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[5], ChannelFeatures::from_le_bytes(id_to_feature_flags(7)), 7);
2254 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2255 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2256 short_channel_id: 7,
2259 cltv_expiry_delta: (7 << 4) | 1,
2260 htlc_minimum_msat: 0,
2261 htlc_maximum_msat: OptionalField::Absent,
2263 fee_proportional_millionths: 1000000,
2264 excess_data: Vec::new()
2266 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[5], UnsignedChannelUpdate {
2267 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2268 short_channel_id: 7,
2271 cltv_expiry_delta: (7 << 4) | 2,
2272 htlc_minimum_msat: 0,
2273 htlc_maximum_msat: OptionalField::Absent,
2275 fee_proportional_millionths: 0,
2276 excess_data: Vec::new()
2279 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[5], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
2281 (secp_ctx, network_graph, net_graph_msg_handler, chain_monitor, logger)
2285 fn simple_route_test() {
2286 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2287 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2288 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2289 let scorer = test_utils::TestScorer::with_penalty(0);
2290 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2291 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2293 // Simple route to 2 via 1
2295 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) {
2296 assert_eq!(err, "Cannot send a payment of 0 msat");
2297 } else { panic!(); }
2299 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2300 assert_eq!(route.paths[0].len(), 2);
2302 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2303 assert_eq!(route.paths[0][0].short_channel_id, 2);
2304 assert_eq!(route.paths[0][0].fee_msat, 100);
2305 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2306 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2307 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2309 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2310 assert_eq!(route.paths[0][1].short_channel_id, 4);
2311 assert_eq!(route.paths[0][1].fee_msat, 100);
2312 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2313 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2314 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2318 fn invalid_first_hop_test() {
2319 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2320 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2321 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2322 let scorer = test_utils::TestScorer::with_penalty(0);
2323 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2324 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2326 // Simple route to 2 via 1
2328 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
2330 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) =
2331 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) {
2332 assert_eq!(err, "First hop cannot have our_node_pubkey as a destination.");
2333 } else { panic!(); }
2335 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2336 assert_eq!(route.paths[0].len(), 2);
2340 fn htlc_minimum_test() {
2341 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2342 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2343 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2344 let scorer = test_utils::TestScorer::with_penalty(0);
2345 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2346 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2348 // Simple route to 2 via 1
2350 // Disable other paths
2351 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2352 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2353 short_channel_id: 12,
2355 flags: 2, // to disable
2356 cltv_expiry_delta: 0,
2357 htlc_minimum_msat: 0,
2358 htlc_maximum_msat: OptionalField::Absent,
2360 fee_proportional_millionths: 0,
2361 excess_data: Vec::new()
2363 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2364 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2365 short_channel_id: 3,
2367 flags: 2, // to disable
2368 cltv_expiry_delta: 0,
2369 htlc_minimum_msat: 0,
2370 htlc_maximum_msat: OptionalField::Absent,
2372 fee_proportional_millionths: 0,
2373 excess_data: Vec::new()
2375 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2376 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2377 short_channel_id: 13,
2379 flags: 2, // to disable
2380 cltv_expiry_delta: 0,
2381 htlc_minimum_msat: 0,
2382 htlc_maximum_msat: OptionalField::Absent,
2384 fee_proportional_millionths: 0,
2385 excess_data: Vec::new()
2387 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2388 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2389 short_channel_id: 6,
2391 flags: 2, // to disable
2392 cltv_expiry_delta: 0,
2393 htlc_minimum_msat: 0,
2394 htlc_maximum_msat: OptionalField::Absent,
2396 fee_proportional_millionths: 0,
2397 excess_data: Vec::new()
2399 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2400 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2401 short_channel_id: 7,
2403 flags: 2, // to disable
2404 cltv_expiry_delta: 0,
2405 htlc_minimum_msat: 0,
2406 htlc_maximum_msat: OptionalField::Absent,
2408 fee_proportional_millionths: 0,
2409 excess_data: Vec::new()
2412 // Check against amount_to_transfer_over_msat.
2413 // Set minimal HTLC of 200_000_000 msat.
2414 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2415 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2416 short_channel_id: 2,
2419 cltv_expiry_delta: 0,
2420 htlc_minimum_msat: 200_000_000,
2421 htlc_maximum_msat: OptionalField::Absent,
2423 fee_proportional_millionths: 0,
2424 excess_data: Vec::new()
2427 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
2429 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2430 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2431 short_channel_id: 4,
2434 cltv_expiry_delta: 0,
2435 htlc_minimum_msat: 0,
2436 htlc_maximum_msat: OptionalField::Present(199_999_999),
2438 fee_proportional_millionths: 0,
2439 excess_data: Vec::new()
2442 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
2443 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) {
2444 assert_eq!(err, "Failed to find a path to the given destination");
2445 } else { panic!(); }
2447 // Lift the restriction on the first hop.
2448 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2449 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2450 short_channel_id: 2,
2453 cltv_expiry_delta: 0,
2454 htlc_minimum_msat: 0,
2455 htlc_maximum_msat: OptionalField::Absent,
2457 fee_proportional_millionths: 0,
2458 excess_data: Vec::new()
2461 // A payment above the minimum should pass
2462 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();
2463 assert_eq!(route.paths[0].len(), 2);
2467 fn htlc_minimum_overpay_test() {
2468 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2469 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2470 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
2471 let scorer = test_utils::TestScorer::with_penalty(0);
2472 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2473 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2475 // A route to node#2 via two paths.
2476 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
2477 // Thus, they can't send 60 without overpaying.
2478 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2479 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2480 short_channel_id: 2,
2483 cltv_expiry_delta: 0,
2484 htlc_minimum_msat: 35_000,
2485 htlc_maximum_msat: OptionalField::Present(40_000),
2487 fee_proportional_millionths: 0,
2488 excess_data: Vec::new()
2490 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2491 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2492 short_channel_id: 12,
2495 cltv_expiry_delta: 0,
2496 htlc_minimum_msat: 35_000,
2497 htlc_maximum_msat: OptionalField::Present(40_000),
2499 fee_proportional_millionths: 0,
2500 excess_data: Vec::new()
2504 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2505 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2506 short_channel_id: 13,
2509 cltv_expiry_delta: 0,
2510 htlc_minimum_msat: 0,
2511 htlc_maximum_msat: OptionalField::Absent,
2513 fee_proportional_millionths: 0,
2514 excess_data: Vec::new()
2516 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2517 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2518 short_channel_id: 4,
2521 cltv_expiry_delta: 0,
2522 htlc_minimum_msat: 0,
2523 htlc_maximum_msat: OptionalField::Absent,
2525 fee_proportional_millionths: 0,
2526 excess_data: Vec::new()
2529 // Disable other paths
2530 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2531 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2532 short_channel_id: 1,
2534 flags: 2, // to disable
2535 cltv_expiry_delta: 0,
2536 htlc_minimum_msat: 0,
2537 htlc_maximum_msat: OptionalField::Absent,
2539 fee_proportional_millionths: 0,
2540 excess_data: Vec::new()
2543 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 60_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2544 // Overpay fees to hit htlc_minimum_msat.
2545 let overpaid_fees = route.paths[0][0].fee_msat + route.paths[1][0].fee_msat;
2546 // TODO: this could be better balanced to overpay 10k and not 15k.
2547 assert_eq!(overpaid_fees, 15_000);
2549 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
2550 // while taking even more fee to match htlc_minimum_msat.
2551 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2552 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2553 short_channel_id: 12,
2556 cltv_expiry_delta: 0,
2557 htlc_minimum_msat: 65_000,
2558 htlc_maximum_msat: OptionalField::Present(80_000),
2560 fee_proportional_millionths: 0,
2561 excess_data: Vec::new()
2563 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2564 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2565 short_channel_id: 2,
2568 cltv_expiry_delta: 0,
2569 htlc_minimum_msat: 0,
2570 htlc_maximum_msat: OptionalField::Absent,
2572 fee_proportional_millionths: 0,
2573 excess_data: Vec::new()
2575 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2576 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2577 short_channel_id: 4,
2580 cltv_expiry_delta: 0,
2581 htlc_minimum_msat: 0,
2582 htlc_maximum_msat: OptionalField::Absent,
2584 fee_proportional_millionths: 100_000,
2585 excess_data: Vec::new()
2588 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 60_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2589 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
2590 assert_eq!(route.paths.len(), 1);
2591 assert_eq!(route.paths[0][0].short_channel_id, 12);
2592 let fees = route.paths[0][0].fee_msat;
2593 assert_eq!(fees, 5_000);
2595 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2596 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
2597 // the other channel.
2598 assert_eq!(route.paths.len(), 1);
2599 assert_eq!(route.paths[0][0].short_channel_id, 2);
2600 let fees = route.paths[0][0].fee_msat;
2601 assert_eq!(fees, 5_000);
2605 fn disable_channels_test() {
2606 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2607 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2608 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2609 let scorer = test_utils::TestScorer::with_penalty(0);
2610 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2611 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2613 // // Disable channels 4 and 12 by flags=2
2614 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2615 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2616 short_channel_id: 4,
2618 flags: 2, // to disable
2619 cltv_expiry_delta: 0,
2620 htlc_minimum_msat: 0,
2621 htlc_maximum_msat: OptionalField::Absent,
2623 fee_proportional_millionths: 0,
2624 excess_data: Vec::new()
2626 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2627 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2628 short_channel_id: 12,
2630 flags: 2, // to disable
2631 cltv_expiry_delta: 0,
2632 htlc_minimum_msat: 0,
2633 htlc_maximum_msat: OptionalField::Absent,
2635 fee_proportional_millionths: 0,
2636 excess_data: Vec::new()
2639 // If all the channels require some features we don't understand, route should fail
2640 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) {
2641 assert_eq!(err, "Failed to find a path to the given destination");
2642 } else { panic!(); }
2644 // If we specify a channel to node7, that overrides our local channel view and that gets used
2645 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2646 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();
2647 assert_eq!(route.paths[0].len(), 2);
2649 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2650 assert_eq!(route.paths[0][0].short_channel_id, 42);
2651 assert_eq!(route.paths[0][0].fee_msat, 200);
2652 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2653 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2654 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2656 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2657 assert_eq!(route.paths[0][1].short_channel_id, 13);
2658 assert_eq!(route.paths[0][1].fee_msat, 100);
2659 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2660 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2661 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2665 fn disable_node_test() {
2666 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2667 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2668 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2669 let scorer = test_utils::TestScorer::with_penalty(0);
2670 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2671 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2673 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
2674 let mut unknown_features = NodeFeatures::known();
2675 unknown_features.set_unknown_feature_required();
2676 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
2677 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
2678 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
2680 // If all nodes require some features we don't understand, route should fail
2681 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) {
2682 assert_eq!(err, "Failed to find a path to the given destination");
2683 } else { panic!(); }
2685 // If we specify a channel to node7, that overrides our local channel view and that gets used
2686 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2687 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();
2688 assert_eq!(route.paths[0].len(), 2);
2690 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2691 assert_eq!(route.paths[0][0].short_channel_id, 42);
2692 assert_eq!(route.paths[0][0].fee_msat, 200);
2693 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2694 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2695 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2697 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2698 assert_eq!(route.paths[0][1].short_channel_id, 13);
2699 assert_eq!(route.paths[0][1].fee_msat, 100);
2700 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2701 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2702 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2704 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
2705 // naively) assume that the user checked the feature bits on the invoice, which override
2706 // the node_announcement.
2710 fn our_chans_test() {
2711 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2712 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2713 let scorer = test_utils::TestScorer::with_penalty(0);
2714 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2715 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2717 // Route to 1 via 2 and 3 because our channel to 1 is disabled
2718 let payment_params = PaymentParameters::from_node_id(nodes[0]);
2719 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2720 assert_eq!(route.paths[0].len(), 3);
2722 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2723 assert_eq!(route.paths[0][0].short_channel_id, 2);
2724 assert_eq!(route.paths[0][0].fee_msat, 200);
2725 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2726 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2727 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2729 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2730 assert_eq!(route.paths[0][1].short_channel_id, 4);
2731 assert_eq!(route.paths[0][1].fee_msat, 100);
2732 assert_eq!(route.paths[0][1].cltv_expiry_delta, (3 << 4) | 2);
2733 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2734 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2736 assert_eq!(route.paths[0][2].pubkey, nodes[0]);
2737 assert_eq!(route.paths[0][2].short_channel_id, 3);
2738 assert_eq!(route.paths[0][2].fee_msat, 100);
2739 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
2740 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(1));
2741 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(3));
2743 // If we specify a channel to node7, that overrides our local channel view and that gets used
2744 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2745 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2746 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();
2747 assert_eq!(route.paths[0].len(), 2);
2749 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2750 assert_eq!(route.paths[0][0].short_channel_id, 42);
2751 assert_eq!(route.paths[0][0].fee_msat, 200);
2752 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2753 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2754 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2756 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2757 assert_eq!(route.paths[0][1].short_channel_id, 13);
2758 assert_eq!(route.paths[0][1].fee_msat, 100);
2759 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2760 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2761 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2764 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2765 let zero_fees = RoutingFees {
2767 proportional_millionths: 0,
2769 vec![RouteHint(vec![RouteHintHop {
2770 src_node_id: nodes[3],
2771 short_channel_id: 8,
2773 cltv_expiry_delta: (8 << 4) | 1,
2774 htlc_minimum_msat: None,
2775 htlc_maximum_msat: None,
2777 ]), RouteHint(vec![RouteHintHop {
2778 src_node_id: nodes[4],
2779 short_channel_id: 9,
2782 proportional_millionths: 0,
2784 cltv_expiry_delta: (9 << 4) | 1,
2785 htlc_minimum_msat: None,
2786 htlc_maximum_msat: None,
2787 }]), RouteHint(vec![RouteHintHop {
2788 src_node_id: nodes[5],
2789 short_channel_id: 10,
2791 cltv_expiry_delta: (10 << 4) | 1,
2792 htlc_minimum_msat: None,
2793 htlc_maximum_msat: None,
2797 fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2798 let zero_fees = RoutingFees {
2800 proportional_millionths: 0,
2802 vec![RouteHint(vec![RouteHintHop {
2803 src_node_id: nodes[2],
2804 short_channel_id: 5,
2807 proportional_millionths: 0,
2809 cltv_expiry_delta: (5 << 4) | 1,
2810 htlc_minimum_msat: None,
2811 htlc_maximum_msat: None,
2813 src_node_id: nodes[3],
2814 short_channel_id: 8,
2816 cltv_expiry_delta: (8 << 4) | 1,
2817 htlc_minimum_msat: None,
2818 htlc_maximum_msat: None,
2820 ]), RouteHint(vec![RouteHintHop {
2821 src_node_id: nodes[4],
2822 short_channel_id: 9,
2825 proportional_millionths: 0,
2827 cltv_expiry_delta: (9 << 4) | 1,
2828 htlc_minimum_msat: None,
2829 htlc_maximum_msat: None,
2830 }]), RouteHint(vec![RouteHintHop {
2831 src_node_id: nodes[5],
2832 short_channel_id: 10,
2834 cltv_expiry_delta: (10 << 4) | 1,
2835 htlc_minimum_msat: None,
2836 htlc_maximum_msat: None,
2841 fn partial_route_hint_test() {
2842 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2843 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2844 let scorer = test_utils::TestScorer::with_penalty(0);
2845 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2846 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2848 // Simple test across 2, 3, 5, and 4 via a last_hop channel
2849 // Tests the behaviour when the RouteHint contains a suboptimal hop.
2850 // RouteHint may be partially used by the algo to build the best path.
2852 // First check that last hop can't have its source as the payee.
2853 let invalid_last_hop = RouteHint(vec![RouteHintHop {
2854 src_node_id: nodes[6],
2855 short_channel_id: 8,
2858 proportional_millionths: 0,
2860 cltv_expiry_delta: (8 << 4) | 1,
2861 htlc_minimum_msat: None,
2862 htlc_maximum_msat: None,
2865 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
2866 invalid_last_hops.push(invalid_last_hop);
2868 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(invalid_last_hops);
2869 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) {
2870 assert_eq!(err, "Route hint cannot have the payee as the source.");
2871 } else { panic!(); }
2874 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops_multi_private_channels(&nodes));
2875 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2876 assert_eq!(route.paths[0].len(), 5);
2878 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2879 assert_eq!(route.paths[0][0].short_channel_id, 2);
2880 assert_eq!(route.paths[0][0].fee_msat, 100);
2881 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2882 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2883 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2885 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2886 assert_eq!(route.paths[0][1].short_channel_id, 4);
2887 assert_eq!(route.paths[0][1].fee_msat, 0);
2888 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
2889 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2890 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2892 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2893 assert_eq!(route.paths[0][2].short_channel_id, 6);
2894 assert_eq!(route.paths[0][2].fee_msat, 0);
2895 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
2896 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2897 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2899 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2900 assert_eq!(route.paths[0][3].short_channel_id, 11);
2901 assert_eq!(route.paths[0][3].fee_msat, 0);
2902 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
2903 // If we have a peer in the node map, we'll use their features here since we don't have
2904 // a way of figuring out their features from the invoice:
2905 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2906 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2908 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2909 assert_eq!(route.paths[0][4].short_channel_id, 8);
2910 assert_eq!(route.paths[0][4].fee_msat, 100);
2911 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2912 assert_eq!(route.paths[0][4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
2913 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2916 fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2917 let zero_fees = RoutingFees {
2919 proportional_millionths: 0,
2921 vec![RouteHint(vec![RouteHintHop {
2922 src_node_id: nodes[3],
2923 short_channel_id: 8,
2925 cltv_expiry_delta: (8 << 4) | 1,
2926 htlc_minimum_msat: None,
2927 htlc_maximum_msat: None,
2928 }]), RouteHint(vec![
2930 ]), RouteHint(vec![RouteHintHop {
2931 src_node_id: nodes[5],
2932 short_channel_id: 10,
2934 cltv_expiry_delta: (10 << 4) | 1,
2935 htlc_minimum_msat: None,
2936 htlc_maximum_msat: None,
2941 fn ignores_empty_last_hops_test() {
2942 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2943 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2944 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(empty_last_hop(&nodes));
2945 let scorer = test_utils::TestScorer::with_penalty(0);
2946 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2947 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2949 // Test handling of an empty RouteHint passed in Invoice.
2951 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2952 assert_eq!(route.paths[0].len(), 5);
2954 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2955 assert_eq!(route.paths[0][0].short_channel_id, 2);
2956 assert_eq!(route.paths[0][0].fee_msat, 100);
2957 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2958 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2959 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2961 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2962 assert_eq!(route.paths[0][1].short_channel_id, 4);
2963 assert_eq!(route.paths[0][1].fee_msat, 0);
2964 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
2965 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2966 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2968 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2969 assert_eq!(route.paths[0][2].short_channel_id, 6);
2970 assert_eq!(route.paths[0][2].fee_msat, 0);
2971 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
2972 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2973 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2975 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2976 assert_eq!(route.paths[0][3].short_channel_id, 11);
2977 assert_eq!(route.paths[0][3].fee_msat, 0);
2978 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
2979 // If we have a peer in the node map, we'll use their features here since we don't have
2980 // a way of figuring out their features from the invoice:
2981 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2982 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2984 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2985 assert_eq!(route.paths[0][4].short_channel_id, 8);
2986 assert_eq!(route.paths[0][4].fee_msat, 100);
2987 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2988 assert_eq!(route.paths[0][4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
2989 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2992 /// Builds a trivial last-hop hint that passes through the two nodes given, with channel 0xff00
2994 fn multi_hop_last_hops_hint(hint_hops: [PublicKey; 2]) -> Vec<RouteHint> {
2995 let zero_fees = RoutingFees {
2997 proportional_millionths: 0,
2999 vec![RouteHint(vec![RouteHintHop {
3000 src_node_id: hint_hops[0],
3001 short_channel_id: 0xff00,
3004 proportional_millionths: 0,
3006 cltv_expiry_delta: (5 << 4) | 1,
3007 htlc_minimum_msat: None,
3008 htlc_maximum_msat: None,
3010 src_node_id: hint_hops[1],
3011 short_channel_id: 0xff01,
3013 cltv_expiry_delta: (8 << 4) | 1,
3014 htlc_minimum_msat: None,
3015 htlc_maximum_msat: None,
3020 fn multi_hint_last_hops_test() {
3021 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3022 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3023 let last_hops = multi_hop_last_hops_hint([nodes[2], nodes[3]]);
3024 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops.clone());
3025 let scorer = test_utils::TestScorer::with_penalty(0);
3026 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3027 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3028 // Test through channels 2, 3, 0xff00, 0xff01.
3029 // Test shows that multiple hop hints are considered.
3031 // Disabling channels 6 & 7 by flags=2
3032 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3033 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3034 short_channel_id: 6,
3036 flags: 2, // to disable
3037 cltv_expiry_delta: 0,
3038 htlc_minimum_msat: 0,
3039 htlc_maximum_msat: OptionalField::Absent,
3041 fee_proportional_millionths: 0,
3042 excess_data: Vec::new()
3044 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3045 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3046 short_channel_id: 7,
3048 flags: 2, // to disable
3049 cltv_expiry_delta: 0,
3050 htlc_minimum_msat: 0,
3051 htlc_maximum_msat: OptionalField::Absent,
3053 fee_proportional_millionths: 0,
3054 excess_data: Vec::new()
3057 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3058 assert_eq!(route.paths[0].len(), 4);
3060 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3061 assert_eq!(route.paths[0][0].short_channel_id, 2);
3062 assert_eq!(route.paths[0][0].fee_msat, 200);
3063 assert_eq!(route.paths[0][0].cltv_expiry_delta, 65);
3064 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3065 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3067 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3068 assert_eq!(route.paths[0][1].short_channel_id, 4);
3069 assert_eq!(route.paths[0][1].fee_msat, 100);
3070 assert_eq!(route.paths[0][1].cltv_expiry_delta, 81);
3071 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3072 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3074 assert_eq!(route.paths[0][2].pubkey, nodes[3]);
3075 assert_eq!(route.paths[0][2].short_channel_id, last_hops[0].0[0].short_channel_id);
3076 assert_eq!(route.paths[0][2].fee_msat, 0);
3077 assert_eq!(route.paths[0][2].cltv_expiry_delta, 129);
3078 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(4));
3079 assert_eq!(route.paths[0][2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3081 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
3082 assert_eq!(route.paths[0][3].short_channel_id, last_hops[0].0[1].short_channel_id);
3083 assert_eq!(route.paths[0][3].fee_msat, 100);
3084 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
3085 assert_eq!(route.paths[0][3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3086 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3090 fn private_multi_hint_last_hops_test() {
3091 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3092 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3094 let non_announced_privkey = SecretKey::from_slice(&hex::decode(format!("{:02x}", 0xf0).repeat(32)).unwrap()[..]).unwrap();
3095 let non_announced_pubkey = PublicKey::from_secret_key(&secp_ctx, &non_announced_privkey);
3097 let last_hops = multi_hop_last_hops_hint([nodes[2], non_announced_pubkey]);
3098 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops.clone());
3099 let scorer = test_utils::TestScorer::with_penalty(0);
3100 // Test through channels 2, 3, 0xff00, 0xff01.
3101 // Test shows that multiple hop hints are considered.
3103 // Disabling channels 6 & 7 by flags=2
3104 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3105 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3106 short_channel_id: 6,
3108 flags: 2, // to disable
3109 cltv_expiry_delta: 0,
3110 htlc_minimum_msat: 0,
3111 htlc_maximum_msat: OptionalField::Absent,
3113 fee_proportional_millionths: 0,
3114 excess_data: Vec::new()
3116 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3117 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3118 short_channel_id: 7,
3120 flags: 2, // to disable
3121 cltv_expiry_delta: 0,
3122 htlc_minimum_msat: 0,
3123 htlc_maximum_msat: OptionalField::Absent,
3125 fee_proportional_millionths: 0,
3126 excess_data: Vec::new()
3129 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &[42u8; 32]).unwrap();
3130 assert_eq!(route.paths[0].len(), 4);
3132 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3133 assert_eq!(route.paths[0][0].short_channel_id, 2);
3134 assert_eq!(route.paths[0][0].fee_msat, 200);
3135 assert_eq!(route.paths[0][0].cltv_expiry_delta, 65);
3136 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3137 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3139 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3140 assert_eq!(route.paths[0][1].short_channel_id, 4);
3141 assert_eq!(route.paths[0][1].fee_msat, 100);
3142 assert_eq!(route.paths[0][1].cltv_expiry_delta, 81);
3143 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3144 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3146 assert_eq!(route.paths[0][2].pubkey, non_announced_pubkey);
3147 assert_eq!(route.paths[0][2].short_channel_id, last_hops[0].0[0].short_channel_id);
3148 assert_eq!(route.paths[0][2].fee_msat, 0);
3149 assert_eq!(route.paths[0][2].cltv_expiry_delta, 129);
3150 assert_eq!(route.paths[0][2].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3151 assert_eq!(route.paths[0][2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3153 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
3154 assert_eq!(route.paths[0][3].short_channel_id, last_hops[0].0[1].short_channel_id);
3155 assert_eq!(route.paths[0][3].fee_msat, 100);
3156 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
3157 assert_eq!(route.paths[0][3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3158 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3161 fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3162 let zero_fees = RoutingFees {
3164 proportional_millionths: 0,
3166 vec![RouteHint(vec![RouteHintHop {
3167 src_node_id: nodes[4],
3168 short_channel_id: 11,
3170 cltv_expiry_delta: (11 << 4) | 1,
3171 htlc_minimum_msat: None,
3172 htlc_maximum_msat: None,
3174 src_node_id: nodes[3],
3175 short_channel_id: 8,
3177 cltv_expiry_delta: (8 << 4) | 1,
3178 htlc_minimum_msat: None,
3179 htlc_maximum_msat: None,
3180 }]), RouteHint(vec![RouteHintHop {
3181 src_node_id: nodes[4],
3182 short_channel_id: 9,
3185 proportional_millionths: 0,
3187 cltv_expiry_delta: (9 << 4) | 1,
3188 htlc_minimum_msat: None,
3189 htlc_maximum_msat: None,
3190 }]), RouteHint(vec![RouteHintHop {
3191 src_node_id: nodes[5],
3192 short_channel_id: 10,
3194 cltv_expiry_delta: (10 << 4) | 1,
3195 htlc_minimum_msat: None,
3196 htlc_maximum_msat: None,
3201 fn last_hops_with_public_channel_test() {
3202 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3203 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3204 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops_with_public_channel(&nodes));
3205 let scorer = test_utils::TestScorer::with_penalty(0);
3206 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3207 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3208 // This test shows that public routes can be present in the invoice
3209 // which would be handled in the same manner.
3211 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3212 assert_eq!(route.paths[0].len(), 5);
3214 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3215 assert_eq!(route.paths[0][0].short_channel_id, 2);
3216 assert_eq!(route.paths[0][0].fee_msat, 100);
3217 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
3218 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3219 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3221 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3222 assert_eq!(route.paths[0][1].short_channel_id, 4);
3223 assert_eq!(route.paths[0][1].fee_msat, 0);
3224 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
3225 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3226 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3228 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
3229 assert_eq!(route.paths[0][2].short_channel_id, 6);
3230 assert_eq!(route.paths[0][2].fee_msat, 0);
3231 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
3232 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
3233 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
3235 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
3236 assert_eq!(route.paths[0][3].short_channel_id, 11);
3237 assert_eq!(route.paths[0][3].fee_msat, 0);
3238 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
3239 // If we have a peer in the node map, we'll use their features here since we don't have
3240 // a way of figuring out their features from the invoice:
3241 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
3242 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
3244 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
3245 assert_eq!(route.paths[0][4].short_channel_id, 8);
3246 assert_eq!(route.paths[0][4].fee_msat, 100);
3247 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
3248 assert_eq!(route.paths[0][4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3249 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3253 fn our_chans_last_hop_connect_test() {
3254 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3255 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3256 let scorer = test_utils::TestScorer::with_penalty(0);
3257 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3258 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3260 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
3261 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3262 let mut last_hops = last_hops(&nodes);
3263 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops.clone());
3264 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();
3265 assert_eq!(route.paths[0].len(), 2);
3267 assert_eq!(route.paths[0][0].pubkey, nodes[3]);
3268 assert_eq!(route.paths[0][0].short_channel_id, 42);
3269 assert_eq!(route.paths[0][0].fee_msat, 0);
3270 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 4) | 1);
3271 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
3272 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3274 assert_eq!(route.paths[0][1].pubkey, nodes[6]);
3275 assert_eq!(route.paths[0][1].short_channel_id, 8);
3276 assert_eq!(route.paths[0][1].fee_msat, 100);
3277 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
3278 assert_eq!(route.paths[0][1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3279 assert_eq!(route.paths[0][1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3281 last_hops[0].0[0].fees.base_msat = 1000;
3283 // Revert to via 6 as the fee on 8 goes up
3284 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops);
3285 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3286 assert_eq!(route.paths[0].len(), 4);
3288 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3289 assert_eq!(route.paths[0][0].short_channel_id, 2);
3290 assert_eq!(route.paths[0][0].fee_msat, 200); // fee increased as its % of value transferred across node
3291 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
3292 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3293 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3295 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3296 assert_eq!(route.paths[0][1].short_channel_id, 4);
3297 assert_eq!(route.paths[0][1].fee_msat, 100);
3298 assert_eq!(route.paths[0][1].cltv_expiry_delta, (7 << 4) | 1);
3299 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3300 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3302 assert_eq!(route.paths[0][2].pubkey, nodes[5]);
3303 assert_eq!(route.paths[0][2].short_channel_id, 7);
3304 assert_eq!(route.paths[0][2].fee_msat, 0);
3305 assert_eq!(route.paths[0][2].cltv_expiry_delta, (10 << 4) | 1);
3306 // If we have a peer in the node map, we'll use their features here since we don't have
3307 // a way of figuring out their features from the invoice:
3308 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
3309 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(7));
3311 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
3312 assert_eq!(route.paths[0][3].short_channel_id, 10);
3313 assert_eq!(route.paths[0][3].fee_msat, 100);
3314 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
3315 assert_eq!(route.paths[0][3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3316 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3318 // ...but still use 8 for larger payments as 6 has a variable feerate
3319 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 2000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3320 assert_eq!(route.paths[0].len(), 5);
3322 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3323 assert_eq!(route.paths[0][0].short_channel_id, 2);
3324 assert_eq!(route.paths[0][0].fee_msat, 3000);
3325 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
3326 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3327 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3329 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3330 assert_eq!(route.paths[0][1].short_channel_id, 4);
3331 assert_eq!(route.paths[0][1].fee_msat, 0);
3332 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
3333 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3334 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3336 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
3337 assert_eq!(route.paths[0][2].short_channel_id, 6);
3338 assert_eq!(route.paths[0][2].fee_msat, 0);
3339 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
3340 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
3341 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
3343 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
3344 assert_eq!(route.paths[0][3].short_channel_id, 11);
3345 assert_eq!(route.paths[0][3].fee_msat, 1000);
3346 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
3347 // If we have a peer in the node map, we'll use their features here since we don't have
3348 // a way of figuring out their features from the invoice:
3349 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
3350 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
3352 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
3353 assert_eq!(route.paths[0][4].short_channel_id, 8);
3354 assert_eq!(route.paths[0][4].fee_msat, 2000);
3355 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
3356 assert_eq!(route.paths[0][4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3357 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3360 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> {
3361 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
3362 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3363 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3365 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
3366 let last_hops = RouteHint(vec![RouteHintHop {
3367 src_node_id: middle_node_id,
3368 short_channel_id: 8,
3371 proportional_millionths: last_hop_fee_prop,
3373 cltv_expiry_delta: (8 << 4) | 1,
3374 htlc_minimum_msat: None,
3375 htlc_maximum_msat: last_hop_htlc_max,
3377 let payment_params = PaymentParameters::from_node_id(target_node_id).with_route_hints(vec![last_hops]);
3378 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
3379 let scorer = test_utils::TestScorer::with_penalty(0);
3380 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3381 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3382 get_route(&source_node_id, &payment_params, &NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash()).read_only(),
3383 Some(&our_chans.iter().collect::<Vec<_>>()), route_val, 42, &test_utils::TestLogger::new(), &scorer, &random_seed_bytes)
3387 fn unannounced_path_test() {
3388 // We should be able to send a payment to a destination without any help of a routing graph
3389 // if we have a channel with a common counterparty that appears in the first and last hop
3391 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
3393 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3394 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3395 assert_eq!(route.paths[0].len(), 2);
3397 assert_eq!(route.paths[0][0].pubkey, middle_node_id);
3398 assert_eq!(route.paths[0][0].short_channel_id, 42);
3399 assert_eq!(route.paths[0][0].fee_msat, 1001);
3400 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 4) | 1);
3401 assert_eq!(route.paths[0][0].node_features.le_flags(), &[0b11]);
3402 assert_eq!(route.paths[0][0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3404 assert_eq!(route.paths[0][1].pubkey, target_node_id);
3405 assert_eq!(route.paths[0][1].short_channel_id, 8);
3406 assert_eq!(route.paths[0][1].fee_msat, 1000000);
3407 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
3408 assert_eq!(route.paths[0][1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3409 assert_eq!(route.paths[0][1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3413 fn overflow_unannounced_path_test_liquidity_underflow() {
3414 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
3415 // the last-hop had a fee which overflowed a u64, we'd panic.
3416 // This was due to us adding the first-hop from us unconditionally, causing us to think
3417 // we'd built a path (as our node is in the "best candidate" set), when we had not.
3418 // In this test, we previously hit a subtraction underflow due to having less available
3419 // liquidity at the last hop than 0.
3420 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());
3424 fn overflow_unannounced_path_test_feerate_overflow() {
3425 // This tests for the same case as above, except instead of hitting a subtraction
3426 // underflow, we hit a case where the fee charged at a hop overflowed.
3427 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());
3431 fn available_amount_while_routing_test() {
3432 // Tests whether we choose the correct available channel amount while routing.
3434 let (secp_ctx, network_graph, mut net_graph_msg_handler, chain_monitor, logger) = build_graph();
3435 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3436 let scorer = test_utils::TestScorer::with_penalty(0);
3437 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3438 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3439 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
3441 // We will use a simple single-path route from
3442 // our node to node2 via node0: channels {1, 3}.
3444 // First disable all other paths.
3445 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3446 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3447 short_channel_id: 2,
3450 cltv_expiry_delta: 0,
3451 htlc_minimum_msat: 0,
3452 htlc_maximum_msat: OptionalField::Present(100_000),
3454 fee_proportional_millionths: 0,
3455 excess_data: Vec::new()
3457 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3458 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3459 short_channel_id: 12,
3462 cltv_expiry_delta: 0,
3463 htlc_minimum_msat: 0,
3464 htlc_maximum_msat: OptionalField::Present(100_000),
3466 fee_proportional_millionths: 0,
3467 excess_data: Vec::new()
3470 // Make the first channel (#1) very permissive,
3471 // and we will be testing all limits on the second channel.
3472 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3473 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3474 short_channel_id: 1,
3477 cltv_expiry_delta: 0,
3478 htlc_minimum_msat: 0,
3479 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3481 fee_proportional_millionths: 0,
3482 excess_data: Vec::new()
3485 // First, let's see if routing works if we have absolutely no idea about the available amount.
3486 // In this case, it should be set to 250_000 sats.
3487 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3488 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3489 short_channel_id: 3,
3492 cltv_expiry_delta: 0,
3493 htlc_minimum_msat: 0,
3494 htlc_maximum_msat: OptionalField::Absent,
3496 fee_proportional_millionths: 0,
3497 excess_data: Vec::new()
3501 // Attempt to route more than available results in a failure.
3502 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3503 &our_id, &payment_params, &network_graph.read_only(), None, 250_000_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3504 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3505 } else { panic!(); }
3509 // Now, attempt to route an exact amount we have should be fine.
3510 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();
3511 assert_eq!(route.paths.len(), 1);
3512 let path = route.paths.last().unwrap();
3513 assert_eq!(path.len(), 2);
3514 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3515 assert_eq!(path.last().unwrap().fee_msat, 250_000_000);
3518 // Check that setting next_outbound_htlc_limit_msat in first_hops limits the channels.
3519 // Disable channel #1 and use another first hop.
3520 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3521 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3522 short_channel_id: 1,
3525 cltv_expiry_delta: 0,
3526 htlc_minimum_msat: 0,
3527 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3529 fee_proportional_millionths: 0,
3530 excess_data: Vec::new()
3533 // Now, limit the first_hop by the next_outbound_htlc_limit_msat of 200_000 sats.
3534 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
3537 // Attempt to route more than available results in a failure.
3538 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3539 &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) {
3540 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3541 } else { panic!(); }
3545 // Now, attempt to route an exact amount we have should be fine.
3546 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();
3547 assert_eq!(route.paths.len(), 1);
3548 let path = route.paths.last().unwrap();
3549 assert_eq!(path.len(), 2);
3550 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3551 assert_eq!(path.last().unwrap().fee_msat, 200_000_000);
3554 // Enable channel #1 back.
3555 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3556 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3557 short_channel_id: 1,
3560 cltv_expiry_delta: 0,
3561 htlc_minimum_msat: 0,
3562 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3564 fee_proportional_millionths: 0,
3565 excess_data: Vec::new()
3569 // Now let's see if routing works if we know only htlc_maximum_msat.
3570 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3571 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3572 short_channel_id: 3,
3575 cltv_expiry_delta: 0,
3576 htlc_minimum_msat: 0,
3577 htlc_maximum_msat: OptionalField::Present(15_000),
3579 fee_proportional_millionths: 0,
3580 excess_data: Vec::new()
3584 // Attempt to route more than available results in a failure.
3585 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3586 &our_id, &payment_params, &network_graph.read_only(), None, 15_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3587 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3588 } else { panic!(); }
3592 // Now, attempt to route an exact amount we have should be fine.
3593 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 15_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3594 assert_eq!(route.paths.len(), 1);
3595 let path = route.paths.last().unwrap();
3596 assert_eq!(path.len(), 2);
3597 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3598 assert_eq!(path.last().unwrap().fee_msat, 15_000);
3601 // Now let's see if routing works if we know only capacity from the UTXO.
3603 // We can't change UTXO capacity on the fly, so we'll disable
3604 // the existing channel and add another one with the capacity we need.
3605 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3606 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3607 short_channel_id: 3,
3610 cltv_expiry_delta: 0,
3611 htlc_minimum_msat: 0,
3612 htlc_maximum_msat: OptionalField::Absent,
3614 fee_proportional_millionths: 0,
3615 excess_data: Vec::new()
3618 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
3619 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
3620 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
3621 .push_opcode(opcodes::all::OP_PUSHNUM_2)
3622 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
3624 *chain_monitor.utxo_ret.lock().unwrap() = Ok(TxOut { value: 15, script_pubkey: good_script.clone() });
3625 net_graph_msg_handler.add_chain_access(Some(chain_monitor));
3627 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
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: 333,
3633 cltv_expiry_delta: (3 << 4) | 1,
3634 htlc_minimum_msat: 0,
3635 htlc_maximum_msat: OptionalField::Absent,
3637 fee_proportional_millionths: 0,
3638 excess_data: Vec::new()
3640 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3641 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3642 short_channel_id: 333,
3645 cltv_expiry_delta: (3 << 4) | 2,
3646 htlc_minimum_msat: 0,
3647 htlc_maximum_msat: OptionalField::Absent,
3649 fee_proportional_millionths: 0,
3650 excess_data: Vec::new()
3654 // Attempt to route more than available results in a failure.
3655 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3656 &our_id, &payment_params, &network_graph.read_only(), None, 15_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3657 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3658 } else { panic!(); }
3662 // Now, attempt to route an exact amount we have should be fine.
3663 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 15_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3664 assert_eq!(route.paths.len(), 1);
3665 let path = route.paths.last().unwrap();
3666 assert_eq!(path.len(), 2);
3667 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3668 assert_eq!(path.last().unwrap().fee_msat, 15_000);
3671 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
3672 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3673 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3674 short_channel_id: 333,
3677 cltv_expiry_delta: 0,
3678 htlc_minimum_msat: 0,
3679 htlc_maximum_msat: OptionalField::Present(10_000),
3681 fee_proportional_millionths: 0,
3682 excess_data: Vec::new()
3686 // Attempt to route more than available results in a failure.
3687 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3688 &our_id, &payment_params, &network_graph.read_only(), None, 10_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3689 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3690 } else { panic!(); }
3694 // Now, attempt to route an exact amount we have should be fine.
3695 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 10_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3696 assert_eq!(route.paths.len(), 1);
3697 let path = route.paths.last().unwrap();
3698 assert_eq!(path.len(), 2);
3699 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3700 assert_eq!(path.last().unwrap().fee_msat, 10_000);
3705 fn available_liquidity_last_hop_test() {
3706 // Check that available liquidity properly limits the path even when only
3707 // one of the latter hops is limited.
3708 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3709 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3710 let scorer = test_utils::TestScorer::with_penalty(0);
3711 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3712 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3713 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
3715 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3716 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
3717 // Total capacity: 50 sats.
3719 // Disable other potential paths.
3720 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3721 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3722 short_channel_id: 2,
3725 cltv_expiry_delta: 0,
3726 htlc_minimum_msat: 0,
3727 htlc_maximum_msat: OptionalField::Present(100_000),
3729 fee_proportional_millionths: 0,
3730 excess_data: Vec::new()
3732 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3733 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3734 short_channel_id: 7,
3737 cltv_expiry_delta: 0,
3738 htlc_minimum_msat: 0,
3739 htlc_maximum_msat: OptionalField::Present(100_000),
3741 fee_proportional_millionths: 0,
3742 excess_data: Vec::new()
3747 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3748 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3749 short_channel_id: 12,
3752 cltv_expiry_delta: 0,
3753 htlc_minimum_msat: 0,
3754 htlc_maximum_msat: OptionalField::Present(100_000),
3756 fee_proportional_millionths: 0,
3757 excess_data: Vec::new()
3759 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3760 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3761 short_channel_id: 13,
3764 cltv_expiry_delta: 0,
3765 htlc_minimum_msat: 0,
3766 htlc_maximum_msat: OptionalField::Present(100_000),
3768 fee_proportional_millionths: 0,
3769 excess_data: Vec::new()
3772 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3773 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3774 short_channel_id: 6,
3777 cltv_expiry_delta: 0,
3778 htlc_minimum_msat: 0,
3779 htlc_maximum_msat: OptionalField::Present(50_000),
3781 fee_proportional_millionths: 0,
3782 excess_data: Vec::new()
3784 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3785 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3786 short_channel_id: 11,
3789 cltv_expiry_delta: 0,
3790 htlc_minimum_msat: 0,
3791 htlc_maximum_msat: OptionalField::Present(100_000),
3793 fee_proportional_millionths: 0,
3794 excess_data: Vec::new()
3797 // Attempt to route more than available results in a failure.
3798 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3799 &our_id, &payment_params, &network_graph.read_only(), None, 60_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3800 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3801 } else { panic!(); }
3805 // Now, attempt to route 49 sats (just a bit below the capacity).
3806 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 49_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3807 assert_eq!(route.paths.len(), 1);
3808 let mut total_amount_paid_msat = 0;
3809 for path in &route.paths {
3810 assert_eq!(path.len(), 4);
3811 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3812 total_amount_paid_msat += path.last().unwrap().fee_msat;
3814 assert_eq!(total_amount_paid_msat, 49_000);
3818 // Attempt to route an exact amount is also fine
3819 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3820 assert_eq!(route.paths.len(), 1);
3821 let mut total_amount_paid_msat = 0;
3822 for path in &route.paths {
3823 assert_eq!(path.len(), 4);
3824 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3825 total_amount_paid_msat += path.last().unwrap().fee_msat;
3827 assert_eq!(total_amount_paid_msat, 50_000);
3832 fn ignore_fee_first_hop_test() {
3833 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3834 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3835 let scorer = test_utils::TestScorer::with_penalty(0);
3836 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3837 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3838 let payment_params = PaymentParameters::from_node_id(nodes[2]);
3840 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3841 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3842 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3843 short_channel_id: 1,
3846 cltv_expiry_delta: 0,
3847 htlc_minimum_msat: 0,
3848 htlc_maximum_msat: OptionalField::Present(100_000),
3849 fee_base_msat: 1_000_000,
3850 fee_proportional_millionths: 0,
3851 excess_data: Vec::new()
3853 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3854 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3855 short_channel_id: 3,
3858 cltv_expiry_delta: 0,
3859 htlc_minimum_msat: 0,
3860 htlc_maximum_msat: OptionalField::Present(50_000),
3862 fee_proportional_millionths: 0,
3863 excess_data: Vec::new()
3867 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3868 assert_eq!(route.paths.len(), 1);
3869 let mut total_amount_paid_msat = 0;
3870 for path in &route.paths {
3871 assert_eq!(path.len(), 2);
3872 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3873 total_amount_paid_msat += path.last().unwrap().fee_msat;
3875 assert_eq!(total_amount_paid_msat, 50_000);
3880 fn simple_mpp_route_test() {
3881 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3882 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3883 let scorer = test_utils::TestScorer::with_penalty(0);
3884 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3885 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3886 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
3888 // We need a route consisting of 3 paths:
3889 // From our node to node2 via node0, node7, node1 (three paths one hop each).
3890 // To achieve this, the amount being transferred should be around
3891 // the total capacity of these 3 paths.
3893 // First, we set limits on these (previously unlimited) channels.
3894 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
3896 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3897 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3898 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3899 short_channel_id: 1,
3902 cltv_expiry_delta: 0,
3903 htlc_minimum_msat: 0,
3904 htlc_maximum_msat: OptionalField::Present(100_000),
3906 fee_proportional_millionths: 0,
3907 excess_data: Vec::new()
3909 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3910 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3911 short_channel_id: 3,
3914 cltv_expiry_delta: 0,
3915 htlc_minimum_msat: 0,
3916 htlc_maximum_msat: OptionalField::Present(50_000),
3918 fee_proportional_millionths: 0,
3919 excess_data: Vec::new()
3922 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
3923 // (total limit 60).
3924 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3925 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3926 short_channel_id: 12,
3929 cltv_expiry_delta: 0,
3930 htlc_minimum_msat: 0,
3931 htlc_maximum_msat: OptionalField::Present(60_000),
3933 fee_proportional_millionths: 0,
3934 excess_data: Vec::new()
3936 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3937 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3938 short_channel_id: 13,
3941 cltv_expiry_delta: 0,
3942 htlc_minimum_msat: 0,
3943 htlc_maximum_msat: OptionalField::Present(60_000),
3945 fee_proportional_millionths: 0,
3946 excess_data: Vec::new()
3949 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
3950 // (total capacity 180 sats).
3951 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3952 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3953 short_channel_id: 2,
3956 cltv_expiry_delta: 0,
3957 htlc_minimum_msat: 0,
3958 htlc_maximum_msat: OptionalField::Present(200_000),
3960 fee_proportional_millionths: 0,
3961 excess_data: Vec::new()
3963 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3964 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3965 short_channel_id: 4,
3968 cltv_expiry_delta: 0,
3969 htlc_minimum_msat: 0,
3970 htlc_maximum_msat: OptionalField::Present(180_000),
3972 fee_proportional_millionths: 0,
3973 excess_data: Vec::new()
3977 // Attempt to route more than available results in a failure.
3978 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3979 &our_id, &payment_params, &network_graph.read_only(), None, 300_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3980 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3981 } else { panic!(); }
3985 // Now, attempt to route 250 sats (just a bit below the capacity).
3986 // Our algorithm should provide us with these 3 paths.
3987 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 250_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3988 assert_eq!(route.paths.len(), 3);
3989 let mut total_amount_paid_msat = 0;
3990 for path in &route.paths {
3991 assert_eq!(path.len(), 2);
3992 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3993 total_amount_paid_msat += path.last().unwrap().fee_msat;
3995 assert_eq!(total_amount_paid_msat, 250_000);
3999 // Attempt to route an exact amount is also fine
4000 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 290_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4001 assert_eq!(route.paths.len(), 3);
4002 let mut total_amount_paid_msat = 0;
4003 for path in &route.paths {
4004 assert_eq!(path.len(), 2);
4005 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4006 total_amount_paid_msat += path.last().unwrap().fee_msat;
4008 assert_eq!(total_amount_paid_msat, 290_000);
4013 fn long_mpp_route_test() {
4014 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4015 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4016 let scorer = test_utils::TestScorer::with_penalty(0);
4017 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4018 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4019 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
4021 // We need a route consisting of 3 paths:
4022 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
4023 // Note that these paths overlap (channels 5, 12, 13).
4024 // We will route 300 sats.
4025 // Each path will have 100 sats capacity, those channels which
4026 // are used twice will have 200 sats capacity.
4028 // Disable other potential paths.
4029 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4030 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4031 short_channel_id: 2,
4034 cltv_expiry_delta: 0,
4035 htlc_minimum_msat: 0,
4036 htlc_maximum_msat: OptionalField::Present(100_000),
4038 fee_proportional_millionths: 0,
4039 excess_data: Vec::new()
4041 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4042 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4043 short_channel_id: 7,
4046 cltv_expiry_delta: 0,
4047 htlc_minimum_msat: 0,
4048 htlc_maximum_msat: OptionalField::Present(100_000),
4050 fee_proportional_millionths: 0,
4051 excess_data: Vec::new()
4054 // Path via {node0, node2} is channels {1, 3, 5}.
4055 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4056 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4057 short_channel_id: 1,
4060 cltv_expiry_delta: 0,
4061 htlc_minimum_msat: 0,
4062 htlc_maximum_msat: OptionalField::Present(100_000),
4064 fee_proportional_millionths: 0,
4065 excess_data: Vec::new()
4067 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4068 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4069 short_channel_id: 3,
4072 cltv_expiry_delta: 0,
4073 htlc_minimum_msat: 0,
4074 htlc_maximum_msat: OptionalField::Present(100_000),
4076 fee_proportional_millionths: 0,
4077 excess_data: Vec::new()
4080 // Capacity of 200 sats because this channel will be used by 3rd path as well.
4081 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4082 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4083 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4084 short_channel_id: 5,
4087 cltv_expiry_delta: 0,
4088 htlc_minimum_msat: 0,
4089 htlc_maximum_msat: OptionalField::Present(200_000),
4091 fee_proportional_millionths: 0,
4092 excess_data: Vec::new()
4095 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4096 // Add 100 sats to the capacities of {12, 13}, because these channels
4097 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
4098 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4099 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4100 short_channel_id: 12,
4103 cltv_expiry_delta: 0,
4104 htlc_minimum_msat: 0,
4105 htlc_maximum_msat: OptionalField::Present(200_000),
4107 fee_proportional_millionths: 0,
4108 excess_data: Vec::new()
4110 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4111 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4112 short_channel_id: 13,
4115 cltv_expiry_delta: 0,
4116 htlc_minimum_msat: 0,
4117 htlc_maximum_msat: OptionalField::Present(200_000),
4119 fee_proportional_millionths: 0,
4120 excess_data: Vec::new()
4123 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4124 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4125 short_channel_id: 6,
4128 cltv_expiry_delta: 0,
4129 htlc_minimum_msat: 0,
4130 htlc_maximum_msat: OptionalField::Present(100_000),
4132 fee_proportional_millionths: 0,
4133 excess_data: Vec::new()
4135 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4136 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4137 short_channel_id: 11,
4140 cltv_expiry_delta: 0,
4141 htlc_minimum_msat: 0,
4142 htlc_maximum_msat: OptionalField::Present(100_000),
4144 fee_proportional_millionths: 0,
4145 excess_data: Vec::new()
4148 // Path via {node7, node2} is channels {12, 13, 5}.
4149 // We already limited them to 200 sats (they are used twice for 100 sats).
4150 // Nothing to do here.
4153 // Attempt to route more than available results in a failure.
4154 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4155 &our_id, &payment_params, &network_graph.read_only(), None, 350_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
4156 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4157 } else { panic!(); }
4161 // Now, attempt to route 300 sats (exact amount we can route).
4162 // Our algorithm should provide us with these 3 paths, 100 sats each.
4163 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 300_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4164 assert_eq!(route.paths.len(), 3);
4166 let mut total_amount_paid_msat = 0;
4167 for path in &route.paths {
4168 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
4169 total_amount_paid_msat += path.last().unwrap().fee_msat;
4171 assert_eq!(total_amount_paid_msat, 300_000);
4177 fn mpp_cheaper_route_test() {
4178 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4179 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4180 let scorer = test_utils::TestScorer::with_penalty(0);
4181 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4182 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4183 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
4185 // This test checks that if we have two cheaper paths and one more expensive path,
4186 // so that liquidity-wise any 2 of 3 combination is sufficient,
4187 // two cheaper paths will be taken.
4188 // These paths have equal available liquidity.
4190 // We need a combination of 3 paths:
4191 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
4192 // Note that these paths overlap (channels 5, 12, 13).
4193 // Each path will have 100 sats capacity, those channels which
4194 // are used twice will have 200 sats capacity.
4196 // Disable other potential paths.
4197 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4198 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4199 short_channel_id: 2,
4202 cltv_expiry_delta: 0,
4203 htlc_minimum_msat: 0,
4204 htlc_maximum_msat: OptionalField::Present(100_000),
4206 fee_proportional_millionths: 0,
4207 excess_data: Vec::new()
4209 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4210 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4211 short_channel_id: 7,
4214 cltv_expiry_delta: 0,
4215 htlc_minimum_msat: 0,
4216 htlc_maximum_msat: OptionalField::Present(100_000),
4218 fee_proportional_millionths: 0,
4219 excess_data: Vec::new()
4222 // Path via {node0, node2} is channels {1, 3, 5}.
4223 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4224 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4225 short_channel_id: 1,
4228 cltv_expiry_delta: 0,
4229 htlc_minimum_msat: 0,
4230 htlc_maximum_msat: OptionalField::Present(100_000),
4232 fee_proportional_millionths: 0,
4233 excess_data: Vec::new()
4235 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4236 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4237 short_channel_id: 3,
4240 cltv_expiry_delta: 0,
4241 htlc_minimum_msat: 0,
4242 htlc_maximum_msat: OptionalField::Present(100_000),
4244 fee_proportional_millionths: 0,
4245 excess_data: Vec::new()
4248 // Capacity of 200 sats because this channel will be used by 3rd path as well.
4249 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4250 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4251 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4252 short_channel_id: 5,
4255 cltv_expiry_delta: 0,
4256 htlc_minimum_msat: 0,
4257 htlc_maximum_msat: OptionalField::Present(200_000),
4259 fee_proportional_millionths: 0,
4260 excess_data: Vec::new()
4263 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4264 // Add 100 sats to the capacities of {12, 13}, because these channels
4265 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
4266 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4267 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4268 short_channel_id: 12,
4271 cltv_expiry_delta: 0,
4272 htlc_minimum_msat: 0,
4273 htlc_maximum_msat: OptionalField::Present(200_000),
4275 fee_proportional_millionths: 0,
4276 excess_data: Vec::new()
4278 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4279 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4280 short_channel_id: 13,
4283 cltv_expiry_delta: 0,
4284 htlc_minimum_msat: 0,
4285 htlc_maximum_msat: OptionalField::Present(200_000),
4287 fee_proportional_millionths: 0,
4288 excess_data: Vec::new()
4291 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4292 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4293 short_channel_id: 6,
4296 cltv_expiry_delta: 0,
4297 htlc_minimum_msat: 0,
4298 htlc_maximum_msat: OptionalField::Present(100_000),
4299 fee_base_msat: 1_000,
4300 fee_proportional_millionths: 0,
4301 excess_data: Vec::new()
4303 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4304 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4305 short_channel_id: 11,
4308 cltv_expiry_delta: 0,
4309 htlc_minimum_msat: 0,
4310 htlc_maximum_msat: OptionalField::Present(100_000),
4312 fee_proportional_millionths: 0,
4313 excess_data: Vec::new()
4316 // Path via {node7, node2} is channels {12, 13, 5}.
4317 // We already limited them to 200 sats (they are used twice for 100 sats).
4318 // Nothing to do here.
4321 // Now, attempt to route 180 sats.
4322 // Our algorithm should provide us with these 2 paths.
4323 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 180_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4324 assert_eq!(route.paths.len(), 2);
4326 let mut total_value_transferred_msat = 0;
4327 let mut total_paid_msat = 0;
4328 for path in &route.paths {
4329 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
4330 total_value_transferred_msat += path.last().unwrap().fee_msat;
4332 total_paid_msat += hop.fee_msat;
4335 // If we paid fee, this would be higher.
4336 assert_eq!(total_value_transferred_msat, 180_000);
4337 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
4338 assert_eq!(total_fees_paid, 0);
4343 fn fees_on_mpp_route_test() {
4344 // This test makes sure that MPP algorithm properly takes into account
4345 // fees charged on the channels, by making the fees impactful:
4346 // if the fee is not properly accounted for, the behavior is different.
4347 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4348 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4349 let scorer = test_utils::TestScorer::with_penalty(0);
4350 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4351 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4352 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
4354 // We need a route consisting of 2 paths:
4355 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
4356 // We will route 200 sats, Each path will have 100 sats capacity.
4358 // This test is not particularly stable: e.g.,
4359 // there's a way to route via {node0, node2, node4}.
4360 // It works while pathfinding is deterministic, but can be broken otherwise.
4361 // It's fine to ignore this concern for now.
4363 // Disable other potential paths.
4364 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4365 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4366 short_channel_id: 2,
4369 cltv_expiry_delta: 0,
4370 htlc_minimum_msat: 0,
4371 htlc_maximum_msat: OptionalField::Present(100_000),
4373 fee_proportional_millionths: 0,
4374 excess_data: Vec::new()
4377 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4378 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4379 short_channel_id: 7,
4382 cltv_expiry_delta: 0,
4383 htlc_minimum_msat: 0,
4384 htlc_maximum_msat: OptionalField::Present(100_000),
4386 fee_proportional_millionths: 0,
4387 excess_data: Vec::new()
4390 // Path via {node0, node2} is channels {1, 3, 5}.
4391 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4392 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4393 short_channel_id: 1,
4396 cltv_expiry_delta: 0,
4397 htlc_minimum_msat: 0,
4398 htlc_maximum_msat: OptionalField::Present(100_000),
4400 fee_proportional_millionths: 0,
4401 excess_data: Vec::new()
4403 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4404 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4405 short_channel_id: 3,
4408 cltv_expiry_delta: 0,
4409 htlc_minimum_msat: 0,
4410 htlc_maximum_msat: OptionalField::Present(100_000),
4412 fee_proportional_millionths: 0,
4413 excess_data: Vec::new()
4416 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4417 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4418 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4419 short_channel_id: 5,
4422 cltv_expiry_delta: 0,
4423 htlc_minimum_msat: 0,
4424 htlc_maximum_msat: OptionalField::Present(100_000),
4426 fee_proportional_millionths: 0,
4427 excess_data: Vec::new()
4430 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4431 // All channels should be 100 sats capacity. But for the fee experiment,
4432 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
4433 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
4434 // 100 sats (and pay 150 sats in fees for the use of channel 6),
4435 // so no matter how large are other channels,
4436 // the whole path will be limited by 100 sats with just these 2 conditions:
4437 // - channel 12 capacity is 250 sats
4438 // - fee for channel 6 is 150 sats
4439 // Let's test this by enforcing these 2 conditions and removing other limits.
4440 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4441 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4442 short_channel_id: 12,
4445 cltv_expiry_delta: 0,
4446 htlc_minimum_msat: 0,
4447 htlc_maximum_msat: OptionalField::Present(250_000),
4449 fee_proportional_millionths: 0,
4450 excess_data: Vec::new()
4452 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4453 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4454 short_channel_id: 13,
4457 cltv_expiry_delta: 0,
4458 htlc_minimum_msat: 0,
4459 htlc_maximum_msat: OptionalField::Absent,
4461 fee_proportional_millionths: 0,
4462 excess_data: Vec::new()
4465 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4466 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4467 short_channel_id: 6,
4470 cltv_expiry_delta: 0,
4471 htlc_minimum_msat: 0,
4472 htlc_maximum_msat: OptionalField::Absent,
4473 fee_base_msat: 150_000,
4474 fee_proportional_millionths: 0,
4475 excess_data: Vec::new()
4477 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4478 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4479 short_channel_id: 11,
4482 cltv_expiry_delta: 0,
4483 htlc_minimum_msat: 0,
4484 htlc_maximum_msat: OptionalField::Absent,
4486 fee_proportional_millionths: 0,
4487 excess_data: Vec::new()
4491 // Attempt to route more than available results in a failure.
4492 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4493 &our_id, &payment_params, &network_graph.read_only(), None, 210_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
4494 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4495 } else { panic!(); }
4499 // Now, attempt to route 200 sats (exact amount we can route).
4500 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 200_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4501 assert_eq!(route.paths.len(), 2);
4503 let mut total_amount_paid_msat = 0;
4504 for path in &route.paths {
4505 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
4506 total_amount_paid_msat += path.last().unwrap().fee_msat;
4508 assert_eq!(total_amount_paid_msat, 200_000);
4509 assert_eq!(route.get_total_fees(), 150_000);
4514 fn mpp_with_last_hops() {
4515 // Previously, if we tried to send an MPP payment to a destination which was only reachable
4516 // via a single last-hop route hint, we'd fail to route if we first collected routes
4517 // totaling close but not quite enough to fund the full payment.
4519 // This was because we considered last-hop hints to have exactly the sought payment amount
4520 // instead of the amount we were trying to collect, needlessly limiting our path searching
4521 // at the very first hop.
4523 // Specifically, this interacted with our "all paths must fund at least 5% of total target"
4524 // criterion to cause us to refuse all routes at the last hop hint which would be considered
4525 // to only have the remaining to-collect amount in available liquidity.
4527 // This bug appeared in production in some specific channel configurations.
4528 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4529 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4530 let scorer = test_utils::TestScorer::with_penalty(0);
4531 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4532 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4533 let payment_params = PaymentParameters::from_node_id(PublicKey::from_slice(&[02; 33]).unwrap()).with_features(InvoiceFeatures::known())
4534 .with_route_hints(vec![RouteHint(vec![RouteHintHop {
4535 src_node_id: nodes[2],
4536 short_channel_id: 42,
4537 fees: RoutingFees { base_msat: 0, proportional_millionths: 0 },
4538 cltv_expiry_delta: 42,
4539 htlc_minimum_msat: None,
4540 htlc_maximum_msat: None,
4543 // Keep only two paths from us to nodes[2], both with a 99sat HTLC maximum, with one with
4544 // no fee and one with a 1msat fee. Previously, trying to route 100 sats to nodes[2] here
4545 // would first use the no-fee route and then fail to find a path along the second route as
4546 // we think we can only send up to 1 additional sat over the last-hop but refuse to as its
4547 // under 5% of our payment amount.
4548 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4549 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4550 short_channel_id: 1,
4553 cltv_expiry_delta: (5 << 4) | 5,
4554 htlc_minimum_msat: 0,
4555 htlc_maximum_msat: OptionalField::Present(99_000),
4556 fee_base_msat: u32::max_value(),
4557 fee_proportional_millionths: u32::max_value(),
4558 excess_data: Vec::new()
4560 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4561 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4562 short_channel_id: 2,
4565 cltv_expiry_delta: (5 << 4) | 3,
4566 htlc_minimum_msat: 0,
4567 htlc_maximum_msat: OptionalField::Present(99_000),
4568 fee_base_msat: u32::max_value(),
4569 fee_proportional_millionths: u32::max_value(),
4570 excess_data: Vec::new()
4572 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4573 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4574 short_channel_id: 4,
4577 cltv_expiry_delta: (4 << 4) | 1,
4578 htlc_minimum_msat: 0,
4579 htlc_maximum_msat: OptionalField::Absent,
4581 fee_proportional_millionths: 0,
4582 excess_data: Vec::new()
4584 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4585 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4586 short_channel_id: 13,
4588 flags: 0|2, // Channel disabled
4589 cltv_expiry_delta: (13 << 4) | 1,
4590 htlc_minimum_msat: 0,
4591 htlc_maximum_msat: OptionalField::Absent,
4593 fee_proportional_millionths: 2000000,
4594 excess_data: Vec::new()
4597 // Get a route for 100 sats and check that we found the MPP route no problem and didn't
4599 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4600 assert_eq!(route.paths.len(), 2);
4601 // Paths are somewhat randomly ordered, but:
4602 // * the first is channel 2 (1 msat fee) -> channel 4 -> channel 42
4603 // * the second is channel 1 (0 fee, but 99 sat maximum) -> channel 3 -> channel 42
4604 assert_eq!(route.paths[0][0].short_channel_id, 2);
4605 assert_eq!(route.paths[0][0].fee_msat, 1);
4606 assert_eq!(route.paths[0][2].fee_msat, 1_000);
4607 assert_eq!(route.paths[1][0].short_channel_id, 1);
4608 assert_eq!(route.paths[1][0].fee_msat, 0);
4609 assert_eq!(route.paths[1][2].fee_msat, 99_000);
4610 assert_eq!(route.get_total_fees(), 1);
4611 assert_eq!(route.get_total_amount(), 100_000);
4615 fn drop_lowest_channel_mpp_route_test() {
4616 // This test checks that low-capacity channel is dropped when after
4617 // path finding we realize that we found more capacity than we need.
4618 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4619 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4620 let scorer = test_utils::TestScorer::with_penalty(0);
4621 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4622 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4623 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
4625 // We need a route consisting of 3 paths:
4626 // From our node to node2 via node0, node7, node1 (three paths one hop each).
4628 // The first and the second paths should be sufficient, but the third should be
4629 // cheaper, so that we select it but drop later.
4631 // First, we set limits on these (previously unlimited) channels.
4632 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
4634 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
4635 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4636 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4637 short_channel_id: 1,
4640 cltv_expiry_delta: 0,
4641 htlc_minimum_msat: 0,
4642 htlc_maximum_msat: OptionalField::Present(100_000),
4644 fee_proportional_millionths: 0,
4645 excess_data: Vec::new()
4647 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4648 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4649 short_channel_id: 3,
4652 cltv_expiry_delta: 0,
4653 htlc_minimum_msat: 0,
4654 htlc_maximum_msat: OptionalField::Present(50_000),
4656 fee_proportional_millionths: 0,
4657 excess_data: Vec::new()
4660 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
4661 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4662 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4663 short_channel_id: 12,
4666 cltv_expiry_delta: 0,
4667 htlc_minimum_msat: 0,
4668 htlc_maximum_msat: OptionalField::Present(60_000),
4670 fee_proportional_millionths: 0,
4671 excess_data: Vec::new()
4673 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4674 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4675 short_channel_id: 13,
4678 cltv_expiry_delta: 0,
4679 htlc_minimum_msat: 0,
4680 htlc_maximum_msat: OptionalField::Present(60_000),
4682 fee_proportional_millionths: 0,
4683 excess_data: Vec::new()
4686 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
4687 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4688 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4689 short_channel_id: 2,
4692 cltv_expiry_delta: 0,
4693 htlc_minimum_msat: 0,
4694 htlc_maximum_msat: OptionalField::Present(20_000),
4696 fee_proportional_millionths: 0,
4697 excess_data: Vec::new()
4699 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4700 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4701 short_channel_id: 4,
4704 cltv_expiry_delta: 0,
4705 htlc_minimum_msat: 0,
4706 htlc_maximum_msat: OptionalField::Present(20_000),
4708 fee_proportional_millionths: 0,
4709 excess_data: Vec::new()
4713 // Attempt to route more than available results in a failure.
4714 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4715 &our_id, &payment_params, &network_graph.read_only(), None, 150_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
4716 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4717 } else { panic!(); }
4721 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
4722 // Our algorithm should provide us with these 3 paths.
4723 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 125_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4724 assert_eq!(route.paths.len(), 3);
4725 let mut total_amount_paid_msat = 0;
4726 for path in &route.paths {
4727 assert_eq!(path.len(), 2);
4728 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4729 total_amount_paid_msat += path.last().unwrap().fee_msat;
4731 assert_eq!(total_amount_paid_msat, 125_000);
4735 // Attempt to route without the last small cheap channel
4736 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4737 assert_eq!(route.paths.len(), 2);
4738 let mut total_amount_paid_msat = 0;
4739 for path in &route.paths {
4740 assert_eq!(path.len(), 2);
4741 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4742 total_amount_paid_msat += path.last().unwrap().fee_msat;
4744 assert_eq!(total_amount_paid_msat, 90_000);
4749 fn min_criteria_consistency() {
4750 // Test that we don't use an inconsistent metric between updating and walking nodes during
4751 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
4752 // was updated with a different criterion from the heap sorting, resulting in loops in
4753 // calculated paths. We test for that specific case here.
4755 // We construct a network that looks like this:
4757 // node2 -1(3)2- node3
4761 // node1 -1(5)2- node4 -1(1)2- node6
4767 // We create a loop on the side of our real path - our destination is node 6, with a
4768 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
4769 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
4770 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
4771 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
4772 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
4773 // "previous hop" being set to node 3, creating a loop in the path.
4774 let secp_ctx = Secp256k1::new();
4775 let logger = Arc::new(test_utils::TestLogger::new());
4776 let network = Arc::new(NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash()));
4777 let net_graph_msg_handler = NetGraphMsgHandler::new(Arc::clone(&network), None, Arc::clone(&logger));
4778 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4779 let scorer = test_utils::TestScorer::with_penalty(0);
4780 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4781 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4782 let payment_params = PaymentParameters::from_node_id(nodes[6]);
4784 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
4785 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4786 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4787 short_channel_id: 6,
4790 cltv_expiry_delta: (6 << 4) | 0,
4791 htlc_minimum_msat: 0,
4792 htlc_maximum_msat: OptionalField::Absent,
4794 fee_proportional_millionths: 0,
4795 excess_data: Vec::new()
4797 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
4799 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4800 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4801 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4802 short_channel_id: 5,
4805 cltv_expiry_delta: (5 << 4) | 0,
4806 htlc_minimum_msat: 0,
4807 htlc_maximum_msat: OptionalField::Absent,
4809 fee_proportional_millionths: 0,
4810 excess_data: Vec::new()
4812 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
4814 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
4815 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4816 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4817 short_channel_id: 4,
4820 cltv_expiry_delta: (4 << 4) | 0,
4821 htlc_minimum_msat: 0,
4822 htlc_maximum_msat: OptionalField::Absent,
4824 fee_proportional_millionths: 0,
4825 excess_data: Vec::new()
4827 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
4829 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
4830 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
4831 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4832 short_channel_id: 3,
4835 cltv_expiry_delta: (3 << 4) | 0,
4836 htlc_minimum_msat: 0,
4837 htlc_maximum_msat: OptionalField::Absent,
4839 fee_proportional_millionths: 0,
4840 excess_data: Vec::new()
4842 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
4844 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
4845 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4846 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4847 short_channel_id: 2,
4850 cltv_expiry_delta: (2 << 4) | 0,
4851 htlc_minimum_msat: 0,
4852 htlc_maximum_msat: OptionalField::Absent,
4854 fee_proportional_millionths: 0,
4855 excess_data: Vec::new()
4858 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
4859 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4860 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4861 short_channel_id: 1,
4864 cltv_expiry_delta: (1 << 4) | 0,
4865 htlc_minimum_msat: 100,
4866 htlc_maximum_msat: OptionalField::Absent,
4868 fee_proportional_millionths: 0,
4869 excess_data: Vec::new()
4871 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
4874 // Now ensure the route flows simply over nodes 1 and 4 to 6.
4875 let route = get_route(&our_id, &payment_params, &network.read_only(), None, 10_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4876 assert_eq!(route.paths.len(), 1);
4877 assert_eq!(route.paths[0].len(), 3);
4879 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
4880 assert_eq!(route.paths[0][0].short_channel_id, 6);
4881 assert_eq!(route.paths[0][0].fee_msat, 100);
4882 assert_eq!(route.paths[0][0].cltv_expiry_delta, (5 << 4) | 0);
4883 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(1));
4884 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(6));
4886 assert_eq!(route.paths[0][1].pubkey, nodes[4]);
4887 assert_eq!(route.paths[0][1].short_channel_id, 5);
4888 assert_eq!(route.paths[0][1].fee_msat, 0);
4889 assert_eq!(route.paths[0][1].cltv_expiry_delta, (1 << 4) | 0);
4890 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(4));
4891 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(5));
4893 assert_eq!(route.paths[0][2].pubkey, nodes[6]);
4894 assert_eq!(route.paths[0][2].short_channel_id, 1);
4895 assert_eq!(route.paths[0][2].fee_msat, 10_000);
4896 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
4897 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
4898 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(1));
4904 fn exact_fee_liquidity_limit() {
4905 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
4906 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
4907 // we calculated fees on a higher value, resulting in us ignoring such paths.
4908 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4909 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
4910 let scorer = test_utils::TestScorer::with_penalty(0);
4911 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4912 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4913 let payment_params = PaymentParameters::from_node_id(nodes[2]);
4915 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
4917 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4918 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4919 short_channel_id: 2,
4922 cltv_expiry_delta: 0,
4923 htlc_minimum_msat: 0,
4924 htlc_maximum_msat: OptionalField::Present(85_000),
4926 fee_proportional_millionths: 0,
4927 excess_data: Vec::new()
4930 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4931 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4932 short_channel_id: 12,
4935 cltv_expiry_delta: (4 << 4) | 1,
4936 htlc_minimum_msat: 0,
4937 htlc_maximum_msat: OptionalField::Present(270_000),
4939 fee_proportional_millionths: 1000000,
4940 excess_data: Vec::new()
4944 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
4945 // 200% fee charged channel 13 in the 1-to-2 direction.
4946 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4947 assert_eq!(route.paths.len(), 1);
4948 assert_eq!(route.paths[0].len(), 2);
4950 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
4951 assert_eq!(route.paths[0][0].short_channel_id, 12);
4952 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
4953 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
4954 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
4955 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
4957 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
4958 assert_eq!(route.paths[0][1].short_channel_id, 13);
4959 assert_eq!(route.paths[0][1].fee_msat, 90_000);
4960 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
4961 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
4962 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
4967 fn htlc_max_reduction_below_min() {
4968 // Test that if, while walking the graph, we reduce the value being sent to meet an
4969 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
4970 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
4971 // resulting in us thinking there is no possible path, even if other paths exist.
4972 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4973 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4974 let scorer = test_utils::TestScorer::with_penalty(0);
4975 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4976 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4977 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
4979 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
4980 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
4981 // then try to send 90_000.
4982 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4983 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4984 short_channel_id: 2,
4987 cltv_expiry_delta: 0,
4988 htlc_minimum_msat: 0,
4989 htlc_maximum_msat: OptionalField::Present(80_000),
4991 fee_proportional_millionths: 0,
4992 excess_data: Vec::new()
4994 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4995 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4996 short_channel_id: 4,
4999 cltv_expiry_delta: (4 << 4) | 1,
5000 htlc_minimum_msat: 90_000,
5001 htlc_maximum_msat: OptionalField::Absent,
5003 fee_proportional_millionths: 0,
5004 excess_data: Vec::new()
5008 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
5009 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
5010 // expensive) channels 12-13 path.
5011 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5012 assert_eq!(route.paths.len(), 1);
5013 assert_eq!(route.paths[0].len(), 2);
5015 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
5016 assert_eq!(route.paths[0][0].short_channel_id, 12);
5017 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
5018 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
5019 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
5020 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
5022 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
5023 assert_eq!(route.paths[0][1].short_channel_id, 13);
5024 assert_eq!(route.paths[0][1].fee_msat, 90_000);
5025 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
5026 assert_eq!(route.paths[0][1].node_features.le_flags(), InvoiceFeatures::known().le_flags());
5027 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
5032 fn multiple_direct_first_hops() {
5033 // Previously we'd only ever considered one first hop path per counterparty.
5034 // However, as we don't restrict users to one channel per peer, we really need to support
5035 // looking at all first hop paths.
5036 // Here we test that we do not ignore all-but-the-last first hop paths per counterparty (as
5037 // we used to do by overwriting the `first_hop_targets` hashmap entry) and that we can MPP
5038 // route over multiple channels with the same first hop.
5039 let secp_ctx = Secp256k1::new();
5040 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5041 let logger = Arc::new(test_utils::TestLogger::new());
5042 let network_graph = NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash());
5043 let scorer = test_utils::TestScorer::with_penalty(0);
5044 let payment_params = PaymentParameters::from_node_id(nodes[0]).with_features(InvoiceFeatures::known());
5045 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5046 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5049 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
5050 &get_channel_details(Some(3), nodes[0], InitFeatures::known(), 200_000),
5051 &get_channel_details(Some(2), nodes[0], InitFeatures::known(), 10_000),
5052 ]), 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5053 assert_eq!(route.paths.len(), 1);
5054 assert_eq!(route.paths[0].len(), 1);
5056 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
5057 assert_eq!(route.paths[0][0].short_channel_id, 3);
5058 assert_eq!(route.paths[0][0].fee_msat, 100_000);
5061 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
5062 &get_channel_details(Some(3), nodes[0], InitFeatures::known(), 50_000),
5063 &get_channel_details(Some(2), nodes[0], InitFeatures::known(), 50_000),
5064 ]), 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5065 assert_eq!(route.paths.len(), 2);
5066 assert_eq!(route.paths[0].len(), 1);
5067 assert_eq!(route.paths[1].len(), 1);
5069 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
5070 assert_eq!(route.paths[0][0].short_channel_id, 3);
5071 assert_eq!(route.paths[0][0].fee_msat, 50_000);
5073 assert_eq!(route.paths[1][0].pubkey, nodes[0]);
5074 assert_eq!(route.paths[1][0].short_channel_id, 2);
5075 assert_eq!(route.paths[1][0].fee_msat, 50_000);
5079 // If we have a bunch of outbound channels to the same node, where most are not
5080 // sufficient to pay the full payment, but one is, we should default to just using the
5081 // one single channel that has sufficient balance, avoiding MPP.
5083 // If we have several options above the 3xpayment value threshold, we should pick the
5084 // smallest of them, avoiding further fragmenting our available outbound balance to
5086 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
5087 &get_channel_details(Some(2), nodes[0], InitFeatures::known(), 50_000),
5088 &get_channel_details(Some(3), nodes[0], InitFeatures::known(), 50_000),
5089 &get_channel_details(Some(5), nodes[0], InitFeatures::known(), 50_000),
5090 &get_channel_details(Some(6), nodes[0], InitFeatures::known(), 300_000),
5091 &get_channel_details(Some(7), nodes[0], InitFeatures::known(), 50_000),
5092 &get_channel_details(Some(8), nodes[0], InitFeatures::known(), 50_000),
5093 &get_channel_details(Some(9), nodes[0], InitFeatures::known(), 50_000),
5094 &get_channel_details(Some(4), nodes[0], InitFeatures::known(), 1_000_000),
5095 ]), 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5096 assert_eq!(route.paths.len(), 1);
5097 assert_eq!(route.paths[0].len(), 1);
5099 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
5100 assert_eq!(route.paths[0][0].short_channel_id, 6);
5101 assert_eq!(route.paths[0][0].fee_msat, 100_000);
5106 fn prefers_shorter_route_with_higher_fees() {
5107 let (secp_ctx, network_graph, _, _, logger) = build_graph();
5108 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5109 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
5111 // Without penalizing each hop 100 msats, a longer path with lower fees is chosen.
5112 let scorer = test_utils::TestScorer::with_penalty(0);
5113 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5114 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5115 let route = get_route(
5116 &our_id, &payment_params, &network_graph.read_only(), None, 100, 42,
5117 Arc::clone(&logger), &scorer, &random_seed_bytes
5119 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5121 assert_eq!(route.get_total_fees(), 100);
5122 assert_eq!(route.get_total_amount(), 100);
5123 assert_eq!(path, vec![2, 4, 6, 11, 8]);
5125 // Applying a 100 msat penalty to each hop results in taking channels 7 and 10 to nodes[6]
5126 // from nodes[2] rather than channel 6, 11, and 8, even though the longer path is cheaper.
5127 let scorer = test_utils::TestScorer::with_penalty(100);
5128 let route = get_route(
5129 &our_id, &payment_params, &network_graph.read_only(), None, 100, 42,
5130 Arc::clone(&logger), &scorer, &random_seed_bytes
5132 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5134 assert_eq!(route.get_total_fees(), 300);
5135 assert_eq!(route.get_total_amount(), 100);
5136 assert_eq!(path, vec![2, 4, 7, 10]);
5139 struct BadChannelScorer {
5140 short_channel_id: u64,
5144 impl Writeable for BadChannelScorer {
5145 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), ::io::Error> { unimplemented!() }
5147 impl Score for BadChannelScorer {
5148 fn channel_penalty_msat(&self, short_channel_id: u64, _send_amt: u64, _capacity_msat: u64, _source: &NodeId, _target: &NodeId) -> u64 {
5149 if short_channel_id == self.short_channel_id { u64::max_value() } else { 0 }
5152 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
5153 fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
5156 struct BadNodeScorer {
5161 impl Writeable for BadNodeScorer {
5162 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), ::io::Error> { unimplemented!() }
5165 impl Score for BadNodeScorer {
5166 fn channel_penalty_msat(&self, _short_channel_id: u64, _send_amt: u64, _capacity_msat: u64, _source: &NodeId, target: &NodeId) -> u64 {
5167 if *target == self.node_id { u64::max_value() } else { 0 }
5170 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
5171 fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
5175 fn avoids_routing_through_bad_channels_and_nodes() {
5176 let (secp_ctx, network, _, _, logger) = build_graph();
5177 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5178 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
5179 let network_graph = network.read_only();
5181 // A path to nodes[6] exists when no penalties are applied to any channel.
5182 let scorer = test_utils::TestScorer::with_penalty(0);
5183 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5184 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5185 let route = get_route(
5186 &our_id, &payment_params, &network_graph, None, 100, 42,
5187 Arc::clone(&logger), &scorer, &random_seed_bytes
5189 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5191 assert_eq!(route.get_total_fees(), 100);
5192 assert_eq!(route.get_total_amount(), 100);
5193 assert_eq!(path, vec![2, 4, 6, 11, 8]);
5195 // A different path to nodes[6] exists if channel 6 cannot be routed over.
5196 let scorer = BadChannelScorer { short_channel_id: 6 };
5197 let route = get_route(
5198 &our_id, &payment_params, &network_graph, None, 100, 42,
5199 Arc::clone(&logger), &scorer, &random_seed_bytes
5201 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5203 assert_eq!(route.get_total_fees(), 300);
5204 assert_eq!(route.get_total_amount(), 100);
5205 assert_eq!(path, vec![2, 4, 7, 10]);
5207 // A path to nodes[6] does not exist if nodes[2] cannot be routed through.
5208 let scorer = BadNodeScorer { node_id: NodeId::from_pubkey(&nodes[2]) };
5210 &our_id, &payment_params, &network_graph, None, 100, 42,
5211 Arc::clone(&logger), &scorer, &random_seed_bytes
5213 Err(LightningError { err, .. } ) => {
5214 assert_eq!(err, "Failed to find a path to the given destination");
5216 Ok(_) => panic!("Expected error"),
5221 fn total_fees_single_path() {
5225 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5226 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5227 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5230 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5231 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5232 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5235 pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
5236 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5237 short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0
5240 payment_params: None,
5243 assert_eq!(route.get_total_fees(), 250);
5244 assert_eq!(route.get_total_amount(), 225);
5248 fn total_fees_multi_path() {
5252 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5253 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5254 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5257 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5258 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5259 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5263 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5264 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5265 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5268 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5269 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5270 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5273 payment_params: None,
5276 assert_eq!(route.get_total_fees(), 200);
5277 assert_eq!(route.get_total_amount(), 300);
5281 fn total_empty_route_no_panic() {
5282 // In an earlier version of `Route::get_total_fees` and `Route::get_total_amount`, they
5283 // would both panic if the route was completely empty. We test to ensure they return 0
5284 // here, even though its somewhat nonsensical as a route.
5285 let route = Route { paths: Vec::new(), payment_params: None };
5287 assert_eq!(route.get_total_fees(), 0);
5288 assert_eq!(route.get_total_amount(), 0);
5292 fn limits_total_cltv_delta() {
5293 let (secp_ctx, network, _, _, logger) = build_graph();
5294 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5295 let network_graph = network.read_only();
5297 let scorer = test_utils::TestScorer::with_penalty(0);
5299 // Make sure that generally there is at least one route available
5300 let feasible_max_total_cltv_delta = 1008;
5301 let feasible_payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes))
5302 .with_max_total_cltv_expiry_delta(feasible_max_total_cltv_delta);
5303 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5304 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5305 let route = get_route(&our_id, &feasible_payment_params, &network_graph, None, 100, 0, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5306 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5307 assert_ne!(path.len(), 0);
5309 // But not if we exclude all paths on the basis of their accumulated CLTV delta
5310 let fail_max_total_cltv_delta = 23;
5311 let fail_payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes))
5312 .with_max_total_cltv_expiry_delta(fail_max_total_cltv_delta);
5313 match get_route(&our_id, &fail_payment_params, &network_graph, None, 100, 0, Arc::clone(&logger), &scorer, &random_seed_bytes)
5315 Err(LightningError { err, .. } ) => {
5316 assert_eq!(err, "Failed to find a path to the given destination");
5318 Ok(_) => panic!("Expected error"),
5323 fn limits_path_length() {
5324 let (secp_ctx, network, _, _, logger) = build_line_graph();
5325 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5326 let network_graph = network.read_only();
5328 let scorer = test_utils::TestScorer::with_penalty(0);
5329 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5330 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5332 // First check we can actually create a long route on this graph.
5333 let feasible_payment_params = PaymentParameters::from_node_id(nodes[18]);
5334 let route = get_route(&our_id, &feasible_payment_params, &network_graph, None, 100, 0,
5335 Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5336 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5337 assert!(path.len() == MAX_PATH_LENGTH_ESTIMATE.into());
5339 // But we can't create a path surpassing the MAX_PATH_LENGTH_ESTIMATE limit.
5340 let fail_payment_params = PaymentParameters::from_node_id(nodes[19]);
5341 match get_route(&our_id, &fail_payment_params, &network_graph, None, 100, 0,
5342 Arc::clone(&logger), &scorer, &random_seed_bytes)
5344 Err(LightningError { err, .. } ) => {
5345 assert_eq!(err, "Failed to find a path to the given destination");
5347 Ok(_) => panic!("Expected error"),
5352 fn adds_and_limits_cltv_offset() {
5353 let (secp_ctx, network_graph, _, _, logger) = build_graph();
5354 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5356 let scorer = test_utils::TestScorer::with_penalty(0);
5358 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
5359 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5360 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5361 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5362 assert_eq!(route.paths.len(), 1);
5364 let cltv_expiry_deltas_before = route.paths[0].iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5366 // Check whether the offset added to the last hop by default is in [1 .. DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA]
5367 let mut route_default = route.clone();
5368 add_random_cltv_offset(&mut route_default, &payment_params, &network_graph.read_only(), &random_seed_bytes);
5369 let cltv_expiry_deltas_default = route_default.paths[0].iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5370 assert_eq!(cltv_expiry_deltas_before.split_last().unwrap().1, cltv_expiry_deltas_default.split_last().unwrap().1);
5371 assert!(cltv_expiry_deltas_default.last() > cltv_expiry_deltas_before.last());
5372 assert!(cltv_expiry_deltas_default.last().unwrap() <= &DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA);
5374 // Check that no offset is added when we restrict the max_total_cltv_expiry_delta
5375 let mut route_limited = route.clone();
5376 let limited_max_total_cltv_expiry_delta = cltv_expiry_deltas_before.iter().sum();
5377 let limited_payment_params = payment_params.with_max_total_cltv_expiry_delta(limited_max_total_cltv_expiry_delta);
5378 add_random_cltv_offset(&mut route_limited, &limited_payment_params, &network_graph.read_only(), &random_seed_bytes);
5379 let cltv_expiry_deltas_limited = route_limited.paths[0].iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5380 assert_eq!(cltv_expiry_deltas_before, cltv_expiry_deltas_limited);
5384 fn adds_plausible_cltv_offset() {
5385 let (secp_ctx, network, _, _, logger) = build_graph();
5386 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5387 let network_graph = network.read_only();
5388 let network_nodes = network_graph.nodes();
5389 let network_channels = network_graph.channels();
5390 let scorer = test_utils::TestScorer::with_penalty(0);
5391 let payment_params = PaymentParameters::from_node_id(nodes[3]);
5392 let keys_manager = test_utils::TestKeysInterface::new(&[4u8; 32], Network::Testnet);
5393 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5395 let mut route = get_route(&our_id, &payment_params, &network_graph, None, 100, 0,
5396 Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5397 add_random_cltv_offset(&mut route, &payment_params, &network_graph, &random_seed_bytes);
5399 let mut path_plausibility = vec![];
5401 for p in route.paths {
5402 // 1. Select random observation point
5403 let mut prng = ChaCha20::new(&random_seed_bytes, &[0u8; 12]);
5404 let mut random_bytes = [0u8; ::core::mem::size_of::<usize>()];
5406 prng.process_in_place(&mut random_bytes);
5407 let random_path_index = usize::from_be_bytes(random_bytes).wrapping_rem(p.len());
5408 let observation_point = NodeId::from_pubkey(&p.get(random_path_index).unwrap().pubkey);
5410 // 2. Calculate what CLTV expiry delta we would observe there
5411 let observed_cltv_expiry_delta: u32 = p[random_path_index..].iter().map(|h| h.cltv_expiry_delta).sum();
5413 // 3. Starting from the observation point, find candidate paths
5414 let mut candidates: VecDeque<(NodeId, Vec<u32>)> = VecDeque::new();
5415 candidates.push_back((observation_point, vec![]));
5417 let mut found_plausible_candidate = false;
5419 'candidate_loop: while let Some((cur_node_id, cur_path_cltv_deltas)) = candidates.pop_front() {
5420 if let Some(remaining) = observed_cltv_expiry_delta.checked_sub(cur_path_cltv_deltas.iter().sum::<u32>()) {
5421 if remaining == 0 || remaining.wrapping_rem(40) == 0 || remaining.wrapping_rem(144) == 0 {
5422 found_plausible_candidate = true;
5423 break 'candidate_loop;
5427 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
5428 for channel_id in &cur_node.channels {
5429 if let Some(channel_info) = network_channels.get(&channel_id) {
5430 if let Some((dir_info, next_id)) = channel_info.as_directed_from(&cur_node_id) {
5431 if let Some(channel_update_info) = dir_info.direction() {
5432 let next_cltv_expiry_delta = channel_update_info.cltv_expiry_delta as u32;
5433 if cur_path_cltv_deltas.iter().sum::<u32>()
5434 .saturating_add(next_cltv_expiry_delta) <= observed_cltv_expiry_delta {
5435 let mut new_path_cltv_deltas = cur_path_cltv_deltas.clone();
5436 new_path_cltv_deltas.push(next_cltv_expiry_delta);
5437 candidates.push_back((*next_id, new_path_cltv_deltas));
5446 path_plausibility.push(found_plausible_candidate);
5448 assert!(path_plausibility.iter().all(|x| *x));
5451 #[cfg(not(feature = "no-std"))]
5452 pub(super) fn random_init_seed() -> u64 {
5453 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
5454 use core::hash::{BuildHasher, Hasher};
5455 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
5456 println!("Using seed of {}", seed);
5459 #[cfg(not(feature = "no-std"))]
5460 use util::ser::Readable;
5463 #[cfg(not(feature = "no-std"))]
5464 fn generate_routes() {
5465 use routing::scoring::{ProbabilisticScorer, ProbabilisticScoringParameters};
5467 let mut d = match super::test_utils::get_route_file() {
5474 let graph = NetworkGraph::read(&mut d).unwrap();
5475 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5476 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5478 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
5479 let mut seed = random_init_seed() as usize;
5480 let nodes = graph.read_only().nodes().clone();
5481 'load_endpoints: for _ in 0..10 {
5483 seed = seed.overflowing_mul(0xdeadbeef).0;
5484 let src = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5485 seed = seed.overflowing_mul(0xdeadbeef).0;
5486 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5487 let payment_params = PaymentParameters::from_node_id(dst);
5488 let amt = seed as u64 % 200_000_000;
5489 let params = ProbabilisticScoringParameters::default();
5490 let logger = test_utils::TestLogger::new();
5491 let scorer = ProbabilisticScorer::new(params, &graph, &logger);
5492 if get_route(src, &payment_params, &graph.read_only(), None, amt, 42, &logger, &scorer, &random_seed_bytes).is_ok() {
5493 continue 'load_endpoints;
5500 #[cfg(not(feature = "no-std"))]
5501 fn generate_routes_mpp() {
5502 use routing::scoring::{ProbabilisticScorer, ProbabilisticScoringParameters};
5504 let mut d = match super::test_utils::get_route_file() {
5511 let graph = NetworkGraph::read(&mut d).unwrap();
5512 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5513 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5515 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
5516 let mut seed = random_init_seed() as usize;
5517 let nodes = graph.read_only().nodes().clone();
5518 'load_endpoints: for _ in 0..10 {
5520 seed = seed.overflowing_mul(0xdeadbeef).0;
5521 let src = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5522 seed = seed.overflowing_mul(0xdeadbeef).0;
5523 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5524 let payment_params = PaymentParameters::from_node_id(dst).with_features(InvoiceFeatures::known());
5525 let amt = seed as u64 % 200_000_000;
5526 let params = ProbabilisticScoringParameters::default();
5527 let logger = test_utils::TestLogger::new();
5528 let scorer = ProbabilisticScorer::new(params, &graph, &logger);
5529 if get_route(src, &payment_params, &graph.read_only(), None, amt, 42, &logger, &scorer, &random_seed_bytes).is_ok() {
5530 continue 'load_endpoints;
5537 #[cfg(all(test, not(feature = "no-std")))]
5538 pub(crate) mod test_utils {
5540 /// Tries to open a network graph file, or panics with a URL to fetch it.
5541 pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
5542 let res = File::open("net_graph-2021-05-31.bin") // By default we're run in RL/lightning
5543 .or_else(|_| File::open("lightning/net_graph-2021-05-31.bin")) // We may be run manually in RL/
5544 .or_else(|_| { // Fall back to guessing based on the binary location
5545 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
5546 let mut path = std::env::current_exe().unwrap();
5547 path.pop(); // lightning-...
5549 path.pop(); // debug
5550 path.pop(); // target
5551 path.push("lightning");
5552 path.push("net_graph-2021-05-31.bin");
5553 eprintln!("{}", path.to_str().unwrap());
5556 .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");
5557 #[cfg(require_route_graph_test)]
5558 return Ok(res.unwrap());
5559 #[cfg(not(require_route_graph_test))]
5564 #[cfg(all(test, feature = "_bench_unstable", not(feature = "no-std")))]
5567 use bitcoin::hashes::Hash;
5568 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
5569 use chain::transaction::OutPoint;
5570 use chain::keysinterface::{KeysManager,KeysInterface};
5571 use ln::channelmanager::{ChannelCounterparty, ChannelDetails};
5572 use ln::features::{InitFeatures, InvoiceFeatures};
5573 use routing::scoring::{FixedPenaltyScorer, ProbabilisticScorer, ProbabilisticScoringParameters, Scorer};
5574 use util::logger::{Logger, Record};
5575 use util::test_utils::TestLogger;
5579 struct DummyLogger {}
5580 impl Logger for DummyLogger {
5581 fn log(&self, _record: &Record) {}
5584 fn read_network_graph() -> NetworkGraph {
5585 let mut d = test_utils::get_route_file().unwrap();
5586 NetworkGraph::read(&mut d).unwrap()
5589 fn payer_pubkey() -> PublicKey {
5590 let secp_ctx = Secp256k1::new();
5591 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
5595 fn first_hop(node_id: PublicKey) -> ChannelDetails {
5597 channel_id: [0; 32],
5598 counterparty: ChannelCounterparty {
5599 features: InitFeatures::known(),
5601 unspendable_punishment_reserve: 0,
5602 forwarding_info: None,
5603 outbound_htlc_minimum_msat: None,
5604 outbound_htlc_maximum_msat: None,
5606 funding_txo: Some(OutPoint {
5607 txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0
5610 short_channel_id: Some(1),
5611 inbound_scid_alias: None,
5612 channel_value_satoshis: 10_000_000,
5614 balance_msat: 10_000_000,
5615 outbound_capacity_msat: 10_000_000,
5616 next_outbound_htlc_limit_msat: 10_000_000,
5617 inbound_capacity_msat: 0,
5618 unspendable_punishment_reserve: None,
5619 confirmations_required: None,
5620 force_close_spend_delay: None,
5622 is_funding_locked: true,
5625 inbound_htlc_minimum_msat: None,
5626 inbound_htlc_maximum_msat: None,
5631 fn generate_routes_with_zero_penalty_scorer(bench: &mut Bencher) {
5632 let network_graph = read_network_graph();
5633 let scorer = FixedPenaltyScorer::with_penalty(0);
5634 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::empty());
5638 fn generate_mpp_routes_with_zero_penalty_scorer(bench: &mut Bencher) {
5639 let network_graph = read_network_graph();
5640 let scorer = FixedPenaltyScorer::with_penalty(0);
5641 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::known());
5645 fn generate_routes_with_default_scorer(bench: &mut Bencher) {
5646 let network_graph = read_network_graph();
5647 let scorer = Scorer::default();
5648 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::empty());
5652 fn generate_mpp_routes_with_default_scorer(bench: &mut Bencher) {
5653 let network_graph = read_network_graph();
5654 let scorer = Scorer::default();
5655 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::known());
5659 fn generate_routes_with_probabilistic_scorer(bench: &mut Bencher) {
5660 let logger = TestLogger::new();
5661 let network_graph = read_network_graph();
5662 let params = ProbabilisticScoringParameters::default();
5663 let scorer = ProbabilisticScorer::new(params, &network_graph, &logger);
5664 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::empty());
5668 fn generate_mpp_routes_with_probabilistic_scorer(bench: &mut Bencher) {
5669 let logger = TestLogger::new();
5670 let network_graph = read_network_graph();
5671 let params = ProbabilisticScoringParameters::default();
5672 let scorer = ProbabilisticScorer::new(params, &network_graph, &logger);
5673 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::known());
5676 fn generate_routes<S: Score>(
5677 bench: &mut Bencher, graph: &NetworkGraph, mut scorer: S, features: InvoiceFeatures
5679 let nodes = graph.read_only().nodes().clone();
5680 let payer = payer_pubkey();
5681 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
5682 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5684 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
5685 let mut routes = Vec::new();
5686 let mut route_endpoints = Vec::new();
5687 let mut seed: usize = 0xdeadbeef;
5688 'load_endpoints: for _ in 0..150 {
5691 let src = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5693 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5694 let params = PaymentParameters::from_node_id(dst).with_features(features.clone());
5695 let first_hop = first_hop(src);
5696 let amt = seed as u64 % 1_000_000;
5697 if let Ok(route) = get_route(&payer, ¶ms, &graph.read_only(), Some(&[&first_hop]), amt, 42, &DummyLogger{}, &scorer, &random_seed_bytes) {
5699 route_endpoints.push((first_hop, params, amt));
5700 continue 'load_endpoints;
5705 // ...and seed the scorer with success and failure data...
5706 for route in routes {
5707 let amount = route.get_total_amount();
5708 if amount < 250_000 {
5709 for path in route.paths {
5710 scorer.payment_path_successful(&path.iter().collect::<Vec<_>>());
5712 } else if amount > 750_000 {
5713 for path in route.paths {
5714 let short_channel_id = path[path.len() / 2].short_channel_id;
5715 scorer.payment_path_failed(&path.iter().collect::<Vec<_>>(), short_channel_id);
5720 // Because we've changed channel scores, its possible we'll take different routes to the
5721 // selected destinations, possibly causing us to fail because, eg, the newly-selected path
5722 // requires a too-high CLTV delta.
5723 route_endpoints.retain(|(first_hop, params, amt)| {
5724 get_route(&payer, params, &graph.read_only(), Some(&[first_hop]), *amt, 42, &DummyLogger{}, &scorer, &random_seed_bytes).is_ok()
5726 route_endpoints.truncate(100);
5727 assert_eq!(route_endpoints.len(), 100);
5729 // ...then benchmark finding paths between the nodes we learned.
5732 let (first_hop, params, amt) = &route_endpoints[idx % route_endpoints.len()];
5733 assert!(get_route(&payer, params, &graph.read_only(), Some(&[first_hop]), *amt, 42, &DummyLogger{}, &scorer, &random_seed_bytes).is_ok());