1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! The top-level routing/network map tracking logic lives here.
12 //! You probably want to create a NetGraphMsgHandler and use that as your RoutingMessageHandler and then
13 //! interrogate it to get routes for your own payments.
15 use bitcoin::secp256k1::PublicKey;
17 use ln::channelmanager::ChannelDetails;
18 use ln::features::{ChannelFeatures, InvoiceFeatures, NodeFeatures};
19 use ln::msgs::{DecodeError, ErrorAction, LightningError, MAX_VALUE_MSAT};
20 use routing::scoring::{ChannelUsage, Score};
21 use routing::network_graph::{DirectedChannelInfoWithUpdate, EffectiveCapacity, NetworkGraph, ReadOnlyNetworkGraph, NodeId, RoutingFees};
22 use util::ser::{Writeable, Readable, Writer};
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 [`build_route_from_hops`], but also provided in
155 /// [`Event::PaymentPathFailed`] for retrying a failed payment path.
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.get_outbound_payment_scid().unwrap(),
387 CandidateRouteHop::PublicHop { short_channel_id, .. } => *short_channel_id,
388 CandidateRouteHop::PrivateHop { hint } => hint.short_channel_id,
392 // NOTE: This may alloc memory so avoid calling it in a hot code path.
393 fn features(&self) -> ChannelFeatures {
395 CandidateRouteHop::FirstHop { details } => details.counterparty.features.to_context(),
396 CandidateRouteHop::PublicHop { info, .. } => info.channel().features.clone(),
397 CandidateRouteHop::PrivateHop { .. } => ChannelFeatures::empty(),
401 fn cltv_expiry_delta(&self) -> u32 {
403 CandidateRouteHop::FirstHop { .. } => 0,
404 CandidateRouteHop::PublicHop { info, .. } => info.direction().cltv_expiry_delta as u32,
405 CandidateRouteHop::PrivateHop { hint } => hint.cltv_expiry_delta as u32,
409 fn htlc_minimum_msat(&self) -> u64 {
411 CandidateRouteHop::FirstHop { .. } => 0,
412 CandidateRouteHop::PublicHop { info, .. } => info.direction().htlc_minimum_msat,
413 CandidateRouteHop::PrivateHop { hint } => hint.htlc_minimum_msat.unwrap_or(0),
417 fn htlc_maximum_msat(&self) -> u64 {
419 CandidateRouteHop::FirstHop { details } => details.next_outbound_htlc_limit_msat,
420 CandidateRouteHop::PublicHop { info, .. } => info.htlc_maximum_msat(),
421 CandidateRouteHop::PrivateHop { hint } => {
422 hint.htlc_maximum_msat.unwrap_or(u64::max_value())
427 fn fees(&self) -> RoutingFees {
429 CandidateRouteHop::FirstHop { .. } => RoutingFees {
430 base_msat: 0, proportional_millionths: 0,
432 CandidateRouteHop::PublicHop { info, .. } => info.direction().fees,
433 CandidateRouteHop::PrivateHop { hint } => hint.fees,
437 fn effective_capacity(&self) -> EffectiveCapacity {
439 CandidateRouteHop::FirstHop { details } => EffectiveCapacity::ExactLiquidity {
440 liquidity_msat: details.next_outbound_htlc_limit_msat,
442 CandidateRouteHop::PublicHop { info, .. } => info.effective_capacity(),
443 CandidateRouteHop::PrivateHop { .. } => EffectiveCapacity::Infinite,
448 /// It's useful to keep track of the hops associated with the fees required to use them,
449 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
450 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
451 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
453 struct PathBuildingHop<'a> {
454 // Note that this should be dropped in favor of loading it from CandidateRouteHop, but doing so
455 // is a larger refactor and will require careful performance analysis.
457 candidate: CandidateRouteHop<'a>,
460 /// Minimal fees required to route to the source node of the current hop via any of its inbound channels.
461 src_lowest_inbound_fees: RoutingFees,
462 /// All the fees paid *after* this channel on the way to the destination
463 next_hops_fee_msat: u64,
464 /// Fee paid for the use of the current channel (see candidate.fees()).
465 /// The value will be actually deducted from the counterparty balance on the previous link.
466 hop_use_fee_msat: u64,
467 /// Used to compare channels when choosing the for routing.
468 /// Includes paying for the use of a hop and the following hops, as well as
469 /// an estimated cost of reaching this hop.
470 /// Might get stale when fees are recomputed. Primarily for internal use.
472 /// A mirror of the same field in RouteGraphNode. Note that this is only used during the graph
473 /// walk and may be invalid thereafter.
474 path_htlc_minimum_msat: u64,
475 /// All penalties incurred from this channel on the way to the destination, as calculated using
477 path_penalty_msat: u64,
478 /// If we've already processed a node as the best node, we shouldn't process it again. Normally
479 /// we'd just ignore it if we did as all channels would have a higher new fee, but because we
480 /// may decrease the amounts in use as we walk the graph, the actual calculated fee may
481 /// decrease as well. Thus, we have to explicitly track which nodes have been processed and
482 /// avoid processing them again.
484 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
485 // In tests, we apply further sanity checks on cases where we skip nodes we already processed
486 // to ensure it is specifically in cases where the fee has gone down because of a decrease in
487 // value_contribution_msat, which requires tracking it here. See comments below where it is
488 // used for more info.
489 value_contribution_msat: u64,
492 impl<'a> core::fmt::Debug for PathBuildingHop<'a> {
493 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
494 let mut debug_struct = f.debug_struct("PathBuildingHop");
496 .field("node_id", &self.node_id)
497 .field("short_channel_id", &self.candidate.short_channel_id())
498 .field("total_fee_msat", &self.total_fee_msat)
499 .field("next_hops_fee_msat", &self.next_hops_fee_msat)
500 .field("hop_use_fee_msat", &self.hop_use_fee_msat)
501 .field("total_fee_msat - (next_hops_fee_msat + hop_use_fee_msat)", &(&self.total_fee_msat - (&self.next_hops_fee_msat + &self.hop_use_fee_msat)))
502 .field("path_penalty_msat", &self.path_penalty_msat)
503 .field("path_htlc_minimum_msat", &self.path_htlc_minimum_msat)
504 .field("cltv_expiry_delta", &self.candidate.cltv_expiry_delta());
505 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
506 let debug_struct = debug_struct
507 .field("value_contribution_msat", &self.value_contribution_msat);
508 debug_struct.finish()
512 // Instantiated with a list of hops with correct data in them collected during path finding,
513 // an instance of this struct should be further modified only via given methods.
515 struct PaymentPath<'a> {
516 hops: Vec<(PathBuildingHop<'a>, NodeFeatures)>,
519 impl<'a> PaymentPath<'a> {
520 // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
521 fn get_value_msat(&self) -> u64 {
522 self.hops.last().unwrap().0.fee_msat
525 fn get_path_penalty_msat(&self) -> u64 {
526 self.hops.first().map(|h| h.0.path_penalty_msat).unwrap_or(u64::max_value())
529 fn get_total_fee_paid_msat(&self) -> u64 {
530 if self.hops.len() < 1 {
534 // Can't use next_hops_fee_msat because it gets outdated.
535 for (i, (hop, _)) in self.hops.iter().enumerate() {
536 if i != self.hops.len() - 1 {
537 result += hop.fee_msat;
543 fn get_cost_msat(&self) -> u64 {
544 self.get_total_fee_paid_msat().saturating_add(self.get_path_penalty_msat())
547 // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
548 // to change fees may result in an inconsistency.
550 // Sometimes we call this function right after constructing a path which is inconsistent in
551 // that it the value being transferred has decreased while we were doing path finding, leading
552 // to the fees being paid not lining up with the actual limits.
554 // Note that this function is not aware of the available_liquidity limit, and thus does not
555 // support increasing the value being transferred.
556 fn update_value_and_recompute_fees(&mut self, value_msat: u64) {
557 assert!(value_msat <= self.hops.last().unwrap().0.fee_msat);
559 let mut total_fee_paid_msat = 0 as u64;
560 for i in (0..self.hops.len()).rev() {
561 let last_hop = i == self.hops.len() - 1;
563 // For non-last-hop, this value will represent the fees paid on the current hop. It
564 // will consist of the fees for the use of the next hop, and extra fees to match
565 // htlc_minimum_msat of the current channel. Last hop is handled separately.
566 let mut cur_hop_fees_msat = 0;
568 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().0.hop_use_fee_msat;
571 let mut cur_hop = &mut self.hops.get_mut(i).unwrap().0;
572 cur_hop.next_hops_fee_msat = total_fee_paid_msat;
573 // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
574 // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
575 // set it too high just to maliciously take more fees by exploiting this
576 // match htlc_minimum_msat logic.
577 let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
578 if let Some(extra_fees_msat) = cur_hop.candidate.htlc_minimum_msat().checked_sub(cur_hop_transferred_amount_msat) {
579 // Note that there is a risk that *previous hops* (those closer to us, as we go
580 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
582 // This might make us end up with a broken route, although this should be super-rare
583 // in practice, both because of how healthy channels look like, and how we pick
584 // channels in add_entry.
585 // Also, this can't be exploited more heavily than *announce a free path and fail
587 cur_hop_transferred_amount_msat += extra_fees_msat;
588 total_fee_paid_msat += extra_fees_msat;
589 cur_hop_fees_msat += extra_fees_msat;
593 // Final hop is a special case: it usually has just value_msat (by design), but also
594 // it still could overpay for the htlc_minimum_msat.
595 cur_hop.fee_msat = cur_hop_transferred_amount_msat;
597 // Propagate updated fees for the use of the channels to one hop back, where they
598 // will be actually paid (fee_msat). The last hop is handled above separately.
599 cur_hop.fee_msat = cur_hop_fees_msat;
602 // Fee for the use of the current hop which will be deducted on the previous hop.
603 // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
604 // this channel is free for us.
606 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.candidate.fees()) {
607 cur_hop.hop_use_fee_msat = new_fee;
608 total_fee_paid_msat += new_fee;
610 // It should not be possible because this function is called only to reduce the
611 // value. In that case, compute_fee was already called with the same fees for
612 // larger amount and there was no overflow.
620 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
621 let proportional_fee_millions =
622 amount_msat.checked_mul(channel_fees.proportional_millionths as u64);
623 if let Some(new_fee) = proportional_fee_millions.and_then(|part| {
624 (channel_fees.base_msat as u64).checked_add(part / 1_000_000) }) {
628 // This function may be (indirectly) called without any verification,
629 // with channel_fees provided by a caller. We should handle it gracefully.
634 /// The default `features` we assume for a node in a route, when no `features` are known about that
637 /// Default features are:
638 /// * variable_length_onion_optional
639 fn default_node_features() -> NodeFeatures {
640 let mut features = NodeFeatures::empty();
641 features.set_variable_length_onion_optional();
645 /// Finds a route from us (payer) to the given target node (payee).
647 /// If the payee provided features in their invoice, they should be provided via `params.payee`.
648 /// Without this, MPP will only be used if the payee's features are available in the network graph.
650 /// Private routing paths between a public node and the target may be included in `params.payee`.
652 /// If some channels aren't announced, it may be useful to fill in `first_hops` with the results
653 /// from [`ChannelManager::list_usable_channels`]. If it is filled in, the view of our local
654 /// channels from [`NetworkGraph`] will be ignored, and only those in `first_hops` will be used.
656 /// The fees on channels from us to the next hop are ignored as they are assumed to all be equal.
657 /// However, the enabled/disabled bit on such channels as well as the `htlc_minimum_msat` /
658 /// `htlc_maximum_msat` *are* checked as they may change based on the receiving node.
662 /// May be used to re-compute a [`Route`] when handling a [`Event::PaymentPathFailed`]. Any
663 /// adjustments to the [`NetworkGraph`] and channel scores should be made prior to calling this
668 /// Panics if first_hops contains channels without short_channel_ids;
669 /// [`ChannelManager::list_usable_channels`] will never include such channels.
671 /// [`ChannelManager::list_usable_channels`]: crate::ln::channelmanager::ChannelManager::list_usable_channels
672 /// [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed
673 pub fn find_route<L: Deref, S: Score>(
674 our_node_pubkey: &PublicKey, route_params: &RouteParameters, network: &NetworkGraph,
675 first_hops: Option<&[&ChannelDetails]>, logger: L, scorer: &S, random_seed_bytes: &[u8; 32]
676 ) -> Result<Route, LightningError>
677 where L::Target: Logger {
678 let network_graph = network.read_only();
679 let mut route = get_route(our_node_pubkey, &route_params.payment_params, &network_graph, first_hops,
680 route_params.final_value_msat, route_params.final_cltv_expiry_delta, logger, scorer,
682 add_random_cltv_offset(&mut route, &route_params.payment_params, &network_graph, random_seed_bytes);
686 pub(crate) fn get_route<L: Deref, S: Score>(
687 our_node_pubkey: &PublicKey, payment_params: &PaymentParameters, network_graph: &ReadOnlyNetworkGraph,
688 first_hops: Option<&[&ChannelDetails]>, final_value_msat: u64, final_cltv_expiry_delta: u32,
689 logger: L, scorer: &S, random_seed_bytes: &[u8; 32]
690 ) -> Result<Route, LightningError>
691 where L::Target: Logger {
692 let payee_node_id = NodeId::from_pubkey(&payment_params.payee_pubkey);
693 let our_node_id = NodeId::from_pubkey(&our_node_pubkey);
695 if payee_node_id == our_node_id {
696 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
699 if final_value_msat > MAX_VALUE_MSAT {
700 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
703 if final_value_msat == 0 {
704 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
707 for route in payment_params.route_hints.iter() {
708 for hop in &route.0 {
709 if hop.src_node_id == payment_params.payee_pubkey {
710 return Err(LightningError{err: "Route hint cannot have the payee as the source.".to_owned(), action: ErrorAction::IgnoreError});
714 if payment_params.max_total_cltv_expiry_delta <= final_cltv_expiry_delta {
715 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});
718 // The general routing idea is the following:
719 // 1. Fill first/last hops communicated by the caller.
720 // 2. Attempt to construct a path from payer to payee for transferring
721 // any ~sufficient (described later) value.
722 // If succeed, remember which channels were used and how much liquidity they have available,
723 // so that future paths don't rely on the same liquidity.
724 // 3. Proceed to the next step if:
725 // - we hit the recommended target value;
726 // - OR if we could not construct a new path. Any next attempt will fail too.
727 // Otherwise, repeat step 2.
728 // 4. See if we managed to collect paths which aggregately are able to transfer target value
729 // (not recommended value).
730 // 5. If yes, proceed. If not, fail routing.
731 // 6. Randomly combine paths into routes having enough to fulfill the payment. (TODO: knapsack)
732 // 7. Of all the found paths, select only those with the lowest total fee.
733 // 8. The last path in every selected route is likely to be more than we need.
734 // Reduce its value-to-transfer and recompute fees.
735 // 9. Choose the best route by the lowest total fee.
737 // As for the actual search algorithm,
738 // we do a payee-to-payer pseudo-Dijkstra's sorting by each node's distance from the payee
739 // plus the minimum per-HTLC fee to get from it to another node (aka "shitty pseudo-A*").
741 // We are not a faithful Dijkstra's implementation because we can change values which impact
742 // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
743 // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) than
744 // the value we are currently attempting to send over a path, we simply reduce the value being
745 // sent along the path for any hops after that channel. This may imply that later fees (which
746 // we've already tabulated) are lower because a smaller value is passing through the channels
747 // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
748 // channels which were selected earlier (and which may still be used for other paths without a
749 // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
752 // One potentially problematic case for this algorithm would be if there are many
753 // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
754 // graph walking), we may never find a path which is not liquidity-limited and has lower
755 // proportional fee (and only lower absolute fee when considering the ultimate value sent).
756 // Because we only consider paths with at least 5% of the total value being sent, the damage
757 // from such a case should be limited, however this could be further reduced in the future by
758 // calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
759 // limits for the purposes of fee calculation.
761 // Alternatively, we could store more detailed path information in the heap (targets, below)
762 // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
763 // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
764 // and practically (as we would need to store dynamically-allocated path information in heap
765 // objects, increasing malloc traffic and indirect memory access significantly). Further, the
766 // results of such an algorithm would likely be biased towards lower-value paths.
768 // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
769 // outside of our current search value, running a path search more times to gather candidate
770 // paths at different values. While this may be acceptable, further path searches may increase
771 // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
772 // graph for candidate paths, calculating the maximum value which can realistically be sent at
773 // the same time, remaining generic across different payment values.
775 // TODO: There are a few tweaks we could do, including possibly pre-calculating more stuff
776 // to use as the A* heuristic beyond just the cost to get one node further than the current
779 let network_channels = network_graph.channels();
780 let network_nodes = network_graph.nodes();
782 // Allow MPP only if we have a features set from somewhere that indicates the payee supports
783 // it. If the payee supports it they're supposed to include it in the invoice, so that should
785 let allow_mpp = if let Some(features) = &payment_params.features {
786 features.supports_basic_mpp()
787 } else if let Some(node) = network_nodes.get(&payee_node_id) {
788 if let Some(node_info) = node.announcement_info.as_ref() {
789 node_info.features.supports_basic_mpp()
792 log_trace!(logger, "Searching for a route from payer {} to payee {} {} MPP and {} first hops {}overriding the network graph", our_node_pubkey,
793 payment_params.payee_pubkey, if allow_mpp { "with" } else { "without" },
794 first_hops.map(|hops| hops.len()).unwrap_or(0), if first_hops.is_some() { "" } else { "not " });
797 // Prepare the data we'll use for payee-to-payer search by
798 // inserting first hops suggested by the caller as targets.
799 // Our search will then attempt to reach them while traversing from the payee node.
800 let mut first_hop_targets: HashMap<_, Vec<&ChannelDetails>> =
801 HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
802 if let Some(hops) = first_hops {
804 if chan.get_outbound_payment_scid().is_none() {
805 panic!("first_hops should be filled in with usable channels, not pending ones");
807 if chan.counterparty.node_id == *our_node_pubkey {
808 return Err(LightningError{err: "First hop cannot have our_node_pubkey as a destination.".to_owned(), action: ErrorAction::IgnoreError});
811 .entry(NodeId::from_pubkey(&chan.counterparty.node_id))
812 .or_insert(Vec::new())
815 if first_hop_targets.is_empty() {
816 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
820 // The main heap containing all candidate next-hops sorted by their score (max(A* fee,
821 // htlc_minimum)). Ideally this would be a heap which allowed cheap score reduction instead of
822 // adding duplicate entries when we find a better path to a given node.
823 let mut targets: BinaryHeap<RouteGraphNode> = BinaryHeap::new();
825 // Map from node_id to information about the best current path to that node, including feerate
827 let mut dist: HashMap<NodeId, PathBuildingHop> = HashMap::with_capacity(network_nodes.len());
829 // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
830 // indicating that we may wish to try again with a higher value, potentially paying to meet an
831 // htlc_minimum with extra fees while still finding a cheaper path.
832 let mut hit_minimum_limit;
834 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
835 // We start with a path_value of the exact amount we want, and if that generates a route we may
836 // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
837 // amount we want in total across paths, selecting the best subset at the end.
838 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
839 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
840 let mut path_value_msat = final_value_msat;
842 // Keep track of how much liquidity has been used in selected channels. Used to determine
843 // if the channel can be used by additional MPP paths or to inform path finding decisions. It is
844 // aware of direction *only* to ensure that the correct htlc_maximum_msat value is used. Hence,
845 // liquidity used in one direction will not offset any used in the opposite direction.
846 let mut used_channel_liquidities: HashMap<(u64, bool), u64> =
847 HashMap::with_capacity(network_nodes.len());
849 // Keeping track of how much value we already collected across other paths. Helps to decide:
850 // - how much a new path should be transferring (upper bound);
851 // - whether a channel should be disregarded because
852 // it's available liquidity is too small comparing to how much more we need to collect;
853 // - when we want to stop looking for new paths.
854 let mut already_collected_value_msat = 0;
856 for (_, channels) in first_hop_targets.iter_mut() {
857 // Sort the first_hops channels to the same node(s) in priority order of which channel we'd
860 // First, if channels are below `recommended_value_msat`, sort them in descending order,
861 // preferring larger channels to avoid splitting the payment into more MPP parts than is
864 // Second, because simply always sorting in descending order would always use our largest
865 // available outbound capacity, needlessly fragmenting our available channel capacities,
866 // sort channels above `recommended_value_msat` in ascending order, preferring channels
867 // which have enough, but not too much, capacity for the payment.
868 channels.sort_unstable_by(|chan_a, chan_b| {
869 if chan_b.next_outbound_htlc_limit_msat < recommended_value_msat || chan_a.next_outbound_htlc_limit_msat < recommended_value_msat {
870 // Sort in descending order
871 chan_b.next_outbound_htlc_limit_msat.cmp(&chan_a.next_outbound_htlc_limit_msat)
873 // Sort in ascending order
874 chan_a.next_outbound_htlc_limit_msat.cmp(&chan_b.next_outbound_htlc_limit_msat)
879 log_trace!(logger, "Building path from {} (payee) to {} (us/payer) for value {} msat.", payment_params.payee_pubkey, our_node_pubkey, final_value_msat);
881 macro_rules! add_entry {
882 // Adds entry which goes from $src_node_id to $dest_node_id over the $candidate hop.
883 // $next_hops_fee_msat represents the fees paid for using all the channels *after* this one,
884 // since that value has to be transferred over this channel.
885 // Returns whether this channel caused an update to `targets`.
886 ( $candidate: expr, $src_node_id: expr, $dest_node_id: expr, $next_hops_fee_msat: expr,
887 $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr,
888 $next_hops_path_penalty_msat: expr, $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => { {
889 // We "return" whether we updated the path at the end, via this:
890 let mut did_add_update_path_to_src_node = false;
891 // Channels to self should not be used. This is more of belt-and-suspenders, because in
892 // practice these cases should be caught earlier:
893 // - for regular channels at channel announcement (TODO)
894 // - for first and last hops early in get_route
895 if $src_node_id != $dest_node_id {
896 let short_channel_id = $candidate.short_channel_id();
897 let htlc_maximum_msat = $candidate.htlc_maximum_msat();
899 // It is tricky to subtract $next_hops_fee_msat from available liquidity here.
900 // It may be misleading because we might later choose to reduce the value transferred
901 // over these channels, and the channel which was insufficient might become sufficient.
902 // Worst case: we drop a good channel here because it can't cover the high following
903 // fees caused by one expensive channel, but then this channel could have been used
904 // if the amount being transferred over this path is lower.
905 // We do this for now, but this is a subject for removal.
906 if let Some(mut available_value_contribution_msat) = htlc_maximum_msat.checked_sub($next_hops_fee_msat) {
907 let used_liquidity_msat = used_channel_liquidities
908 .get(&(short_channel_id, $src_node_id < $dest_node_id))
909 .map_or(0, |used_liquidity_msat| {
910 available_value_contribution_msat = available_value_contribution_msat
911 .saturating_sub(*used_liquidity_msat);
915 // Routing Fragmentation Mitigation heuristic:
917 // Routing fragmentation across many payment paths increases the overall routing
918 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
919 // Taking too many smaller paths also increases the chance of payment failure.
920 // Thus to avoid this effect, we require from our collected links to provide
921 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
923 // This requirement is currently 5% of the remaining-to-be-collected value.
924 // This means as we successfully advance in our collection,
925 // the absolute liquidity contribution is lowered,
926 // thus increasing the number of potential channels to be selected.
928 // Derive the minimal liquidity contribution with a ratio of 20 (5%, rounded up)
929 // or 100% if we're not allowed to do multipath payments.
930 let minimal_value_contribution_msat: u64 = if allow_mpp {
931 (recommended_value_msat - already_collected_value_msat + 19) / 20
935 // Verify the liquidity offered by this channel complies to the minimal contribution.
936 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
937 // Do not consider candidate hops that would exceed the maximum path length.
938 let path_length_to_node = $next_hops_path_length + 1;
939 let doesnt_exceed_max_path_length = path_length_to_node <= MAX_PATH_LENGTH_ESTIMATE;
941 // Do not consider candidates that exceed the maximum total cltv expiry limit.
942 // In order to already account for some of the privacy enhancing random CLTV
943 // expiry delta offset we add on top later, we subtract a rough estimate
944 // (2*MEDIAN_HOP_CLTV_EXPIRY_DELTA) here.
945 let max_total_cltv_expiry_delta = (payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta)
946 .checked_sub(2*MEDIAN_HOP_CLTV_EXPIRY_DELTA)
947 .unwrap_or(payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta);
948 let hop_total_cltv_delta = ($next_hops_cltv_delta as u32)
949 .saturating_add($candidate.cltv_expiry_delta());
950 let doesnt_exceed_cltv_delta_limit = hop_total_cltv_delta <= max_total_cltv_expiry_delta;
952 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
953 // Includes paying fees for the use of the following channels.
954 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
955 Some(result) => result,
956 // Can't overflow due to how the values were computed right above.
957 None => unreachable!(),
959 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
960 let over_path_minimum_msat = amount_to_transfer_over_msat >= $candidate.htlc_minimum_msat() &&
961 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
963 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
964 let may_overpay_to_meet_path_minimum_msat =
965 ((amount_to_transfer_over_msat < $candidate.htlc_minimum_msat() &&
966 recommended_value_msat > $candidate.htlc_minimum_msat()) ||
967 (amount_to_transfer_over_msat < $next_hops_path_htlc_minimum_msat &&
968 recommended_value_msat > $next_hops_path_htlc_minimum_msat));
970 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
971 // bother considering this channel. If retrying with recommended_value_msat may
972 // allow us to hit the HTLC minimum limit, set htlc_minimum_limit so that we go
973 // around again with a higher amount.
974 if contributes_sufficient_value && doesnt_exceed_max_path_length &&
975 doesnt_exceed_cltv_delta_limit && may_overpay_to_meet_path_minimum_msat {
976 hit_minimum_limit = true;
977 } else if contributes_sufficient_value && doesnt_exceed_max_path_length &&
978 doesnt_exceed_cltv_delta_limit && over_path_minimum_msat {
979 // Note that low contribution here (limited by available_liquidity_msat)
980 // might violate htlc_minimum_msat on the hops which are next along the
981 // payment path (upstream to the payee). To avoid that, we recompute
982 // path fees knowing the final path contribution after constructing it.
983 let path_htlc_minimum_msat = compute_fees($next_hops_path_htlc_minimum_msat, $candidate.fees())
984 .and_then(|fee_msat| fee_msat.checked_add($next_hops_path_htlc_minimum_msat))
985 .map(|fee_msat| cmp::max(fee_msat, $candidate.htlc_minimum_msat()))
986 .unwrap_or_else(|| u64::max_value());
987 let hm_entry = dist.entry($src_node_id);
988 let old_entry = hm_entry.or_insert_with(|| {
989 // If there was previously no known way to access the source node
990 // (recall it goes payee-to-payer) of short_channel_id, first add a
991 // semi-dummy record just to compute the fees to reach the source node.
992 // This will affect our decision on selecting short_channel_id
993 // as a way to reach the $dest_node_id.
994 let mut fee_base_msat = 0;
995 let mut fee_proportional_millionths = 0;
996 if let Some(Some(fees)) = network_nodes.get(&$src_node_id).map(|node| node.lowest_inbound_channel_fees) {
997 fee_base_msat = fees.base_msat;
998 fee_proportional_millionths = fees.proportional_millionths;
1001 node_id: $dest_node_id.clone(),
1002 candidate: $candidate.clone(),
1004 src_lowest_inbound_fees: RoutingFees {
1005 base_msat: fee_base_msat,
1006 proportional_millionths: fee_proportional_millionths,
1008 next_hops_fee_msat: u64::max_value(),
1009 hop_use_fee_msat: u64::max_value(),
1010 total_fee_msat: u64::max_value(),
1011 path_htlc_minimum_msat,
1012 path_penalty_msat: u64::max_value(),
1013 was_processed: false,
1014 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
1015 value_contribution_msat,
1019 #[allow(unused_mut)] // We only use the mut in cfg(test)
1020 let mut should_process = !old_entry.was_processed;
1021 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
1023 // In test/fuzzing builds, we do extra checks to make sure the skipping
1024 // of already-seen nodes only happens in cases we expect (see below).
1025 if !should_process { should_process = true; }
1029 let mut hop_use_fee_msat = 0;
1030 let mut total_fee_msat = $next_hops_fee_msat;
1032 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
1033 // will have the same effective-fee
1034 if $src_node_id != our_node_id {
1035 match compute_fees(amount_to_transfer_over_msat, $candidate.fees()) {
1036 // max_value means we'll always fail
1037 // the old_entry.total_fee_msat > total_fee_msat check
1038 None => total_fee_msat = u64::max_value(),
1040 hop_use_fee_msat = fee_msat;
1041 total_fee_msat += hop_use_fee_msat;
1042 // When calculating the lowest inbound fees to a node, we
1043 // calculate fees here not based on the actual value we think
1044 // will flow over this channel, but on the minimum value that
1045 // we'll accept flowing over it. The minimum accepted value
1046 // is a constant through each path collection run, ensuring
1047 // consistent basis. Otherwise we may later find a
1048 // different path to the source node that is more expensive,
1049 // but which we consider to be cheaper because we are capacity
1050 // constrained and the relative fee becomes lower.
1051 match compute_fees(minimal_value_contribution_msat, old_entry.src_lowest_inbound_fees)
1052 .map(|a| a.checked_add(total_fee_msat)) {
1057 total_fee_msat = u64::max_value();
1064 let channel_usage = ChannelUsage {
1065 amount_msat: amount_to_transfer_over_msat,
1066 inflight_htlc_msat: used_liquidity_msat,
1067 effective_capacity: $candidate.effective_capacity(),
1069 let channel_penalty_msat = scorer.channel_penalty_msat(
1070 short_channel_id, &$src_node_id, &$dest_node_id, channel_usage
1072 let path_penalty_msat = $next_hops_path_penalty_msat
1073 .saturating_add(channel_penalty_msat);
1074 let new_graph_node = RouteGraphNode {
1075 node_id: $src_node_id,
1076 lowest_fee_to_peer_through_node: total_fee_msat,
1077 lowest_fee_to_node: $next_hops_fee_msat as u64 + hop_use_fee_msat,
1078 total_cltv_delta: hop_total_cltv_delta,
1079 value_contribution_msat: value_contribution_msat,
1080 path_htlc_minimum_msat,
1082 path_length_to_node,
1085 // Update the way of reaching $src_node_id with the given short_channel_id (from $dest_node_id),
1086 // if this way is cheaper than the already known
1087 // (considering the cost to "reach" this channel from the route destination,
1088 // the cost of using this channel,
1089 // and the cost of routing to the source node of this channel).
1090 // Also, consider that htlc_minimum_msat_difference, because we might end up
1091 // paying it. Consider the following exploit:
1092 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
1093 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
1094 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
1095 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
1097 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
1098 // but it may require additional tracking - we don't want to double-count
1099 // the fees included in $next_hops_path_htlc_minimum_msat, but also
1100 // can't use something that may decrease on future hops.
1101 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat)
1102 .saturating_add(old_entry.path_penalty_msat);
1103 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat)
1104 .saturating_add(path_penalty_msat);
1106 if !old_entry.was_processed && new_cost < old_cost {
1107 targets.push(new_graph_node);
1108 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
1109 old_entry.hop_use_fee_msat = hop_use_fee_msat;
1110 old_entry.total_fee_msat = total_fee_msat;
1111 old_entry.node_id = $dest_node_id.clone();
1112 old_entry.candidate = $candidate.clone();
1113 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
1114 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
1115 old_entry.path_penalty_msat = path_penalty_msat;
1116 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
1118 old_entry.value_contribution_msat = value_contribution_msat;
1120 did_add_update_path_to_src_node = true;
1121 } else if old_entry.was_processed && new_cost < old_cost {
1122 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
1124 // If we're skipping processing a node which was previously
1125 // processed even though we found another path to it with a
1126 // cheaper fee, check that it was because the second path we
1127 // found (which we are processing now) has a lower value
1128 // contribution due to an HTLC minimum limit.
1130 // e.g. take a graph with two paths from node 1 to node 2, one
1131 // through channel A, and one through channel B. Channel A and
1132 // B are both in the to-process heap, with their scores set by
1133 // a higher htlc_minimum than fee.
1134 // Channel A is processed first, and the channels onwards from
1135 // node 1 are added to the to-process heap. Thereafter, we pop
1136 // Channel B off of the heap, note that it has a much more
1137 // restrictive htlc_maximum_msat, and recalculate the fees for
1138 // all of node 1's channels using the new, reduced, amount.
1140 // This would be bogus - we'd be selecting a higher-fee path
1141 // with a lower htlc_maximum_msat instead of the one we'd
1142 // already decided to use.
1143 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
1145 value_contribution_msat + path_penalty_msat <
1146 old_entry.value_contribution_msat + old_entry.path_penalty_msat
1154 did_add_update_path_to_src_node
1158 let default_node_features = default_node_features();
1160 // Find ways (channels with destination) to reach a given node and store them
1161 // in the corresponding data structures (routing graph etc).
1162 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
1163 // meaning how much will be paid in fees after this node (to the best of our knowledge).
1164 // This data can later be helpful to optimize routing (pay lower fees).
1165 macro_rules! add_entries_to_cheapest_to_target_node {
1166 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr, $next_hops_value_contribution: expr,
1167 $next_hops_path_htlc_minimum_msat: expr, $next_hops_path_penalty_msat: expr,
1168 $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => {
1169 let skip_node = if let Some(elem) = dist.get_mut(&$node_id) {
1170 let was_processed = elem.was_processed;
1171 elem.was_processed = true;
1174 // Entries are added to dist in add_entry!() when there is a channel from a node.
1175 // Because there are no channels from payee, it will not have a dist entry at this point.
1176 // If we're processing any other node, it is always be the result of a channel from it.
1177 assert_eq!($node_id, payee_node_id);
1182 if let Some(first_channels) = first_hop_targets.get(&$node_id) {
1183 for details in first_channels {
1184 let candidate = CandidateRouteHop::FirstHop { details };
1185 add_entry!(candidate, our_node_id, $node_id, $fee_to_target_msat,
1186 $next_hops_value_contribution,
1187 $next_hops_path_htlc_minimum_msat, $next_hops_path_penalty_msat,
1188 $next_hops_cltv_delta, $next_hops_path_length);
1192 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
1195 &default_node_features
1198 if !features.requires_unknown_bits() {
1199 for chan_id in $node.channels.iter() {
1200 let chan = network_channels.get(chan_id).unwrap();
1201 if !chan.features.requires_unknown_bits() {
1202 let (directed_channel, source) =
1203 chan.as_directed_to(&$node_id).expect("inconsistent NetworkGraph");
1204 if first_hops.is_none() || *source != our_node_id {
1205 if let Some(direction) = directed_channel.direction() {
1206 if direction.enabled {
1207 let candidate = CandidateRouteHop::PublicHop {
1208 info: directed_channel.with_update().unwrap(),
1209 short_channel_id: *chan_id,
1211 add_entry!(candidate, *source, $node_id,
1212 $fee_to_target_msat,
1213 $next_hops_value_contribution,
1214 $next_hops_path_htlc_minimum_msat,
1215 $next_hops_path_penalty_msat,
1216 $next_hops_cltv_delta, $next_hops_path_length);
1227 let mut payment_paths = Vec::<PaymentPath>::new();
1229 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
1230 'paths_collection: loop {
1231 // For every new path, start from scratch, except for used_channel_liquidities, which
1232 // helps to avoid reusing previously selected paths in future iterations.
1235 hit_minimum_limit = false;
1237 // If first hop is a private channel and the only way to reach the payee, this is the only
1238 // place where it could be added.
1239 if let Some(first_channels) = first_hop_targets.get(&payee_node_id) {
1240 for details in first_channels {
1241 let candidate = CandidateRouteHop::FirstHop { details };
1242 let added = add_entry!(candidate, our_node_id, payee_node_id, 0, path_value_msat,
1244 log_trace!(logger, "{} direct route to payee via SCID {}",
1245 if added { "Added" } else { "Skipped" }, candidate.short_channel_id());
1249 // Add the payee as a target, so that the payee-to-payer
1250 // search algorithm knows what to start with.
1251 match network_nodes.get(&payee_node_id) {
1252 // The payee is not in our network graph, so nothing to add here.
1253 // There is still a chance of reaching them via last_hops though,
1254 // so don't yet fail the payment here.
1255 // If not, targets.pop() will not even let us enter the loop in step 2.
1258 add_entries_to_cheapest_to_target_node!(node, payee_node_id, 0, path_value_msat, 0, 0u64, 0, 0);
1263 // If a caller provided us with last hops, add them to routing targets. Since this happens
1264 // earlier than general path finding, they will be somewhat prioritized, although currently
1265 // it matters only if the fees are exactly the same.
1266 for route in payment_params.route_hints.iter().filter(|route| !route.0.is_empty()) {
1267 let first_hop_in_route = &(route.0)[0];
1268 let have_hop_src_in_graph =
1269 // Only add the hops in this route to our candidate set if either
1270 // we have a direct channel to the first hop or the first hop is
1271 // in the regular network graph.
1272 first_hop_targets.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some() ||
1273 network_nodes.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some();
1274 if have_hop_src_in_graph {
1275 // We start building the path from reverse, i.e., from payee
1276 // to the first RouteHintHop in the path.
1277 let hop_iter = route.0.iter().rev();
1278 let prev_hop_iter = core::iter::once(&payment_params.payee_pubkey).chain(
1279 route.0.iter().skip(1).rev().map(|hop| &hop.src_node_id));
1280 let mut hop_used = true;
1281 let mut aggregate_next_hops_fee_msat: u64 = 0;
1282 let mut aggregate_next_hops_path_htlc_minimum_msat: u64 = 0;
1283 let mut aggregate_next_hops_path_penalty_msat: u64 = 0;
1284 let mut aggregate_next_hops_cltv_delta: u32 = 0;
1285 let mut aggregate_next_hops_path_length: u8 = 0;
1287 for (idx, (hop, prev_hop_id)) in hop_iter.zip(prev_hop_iter).enumerate() {
1288 let source = NodeId::from_pubkey(&hop.src_node_id);
1289 let target = NodeId::from_pubkey(&prev_hop_id);
1290 let candidate = network_channels
1291 .get(&hop.short_channel_id)
1292 .and_then(|channel| channel.as_directed_to(&target))
1293 .and_then(|(channel, _)| channel.with_update())
1294 .map(|info| CandidateRouteHop::PublicHop {
1296 short_channel_id: hop.short_channel_id,
1298 .unwrap_or_else(|| CandidateRouteHop::PrivateHop { hint: hop });
1300 if !add_entry!(candidate, source, target, aggregate_next_hops_fee_msat,
1301 path_value_msat, aggregate_next_hops_path_htlc_minimum_msat,
1302 aggregate_next_hops_path_penalty_msat,
1303 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length) {
1304 // If this hop was not used then there is no use checking the preceding
1305 // hops in the RouteHint. We can break by just searching for a direct
1306 // channel between last checked hop and first_hop_targets.
1310 let used_liquidity_msat = used_channel_liquidities
1311 .get(&(hop.short_channel_id, source < target)).copied().unwrap_or(0);
1312 let channel_usage = ChannelUsage {
1313 amount_msat: final_value_msat + aggregate_next_hops_fee_msat,
1314 inflight_htlc_msat: used_liquidity_msat,
1315 effective_capacity: candidate.effective_capacity(),
1317 let channel_penalty_msat = scorer.channel_penalty_msat(
1318 hop.short_channel_id, &source, &target, channel_usage
1320 aggregate_next_hops_path_penalty_msat = aggregate_next_hops_path_penalty_msat
1321 .saturating_add(channel_penalty_msat);
1323 aggregate_next_hops_cltv_delta = aggregate_next_hops_cltv_delta
1324 .saturating_add(hop.cltv_expiry_delta as u32);
1326 aggregate_next_hops_path_length = aggregate_next_hops_path_length
1329 // Searching for a direct channel between last checked hop and first_hop_targets
1330 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&prev_hop_id)) {
1331 for details in first_channels {
1332 let candidate = CandidateRouteHop::FirstHop { details };
1333 add_entry!(candidate, our_node_id, NodeId::from_pubkey(&prev_hop_id),
1334 aggregate_next_hops_fee_msat, path_value_msat,
1335 aggregate_next_hops_path_htlc_minimum_msat,
1336 aggregate_next_hops_path_penalty_msat, aggregate_next_hops_cltv_delta,
1337 aggregate_next_hops_path_length);
1345 // In the next values of the iterator, the aggregate fees already reflects
1346 // the sum of value sent from payer (final_value_msat) and routing fees
1347 // for the last node in the RouteHint. We need to just add the fees to
1348 // route through the current node so that the preceding node (next iteration)
1350 let hops_fee = compute_fees(aggregate_next_hops_fee_msat + final_value_msat, hop.fees)
1351 .map_or(None, |inc| inc.checked_add(aggregate_next_hops_fee_msat));
1352 aggregate_next_hops_fee_msat = if let Some(val) = hops_fee { val } else { break; };
1354 let hop_htlc_minimum_msat = candidate.htlc_minimum_msat();
1355 let hop_htlc_minimum_msat_inc = if let Some(val) = compute_fees(aggregate_next_hops_path_htlc_minimum_msat, hop.fees) { val } else { break; };
1356 let hops_path_htlc_minimum = aggregate_next_hops_path_htlc_minimum_msat
1357 .checked_add(hop_htlc_minimum_msat_inc);
1358 aggregate_next_hops_path_htlc_minimum_msat = if let Some(val) = hops_path_htlc_minimum { cmp::max(hop_htlc_minimum_msat, val) } else { break; };
1360 if idx == route.0.len() - 1 {
1361 // The last hop in this iterator is the first hop in
1362 // overall RouteHint.
1363 // If this hop connects to a node with which we have a direct channel,
1364 // ignore the network graph and, if the last hop was added, add our
1365 // direct channel to the candidate set.
1367 // Note that we *must* check if the last hop was added as `add_entry`
1368 // always assumes that the third argument is a node to which we have a
1370 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&hop.src_node_id)) {
1371 for details in first_channels {
1372 let candidate = CandidateRouteHop::FirstHop { details };
1373 add_entry!(candidate, our_node_id,
1374 NodeId::from_pubkey(&hop.src_node_id),
1375 aggregate_next_hops_fee_msat, path_value_msat,
1376 aggregate_next_hops_path_htlc_minimum_msat,
1377 aggregate_next_hops_path_penalty_msat,
1378 aggregate_next_hops_cltv_delta,
1379 aggregate_next_hops_path_length);
1387 log_trace!(logger, "Starting main path collection loop with {} nodes pre-filled from first/last hops.", targets.len());
1389 // At this point, targets are filled with the data from first and
1390 // last hops communicated by the caller, and the payment receiver.
1391 let mut found_new_path = false;
1394 // If this loop terminates due the exhaustion of targets, two situations are possible:
1395 // - not enough outgoing liquidity:
1396 // 0 < already_collected_value_msat < final_value_msat
1397 // - enough outgoing liquidity:
1398 // final_value_msat <= already_collected_value_msat < recommended_value_msat
1399 // Both these cases (and other cases except reaching recommended_value_msat) mean that
1400 // paths_collection will be stopped because found_new_path==false.
1401 // This is not necessarily a routing failure.
1402 '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() {
1404 // Since we're going payee-to-payer, hitting our node as a target means we should stop
1405 // traversing the graph and arrange the path out of what we found.
1406 if node_id == our_node_id {
1407 let mut new_entry = dist.remove(&our_node_id).unwrap();
1408 let mut ordered_hops: Vec<(PathBuildingHop, NodeFeatures)> = vec!((new_entry.clone(), default_node_features.clone()));
1411 let mut features_set = false;
1412 if let Some(first_channels) = first_hop_targets.get(&ordered_hops.last().unwrap().0.node_id) {
1413 for details in first_channels {
1414 if details.get_outbound_payment_scid().unwrap() == ordered_hops.last().unwrap().0.candidate.short_channel_id() {
1415 ordered_hops.last_mut().unwrap().1 = details.counterparty.features.to_context();
1416 features_set = true;
1422 if let Some(node) = network_nodes.get(&ordered_hops.last().unwrap().0.node_id) {
1423 if let Some(node_info) = node.announcement_info.as_ref() {
1424 ordered_hops.last_mut().unwrap().1 = node_info.features.clone();
1426 ordered_hops.last_mut().unwrap().1 = default_node_features.clone();
1429 // We can fill in features for everything except hops which were
1430 // provided via the invoice we're paying. We could guess based on the
1431 // recipient's features but for now we simply avoid guessing at all.
1435 // Means we succesfully traversed from the payer to the payee, now
1436 // save this path for the payment route. Also, update the liquidity
1437 // remaining on the used hops, so that we take them into account
1438 // while looking for more paths.
1439 if ordered_hops.last().unwrap().0.node_id == payee_node_id {
1443 new_entry = match dist.remove(&ordered_hops.last().unwrap().0.node_id) {
1444 Some(payment_hop) => payment_hop,
1445 // We can't arrive at None because, if we ever add an entry to targets,
1446 // we also fill in the entry in dist (see add_entry!).
1447 None => unreachable!(),
1449 // We "propagate" the fees one hop backward (topologically) here,
1450 // so that fees paid for a HTLC forwarding on the current channel are
1451 // associated with the previous channel (where they will be subtracted).
1452 ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
1453 ordered_hops.push((new_entry.clone(), default_node_features.clone()));
1455 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
1456 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
1458 log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: \n {:#?}",
1459 ordered_hops.len(), value_contribution_msat, ordered_hops.iter().map(|h| &(h.0)).collect::<Vec<&PathBuildingHop>>());
1461 let mut payment_path = PaymentPath {hops: ordered_hops};
1463 // We could have possibly constructed a slightly inconsistent path: since we reduce
1464 // value being transferred along the way, we could have violated htlc_minimum_msat
1465 // on some channels we already passed (assuming dest->source direction). Here, we
1466 // recompute the fees again, so that if that's the case, we match the currently
1467 // underpaid htlc_minimum_msat with fees.
1468 payment_path.update_value_and_recompute_fees(cmp::min(value_contribution_msat, final_value_msat));
1470 // Since a path allows to transfer as much value as
1471 // the smallest channel it has ("bottleneck"), we should recompute
1472 // the fees so sender HTLC don't overpay fees when traversing
1473 // larger channels than the bottleneck. This may happen because
1474 // when we were selecting those channels we were not aware how much value
1475 // this path will transfer, and the relative fee for them
1476 // might have been computed considering a larger value.
1477 // Remember that we used these channels so that we don't rely
1478 // on the same liquidity in future paths.
1479 let mut prevented_redundant_path_selection = false;
1480 let prev_hop_iter = core::iter::once(&our_node_id)
1481 .chain(payment_path.hops.iter().map(|(hop, _)| &hop.node_id));
1482 for (prev_hop, (hop, _)) in prev_hop_iter.zip(payment_path.hops.iter()) {
1483 let spent_on_hop_msat = value_contribution_msat + hop.next_hops_fee_msat;
1484 let used_liquidity_msat = used_channel_liquidities
1485 .entry((hop.candidate.short_channel_id(), *prev_hop < hop.node_id))
1486 .and_modify(|used_liquidity_msat| *used_liquidity_msat += spent_on_hop_msat)
1487 .or_insert(spent_on_hop_msat);
1488 if *used_liquidity_msat == hop.candidate.htlc_maximum_msat() {
1489 // If this path used all of this channel's available liquidity, we know
1490 // this path will not be selected again in the next loop iteration.
1491 prevented_redundant_path_selection = true;
1493 debug_assert!(*used_liquidity_msat <= hop.candidate.htlc_maximum_msat());
1495 if !prevented_redundant_path_selection {
1496 // If we weren't capped by hitting a liquidity limit on a channel in the path,
1497 // we'll probably end up picking the same path again on the next iteration.
1498 // Decrease the available liquidity of a hop in the middle of the path.
1499 let victim_scid = payment_path.hops[(payment_path.hops.len()) / 2].0.candidate.short_channel_id();
1500 let exhausted = u64::max_value();
1501 log_trace!(logger, "Disabling channel {} for future path building iterations to avoid duplicates.", victim_scid);
1502 *used_channel_liquidities.entry((victim_scid, false)).or_default() = exhausted;
1503 *used_channel_liquidities.entry((victim_scid, true)).or_default() = exhausted;
1506 // Track the total amount all our collected paths allow to send so that we:
1507 // - know when to stop looking for more paths
1508 // - know which of the hops are useless considering how much more sats we need
1509 // (contributes_sufficient_value)
1510 already_collected_value_msat += value_contribution_msat;
1512 payment_paths.push(payment_path);
1513 found_new_path = true;
1514 break 'path_construction;
1517 // If we found a path back to the payee, we shouldn't try to process it again. This is
1518 // the equivalent of the `elem.was_processed` check in
1519 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
1520 if node_id == payee_node_id { continue 'path_construction; }
1522 // Otherwise, since the current target node is not us,
1523 // keep "unrolling" the payment graph from payee to payer by
1524 // finding a way to reach the current target from the payer side.
1525 match network_nodes.get(&node_id) {
1528 add_entries_to_cheapest_to_target_node!(node, node_id, lowest_fee_to_node,
1529 value_contribution_msat, path_htlc_minimum_msat, path_penalty_msat,
1530 total_cltv_delta, path_length_to_node);
1536 // If we don't support MPP, no use trying to gather more value ever.
1537 break 'paths_collection;
1541 // Stop either when the recommended value is reached or if no new path was found in this
1543 // In the latter case, making another path finding attempt won't help,
1544 // because we deterministically terminated the search due to low liquidity.
1545 if already_collected_value_msat >= recommended_value_msat || !found_new_path {
1546 log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
1547 already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
1548 break 'paths_collection;
1549 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
1550 // Further, if this was our first walk of the graph, and we weren't limited by an
1551 // htlc_minimum_msat, return immediately because this path should suffice. If we were
1552 // limited by an htlc_minimum_msat value, find another path with a higher value,
1553 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
1554 // still keeping a lower total fee than this path.
1555 if !hit_minimum_limit {
1556 log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
1557 break 'paths_collection;
1559 log_trace!(logger, "Collected our payment amount on the first pass, but running again to collect extra paths with a potentially higher limit.");
1560 path_value_msat = recommended_value_msat;
1565 if payment_paths.len() == 0 {
1566 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1569 if already_collected_value_msat < final_value_msat {
1570 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1573 // Sort by total fees and take the best paths.
1574 payment_paths.sort_unstable_by_key(|path| path.get_total_fee_paid_msat());
1575 if payment_paths.len() > 50 {
1576 payment_paths.truncate(50);
1579 // Draw multiple sufficient routes by randomly combining the selected paths.
1580 let mut drawn_routes = Vec::new();
1581 let mut prng = ChaCha20::new(random_seed_bytes, &[0u8; 12]);
1582 let mut random_index_bytes = [0u8; ::core::mem::size_of::<usize>()];
1584 let num_permutations = payment_paths.len();
1585 for _ in 0..num_permutations {
1586 let mut cur_route = Vec::<PaymentPath>::new();
1587 let mut aggregate_route_value_msat = 0;
1590 // Do a Fisher-Yates shuffle to create a random permutation of the payment paths
1591 for cur_index in (1..payment_paths.len()).rev() {
1592 prng.process_in_place(&mut random_index_bytes);
1593 let random_index = usize::from_be_bytes(random_index_bytes).wrapping_rem(cur_index+1);
1594 payment_paths.swap(cur_index, random_index);
1598 for payment_path in &payment_paths {
1599 cur_route.push(payment_path.clone());
1600 aggregate_route_value_msat += payment_path.get_value_msat();
1601 if aggregate_route_value_msat > final_value_msat {
1602 // Last path likely overpaid. Substract it from the most expensive
1603 // (in terms of proportional fee) path in this route and recompute fees.
1604 // This might be not the most economically efficient way, but fewer paths
1605 // also makes routing more reliable.
1606 let mut overpaid_value_msat = aggregate_route_value_msat - final_value_msat;
1608 // First, we drop some expensive low-value paths entirely if possible, since fewer
1609 // paths is better: the payment is less likely to fail. In order to do so, we sort
1610 // by value and fall back to total fees paid, i.e., in case of equal values we
1611 // prefer lower cost paths.
1612 cur_route.sort_unstable_by(|a, b| {
1613 a.get_value_msat().cmp(&b.get_value_msat())
1614 // Reverse ordering for cost, so we drop higher-cost paths first
1615 .then_with(|| b.get_cost_msat().cmp(&a.get_cost_msat()))
1618 // We should make sure that at least 1 path left.
1619 let mut paths_left = cur_route.len();
1620 cur_route.retain(|path| {
1621 if paths_left == 1 {
1624 let mut keep = true;
1625 let path_value_msat = path.get_value_msat();
1626 if path_value_msat <= overpaid_value_msat {
1628 overpaid_value_msat -= path_value_msat;
1634 if overpaid_value_msat == 0 {
1638 assert!(cur_route.len() > 0);
1641 // Now, subtract the overpaid value from the most-expensive path.
1642 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1643 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1644 cur_route.sort_unstable_by_key(|path| { path.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>() });
1645 let expensive_payment_path = cur_route.first_mut().unwrap();
1647 // We already dropped all the small value paths above, meaning all the
1648 // remaining paths are larger than remaining overpaid_value_msat.
1649 // Thus, this can't be negative.
1650 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
1651 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
1655 drawn_routes.push(cur_route);
1659 // Select the best route by lowest total cost.
1660 drawn_routes.sort_unstable_by_key(|paths| paths.iter().map(|path| path.get_cost_msat()).sum::<u64>());
1661 let mut selected_paths = Vec::<Vec<Result<RouteHop, LightningError>>>::new();
1662 for payment_path in drawn_routes.first().unwrap() {
1663 let mut path = payment_path.hops.iter().map(|(payment_hop, node_features)| {
1665 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)})?,
1666 node_features: node_features.clone(),
1667 short_channel_id: payment_hop.candidate.short_channel_id(),
1668 channel_features: payment_hop.candidate.features(),
1669 fee_msat: payment_hop.fee_msat,
1670 cltv_expiry_delta: payment_hop.candidate.cltv_expiry_delta(),
1672 }).collect::<Vec<_>>();
1673 // Propagate the cltv_expiry_delta one hop backwards since the delta from the current hop is
1674 // applicable for the previous hop.
1675 path.iter_mut().rev().fold(final_cltv_expiry_delta, |prev_cltv_expiry_delta, hop| {
1676 core::mem::replace(&mut hop.as_mut().unwrap().cltv_expiry_delta, prev_cltv_expiry_delta)
1678 selected_paths.push(path);
1681 if let Some(features) = &payment_params.features {
1682 for path in selected_paths.iter_mut() {
1683 if let Ok(route_hop) = path.last_mut().unwrap() {
1684 route_hop.node_features = features.to_context();
1690 paths: selected_paths.into_iter().map(|path| path.into_iter().collect()).collect::<Result<Vec<_>, _>>()?,
1691 payment_params: Some(payment_params.clone()),
1693 log_info!(logger, "Got route to {}: {}", payment_params.payee_pubkey, log_route!(route));
1697 // When an adversarial intermediary node observes a payment, it may be able to infer its
1698 // destination, if the remaining CLTV expiry delta exactly matches a feasible path in the network
1699 // graph. In order to improve privacy, this method obfuscates the CLTV expiry deltas along the
1700 // payment path by adding a randomized 'shadow route' offset to the final hop.
1701 fn add_random_cltv_offset(route: &mut Route, payment_params: &PaymentParameters,
1702 network_graph: &ReadOnlyNetworkGraph, random_seed_bytes: &[u8; 32]
1704 let network_channels = network_graph.channels();
1705 let network_nodes = network_graph.nodes();
1707 for path in route.paths.iter_mut() {
1708 let mut shadow_ctlv_expiry_delta_offset: u32 = 0;
1710 // Remember the last three nodes of the random walk and avoid looping back on them.
1711 // Init with the last three nodes from the actual path, if possible.
1712 let mut nodes_to_avoid: [NodeId; 3] = [NodeId::from_pubkey(&path.last().unwrap().pubkey),
1713 NodeId::from_pubkey(&path.get(path.len().saturating_sub(2)).unwrap().pubkey),
1714 NodeId::from_pubkey(&path.get(path.len().saturating_sub(3)).unwrap().pubkey)];
1716 // Choose the last publicly known node as the starting point for the random walk.
1717 let mut cur_hop: Option<NodeId> = None;
1718 let mut path_nonce = [0u8; 12];
1719 if let Some(starting_hop) = path.iter().rev()
1720 .find(|h| network_nodes.contains_key(&NodeId::from_pubkey(&h.pubkey))) {
1721 cur_hop = Some(NodeId::from_pubkey(&starting_hop.pubkey));
1722 path_nonce.copy_from_slice(&cur_hop.unwrap().as_slice()[..12]);
1725 // Init PRNG with the path-dependant nonce, which is static for private paths.
1726 let mut prng = ChaCha20::new(random_seed_bytes, &path_nonce);
1727 let mut random_path_bytes = [0u8; ::core::mem::size_of::<usize>()];
1729 // Pick a random path length in [1 .. 3]
1730 prng.process_in_place(&mut random_path_bytes);
1731 let random_walk_length = usize::from_be_bytes(random_path_bytes).wrapping_rem(3).wrapping_add(1);
1733 for random_hop in 0..random_walk_length {
1734 // If we don't find a suitable offset in the public network graph, we default to
1735 // MEDIAN_HOP_CLTV_EXPIRY_DELTA.
1736 let mut random_hop_offset = MEDIAN_HOP_CLTV_EXPIRY_DELTA;
1738 if let Some(cur_node_id) = cur_hop {
1739 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
1740 // Randomly choose the next unvisited hop.
1741 prng.process_in_place(&mut random_path_bytes);
1742 if let Some(random_channel) = usize::from_be_bytes(random_path_bytes)
1743 .checked_rem(cur_node.channels.len())
1744 .and_then(|index| cur_node.channels.get(index))
1745 .and_then(|id| network_channels.get(id)) {
1746 random_channel.as_directed_from(&cur_node_id).map(|(dir_info, next_id)| {
1747 if !nodes_to_avoid.iter().any(|x| x == next_id) {
1748 nodes_to_avoid[random_hop] = *next_id;
1749 dir_info.direction().map(|channel_update_info| {
1750 random_hop_offset = channel_update_info.cltv_expiry_delta.into();
1751 cur_hop = Some(*next_id);
1759 shadow_ctlv_expiry_delta_offset = shadow_ctlv_expiry_delta_offset
1760 .checked_add(random_hop_offset)
1761 .unwrap_or(shadow_ctlv_expiry_delta_offset);
1764 // Limit the total offset to reduce the worst-case locked liquidity timevalue
1765 const MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET: u32 = 3*144;
1766 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET);
1768 // Limit the offset so we never exceed the max_total_cltv_expiry_delta. To improve plausibility,
1769 // we choose the limit to be the largest possible multiple of MEDIAN_HOP_CLTV_EXPIRY_DELTA.
1770 let path_total_cltv_expiry_delta: u32 = path.iter().map(|h| h.cltv_expiry_delta).sum();
1771 let mut max_path_offset = payment_params.max_total_cltv_expiry_delta - path_total_cltv_expiry_delta;
1772 max_path_offset = cmp::max(
1773 max_path_offset - (max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA),
1774 max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA);
1775 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, max_path_offset);
1777 // Add 'shadow' CLTV offset to the final hop
1778 if let Some(last_hop) = path.last_mut() {
1779 last_hop.cltv_expiry_delta = last_hop.cltv_expiry_delta
1780 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(last_hop.cltv_expiry_delta);
1785 /// Construct a route from us (payer) to the target node (payee) via the given hops (which should
1786 /// exclude the payer, but include the payee). This may be useful, e.g., for probing the chosen path.
1788 /// Re-uses logic from `find_route`, so the restrictions described there also apply here.
1789 pub fn build_route_from_hops<L: Deref>(
1790 our_node_pubkey: &PublicKey, hops: &[PublicKey], route_params: &RouteParameters, network: &NetworkGraph,
1791 logger: L, random_seed_bytes: &[u8; 32]
1792 ) -> Result<Route, LightningError>
1793 where L::Target: Logger {
1794 let network_graph = network.read_only();
1795 let mut route = build_route_from_hops_internal(
1796 our_node_pubkey, hops, &route_params.payment_params, &network_graph,
1797 route_params.final_value_msat, route_params.final_cltv_expiry_delta, logger, random_seed_bytes)?;
1798 add_random_cltv_offset(&mut route, &route_params.payment_params, &network_graph, random_seed_bytes);
1802 fn build_route_from_hops_internal<L: Deref>(
1803 our_node_pubkey: &PublicKey, hops: &[PublicKey], payment_params: &PaymentParameters,
1804 network_graph: &ReadOnlyNetworkGraph, final_value_msat: u64, final_cltv_expiry_delta: u32,
1805 logger: L, random_seed_bytes: &[u8; 32]
1806 ) -> Result<Route, LightningError> where L::Target: Logger {
1809 our_node_id: NodeId,
1810 hop_ids: [Option<NodeId>; MAX_PATH_LENGTH_ESTIMATE as usize],
1813 impl Score for HopScorer {
1814 fn channel_penalty_msat(&self, _short_channel_id: u64, source: &NodeId, target: &NodeId,
1815 _usage: ChannelUsage) -> u64
1817 let mut cur_id = self.our_node_id;
1818 for i in 0..self.hop_ids.len() {
1819 if let Some(next_id) = self.hop_ids[i] {
1820 if cur_id == *source && next_id == *target {
1831 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
1833 fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
1836 impl<'a> Writeable for HopScorer {
1838 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), io::Error> {
1843 if hops.len() > MAX_PATH_LENGTH_ESTIMATE.into() {
1844 return Err(LightningError{err: "Cannot build a route exceeding the maximum path length.".to_owned(), action: ErrorAction::IgnoreError});
1847 let our_node_id = NodeId::from_pubkey(our_node_pubkey);
1848 let mut hop_ids = [None; MAX_PATH_LENGTH_ESTIMATE as usize];
1849 for i in 0..hops.len() {
1850 hop_ids[i] = Some(NodeId::from_pubkey(&hops[i]));
1853 let scorer = HopScorer { our_node_id, hop_ids };
1855 get_route(our_node_pubkey, payment_params, network_graph, None, final_value_msat,
1856 final_cltv_expiry_delta, logger, &scorer, random_seed_bytes)
1861 use routing::network_graph::{NetworkGraph, NetGraphMsgHandler, NodeId};
1862 use routing::router::{get_route, build_route_from_hops_internal, add_random_cltv_offset, default_node_features,
1863 PaymentParameters, Route, RouteHint, RouteHintHop, RouteHop, RoutingFees,
1864 DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA, MAX_PATH_LENGTH_ESTIMATE};
1865 use routing::scoring::{ChannelUsage, Score};
1866 use chain::transaction::OutPoint;
1867 use chain::keysinterface::KeysInterface;
1868 use ln::features::{ChannelFeatures, InitFeatures, InvoiceFeatures, NodeFeatures};
1869 use ln::msgs::{ErrorAction, LightningError, OptionalField, UnsignedChannelAnnouncement, ChannelAnnouncement, RoutingMessageHandler,
1870 NodeAnnouncement, UnsignedNodeAnnouncement, ChannelUpdate, UnsignedChannelUpdate};
1871 use ln::channelmanager;
1872 use util::test_utils;
1873 use util::chacha20::ChaCha20;
1874 use util::ser::Writeable;
1876 use util::ser::Writer;
1878 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
1879 use bitcoin::hashes::Hash;
1880 use bitcoin::network::constants::Network;
1881 use bitcoin::blockdata::constants::genesis_block;
1882 use bitcoin::blockdata::script::Builder;
1883 use bitcoin::blockdata::opcodes;
1884 use bitcoin::blockdata::transaction::TxOut;
1888 use bitcoin::secp256k1::{PublicKey,SecretKey};
1889 use bitcoin::secp256k1::{Secp256k1, All};
1892 use sync::{self, Arc};
1894 fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
1895 features: InitFeatures, outbound_capacity_msat: u64) -> channelmanager::ChannelDetails {
1896 channelmanager::ChannelDetails {
1897 channel_id: [0; 32],
1898 counterparty: channelmanager::ChannelCounterparty {
1901 unspendable_punishment_reserve: 0,
1902 forwarding_info: None,
1903 outbound_htlc_minimum_msat: None,
1904 outbound_htlc_maximum_msat: None,
1906 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
1909 outbound_scid_alias: None,
1910 inbound_scid_alias: None,
1911 channel_value_satoshis: 0,
1914 outbound_capacity_msat,
1915 next_outbound_htlc_limit_msat: outbound_capacity_msat,
1916 inbound_capacity_msat: 42,
1917 unspendable_punishment_reserve: None,
1918 confirmations_required: None,
1919 force_close_spend_delay: None,
1920 is_outbound: true, is_channel_ready: true,
1921 is_usable: true, is_public: true,
1922 inbound_htlc_minimum_msat: None,
1923 inbound_htlc_maximum_msat: None,
1927 // Using the same keys for LN and BTC ids
1929 net_graph_msg_handler: &NetGraphMsgHandler<Arc<NetworkGraph>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1930 secp_ctx: &Secp256k1<All>, node_1_privkey: &SecretKey, node_2_privkey: &SecretKey, features: ChannelFeatures, short_channel_id: u64
1932 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1933 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1935 let unsigned_announcement = UnsignedChannelAnnouncement {
1937 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1941 bitcoin_key_1: node_id_1,
1942 bitcoin_key_2: node_id_2,
1943 excess_data: Vec::new(),
1946 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1947 let valid_announcement = ChannelAnnouncement {
1948 node_signature_1: secp_ctx.sign_ecdsa(&msghash, node_1_privkey),
1949 node_signature_2: secp_ctx.sign_ecdsa(&msghash, node_2_privkey),
1950 bitcoin_signature_1: secp_ctx.sign_ecdsa(&msghash, node_1_privkey),
1951 bitcoin_signature_2: secp_ctx.sign_ecdsa(&msghash, node_2_privkey),
1952 contents: unsigned_announcement.clone(),
1954 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1955 Ok(res) => assert!(res),
1961 net_graph_msg_handler: &NetGraphMsgHandler<Arc<NetworkGraph>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1962 secp_ctx: &Secp256k1<All>, node_privkey: &SecretKey, update: UnsignedChannelUpdate
1964 let msghash = hash_to_message!(&Sha256dHash::hash(&update.encode()[..])[..]);
1965 let valid_channel_update = ChannelUpdate {
1966 signature: secp_ctx.sign_ecdsa(&msghash, node_privkey),
1967 contents: update.clone()
1970 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1971 Ok(res) => assert!(res),
1976 fn add_or_update_node(
1977 net_graph_msg_handler: &NetGraphMsgHandler<Arc<NetworkGraph>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1978 secp_ctx: &Secp256k1<All>, node_privkey: &SecretKey, features: NodeFeatures, timestamp: u32
1980 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
1981 let unsigned_announcement = UnsignedNodeAnnouncement {
1987 addresses: Vec::new(),
1988 excess_address_data: Vec::new(),
1989 excess_data: Vec::new(),
1991 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1992 let valid_announcement = NodeAnnouncement {
1993 signature: secp_ctx.sign_ecdsa(&msghash, node_privkey),
1994 contents: unsigned_announcement.clone()
1997 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
2003 fn get_nodes(secp_ctx: &Secp256k1<All>) -> (SecretKey, PublicKey, Vec<SecretKey>, Vec<PublicKey>) {
2004 let privkeys: Vec<SecretKey> = (2..22).map(|i| {
2005 SecretKey::from_slice(&hex::decode(format!("{:02x}", i).repeat(32)).unwrap()[..]).unwrap()
2008 let pubkeys = privkeys.iter().map(|secret| PublicKey::from_secret_key(&secp_ctx, secret)).collect();
2010 let our_privkey = SecretKey::from_slice(&hex::decode("01".repeat(32)).unwrap()[..]).unwrap();
2011 let our_id = PublicKey::from_secret_key(&secp_ctx, &our_privkey);
2013 (our_privkey, our_id, privkeys, pubkeys)
2016 fn id_to_feature_flags(id: u8) -> Vec<u8> {
2017 // Set the feature flags to the id'th odd (ie non-required) feature bit so that we can
2018 // test for it later.
2019 let idx = (id - 1) * 2 + 1;
2021 vec![1 << (idx - 8*3), 0, 0, 0]
2022 } else if idx > 8*2 {
2023 vec![1 << (idx - 8*2), 0, 0]
2024 } else if idx > 8*1 {
2025 vec![1 << (idx - 8*1), 0]
2031 fn build_line_graph() -> (
2032 Secp256k1<All>, sync::Arc<NetworkGraph>, NetGraphMsgHandler<sync::Arc<NetworkGraph>,
2033 sync::Arc<test_utils::TestChainSource>, sync::Arc<crate::util::test_utils::TestLogger>>,
2034 sync::Arc<test_utils::TestChainSource>, sync::Arc<test_utils::TestLogger>,
2036 let secp_ctx = Secp256k1::new();
2037 let logger = Arc::new(test_utils::TestLogger::new());
2038 let chain_monitor = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
2039 let network_graph = Arc::new(NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash()));
2040 let net_graph_msg_handler = NetGraphMsgHandler::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
2042 // Build network from our_id to node 19:
2043 // our_id -1(1)2- node0 -1(2)2- node1 - ... - node19
2044 let (our_privkey, _, privkeys, _) = get_nodes(&secp_ctx);
2046 for (idx, (cur_privkey, next_privkey)) in core::iter::once(&our_privkey)
2047 .chain(privkeys.iter()).zip(privkeys.iter()).enumerate() {
2048 let cur_short_channel_id = (idx as u64) + 1;
2049 add_channel(&net_graph_msg_handler, &secp_ctx, &cur_privkey, &next_privkey,
2050 ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), cur_short_channel_id);
2051 update_channel(&net_graph_msg_handler, &secp_ctx, &cur_privkey, UnsignedChannelUpdate {
2052 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2053 short_channel_id: cur_short_channel_id,
2054 timestamp: idx as u32,
2056 cltv_expiry_delta: 0,
2057 htlc_minimum_msat: 0,
2058 htlc_maximum_msat: OptionalField::Absent,
2060 fee_proportional_millionths: 0,
2061 excess_data: Vec::new()
2063 update_channel(&net_graph_msg_handler, &secp_ctx, &next_privkey, UnsignedChannelUpdate {
2064 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2065 short_channel_id: cur_short_channel_id,
2066 timestamp: (idx as u32)+1,
2068 cltv_expiry_delta: 0,
2069 htlc_minimum_msat: 0,
2070 htlc_maximum_msat: OptionalField::Absent,
2072 fee_proportional_millionths: 0,
2073 excess_data: Vec::new()
2075 add_or_update_node(&net_graph_msg_handler, &secp_ctx, next_privkey,
2076 NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
2079 (secp_ctx, network_graph, net_graph_msg_handler, chain_monitor, logger)
2082 fn build_graph() -> (
2084 sync::Arc<NetworkGraph>,
2085 NetGraphMsgHandler<sync::Arc<NetworkGraph>, sync::Arc<test_utils::TestChainSource>, sync::Arc<crate::util::test_utils::TestLogger>>,
2086 sync::Arc<test_utils::TestChainSource>,
2087 sync::Arc<test_utils::TestLogger>,
2089 let secp_ctx = Secp256k1::new();
2090 let logger = Arc::new(test_utils::TestLogger::new());
2091 let chain_monitor = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
2092 let network_graph = Arc::new(NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash()));
2093 let net_graph_msg_handler = NetGraphMsgHandler::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
2094 // Build network from our_id to node6:
2096 // -1(1)2- node0 -1(3)2-
2098 // our_id -1(12)2- node7 -1(13)2--- node2
2100 // -1(2)2- node1 -1(4)2-
2103 // chan1 1-to-2: disabled
2104 // chan1 2-to-1: enabled, 0 fee
2106 // chan2 1-to-2: enabled, ignored fee
2107 // chan2 2-to-1: enabled, 0 fee
2109 // chan3 1-to-2: enabled, 0 fee
2110 // chan3 2-to-1: enabled, 100 msat fee
2112 // chan4 1-to-2: enabled, 100% fee
2113 // chan4 2-to-1: enabled, 0 fee
2115 // chan12 1-to-2: enabled, ignored fee
2116 // chan12 2-to-1: enabled, 0 fee
2118 // chan13 1-to-2: enabled, 200% fee
2119 // chan13 2-to-1: enabled, 0 fee
2122 // -1(5)2- node3 -1(8)2--
2126 // node2--1(6)2- node4 -1(9)2--- node6 (not in global route map)
2128 // -1(7)2- node5 -1(10)2-
2130 // Channels 5, 8, 9 and 10 are private channels.
2132 // chan5 1-to-2: enabled, 100 msat fee
2133 // chan5 2-to-1: enabled, 0 fee
2135 // chan6 1-to-2: enabled, 0 fee
2136 // chan6 2-to-1: enabled, 0 fee
2138 // chan7 1-to-2: enabled, 100% fee
2139 // chan7 2-to-1: enabled, 0 fee
2141 // chan8 1-to-2: enabled, variable fee (0 then 1000 msat)
2142 // chan8 2-to-1: enabled, 0 fee
2144 // chan9 1-to-2: enabled, 1001 msat fee
2145 // chan9 2-to-1: enabled, 0 fee
2147 // chan10 1-to-2: enabled, 0 fee
2148 // chan10 2-to-1: enabled, 0 fee
2150 // chan11 1-to-2: enabled, 0 fee
2151 // chan11 2-to-1: enabled, 0 fee
2153 let (our_privkey, _, privkeys, _) = get_nodes(&secp_ctx);
2155 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[0], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
2156 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2157 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2158 short_channel_id: 1,
2161 cltv_expiry_delta: 0,
2162 htlc_minimum_msat: 0,
2163 htlc_maximum_msat: OptionalField::Absent,
2165 fee_proportional_millionths: 0,
2166 excess_data: Vec::new()
2169 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
2171 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
2172 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2173 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2174 short_channel_id: 2,
2177 cltv_expiry_delta: (5 << 4) | 3,
2178 htlc_minimum_msat: 0,
2179 htlc_maximum_msat: OptionalField::Absent,
2180 fee_base_msat: u32::max_value(),
2181 fee_proportional_millionths: u32::max_value(),
2182 excess_data: Vec::new()
2184 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2185 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2186 short_channel_id: 2,
2189 cltv_expiry_delta: 0,
2190 htlc_minimum_msat: 0,
2191 htlc_maximum_msat: OptionalField::Absent,
2193 fee_proportional_millionths: 0,
2194 excess_data: Vec::new()
2197 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
2199 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[7], ChannelFeatures::from_le_bytes(id_to_feature_flags(12)), 12);
2200 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2201 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2202 short_channel_id: 12,
2205 cltv_expiry_delta: (5 << 4) | 3,
2206 htlc_minimum_msat: 0,
2207 htlc_maximum_msat: OptionalField::Absent,
2208 fee_base_msat: u32::max_value(),
2209 fee_proportional_millionths: u32::max_value(),
2210 excess_data: Vec::new()
2212 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2213 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2214 short_channel_id: 12,
2217 cltv_expiry_delta: 0,
2218 htlc_minimum_msat: 0,
2219 htlc_maximum_msat: OptionalField::Absent,
2221 fee_proportional_millionths: 0,
2222 excess_data: Vec::new()
2225 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], NodeFeatures::from_le_bytes(id_to_feature_flags(8)), 0);
2227 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
2228 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2229 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2230 short_channel_id: 3,
2233 cltv_expiry_delta: (3 << 4) | 1,
2234 htlc_minimum_msat: 0,
2235 htlc_maximum_msat: OptionalField::Absent,
2237 fee_proportional_millionths: 0,
2238 excess_data: Vec::new()
2240 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2241 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2242 short_channel_id: 3,
2245 cltv_expiry_delta: (3 << 4) | 2,
2246 htlc_minimum_msat: 0,
2247 htlc_maximum_msat: OptionalField::Absent,
2249 fee_proportional_millionths: 0,
2250 excess_data: Vec::new()
2253 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
2254 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2255 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2256 short_channel_id: 4,
2259 cltv_expiry_delta: (4 << 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[2], UnsignedChannelUpdate {
2267 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2268 short_channel_id: 4,
2271 cltv_expiry_delta: (4 << 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_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(13)), 13);
2280 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2281 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2282 short_channel_id: 13,
2285 cltv_expiry_delta: (13 << 4) | 1,
2286 htlc_minimum_msat: 0,
2287 htlc_maximum_msat: OptionalField::Absent,
2289 fee_proportional_millionths: 2000000,
2290 excess_data: Vec::new()
2292 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2293 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2294 short_channel_id: 13,
2297 cltv_expiry_delta: (13 << 4) | 2,
2298 htlc_minimum_msat: 0,
2299 htlc_maximum_msat: OptionalField::Absent,
2301 fee_proportional_millionths: 0,
2302 excess_data: Vec::new()
2305 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
2307 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
2308 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2309 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2310 short_channel_id: 6,
2313 cltv_expiry_delta: (6 << 4) | 1,
2314 htlc_minimum_msat: 0,
2315 htlc_maximum_msat: OptionalField::Absent,
2317 fee_proportional_millionths: 0,
2318 excess_data: Vec::new()
2320 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
2321 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2322 short_channel_id: 6,
2325 cltv_expiry_delta: (6 << 4) | 2,
2326 htlc_minimum_msat: 0,
2327 htlc_maximum_msat: OptionalField::Absent,
2329 fee_proportional_millionths: 0,
2330 excess_data: Vec::new(),
2333 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(11)), 11);
2334 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
2335 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2336 short_channel_id: 11,
2339 cltv_expiry_delta: (11 << 4) | 1,
2340 htlc_minimum_msat: 0,
2341 htlc_maximum_msat: OptionalField::Absent,
2343 fee_proportional_millionths: 0,
2344 excess_data: Vec::new()
2346 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
2347 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2348 short_channel_id: 11,
2351 cltv_expiry_delta: (11 << 4) | 2,
2352 htlc_minimum_msat: 0,
2353 htlc_maximum_msat: OptionalField::Absent,
2355 fee_proportional_millionths: 0,
2356 excess_data: Vec::new()
2359 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(5)), 0);
2361 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
2363 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[5], ChannelFeatures::from_le_bytes(id_to_feature_flags(7)), 7);
2364 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2365 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2366 short_channel_id: 7,
2369 cltv_expiry_delta: (7 << 4) | 1,
2370 htlc_minimum_msat: 0,
2371 htlc_maximum_msat: OptionalField::Absent,
2373 fee_proportional_millionths: 1000000,
2374 excess_data: Vec::new()
2376 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[5], UnsignedChannelUpdate {
2377 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2378 short_channel_id: 7,
2381 cltv_expiry_delta: (7 << 4) | 2,
2382 htlc_minimum_msat: 0,
2383 htlc_maximum_msat: OptionalField::Absent,
2385 fee_proportional_millionths: 0,
2386 excess_data: Vec::new()
2389 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[5], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
2391 (secp_ctx, network_graph, net_graph_msg_handler, chain_monitor, logger)
2395 fn simple_route_test() {
2396 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2397 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2398 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2399 let scorer = test_utils::TestScorer::with_penalty(0);
2400 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2401 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2403 // Simple route to 2 via 1
2405 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) {
2406 assert_eq!(err, "Cannot send a payment of 0 msat");
2407 } else { panic!(); }
2409 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2410 assert_eq!(route.paths[0].len(), 2);
2412 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2413 assert_eq!(route.paths[0][0].short_channel_id, 2);
2414 assert_eq!(route.paths[0][0].fee_msat, 100);
2415 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2416 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2417 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2419 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2420 assert_eq!(route.paths[0][1].short_channel_id, 4);
2421 assert_eq!(route.paths[0][1].fee_msat, 100);
2422 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2423 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2424 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2428 fn invalid_first_hop_test() {
2429 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2430 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2431 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2432 let scorer = test_utils::TestScorer::with_penalty(0);
2433 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2434 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2436 // Simple route to 2 via 1
2438 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
2440 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) =
2441 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) {
2442 assert_eq!(err, "First hop cannot have our_node_pubkey as a destination.");
2443 } else { panic!(); }
2445 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2446 assert_eq!(route.paths[0].len(), 2);
2450 fn htlc_minimum_test() {
2451 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2452 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2453 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2454 let scorer = test_utils::TestScorer::with_penalty(0);
2455 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2456 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2458 // Simple route to 2 via 1
2460 // Disable other paths
2461 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2462 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2463 short_channel_id: 12,
2465 flags: 2, // to disable
2466 cltv_expiry_delta: 0,
2467 htlc_minimum_msat: 0,
2468 htlc_maximum_msat: OptionalField::Absent,
2470 fee_proportional_millionths: 0,
2471 excess_data: Vec::new()
2473 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2474 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2475 short_channel_id: 3,
2477 flags: 2, // to disable
2478 cltv_expiry_delta: 0,
2479 htlc_minimum_msat: 0,
2480 htlc_maximum_msat: OptionalField::Absent,
2482 fee_proportional_millionths: 0,
2483 excess_data: Vec::new()
2485 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2486 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2487 short_channel_id: 13,
2489 flags: 2, // to disable
2490 cltv_expiry_delta: 0,
2491 htlc_minimum_msat: 0,
2492 htlc_maximum_msat: OptionalField::Absent,
2494 fee_proportional_millionths: 0,
2495 excess_data: Vec::new()
2497 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2498 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2499 short_channel_id: 6,
2501 flags: 2, // to disable
2502 cltv_expiry_delta: 0,
2503 htlc_minimum_msat: 0,
2504 htlc_maximum_msat: OptionalField::Absent,
2506 fee_proportional_millionths: 0,
2507 excess_data: Vec::new()
2509 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2510 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2511 short_channel_id: 7,
2513 flags: 2, // to disable
2514 cltv_expiry_delta: 0,
2515 htlc_minimum_msat: 0,
2516 htlc_maximum_msat: OptionalField::Absent,
2518 fee_proportional_millionths: 0,
2519 excess_data: Vec::new()
2522 // Check against amount_to_transfer_over_msat.
2523 // Set minimal HTLC of 200_000_000 msat.
2524 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2525 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2526 short_channel_id: 2,
2529 cltv_expiry_delta: 0,
2530 htlc_minimum_msat: 200_000_000,
2531 htlc_maximum_msat: OptionalField::Absent,
2533 fee_proportional_millionths: 0,
2534 excess_data: Vec::new()
2537 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
2539 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2540 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2541 short_channel_id: 4,
2544 cltv_expiry_delta: 0,
2545 htlc_minimum_msat: 0,
2546 htlc_maximum_msat: OptionalField::Present(199_999_999),
2548 fee_proportional_millionths: 0,
2549 excess_data: Vec::new()
2552 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
2553 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) {
2554 assert_eq!(err, "Failed to find a path to the given destination");
2555 } else { panic!(); }
2557 // Lift the restriction on the first hop.
2558 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2559 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2560 short_channel_id: 2,
2563 cltv_expiry_delta: 0,
2564 htlc_minimum_msat: 0,
2565 htlc_maximum_msat: OptionalField::Absent,
2567 fee_proportional_millionths: 0,
2568 excess_data: Vec::new()
2571 // A payment above the minimum should pass
2572 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();
2573 assert_eq!(route.paths[0].len(), 2);
2577 fn htlc_minimum_overpay_test() {
2578 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2579 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2580 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
2581 let scorer = test_utils::TestScorer::with_penalty(0);
2582 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2583 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2585 // A route to node#2 via two paths.
2586 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
2587 // Thus, they can't send 60 without overpaying.
2588 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2589 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2590 short_channel_id: 2,
2593 cltv_expiry_delta: 0,
2594 htlc_minimum_msat: 35_000,
2595 htlc_maximum_msat: OptionalField::Present(40_000),
2597 fee_proportional_millionths: 0,
2598 excess_data: Vec::new()
2600 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2601 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2602 short_channel_id: 12,
2605 cltv_expiry_delta: 0,
2606 htlc_minimum_msat: 35_000,
2607 htlc_maximum_msat: OptionalField::Present(40_000),
2609 fee_proportional_millionths: 0,
2610 excess_data: Vec::new()
2614 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2615 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2616 short_channel_id: 13,
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, &privkeys[1], UnsignedChannelUpdate {
2627 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2628 short_channel_id: 4,
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 // Disable other paths
2640 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2641 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2642 short_channel_id: 1,
2644 flags: 2, // to disable
2645 cltv_expiry_delta: 0,
2646 htlc_minimum_msat: 0,
2647 htlc_maximum_msat: OptionalField::Absent,
2649 fee_proportional_millionths: 0,
2650 excess_data: Vec::new()
2653 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 60_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2654 // Overpay fees to hit htlc_minimum_msat.
2655 let overpaid_fees = route.paths[0][0].fee_msat + route.paths[1][0].fee_msat;
2656 // TODO: this could be better balanced to overpay 10k and not 15k.
2657 assert_eq!(overpaid_fees, 15_000);
2659 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
2660 // while taking even more fee to match htlc_minimum_msat.
2661 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2662 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2663 short_channel_id: 12,
2666 cltv_expiry_delta: 0,
2667 htlc_minimum_msat: 65_000,
2668 htlc_maximum_msat: OptionalField::Present(80_000),
2670 fee_proportional_millionths: 0,
2671 excess_data: Vec::new()
2673 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2674 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2675 short_channel_id: 2,
2678 cltv_expiry_delta: 0,
2679 htlc_minimum_msat: 0,
2680 htlc_maximum_msat: OptionalField::Absent,
2682 fee_proportional_millionths: 0,
2683 excess_data: Vec::new()
2685 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2686 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2687 short_channel_id: 4,
2690 cltv_expiry_delta: 0,
2691 htlc_minimum_msat: 0,
2692 htlc_maximum_msat: OptionalField::Absent,
2694 fee_proportional_millionths: 100_000,
2695 excess_data: Vec::new()
2698 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 60_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2699 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
2700 assert_eq!(route.paths.len(), 1);
2701 assert_eq!(route.paths[0][0].short_channel_id, 12);
2702 let fees = route.paths[0][0].fee_msat;
2703 assert_eq!(fees, 5_000);
2705 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2706 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
2707 // the other channel.
2708 assert_eq!(route.paths.len(), 1);
2709 assert_eq!(route.paths[0][0].short_channel_id, 2);
2710 let fees = route.paths[0][0].fee_msat;
2711 assert_eq!(fees, 5_000);
2715 fn disable_channels_test() {
2716 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2717 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2718 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2719 let scorer = test_utils::TestScorer::with_penalty(0);
2720 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2721 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2723 // // Disable channels 4 and 12 by flags=2
2724 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2725 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2726 short_channel_id: 4,
2728 flags: 2, // to disable
2729 cltv_expiry_delta: 0,
2730 htlc_minimum_msat: 0,
2731 htlc_maximum_msat: OptionalField::Absent,
2733 fee_proportional_millionths: 0,
2734 excess_data: Vec::new()
2736 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2737 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2738 short_channel_id: 12,
2740 flags: 2, // to disable
2741 cltv_expiry_delta: 0,
2742 htlc_minimum_msat: 0,
2743 htlc_maximum_msat: OptionalField::Absent,
2745 fee_proportional_millionths: 0,
2746 excess_data: Vec::new()
2749 // If all the channels require some features we don't understand, route should fail
2750 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) {
2751 assert_eq!(err, "Failed to find a path to the given destination");
2752 } else { panic!(); }
2754 // If we specify a channel to node7, that overrides our local channel view and that gets used
2755 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2756 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();
2757 assert_eq!(route.paths[0].len(), 2);
2759 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2760 assert_eq!(route.paths[0][0].short_channel_id, 42);
2761 assert_eq!(route.paths[0][0].fee_msat, 200);
2762 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2763 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2764 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2766 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2767 assert_eq!(route.paths[0][1].short_channel_id, 13);
2768 assert_eq!(route.paths[0][1].fee_msat, 100);
2769 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2770 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2771 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2775 fn disable_node_test() {
2776 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2777 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2778 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2779 let scorer = test_utils::TestScorer::with_penalty(0);
2780 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2781 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2783 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
2784 let mut unknown_features = NodeFeatures::known();
2785 unknown_features.set_unknown_feature_required();
2786 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
2787 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
2788 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
2790 // If all nodes require some features we don't understand, route should fail
2791 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) {
2792 assert_eq!(err, "Failed to find a path to the given destination");
2793 } else { panic!(); }
2795 // If we specify a channel to node7, that overrides our local channel view and that gets used
2796 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2797 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();
2798 assert_eq!(route.paths[0].len(), 2);
2800 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2801 assert_eq!(route.paths[0][0].short_channel_id, 42);
2802 assert_eq!(route.paths[0][0].fee_msat, 200);
2803 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2804 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2805 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2807 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2808 assert_eq!(route.paths[0][1].short_channel_id, 13);
2809 assert_eq!(route.paths[0][1].fee_msat, 100);
2810 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2811 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2812 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2814 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
2815 // naively) assume that the user checked the feature bits on the invoice, which override
2816 // the node_announcement.
2820 fn our_chans_test() {
2821 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2822 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2823 let scorer = test_utils::TestScorer::with_penalty(0);
2824 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2825 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2827 // Route to 1 via 2 and 3 because our channel to 1 is disabled
2828 let payment_params = PaymentParameters::from_node_id(nodes[0]);
2829 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2830 assert_eq!(route.paths[0].len(), 3);
2832 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2833 assert_eq!(route.paths[0][0].short_channel_id, 2);
2834 assert_eq!(route.paths[0][0].fee_msat, 200);
2835 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2836 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2837 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2839 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2840 assert_eq!(route.paths[0][1].short_channel_id, 4);
2841 assert_eq!(route.paths[0][1].fee_msat, 100);
2842 assert_eq!(route.paths[0][1].cltv_expiry_delta, (3 << 4) | 2);
2843 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2844 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2846 assert_eq!(route.paths[0][2].pubkey, nodes[0]);
2847 assert_eq!(route.paths[0][2].short_channel_id, 3);
2848 assert_eq!(route.paths[0][2].fee_msat, 100);
2849 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
2850 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(1));
2851 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(3));
2853 // If we specify a channel to node7, that overrides our local channel view and that gets used
2854 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2855 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2856 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();
2857 assert_eq!(route.paths[0].len(), 2);
2859 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2860 assert_eq!(route.paths[0][0].short_channel_id, 42);
2861 assert_eq!(route.paths[0][0].fee_msat, 200);
2862 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2863 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2864 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2866 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2867 assert_eq!(route.paths[0][1].short_channel_id, 13);
2868 assert_eq!(route.paths[0][1].fee_msat, 100);
2869 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2870 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2871 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2874 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2875 let zero_fees = RoutingFees {
2877 proportional_millionths: 0,
2879 vec![RouteHint(vec![RouteHintHop {
2880 src_node_id: nodes[3],
2881 short_channel_id: 8,
2883 cltv_expiry_delta: (8 << 4) | 1,
2884 htlc_minimum_msat: None,
2885 htlc_maximum_msat: None,
2887 ]), RouteHint(vec![RouteHintHop {
2888 src_node_id: nodes[4],
2889 short_channel_id: 9,
2892 proportional_millionths: 0,
2894 cltv_expiry_delta: (9 << 4) | 1,
2895 htlc_minimum_msat: None,
2896 htlc_maximum_msat: None,
2897 }]), RouteHint(vec![RouteHintHop {
2898 src_node_id: nodes[5],
2899 short_channel_id: 10,
2901 cltv_expiry_delta: (10 << 4) | 1,
2902 htlc_minimum_msat: None,
2903 htlc_maximum_msat: None,
2907 fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2908 let zero_fees = RoutingFees {
2910 proportional_millionths: 0,
2912 vec![RouteHint(vec![RouteHintHop {
2913 src_node_id: nodes[2],
2914 short_channel_id: 5,
2917 proportional_millionths: 0,
2919 cltv_expiry_delta: (5 << 4) | 1,
2920 htlc_minimum_msat: None,
2921 htlc_maximum_msat: None,
2923 src_node_id: nodes[3],
2924 short_channel_id: 8,
2926 cltv_expiry_delta: (8 << 4) | 1,
2927 htlc_minimum_msat: None,
2928 htlc_maximum_msat: None,
2930 ]), RouteHint(vec![RouteHintHop {
2931 src_node_id: nodes[4],
2932 short_channel_id: 9,
2935 proportional_millionths: 0,
2937 cltv_expiry_delta: (9 << 4) | 1,
2938 htlc_minimum_msat: None,
2939 htlc_maximum_msat: None,
2940 }]), RouteHint(vec![RouteHintHop {
2941 src_node_id: nodes[5],
2942 short_channel_id: 10,
2944 cltv_expiry_delta: (10 << 4) | 1,
2945 htlc_minimum_msat: None,
2946 htlc_maximum_msat: None,
2951 fn partial_route_hint_test() {
2952 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2953 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2954 let scorer = test_utils::TestScorer::with_penalty(0);
2955 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2956 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2958 // Simple test across 2, 3, 5, and 4 via a last_hop channel
2959 // Tests the behaviour when the RouteHint contains a suboptimal hop.
2960 // RouteHint may be partially used by the algo to build the best path.
2962 // First check that last hop can't have its source as the payee.
2963 let invalid_last_hop = RouteHint(vec![RouteHintHop {
2964 src_node_id: nodes[6],
2965 short_channel_id: 8,
2968 proportional_millionths: 0,
2970 cltv_expiry_delta: (8 << 4) | 1,
2971 htlc_minimum_msat: None,
2972 htlc_maximum_msat: None,
2975 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
2976 invalid_last_hops.push(invalid_last_hop);
2978 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(invalid_last_hops);
2979 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) {
2980 assert_eq!(err, "Route hint cannot have the payee as the source.");
2981 } else { panic!(); }
2984 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops_multi_private_channels(&nodes));
2985 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2986 assert_eq!(route.paths[0].len(), 5);
2988 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2989 assert_eq!(route.paths[0][0].short_channel_id, 2);
2990 assert_eq!(route.paths[0][0].fee_msat, 100);
2991 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2992 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2993 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2995 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2996 assert_eq!(route.paths[0][1].short_channel_id, 4);
2997 assert_eq!(route.paths[0][1].fee_msat, 0);
2998 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
2999 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3000 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3002 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
3003 assert_eq!(route.paths[0][2].short_channel_id, 6);
3004 assert_eq!(route.paths[0][2].fee_msat, 0);
3005 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
3006 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
3007 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
3009 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
3010 assert_eq!(route.paths[0][3].short_channel_id, 11);
3011 assert_eq!(route.paths[0][3].fee_msat, 0);
3012 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
3013 // If we have a peer in the node map, we'll use their features here since we don't have
3014 // a way of figuring out their features from the invoice:
3015 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
3016 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
3018 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
3019 assert_eq!(route.paths[0][4].short_channel_id, 8);
3020 assert_eq!(route.paths[0][4].fee_msat, 100);
3021 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
3022 assert_eq!(route.paths[0][4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3023 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3026 fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3027 let zero_fees = RoutingFees {
3029 proportional_millionths: 0,
3031 vec![RouteHint(vec![RouteHintHop {
3032 src_node_id: nodes[3],
3033 short_channel_id: 8,
3035 cltv_expiry_delta: (8 << 4) | 1,
3036 htlc_minimum_msat: None,
3037 htlc_maximum_msat: None,
3038 }]), RouteHint(vec![
3040 ]), RouteHint(vec![RouteHintHop {
3041 src_node_id: nodes[5],
3042 short_channel_id: 10,
3044 cltv_expiry_delta: (10 << 4) | 1,
3045 htlc_minimum_msat: None,
3046 htlc_maximum_msat: None,
3051 fn ignores_empty_last_hops_test() {
3052 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3053 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3054 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(empty_last_hop(&nodes));
3055 let scorer = test_utils::TestScorer::with_penalty(0);
3056 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3057 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3059 // Test handling of an empty RouteHint passed in Invoice.
3061 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3062 assert_eq!(route.paths[0].len(), 5);
3064 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3065 assert_eq!(route.paths[0][0].short_channel_id, 2);
3066 assert_eq!(route.paths[0][0].fee_msat, 100);
3067 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
3068 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3069 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3071 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3072 assert_eq!(route.paths[0][1].short_channel_id, 4);
3073 assert_eq!(route.paths[0][1].fee_msat, 0);
3074 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
3075 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3076 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3078 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
3079 assert_eq!(route.paths[0][2].short_channel_id, 6);
3080 assert_eq!(route.paths[0][2].fee_msat, 0);
3081 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
3082 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
3083 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
3085 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
3086 assert_eq!(route.paths[0][3].short_channel_id, 11);
3087 assert_eq!(route.paths[0][3].fee_msat, 0);
3088 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
3089 // If we have a peer in the node map, we'll use their features here since we don't have
3090 // a way of figuring out their features from the invoice:
3091 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
3092 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
3094 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
3095 assert_eq!(route.paths[0][4].short_channel_id, 8);
3096 assert_eq!(route.paths[0][4].fee_msat, 100);
3097 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
3098 assert_eq!(route.paths[0][4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3099 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3102 /// Builds a trivial last-hop hint that passes through the two nodes given, with channel 0xff00
3104 fn multi_hop_last_hops_hint(hint_hops: [PublicKey; 2]) -> Vec<RouteHint> {
3105 let zero_fees = RoutingFees {
3107 proportional_millionths: 0,
3109 vec![RouteHint(vec![RouteHintHop {
3110 src_node_id: hint_hops[0],
3111 short_channel_id: 0xff00,
3114 proportional_millionths: 0,
3116 cltv_expiry_delta: (5 << 4) | 1,
3117 htlc_minimum_msat: None,
3118 htlc_maximum_msat: None,
3120 src_node_id: hint_hops[1],
3121 short_channel_id: 0xff01,
3123 cltv_expiry_delta: (8 << 4) | 1,
3124 htlc_minimum_msat: None,
3125 htlc_maximum_msat: None,
3130 fn multi_hint_last_hops_test() {
3131 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3132 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3133 let last_hops = multi_hop_last_hops_hint([nodes[2], nodes[3]]);
3134 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops.clone());
3135 let scorer = test_utils::TestScorer::with_penalty(0);
3136 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3137 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3138 // Test through channels 2, 3, 0xff00, 0xff01.
3139 // Test shows that multiple hop hints are considered.
3141 // Disabling channels 6 & 7 by flags=2
3142 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3143 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3144 short_channel_id: 6,
3146 flags: 2, // to disable
3147 cltv_expiry_delta: 0,
3148 htlc_minimum_msat: 0,
3149 htlc_maximum_msat: OptionalField::Absent,
3151 fee_proportional_millionths: 0,
3152 excess_data: Vec::new()
3154 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3155 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3156 short_channel_id: 7,
3158 flags: 2, // to disable
3159 cltv_expiry_delta: 0,
3160 htlc_minimum_msat: 0,
3161 htlc_maximum_msat: OptionalField::Absent,
3163 fee_proportional_millionths: 0,
3164 excess_data: Vec::new()
3167 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3168 assert_eq!(route.paths[0].len(), 4);
3170 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3171 assert_eq!(route.paths[0][0].short_channel_id, 2);
3172 assert_eq!(route.paths[0][0].fee_msat, 200);
3173 assert_eq!(route.paths[0][0].cltv_expiry_delta, 65);
3174 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3175 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3177 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3178 assert_eq!(route.paths[0][1].short_channel_id, 4);
3179 assert_eq!(route.paths[0][1].fee_msat, 100);
3180 assert_eq!(route.paths[0][1].cltv_expiry_delta, 81);
3181 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3182 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3184 assert_eq!(route.paths[0][2].pubkey, nodes[3]);
3185 assert_eq!(route.paths[0][2].short_channel_id, last_hops[0].0[0].short_channel_id);
3186 assert_eq!(route.paths[0][2].fee_msat, 0);
3187 assert_eq!(route.paths[0][2].cltv_expiry_delta, 129);
3188 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(4));
3189 assert_eq!(route.paths[0][2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3191 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
3192 assert_eq!(route.paths[0][3].short_channel_id, last_hops[0].0[1].short_channel_id);
3193 assert_eq!(route.paths[0][3].fee_msat, 100);
3194 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
3195 assert_eq!(route.paths[0][3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3196 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3200 fn private_multi_hint_last_hops_test() {
3201 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3202 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3204 let non_announced_privkey = SecretKey::from_slice(&hex::decode(format!("{:02x}", 0xf0).repeat(32)).unwrap()[..]).unwrap();
3205 let non_announced_pubkey = PublicKey::from_secret_key(&secp_ctx, &non_announced_privkey);
3207 let last_hops = multi_hop_last_hops_hint([nodes[2], non_announced_pubkey]);
3208 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops.clone());
3209 let scorer = test_utils::TestScorer::with_penalty(0);
3210 // Test through channels 2, 3, 0xff00, 0xff01.
3211 // Test shows that multiple hop hints are considered.
3213 // Disabling channels 6 & 7 by flags=2
3214 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3215 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3216 short_channel_id: 6,
3218 flags: 2, // to disable
3219 cltv_expiry_delta: 0,
3220 htlc_minimum_msat: 0,
3221 htlc_maximum_msat: OptionalField::Absent,
3223 fee_proportional_millionths: 0,
3224 excess_data: Vec::new()
3226 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3227 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3228 short_channel_id: 7,
3230 flags: 2, // to disable
3231 cltv_expiry_delta: 0,
3232 htlc_minimum_msat: 0,
3233 htlc_maximum_msat: OptionalField::Absent,
3235 fee_proportional_millionths: 0,
3236 excess_data: Vec::new()
3239 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &[42u8; 32]).unwrap();
3240 assert_eq!(route.paths[0].len(), 4);
3242 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3243 assert_eq!(route.paths[0][0].short_channel_id, 2);
3244 assert_eq!(route.paths[0][0].fee_msat, 200);
3245 assert_eq!(route.paths[0][0].cltv_expiry_delta, 65);
3246 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3247 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3249 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3250 assert_eq!(route.paths[0][1].short_channel_id, 4);
3251 assert_eq!(route.paths[0][1].fee_msat, 100);
3252 assert_eq!(route.paths[0][1].cltv_expiry_delta, 81);
3253 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3254 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3256 assert_eq!(route.paths[0][2].pubkey, non_announced_pubkey);
3257 assert_eq!(route.paths[0][2].short_channel_id, last_hops[0].0[0].short_channel_id);
3258 assert_eq!(route.paths[0][2].fee_msat, 0);
3259 assert_eq!(route.paths[0][2].cltv_expiry_delta, 129);
3260 assert_eq!(route.paths[0][2].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3261 assert_eq!(route.paths[0][2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3263 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
3264 assert_eq!(route.paths[0][3].short_channel_id, last_hops[0].0[1].short_channel_id);
3265 assert_eq!(route.paths[0][3].fee_msat, 100);
3266 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
3267 assert_eq!(route.paths[0][3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3268 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3271 fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3272 let zero_fees = RoutingFees {
3274 proportional_millionths: 0,
3276 vec![RouteHint(vec![RouteHintHop {
3277 src_node_id: nodes[4],
3278 short_channel_id: 11,
3280 cltv_expiry_delta: (11 << 4) | 1,
3281 htlc_minimum_msat: None,
3282 htlc_maximum_msat: None,
3284 src_node_id: nodes[3],
3285 short_channel_id: 8,
3287 cltv_expiry_delta: (8 << 4) | 1,
3288 htlc_minimum_msat: None,
3289 htlc_maximum_msat: None,
3290 }]), RouteHint(vec![RouteHintHop {
3291 src_node_id: nodes[4],
3292 short_channel_id: 9,
3295 proportional_millionths: 0,
3297 cltv_expiry_delta: (9 << 4) | 1,
3298 htlc_minimum_msat: None,
3299 htlc_maximum_msat: None,
3300 }]), RouteHint(vec![RouteHintHop {
3301 src_node_id: nodes[5],
3302 short_channel_id: 10,
3304 cltv_expiry_delta: (10 << 4) | 1,
3305 htlc_minimum_msat: None,
3306 htlc_maximum_msat: None,
3311 fn last_hops_with_public_channel_test() {
3312 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3313 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3314 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops_with_public_channel(&nodes));
3315 let scorer = test_utils::TestScorer::with_penalty(0);
3316 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3317 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3318 // This test shows that public routes can be present in the invoice
3319 // which would be handled in the same manner.
3321 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3322 assert_eq!(route.paths[0].len(), 5);
3324 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3325 assert_eq!(route.paths[0][0].short_channel_id, 2);
3326 assert_eq!(route.paths[0][0].fee_msat, 100);
3327 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
3328 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3329 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3331 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3332 assert_eq!(route.paths[0][1].short_channel_id, 4);
3333 assert_eq!(route.paths[0][1].fee_msat, 0);
3334 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
3335 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3336 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3338 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
3339 assert_eq!(route.paths[0][2].short_channel_id, 6);
3340 assert_eq!(route.paths[0][2].fee_msat, 0);
3341 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
3342 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
3343 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
3345 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
3346 assert_eq!(route.paths[0][3].short_channel_id, 11);
3347 assert_eq!(route.paths[0][3].fee_msat, 0);
3348 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
3349 // If we have a peer in the node map, we'll use their features here since we don't have
3350 // a way of figuring out their features from the invoice:
3351 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
3352 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
3354 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
3355 assert_eq!(route.paths[0][4].short_channel_id, 8);
3356 assert_eq!(route.paths[0][4].fee_msat, 100);
3357 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
3358 assert_eq!(route.paths[0][4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3359 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3363 fn our_chans_last_hop_connect_test() {
3364 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3365 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3366 let scorer = test_utils::TestScorer::with_penalty(0);
3367 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3368 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3370 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
3371 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3372 let mut last_hops = last_hops(&nodes);
3373 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops.clone());
3374 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();
3375 assert_eq!(route.paths[0].len(), 2);
3377 assert_eq!(route.paths[0][0].pubkey, nodes[3]);
3378 assert_eq!(route.paths[0][0].short_channel_id, 42);
3379 assert_eq!(route.paths[0][0].fee_msat, 0);
3380 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 4) | 1);
3381 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
3382 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3384 assert_eq!(route.paths[0][1].pubkey, nodes[6]);
3385 assert_eq!(route.paths[0][1].short_channel_id, 8);
3386 assert_eq!(route.paths[0][1].fee_msat, 100);
3387 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
3388 assert_eq!(route.paths[0][1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3389 assert_eq!(route.paths[0][1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3391 last_hops[0].0[0].fees.base_msat = 1000;
3393 // Revert to via 6 as the fee on 8 goes up
3394 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops);
3395 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3396 assert_eq!(route.paths[0].len(), 4);
3398 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3399 assert_eq!(route.paths[0][0].short_channel_id, 2);
3400 assert_eq!(route.paths[0][0].fee_msat, 200); // fee increased as its % of value transferred across node
3401 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
3402 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3403 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3405 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3406 assert_eq!(route.paths[0][1].short_channel_id, 4);
3407 assert_eq!(route.paths[0][1].fee_msat, 100);
3408 assert_eq!(route.paths[0][1].cltv_expiry_delta, (7 << 4) | 1);
3409 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3410 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3412 assert_eq!(route.paths[0][2].pubkey, nodes[5]);
3413 assert_eq!(route.paths[0][2].short_channel_id, 7);
3414 assert_eq!(route.paths[0][2].fee_msat, 0);
3415 assert_eq!(route.paths[0][2].cltv_expiry_delta, (10 << 4) | 1);
3416 // If we have a peer in the node map, we'll use their features here since we don't have
3417 // a way of figuring out their features from the invoice:
3418 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
3419 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(7));
3421 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
3422 assert_eq!(route.paths[0][3].short_channel_id, 10);
3423 assert_eq!(route.paths[0][3].fee_msat, 100);
3424 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
3425 assert_eq!(route.paths[0][3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3426 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3428 // ...but still use 8 for larger payments as 6 has a variable feerate
3429 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 2000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3430 assert_eq!(route.paths[0].len(), 5);
3432 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3433 assert_eq!(route.paths[0][0].short_channel_id, 2);
3434 assert_eq!(route.paths[0][0].fee_msat, 3000);
3435 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
3436 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3437 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3439 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3440 assert_eq!(route.paths[0][1].short_channel_id, 4);
3441 assert_eq!(route.paths[0][1].fee_msat, 0);
3442 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
3443 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3444 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3446 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
3447 assert_eq!(route.paths[0][2].short_channel_id, 6);
3448 assert_eq!(route.paths[0][2].fee_msat, 0);
3449 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
3450 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
3451 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
3453 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
3454 assert_eq!(route.paths[0][3].short_channel_id, 11);
3455 assert_eq!(route.paths[0][3].fee_msat, 1000);
3456 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
3457 // If we have a peer in the node map, we'll use their features here since we don't have
3458 // a way of figuring out their features from the invoice:
3459 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
3460 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
3462 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
3463 assert_eq!(route.paths[0][4].short_channel_id, 8);
3464 assert_eq!(route.paths[0][4].fee_msat, 2000);
3465 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
3466 assert_eq!(route.paths[0][4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3467 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3470 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> {
3471 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
3472 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3473 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3475 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
3476 let last_hops = RouteHint(vec![RouteHintHop {
3477 src_node_id: middle_node_id,
3478 short_channel_id: 8,
3481 proportional_millionths: last_hop_fee_prop,
3483 cltv_expiry_delta: (8 << 4) | 1,
3484 htlc_minimum_msat: None,
3485 htlc_maximum_msat: last_hop_htlc_max,
3487 let payment_params = PaymentParameters::from_node_id(target_node_id).with_route_hints(vec![last_hops]);
3488 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
3489 let scorer = test_utils::TestScorer::with_penalty(0);
3490 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3491 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3492 get_route(&source_node_id, &payment_params, &NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash()).read_only(),
3493 Some(&our_chans.iter().collect::<Vec<_>>()), route_val, 42, &test_utils::TestLogger::new(), &scorer, &random_seed_bytes)
3497 fn unannounced_path_test() {
3498 // We should be able to send a payment to a destination without any help of a routing graph
3499 // if we have a channel with a common counterparty that appears in the first and last hop
3501 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
3503 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3504 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3505 assert_eq!(route.paths[0].len(), 2);
3507 assert_eq!(route.paths[0][0].pubkey, middle_node_id);
3508 assert_eq!(route.paths[0][0].short_channel_id, 42);
3509 assert_eq!(route.paths[0][0].fee_msat, 1001);
3510 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 4) | 1);
3511 assert_eq!(route.paths[0][0].node_features.le_flags(), &[0b11]);
3512 assert_eq!(route.paths[0][0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3514 assert_eq!(route.paths[0][1].pubkey, target_node_id);
3515 assert_eq!(route.paths[0][1].short_channel_id, 8);
3516 assert_eq!(route.paths[0][1].fee_msat, 1000000);
3517 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
3518 assert_eq!(route.paths[0][1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3519 assert_eq!(route.paths[0][1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3523 fn overflow_unannounced_path_test_liquidity_underflow() {
3524 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
3525 // the last-hop had a fee which overflowed a u64, we'd panic.
3526 // This was due to us adding the first-hop from us unconditionally, causing us to think
3527 // we'd built a path (as our node is in the "best candidate" set), when we had not.
3528 // In this test, we previously hit a subtraction underflow due to having less available
3529 // liquidity at the last hop than 0.
3530 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());
3534 fn overflow_unannounced_path_test_feerate_overflow() {
3535 // This tests for the same case as above, except instead of hitting a subtraction
3536 // underflow, we hit a case where the fee charged at a hop overflowed.
3537 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());
3541 fn available_amount_while_routing_test() {
3542 // Tests whether we choose the correct available channel amount while routing.
3544 let (secp_ctx, network_graph, mut net_graph_msg_handler, chain_monitor, logger) = build_graph();
3545 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3546 let scorer = test_utils::TestScorer::with_penalty(0);
3547 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3548 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3549 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
3551 // We will use a simple single-path route from
3552 // our node to node2 via node0: channels {1, 3}.
3554 // First disable all other paths.
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: 2,
3560 cltv_expiry_delta: 0,
3561 htlc_minimum_msat: 0,
3562 htlc_maximum_msat: OptionalField::Present(100_000),
3564 fee_proportional_millionths: 0,
3565 excess_data: Vec::new()
3567 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3568 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3569 short_channel_id: 12,
3572 cltv_expiry_delta: 0,
3573 htlc_minimum_msat: 0,
3574 htlc_maximum_msat: OptionalField::Present(100_000),
3576 fee_proportional_millionths: 0,
3577 excess_data: Vec::new()
3580 // Make the first channel (#1) very permissive,
3581 // and we will be testing all limits on the second channel.
3582 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3583 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3584 short_channel_id: 1,
3587 cltv_expiry_delta: 0,
3588 htlc_minimum_msat: 0,
3589 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3591 fee_proportional_millionths: 0,
3592 excess_data: Vec::new()
3595 // First, let's see if routing works if we have absolutely no idea about the available amount.
3596 // In this case, it should be set to 250_000 sats.
3597 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3598 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3599 short_channel_id: 3,
3602 cltv_expiry_delta: 0,
3603 htlc_minimum_msat: 0,
3604 htlc_maximum_msat: OptionalField::Absent,
3606 fee_proportional_millionths: 0,
3607 excess_data: Vec::new()
3611 // Attempt to route more than available results in a failure.
3612 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3613 &our_id, &payment_params, &network_graph.read_only(), None, 250_000_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3614 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3615 } else { panic!(); }
3619 // Now, attempt to route an exact amount we have should be fine.
3620 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();
3621 assert_eq!(route.paths.len(), 1);
3622 let path = route.paths.last().unwrap();
3623 assert_eq!(path.len(), 2);
3624 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3625 assert_eq!(path.last().unwrap().fee_msat, 250_000_000);
3628 // Check that setting next_outbound_htlc_limit_msat in first_hops limits the channels.
3629 // Disable channel #1 and use another first hop.
3630 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3631 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3632 short_channel_id: 1,
3635 cltv_expiry_delta: 0,
3636 htlc_minimum_msat: 0,
3637 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3639 fee_proportional_millionths: 0,
3640 excess_data: Vec::new()
3643 // Now, limit the first_hop by the next_outbound_htlc_limit_msat of 200_000 sats.
3644 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
3647 // Attempt to route more than available results in a failure.
3648 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3649 &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) {
3650 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3651 } else { panic!(); }
3655 // Now, attempt to route an exact amount we have should be fine.
3656 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();
3657 assert_eq!(route.paths.len(), 1);
3658 let path = route.paths.last().unwrap();
3659 assert_eq!(path.len(), 2);
3660 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3661 assert_eq!(path.last().unwrap().fee_msat, 200_000_000);
3664 // Enable channel #1 back.
3665 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3666 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3667 short_channel_id: 1,
3670 cltv_expiry_delta: 0,
3671 htlc_minimum_msat: 0,
3672 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3674 fee_proportional_millionths: 0,
3675 excess_data: Vec::new()
3679 // Now let's see if routing works if we know only htlc_maximum_msat.
3680 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3681 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3682 short_channel_id: 3,
3685 cltv_expiry_delta: 0,
3686 htlc_minimum_msat: 0,
3687 htlc_maximum_msat: OptionalField::Present(15_000),
3689 fee_proportional_millionths: 0,
3690 excess_data: Vec::new()
3694 // Attempt to route more than available results in a failure.
3695 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3696 &our_id, &payment_params, &network_graph.read_only(), None, 15_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3697 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3698 } else { panic!(); }
3702 // Now, attempt to route an exact amount we have should be fine.
3703 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 15_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3704 assert_eq!(route.paths.len(), 1);
3705 let path = route.paths.last().unwrap();
3706 assert_eq!(path.len(), 2);
3707 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3708 assert_eq!(path.last().unwrap().fee_msat, 15_000);
3711 // Now let's see if routing works if we know only capacity from the UTXO.
3713 // We can't change UTXO capacity on the fly, so we'll disable
3714 // the existing channel and add another one with the capacity we need.
3715 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3716 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3717 short_channel_id: 3,
3720 cltv_expiry_delta: 0,
3721 htlc_minimum_msat: 0,
3722 htlc_maximum_msat: OptionalField::Absent,
3724 fee_proportional_millionths: 0,
3725 excess_data: Vec::new()
3728 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
3729 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
3730 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
3731 .push_opcode(opcodes::all::OP_PUSHNUM_2)
3732 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
3734 *chain_monitor.utxo_ret.lock().unwrap() = Ok(TxOut { value: 15, script_pubkey: good_script.clone() });
3735 net_graph_msg_handler.add_chain_access(Some(chain_monitor));
3737 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
3738 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3739 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3740 short_channel_id: 333,
3743 cltv_expiry_delta: (3 << 4) | 1,
3744 htlc_minimum_msat: 0,
3745 htlc_maximum_msat: OptionalField::Absent,
3747 fee_proportional_millionths: 0,
3748 excess_data: Vec::new()
3750 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3751 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3752 short_channel_id: 333,
3755 cltv_expiry_delta: (3 << 4) | 2,
3756 htlc_minimum_msat: 0,
3757 htlc_maximum_msat: OptionalField::Absent,
3759 fee_proportional_millionths: 0,
3760 excess_data: Vec::new()
3764 // Attempt to route more than available results in a failure.
3765 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3766 &our_id, &payment_params, &network_graph.read_only(), None, 15_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3767 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3768 } else { panic!(); }
3772 // Now, attempt to route an exact amount we have should be fine.
3773 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 15_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3774 assert_eq!(route.paths.len(), 1);
3775 let path = route.paths.last().unwrap();
3776 assert_eq!(path.len(), 2);
3777 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3778 assert_eq!(path.last().unwrap().fee_msat, 15_000);
3781 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
3782 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3783 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3784 short_channel_id: 333,
3787 cltv_expiry_delta: 0,
3788 htlc_minimum_msat: 0,
3789 htlc_maximum_msat: OptionalField::Present(10_000),
3791 fee_proportional_millionths: 0,
3792 excess_data: Vec::new()
3796 // Attempt to route more than available results in a failure.
3797 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3798 &our_id, &payment_params, &network_graph.read_only(), None, 10_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3799 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3800 } else { panic!(); }
3804 // Now, attempt to route an exact amount we have should be fine.
3805 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 10_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3806 assert_eq!(route.paths.len(), 1);
3807 let path = route.paths.last().unwrap();
3808 assert_eq!(path.len(), 2);
3809 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3810 assert_eq!(path.last().unwrap().fee_msat, 10_000);
3815 fn available_liquidity_last_hop_test() {
3816 // Check that available liquidity properly limits the path even when only
3817 // one of the latter hops is limited.
3818 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3819 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3820 let scorer = test_utils::TestScorer::with_penalty(0);
3821 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3822 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3823 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
3825 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3826 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
3827 // Total capacity: 50 sats.
3829 // Disable other potential paths.
3830 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3831 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3832 short_channel_id: 2,
3835 cltv_expiry_delta: 0,
3836 htlc_minimum_msat: 0,
3837 htlc_maximum_msat: OptionalField::Present(100_000),
3839 fee_proportional_millionths: 0,
3840 excess_data: Vec::new()
3842 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3843 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3844 short_channel_id: 7,
3847 cltv_expiry_delta: 0,
3848 htlc_minimum_msat: 0,
3849 htlc_maximum_msat: OptionalField::Present(100_000),
3851 fee_proportional_millionths: 0,
3852 excess_data: Vec::new()
3857 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3858 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3859 short_channel_id: 12,
3862 cltv_expiry_delta: 0,
3863 htlc_minimum_msat: 0,
3864 htlc_maximum_msat: OptionalField::Present(100_000),
3866 fee_proportional_millionths: 0,
3867 excess_data: Vec::new()
3869 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3870 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3871 short_channel_id: 13,
3874 cltv_expiry_delta: 0,
3875 htlc_minimum_msat: 0,
3876 htlc_maximum_msat: OptionalField::Present(100_000),
3878 fee_proportional_millionths: 0,
3879 excess_data: Vec::new()
3882 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3883 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3884 short_channel_id: 6,
3887 cltv_expiry_delta: 0,
3888 htlc_minimum_msat: 0,
3889 htlc_maximum_msat: OptionalField::Present(50_000),
3891 fee_proportional_millionths: 0,
3892 excess_data: Vec::new()
3894 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3895 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3896 short_channel_id: 11,
3899 cltv_expiry_delta: 0,
3900 htlc_minimum_msat: 0,
3901 htlc_maximum_msat: OptionalField::Present(100_000),
3903 fee_proportional_millionths: 0,
3904 excess_data: Vec::new()
3907 // Attempt to route more than available results in a failure.
3908 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3909 &our_id, &payment_params, &network_graph.read_only(), None, 60_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3910 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3911 } else { panic!(); }
3915 // Now, attempt to route 49 sats (just a bit below the capacity).
3916 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 49_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3917 assert_eq!(route.paths.len(), 1);
3918 let mut total_amount_paid_msat = 0;
3919 for path in &route.paths {
3920 assert_eq!(path.len(), 4);
3921 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3922 total_amount_paid_msat += path.last().unwrap().fee_msat;
3924 assert_eq!(total_amount_paid_msat, 49_000);
3928 // Attempt to route an exact amount is also fine
3929 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3930 assert_eq!(route.paths.len(), 1);
3931 let mut total_amount_paid_msat = 0;
3932 for path in &route.paths {
3933 assert_eq!(path.len(), 4);
3934 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3935 total_amount_paid_msat += path.last().unwrap().fee_msat;
3937 assert_eq!(total_amount_paid_msat, 50_000);
3942 fn ignore_fee_first_hop_test() {
3943 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3944 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3945 let scorer = test_utils::TestScorer::with_penalty(0);
3946 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3947 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3948 let payment_params = PaymentParameters::from_node_id(nodes[2]);
3950 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
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: 1,
3956 cltv_expiry_delta: 0,
3957 htlc_minimum_msat: 0,
3958 htlc_maximum_msat: OptionalField::Present(100_000),
3959 fee_base_msat: 1_000_000,
3960 fee_proportional_millionths: 0,
3961 excess_data: Vec::new()
3963 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3964 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3965 short_channel_id: 3,
3968 cltv_expiry_delta: 0,
3969 htlc_minimum_msat: 0,
3970 htlc_maximum_msat: OptionalField::Present(50_000),
3972 fee_proportional_millionths: 0,
3973 excess_data: Vec::new()
3977 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3978 assert_eq!(route.paths.len(), 1);
3979 let mut total_amount_paid_msat = 0;
3980 for path in &route.paths {
3981 assert_eq!(path.len(), 2);
3982 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3983 total_amount_paid_msat += path.last().unwrap().fee_msat;
3985 assert_eq!(total_amount_paid_msat, 50_000);
3990 fn simple_mpp_route_test() {
3991 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3992 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3993 let scorer = test_utils::TestScorer::with_penalty(0);
3994 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3995 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3996 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
3998 // We need a route consisting of 3 paths:
3999 // From our node to node2 via node0, node7, node1 (three paths one hop each).
4000 // To achieve this, the amount being transferred should be around
4001 // the total capacity of these 3 paths.
4003 // First, we set limits on these (previously unlimited) channels.
4004 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
4006 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
4007 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4008 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4009 short_channel_id: 1,
4012 cltv_expiry_delta: 0,
4013 htlc_minimum_msat: 0,
4014 htlc_maximum_msat: OptionalField::Present(100_000),
4016 fee_proportional_millionths: 0,
4017 excess_data: Vec::new()
4019 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4020 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4021 short_channel_id: 3,
4024 cltv_expiry_delta: 0,
4025 htlc_minimum_msat: 0,
4026 htlc_maximum_msat: OptionalField::Present(50_000),
4028 fee_proportional_millionths: 0,
4029 excess_data: Vec::new()
4032 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
4033 // (total limit 60).
4034 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4035 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4036 short_channel_id: 12,
4039 cltv_expiry_delta: 0,
4040 htlc_minimum_msat: 0,
4041 htlc_maximum_msat: OptionalField::Present(60_000),
4043 fee_proportional_millionths: 0,
4044 excess_data: Vec::new()
4046 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4047 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4048 short_channel_id: 13,
4051 cltv_expiry_delta: 0,
4052 htlc_minimum_msat: 0,
4053 htlc_maximum_msat: OptionalField::Present(60_000),
4055 fee_proportional_millionths: 0,
4056 excess_data: Vec::new()
4059 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
4060 // (total capacity 180 sats).
4061 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4062 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4063 short_channel_id: 2,
4066 cltv_expiry_delta: 0,
4067 htlc_minimum_msat: 0,
4068 htlc_maximum_msat: OptionalField::Present(200_000),
4070 fee_proportional_millionths: 0,
4071 excess_data: Vec::new()
4073 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4074 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4075 short_channel_id: 4,
4078 cltv_expiry_delta: 0,
4079 htlc_minimum_msat: 0,
4080 htlc_maximum_msat: OptionalField::Present(180_000),
4082 fee_proportional_millionths: 0,
4083 excess_data: Vec::new()
4087 // Attempt to route more than available results in a failure.
4088 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4089 &our_id, &payment_params, &network_graph.read_only(), None, 300_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
4090 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4091 } else { panic!(); }
4095 // Now, attempt to route 250 sats (just a bit below the capacity).
4096 // Our algorithm should provide us with these 3 paths.
4097 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 250_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4098 assert_eq!(route.paths.len(), 3);
4099 let mut total_amount_paid_msat = 0;
4100 for path in &route.paths {
4101 assert_eq!(path.len(), 2);
4102 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4103 total_amount_paid_msat += path.last().unwrap().fee_msat;
4105 assert_eq!(total_amount_paid_msat, 250_000);
4109 // Attempt to route an exact amount is also fine
4110 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 290_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4111 assert_eq!(route.paths.len(), 3);
4112 let mut total_amount_paid_msat = 0;
4113 for path in &route.paths {
4114 assert_eq!(path.len(), 2);
4115 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4116 total_amount_paid_msat += path.last().unwrap().fee_msat;
4118 assert_eq!(total_amount_paid_msat, 290_000);
4123 fn long_mpp_route_test() {
4124 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4125 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4126 let scorer = test_utils::TestScorer::with_penalty(0);
4127 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4128 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4129 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
4131 // We need a route consisting of 3 paths:
4132 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
4133 // Note that these paths overlap (channels 5, 12, 13).
4134 // We will route 300 sats.
4135 // Each path will have 100 sats capacity, those channels which
4136 // are used twice will have 200 sats capacity.
4138 // Disable other potential paths.
4139 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4140 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4141 short_channel_id: 2,
4144 cltv_expiry_delta: 0,
4145 htlc_minimum_msat: 0,
4146 htlc_maximum_msat: OptionalField::Present(100_000),
4148 fee_proportional_millionths: 0,
4149 excess_data: Vec::new()
4151 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4152 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4153 short_channel_id: 7,
4156 cltv_expiry_delta: 0,
4157 htlc_minimum_msat: 0,
4158 htlc_maximum_msat: OptionalField::Present(100_000),
4160 fee_proportional_millionths: 0,
4161 excess_data: Vec::new()
4164 // Path via {node0, node2} is channels {1, 3, 5}.
4165 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4166 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4167 short_channel_id: 1,
4170 cltv_expiry_delta: 0,
4171 htlc_minimum_msat: 0,
4172 htlc_maximum_msat: OptionalField::Present(100_000),
4174 fee_proportional_millionths: 0,
4175 excess_data: Vec::new()
4177 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4178 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4179 short_channel_id: 3,
4182 cltv_expiry_delta: 0,
4183 htlc_minimum_msat: 0,
4184 htlc_maximum_msat: OptionalField::Present(100_000),
4186 fee_proportional_millionths: 0,
4187 excess_data: Vec::new()
4190 // Capacity of 200 sats because this channel will be used by 3rd path as well.
4191 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4192 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4193 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4194 short_channel_id: 5,
4197 cltv_expiry_delta: 0,
4198 htlc_minimum_msat: 0,
4199 htlc_maximum_msat: OptionalField::Present(200_000),
4201 fee_proportional_millionths: 0,
4202 excess_data: Vec::new()
4205 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4206 // Add 100 sats to the capacities of {12, 13}, because these channels
4207 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
4208 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4209 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4210 short_channel_id: 12,
4213 cltv_expiry_delta: 0,
4214 htlc_minimum_msat: 0,
4215 htlc_maximum_msat: OptionalField::Present(200_000),
4217 fee_proportional_millionths: 0,
4218 excess_data: Vec::new()
4220 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4221 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4222 short_channel_id: 13,
4225 cltv_expiry_delta: 0,
4226 htlc_minimum_msat: 0,
4227 htlc_maximum_msat: OptionalField::Present(200_000),
4229 fee_proportional_millionths: 0,
4230 excess_data: Vec::new()
4233 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4234 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4235 short_channel_id: 6,
4238 cltv_expiry_delta: 0,
4239 htlc_minimum_msat: 0,
4240 htlc_maximum_msat: OptionalField::Present(100_000),
4242 fee_proportional_millionths: 0,
4243 excess_data: Vec::new()
4245 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4246 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4247 short_channel_id: 11,
4250 cltv_expiry_delta: 0,
4251 htlc_minimum_msat: 0,
4252 htlc_maximum_msat: OptionalField::Present(100_000),
4254 fee_proportional_millionths: 0,
4255 excess_data: Vec::new()
4258 // Path via {node7, node2} is channels {12, 13, 5}.
4259 // We already limited them to 200 sats (they are used twice for 100 sats).
4260 // Nothing to do here.
4263 // Attempt to route more than available results in a failure.
4264 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4265 &our_id, &payment_params, &network_graph.read_only(), None, 350_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
4266 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4267 } else { panic!(); }
4271 // Now, attempt to route 300 sats (exact amount we can route).
4272 // Our algorithm should provide us with these 3 paths, 100 sats each.
4273 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 300_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4274 assert_eq!(route.paths.len(), 3);
4276 let mut total_amount_paid_msat = 0;
4277 for path in &route.paths {
4278 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
4279 total_amount_paid_msat += path.last().unwrap().fee_msat;
4281 assert_eq!(total_amount_paid_msat, 300_000);
4287 fn mpp_cheaper_route_test() {
4288 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4289 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4290 let scorer = test_utils::TestScorer::with_penalty(0);
4291 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4292 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4293 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
4295 // This test checks that if we have two cheaper paths and one more expensive path,
4296 // so that liquidity-wise any 2 of 3 combination is sufficient,
4297 // two cheaper paths will be taken.
4298 // These paths have equal available liquidity.
4300 // We need a combination of 3 paths:
4301 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
4302 // Note that these paths overlap (channels 5, 12, 13).
4303 // Each path will have 100 sats capacity, those channels which
4304 // are used twice will have 200 sats capacity.
4306 // Disable other potential paths.
4307 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4308 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4309 short_channel_id: 2,
4312 cltv_expiry_delta: 0,
4313 htlc_minimum_msat: 0,
4314 htlc_maximum_msat: OptionalField::Present(100_000),
4316 fee_proportional_millionths: 0,
4317 excess_data: Vec::new()
4319 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4320 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4321 short_channel_id: 7,
4324 cltv_expiry_delta: 0,
4325 htlc_minimum_msat: 0,
4326 htlc_maximum_msat: OptionalField::Present(100_000),
4328 fee_proportional_millionths: 0,
4329 excess_data: Vec::new()
4332 // Path via {node0, node2} is channels {1, 3, 5}.
4333 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4334 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4335 short_channel_id: 1,
4338 cltv_expiry_delta: 0,
4339 htlc_minimum_msat: 0,
4340 htlc_maximum_msat: OptionalField::Present(100_000),
4342 fee_proportional_millionths: 0,
4343 excess_data: Vec::new()
4345 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4346 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4347 short_channel_id: 3,
4350 cltv_expiry_delta: 0,
4351 htlc_minimum_msat: 0,
4352 htlc_maximum_msat: OptionalField::Present(100_000),
4354 fee_proportional_millionths: 0,
4355 excess_data: Vec::new()
4358 // Capacity of 200 sats because this channel will be used by 3rd path as well.
4359 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4360 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4361 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4362 short_channel_id: 5,
4365 cltv_expiry_delta: 0,
4366 htlc_minimum_msat: 0,
4367 htlc_maximum_msat: OptionalField::Present(200_000),
4369 fee_proportional_millionths: 0,
4370 excess_data: Vec::new()
4373 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4374 // Add 100 sats to the capacities of {12, 13}, because these channels
4375 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
4376 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4377 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4378 short_channel_id: 12,
4381 cltv_expiry_delta: 0,
4382 htlc_minimum_msat: 0,
4383 htlc_maximum_msat: OptionalField::Present(200_000),
4385 fee_proportional_millionths: 0,
4386 excess_data: Vec::new()
4388 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4389 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4390 short_channel_id: 13,
4393 cltv_expiry_delta: 0,
4394 htlc_minimum_msat: 0,
4395 htlc_maximum_msat: OptionalField::Present(200_000),
4397 fee_proportional_millionths: 0,
4398 excess_data: Vec::new()
4401 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4402 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4403 short_channel_id: 6,
4406 cltv_expiry_delta: 0,
4407 htlc_minimum_msat: 0,
4408 htlc_maximum_msat: OptionalField::Present(100_000),
4409 fee_base_msat: 1_000,
4410 fee_proportional_millionths: 0,
4411 excess_data: Vec::new()
4413 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4414 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4415 short_channel_id: 11,
4418 cltv_expiry_delta: 0,
4419 htlc_minimum_msat: 0,
4420 htlc_maximum_msat: OptionalField::Present(100_000),
4422 fee_proportional_millionths: 0,
4423 excess_data: Vec::new()
4426 // Path via {node7, node2} is channels {12, 13, 5}.
4427 // We already limited them to 200 sats (they are used twice for 100 sats).
4428 // Nothing to do here.
4431 // Now, attempt to route 180 sats.
4432 // Our algorithm should provide us with these 2 paths.
4433 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 180_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4434 assert_eq!(route.paths.len(), 2);
4436 let mut total_value_transferred_msat = 0;
4437 let mut total_paid_msat = 0;
4438 for path in &route.paths {
4439 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
4440 total_value_transferred_msat += path.last().unwrap().fee_msat;
4442 total_paid_msat += hop.fee_msat;
4445 // If we paid fee, this would be higher.
4446 assert_eq!(total_value_transferred_msat, 180_000);
4447 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
4448 assert_eq!(total_fees_paid, 0);
4453 fn fees_on_mpp_route_test() {
4454 // This test makes sure that MPP algorithm properly takes into account
4455 // fees charged on the channels, by making the fees impactful:
4456 // if the fee is not properly accounted for, the behavior is different.
4457 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4458 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4459 let scorer = test_utils::TestScorer::with_penalty(0);
4460 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4461 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4462 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
4464 // We need a route consisting of 2 paths:
4465 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
4466 // We will route 200 sats, Each path will have 100 sats capacity.
4468 // This test is not particularly stable: e.g.,
4469 // there's a way to route via {node0, node2, node4}.
4470 // It works while pathfinding is deterministic, but can be broken otherwise.
4471 // It's fine to ignore this concern for now.
4473 // Disable other potential paths.
4474 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4475 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4476 short_channel_id: 2,
4479 cltv_expiry_delta: 0,
4480 htlc_minimum_msat: 0,
4481 htlc_maximum_msat: OptionalField::Present(100_000),
4483 fee_proportional_millionths: 0,
4484 excess_data: Vec::new()
4487 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4488 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4489 short_channel_id: 7,
4492 cltv_expiry_delta: 0,
4493 htlc_minimum_msat: 0,
4494 htlc_maximum_msat: OptionalField::Present(100_000),
4496 fee_proportional_millionths: 0,
4497 excess_data: Vec::new()
4500 // Path via {node0, node2} is channels {1, 3, 5}.
4501 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4502 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4503 short_channel_id: 1,
4506 cltv_expiry_delta: 0,
4507 htlc_minimum_msat: 0,
4508 htlc_maximum_msat: OptionalField::Present(100_000),
4510 fee_proportional_millionths: 0,
4511 excess_data: Vec::new()
4513 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4514 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4515 short_channel_id: 3,
4518 cltv_expiry_delta: 0,
4519 htlc_minimum_msat: 0,
4520 htlc_maximum_msat: OptionalField::Present(100_000),
4522 fee_proportional_millionths: 0,
4523 excess_data: Vec::new()
4526 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4527 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4528 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4529 short_channel_id: 5,
4532 cltv_expiry_delta: 0,
4533 htlc_minimum_msat: 0,
4534 htlc_maximum_msat: OptionalField::Present(100_000),
4536 fee_proportional_millionths: 0,
4537 excess_data: Vec::new()
4540 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4541 // All channels should be 100 sats capacity. But for the fee experiment,
4542 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
4543 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
4544 // 100 sats (and pay 150 sats in fees for the use of channel 6),
4545 // so no matter how large are other channels,
4546 // the whole path will be limited by 100 sats with just these 2 conditions:
4547 // - channel 12 capacity is 250 sats
4548 // - fee for channel 6 is 150 sats
4549 // Let's test this by enforcing these 2 conditions and removing other limits.
4550 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4551 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4552 short_channel_id: 12,
4555 cltv_expiry_delta: 0,
4556 htlc_minimum_msat: 0,
4557 htlc_maximum_msat: OptionalField::Present(250_000),
4559 fee_proportional_millionths: 0,
4560 excess_data: Vec::new()
4562 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4563 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4564 short_channel_id: 13,
4567 cltv_expiry_delta: 0,
4568 htlc_minimum_msat: 0,
4569 htlc_maximum_msat: OptionalField::Absent,
4571 fee_proportional_millionths: 0,
4572 excess_data: Vec::new()
4575 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4576 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4577 short_channel_id: 6,
4580 cltv_expiry_delta: 0,
4581 htlc_minimum_msat: 0,
4582 htlc_maximum_msat: OptionalField::Absent,
4583 fee_base_msat: 150_000,
4584 fee_proportional_millionths: 0,
4585 excess_data: Vec::new()
4587 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4588 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4589 short_channel_id: 11,
4592 cltv_expiry_delta: 0,
4593 htlc_minimum_msat: 0,
4594 htlc_maximum_msat: OptionalField::Absent,
4596 fee_proportional_millionths: 0,
4597 excess_data: Vec::new()
4601 // Attempt to route more than available results in a failure.
4602 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4603 &our_id, &payment_params, &network_graph.read_only(), None, 210_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
4604 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4605 } else { panic!(); }
4609 // Now, attempt to route 200 sats (exact amount we can route).
4610 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 200_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4611 assert_eq!(route.paths.len(), 2);
4613 let mut total_amount_paid_msat = 0;
4614 for path in &route.paths {
4615 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
4616 total_amount_paid_msat += path.last().unwrap().fee_msat;
4618 assert_eq!(total_amount_paid_msat, 200_000);
4619 assert_eq!(route.get_total_fees(), 150_000);
4624 fn mpp_with_last_hops() {
4625 // Previously, if we tried to send an MPP payment to a destination which was only reachable
4626 // via a single last-hop route hint, we'd fail to route if we first collected routes
4627 // totaling close but not quite enough to fund the full payment.
4629 // This was because we considered last-hop hints to have exactly the sought payment amount
4630 // instead of the amount we were trying to collect, needlessly limiting our path searching
4631 // at the very first hop.
4633 // Specifically, this interacted with our "all paths must fund at least 5% of total target"
4634 // criterion to cause us to refuse all routes at the last hop hint which would be considered
4635 // to only have the remaining to-collect amount in available liquidity.
4637 // This bug appeared in production in some specific channel configurations.
4638 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4639 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4640 let scorer = test_utils::TestScorer::with_penalty(0);
4641 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4642 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4643 let payment_params = PaymentParameters::from_node_id(PublicKey::from_slice(&[02; 33]).unwrap()).with_features(InvoiceFeatures::known())
4644 .with_route_hints(vec![RouteHint(vec![RouteHintHop {
4645 src_node_id: nodes[2],
4646 short_channel_id: 42,
4647 fees: RoutingFees { base_msat: 0, proportional_millionths: 0 },
4648 cltv_expiry_delta: 42,
4649 htlc_minimum_msat: None,
4650 htlc_maximum_msat: None,
4653 // Keep only two paths from us to nodes[2], both with a 99sat HTLC maximum, with one with
4654 // no fee and one with a 1msat fee. Previously, trying to route 100 sats to nodes[2] here
4655 // would first use the no-fee route and then fail to find a path along the second route as
4656 // we think we can only send up to 1 additional sat over the last-hop but refuse to as its
4657 // under 5% of our payment amount.
4658 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4659 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4660 short_channel_id: 1,
4663 cltv_expiry_delta: (5 << 4) | 5,
4664 htlc_minimum_msat: 0,
4665 htlc_maximum_msat: OptionalField::Present(99_000),
4666 fee_base_msat: u32::max_value(),
4667 fee_proportional_millionths: u32::max_value(),
4668 excess_data: Vec::new()
4670 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4671 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4672 short_channel_id: 2,
4675 cltv_expiry_delta: (5 << 4) | 3,
4676 htlc_minimum_msat: 0,
4677 htlc_maximum_msat: OptionalField::Present(99_000),
4678 fee_base_msat: u32::max_value(),
4679 fee_proportional_millionths: u32::max_value(),
4680 excess_data: Vec::new()
4682 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4683 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4684 short_channel_id: 4,
4687 cltv_expiry_delta: (4 << 4) | 1,
4688 htlc_minimum_msat: 0,
4689 htlc_maximum_msat: OptionalField::Absent,
4691 fee_proportional_millionths: 0,
4692 excess_data: Vec::new()
4694 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4695 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4696 short_channel_id: 13,
4698 flags: 0|2, // Channel disabled
4699 cltv_expiry_delta: (13 << 4) | 1,
4700 htlc_minimum_msat: 0,
4701 htlc_maximum_msat: OptionalField::Absent,
4703 fee_proportional_millionths: 2000000,
4704 excess_data: Vec::new()
4707 // Get a route for 100 sats and check that we found the MPP route no problem and didn't
4709 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4710 assert_eq!(route.paths.len(), 2);
4711 // Paths are somewhat randomly ordered, but:
4712 // * the first is channel 2 (1 msat fee) -> channel 4 -> channel 42
4713 // * the second is channel 1 (0 fee, but 99 sat maximum) -> channel 3 -> channel 42
4714 assert_eq!(route.paths[0][0].short_channel_id, 2);
4715 assert_eq!(route.paths[0][0].fee_msat, 1);
4716 assert_eq!(route.paths[0][2].fee_msat, 1_000);
4717 assert_eq!(route.paths[1][0].short_channel_id, 1);
4718 assert_eq!(route.paths[1][0].fee_msat, 0);
4719 assert_eq!(route.paths[1][2].fee_msat, 99_000);
4720 assert_eq!(route.get_total_fees(), 1);
4721 assert_eq!(route.get_total_amount(), 100_000);
4725 fn drop_lowest_channel_mpp_route_test() {
4726 // This test checks that low-capacity channel is dropped when after
4727 // path finding we realize that we found more capacity than we need.
4728 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4729 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4730 let scorer = test_utils::TestScorer::with_penalty(0);
4731 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4732 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4733 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
4735 // We need a route consisting of 3 paths:
4736 // From our node to node2 via node0, node7, node1 (three paths one hop each).
4738 // The first and the second paths should be sufficient, but the third should be
4739 // cheaper, so that we select it but drop later.
4741 // First, we set limits on these (previously unlimited) channels.
4742 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
4744 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
4745 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4746 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4747 short_channel_id: 1,
4750 cltv_expiry_delta: 0,
4751 htlc_minimum_msat: 0,
4752 htlc_maximum_msat: OptionalField::Present(100_000),
4754 fee_proportional_millionths: 0,
4755 excess_data: Vec::new()
4757 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4758 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4759 short_channel_id: 3,
4762 cltv_expiry_delta: 0,
4763 htlc_minimum_msat: 0,
4764 htlc_maximum_msat: OptionalField::Present(50_000),
4766 fee_proportional_millionths: 0,
4767 excess_data: Vec::new()
4770 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
4771 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4772 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4773 short_channel_id: 12,
4776 cltv_expiry_delta: 0,
4777 htlc_minimum_msat: 0,
4778 htlc_maximum_msat: OptionalField::Present(60_000),
4780 fee_proportional_millionths: 0,
4781 excess_data: Vec::new()
4783 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4784 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4785 short_channel_id: 13,
4788 cltv_expiry_delta: 0,
4789 htlc_minimum_msat: 0,
4790 htlc_maximum_msat: OptionalField::Present(60_000),
4792 fee_proportional_millionths: 0,
4793 excess_data: Vec::new()
4796 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
4797 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4798 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4799 short_channel_id: 2,
4802 cltv_expiry_delta: 0,
4803 htlc_minimum_msat: 0,
4804 htlc_maximum_msat: OptionalField::Present(20_000),
4806 fee_proportional_millionths: 0,
4807 excess_data: Vec::new()
4809 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4810 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4811 short_channel_id: 4,
4814 cltv_expiry_delta: 0,
4815 htlc_minimum_msat: 0,
4816 htlc_maximum_msat: OptionalField::Present(20_000),
4818 fee_proportional_millionths: 0,
4819 excess_data: Vec::new()
4823 // Attempt to route more than available results in a failure.
4824 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4825 &our_id, &payment_params, &network_graph.read_only(), None, 150_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
4826 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4827 } else { panic!(); }
4831 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
4832 // Our algorithm should provide us with these 3 paths.
4833 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 125_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4834 assert_eq!(route.paths.len(), 3);
4835 let mut total_amount_paid_msat = 0;
4836 for path in &route.paths {
4837 assert_eq!(path.len(), 2);
4838 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4839 total_amount_paid_msat += path.last().unwrap().fee_msat;
4841 assert_eq!(total_amount_paid_msat, 125_000);
4845 // Attempt to route without the last small cheap channel
4846 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4847 assert_eq!(route.paths.len(), 2);
4848 let mut total_amount_paid_msat = 0;
4849 for path in &route.paths {
4850 assert_eq!(path.len(), 2);
4851 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4852 total_amount_paid_msat += path.last().unwrap().fee_msat;
4854 assert_eq!(total_amount_paid_msat, 90_000);
4859 fn min_criteria_consistency() {
4860 // Test that we don't use an inconsistent metric between updating and walking nodes during
4861 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
4862 // was updated with a different criterion from the heap sorting, resulting in loops in
4863 // calculated paths. We test for that specific case here.
4865 // We construct a network that looks like this:
4867 // node2 -1(3)2- node3
4871 // node1 -1(5)2- node4 -1(1)2- node6
4877 // We create a loop on the side of our real path - our destination is node 6, with a
4878 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
4879 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
4880 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
4881 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
4882 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
4883 // "previous hop" being set to node 3, creating a loop in the path.
4884 let secp_ctx = Secp256k1::new();
4885 let logger = Arc::new(test_utils::TestLogger::new());
4886 let network = Arc::new(NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash()));
4887 let net_graph_msg_handler = NetGraphMsgHandler::new(Arc::clone(&network), None, Arc::clone(&logger));
4888 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4889 let scorer = test_utils::TestScorer::with_penalty(0);
4890 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4891 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4892 let payment_params = PaymentParameters::from_node_id(nodes[6]);
4894 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
4895 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4896 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4897 short_channel_id: 6,
4900 cltv_expiry_delta: (6 << 4) | 0,
4901 htlc_minimum_msat: 0,
4902 htlc_maximum_msat: OptionalField::Absent,
4904 fee_proportional_millionths: 0,
4905 excess_data: Vec::new()
4907 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
4909 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4910 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4911 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4912 short_channel_id: 5,
4915 cltv_expiry_delta: (5 << 4) | 0,
4916 htlc_minimum_msat: 0,
4917 htlc_maximum_msat: OptionalField::Absent,
4919 fee_proportional_millionths: 0,
4920 excess_data: Vec::new()
4922 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
4924 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
4925 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4926 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4927 short_channel_id: 4,
4930 cltv_expiry_delta: (4 << 4) | 0,
4931 htlc_minimum_msat: 0,
4932 htlc_maximum_msat: OptionalField::Absent,
4934 fee_proportional_millionths: 0,
4935 excess_data: Vec::new()
4937 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
4939 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
4940 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
4941 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4942 short_channel_id: 3,
4945 cltv_expiry_delta: (3 << 4) | 0,
4946 htlc_minimum_msat: 0,
4947 htlc_maximum_msat: OptionalField::Absent,
4949 fee_proportional_millionths: 0,
4950 excess_data: Vec::new()
4952 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
4954 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
4955 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4956 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4957 short_channel_id: 2,
4960 cltv_expiry_delta: (2 << 4) | 0,
4961 htlc_minimum_msat: 0,
4962 htlc_maximum_msat: OptionalField::Absent,
4964 fee_proportional_millionths: 0,
4965 excess_data: Vec::new()
4968 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
4969 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4970 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4971 short_channel_id: 1,
4974 cltv_expiry_delta: (1 << 4) | 0,
4975 htlc_minimum_msat: 100,
4976 htlc_maximum_msat: OptionalField::Absent,
4978 fee_proportional_millionths: 0,
4979 excess_data: Vec::new()
4981 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
4984 // Now ensure the route flows simply over nodes 1 and 4 to 6.
4985 let route = get_route(&our_id, &payment_params, &network.read_only(), None, 10_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4986 assert_eq!(route.paths.len(), 1);
4987 assert_eq!(route.paths[0].len(), 3);
4989 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
4990 assert_eq!(route.paths[0][0].short_channel_id, 6);
4991 assert_eq!(route.paths[0][0].fee_msat, 100);
4992 assert_eq!(route.paths[0][0].cltv_expiry_delta, (5 << 4) | 0);
4993 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(1));
4994 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(6));
4996 assert_eq!(route.paths[0][1].pubkey, nodes[4]);
4997 assert_eq!(route.paths[0][1].short_channel_id, 5);
4998 assert_eq!(route.paths[0][1].fee_msat, 0);
4999 assert_eq!(route.paths[0][1].cltv_expiry_delta, (1 << 4) | 0);
5000 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(4));
5001 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(5));
5003 assert_eq!(route.paths[0][2].pubkey, nodes[6]);
5004 assert_eq!(route.paths[0][2].short_channel_id, 1);
5005 assert_eq!(route.paths[0][2].fee_msat, 10_000);
5006 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
5007 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
5008 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(1));
5014 fn exact_fee_liquidity_limit() {
5015 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
5016 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
5017 // we calculated fees on a higher value, resulting in us ignoring such paths.
5018 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
5019 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
5020 let scorer = test_utils::TestScorer::with_penalty(0);
5021 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5022 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5023 let payment_params = PaymentParameters::from_node_id(nodes[2]);
5025 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
5027 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5028 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5029 short_channel_id: 2,
5032 cltv_expiry_delta: 0,
5033 htlc_minimum_msat: 0,
5034 htlc_maximum_msat: OptionalField::Present(85_000),
5036 fee_proportional_millionths: 0,
5037 excess_data: Vec::new()
5040 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5041 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5042 short_channel_id: 12,
5045 cltv_expiry_delta: (4 << 4) | 1,
5046 htlc_minimum_msat: 0,
5047 htlc_maximum_msat: OptionalField::Present(270_000),
5049 fee_proportional_millionths: 1000000,
5050 excess_data: Vec::new()
5054 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
5055 // 200% fee charged channel 13 in the 1-to-2 direction.
5056 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5057 assert_eq!(route.paths.len(), 1);
5058 assert_eq!(route.paths[0].len(), 2);
5060 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
5061 assert_eq!(route.paths[0][0].short_channel_id, 12);
5062 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
5063 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
5064 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
5065 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
5067 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
5068 assert_eq!(route.paths[0][1].short_channel_id, 13);
5069 assert_eq!(route.paths[0][1].fee_msat, 90_000);
5070 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
5071 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
5072 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
5077 fn htlc_max_reduction_below_min() {
5078 // Test that if, while walking the graph, we reduce the value being sent to meet an
5079 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
5080 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
5081 // resulting in us thinking there is no possible path, even if other paths exist.
5082 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
5083 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5084 let scorer = test_utils::TestScorer::with_penalty(0);
5085 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5086 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5087 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
5089 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
5090 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
5091 // then try to send 90_000.
5092 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5093 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5094 short_channel_id: 2,
5097 cltv_expiry_delta: 0,
5098 htlc_minimum_msat: 0,
5099 htlc_maximum_msat: OptionalField::Present(80_000),
5101 fee_proportional_millionths: 0,
5102 excess_data: Vec::new()
5104 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5105 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5106 short_channel_id: 4,
5109 cltv_expiry_delta: (4 << 4) | 1,
5110 htlc_minimum_msat: 90_000,
5111 htlc_maximum_msat: OptionalField::Absent,
5113 fee_proportional_millionths: 0,
5114 excess_data: Vec::new()
5118 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
5119 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
5120 // expensive) channels 12-13 path.
5121 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5122 assert_eq!(route.paths.len(), 1);
5123 assert_eq!(route.paths[0].len(), 2);
5125 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
5126 assert_eq!(route.paths[0][0].short_channel_id, 12);
5127 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
5128 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
5129 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
5130 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
5132 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
5133 assert_eq!(route.paths[0][1].short_channel_id, 13);
5134 assert_eq!(route.paths[0][1].fee_msat, 90_000);
5135 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
5136 assert_eq!(route.paths[0][1].node_features.le_flags(), InvoiceFeatures::known().le_flags());
5137 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
5142 fn multiple_direct_first_hops() {
5143 // Previously we'd only ever considered one first hop path per counterparty.
5144 // However, as we don't restrict users to one channel per peer, we really need to support
5145 // looking at all first hop paths.
5146 // Here we test that we do not ignore all-but-the-last first hop paths per counterparty (as
5147 // we used to do by overwriting the `first_hop_targets` hashmap entry) and that we can MPP
5148 // route over multiple channels with the same first hop.
5149 let secp_ctx = Secp256k1::new();
5150 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5151 let logger = Arc::new(test_utils::TestLogger::new());
5152 let network_graph = NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash());
5153 let scorer = test_utils::TestScorer::with_penalty(0);
5154 let payment_params = PaymentParameters::from_node_id(nodes[0]).with_features(InvoiceFeatures::known());
5155 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5156 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5159 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
5160 &get_channel_details(Some(3), nodes[0], InitFeatures::known(), 200_000),
5161 &get_channel_details(Some(2), nodes[0], InitFeatures::known(), 10_000),
5162 ]), 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5163 assert_eq!(route.paths.len(), 1);
5164 assert_eq!(route.paths[0].len(), 1);
5166 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
5167 assert_eq!(route.paths[0][0].short_channel_id, 3);
5168 assert_eq!(route.paths[0][0].fee_msat, 100_000);
5171 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
5172 &get_channel_details(Some(3), nodes[0], InitFeatures::known(), 50_000),
5173 &get_channel_details(Some(2), nodes[0], InitFeatures::known(), 50_000),
5174 ]), 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5175 assert_eq!(route.paths.len(), 2);
5176 assert_eq!(route.paths[0].len(), 1);
5177 assert_eq!(route.paths[1].len(), 1);
5179 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
5180 assert_eq!(route.paths[0][0].short_channel_id, 3);
5181 assert_eq!(route.paths[0][0].fee_msat, 50_000);
5183 assert_eq!(route.paths[1][0].pubkey, nodes[0]);
5184 assert_eq!(route.paths[1][0].short_channel_id, 2);
5185 assert_eq!(route.paths[1][0].fee_msat, 50_000);
5189 // If we have a bunch of outbound channels to the same node, where most are not
5190 // sufficient to pay the full payment, but one is, we should default to just using the
5191 // one single channel that has sufficient balance, avoiding MPP.
5193 // If we have several options above the 3xpayment value threshold, we should pick the
5194 // smallest of them, avoiding further fragmenting our available outbound balance to
5196 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
5197 &get_channel_details(Some(2), nodes[0], InitFeatures::known(), 50_000),
5198 &get_channel_details(Some(3), nodes[0], InitFeatures::known(), 50_000),
5199 &get_channel_details(Some(5), nodes[0], InitFeatures::known(), 50_000),
5200 &get_channel_details(Some(6), nodes[0], InitFeatures::known(), 300_000),
5201 &get_channel_details(Some(7), nodes[0], InitFeatures::known(), 50_000),
5202 &get_channel_details(Some(8), nodes[0], InitFeatures::known(), 50_000),
5203 &get_channel_details(Some(9), nodes[0], InitFeatures::known(), 50_000),
5204 &get_channel_details(Some(4), nodes[0], InitFeatures::known(), 1_000_000),
5205 ]), 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5206 assert_eq!(route.paths.len(), 1);
5207 assert_eq!(route.paths[0].len(), 1);
5209 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
5210 assert_eq!(route.paths[0][0].short_channel_id, 6);
5211 assert_eq!(route.paths[0][0].fee_msat, 100_000);
5216 fn prefers_shorter_route_with_higher_fees() {
5217 let (secp_ctx, network_graph, _, _, logger) = build_graph();
5218 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5219 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
5221 // Without penalizing each hop 100 msats, a longer path with lower fees is chosen.
5222 let scorer = test_utils::TestScorer::with_penalty(0);
5223 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5224 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5225 let route = get_route(
5226 &our_id, &payment_params, &network_graph.read_only(), None, 100, 42,
5227 Arc::clone(&logger), &scorer, &random_seed_bytes
5229 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5231 assert_eq!(route.get_total_fees(), 100);
5232 assert_eq!(route.get_total_amount(), 100);
5233 assert_eq!(path, vec![2, 4, 6, 11, 8]);
5235 // Applying a 100 msat penalty to each hop results in taking channels 7 and 10 to nodes[6]
5236 // from nodes[2] rather than channel 6, 11, and 8, even though the longer path is cheaper.
5237 let scorer = test_utils::TestScorer::with_penalty(100);
5238 let route = get_route(
5239 &our_id, &payment_params, &network_graph.read_only(), None, 100, 42,
5240 Arc::clone(&logger), &scorer, &random_seed_bytes
5242 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5244 assert_eq!(route.get_total_fees(), 300);
5245 assert_eq!(route.get_total_amount(), 100);
5246 assert_eq!(path, vec![2, 4, 7, 10]);
5249 struct BadChannelScorer {
5250 short_channel_id: u64,
5254 impl Writeable for BadChannelScorer {
5255 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), ::io::Error> { unimplemented!() }
5257 impl Score for BadChannelScorer {
5258 fn channel_penalty_msat(&self, short_channel_id: u64, _: &NodeId, _: &NodeId, _: ChannelUsage) -> u64 {
5259 if short_channel_id == self.short_channel_id { u64::max_value() } else { 0 }
5262 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
5263 fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
5266 struct BadNodeScorer {
5271 impl Writeable for BadNodeScorer {
5272 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), ::io::Error> { unimplemented!() }
5275 impl Score for BadNodeScorer {
5276 fn channel_penalty_msat(&self, _: u64, _: &NodeId, target: &NodeId, _: ChannelUsage) -> u64 {
5277 if *target == self.node_id { u64::max_value() } else { 0 }
5280 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
5281 fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
5285 fn avoids_routing_through_bad_channels_and_nodes() {
5286 let (secp_ctx, network, _, _, logger) = build_graph();
5287 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5288 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
5289 let network_graph = network.read_only();
5291 // A path to nodes[6] exists when no penalties are applied to any channel.
5292 let scorer = test_utils::TestScorer::with_penalty(0);
5293 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5294 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5295 let route = get_route(
5296 &our_id, &payment_params, &network_graph, None, 100, 42,
5297 Arc::clone(&logger), &scorer, &random_seed_bytes
5299 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5301 assert_eq!(route.get_total_fees(), 100);
5302 assert_eq!(route.get_total_amount(), 100);
5303 assert_eq!(path, vec![2, 4, 6, 11, 8]);
5305 // A different path to nodes[6] exists if channel 6 cannot be routed over.
5306 let scorer = BadChannelScorer { short_channel_id: 6 };
5307 let route = get_route(
5308 &our_id, &payment_params, &network_graph, None, 100, 42,
5309 Arc::clone(&logger), &scorer, &random_seed_bytes
5311 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5313 assert_eq!(route.get_total_fees(), 300);
5314 assert_eq!(route.get_total_amount(), 100);
5315 assert_eq!(path, vec![2, 4, 7, 10]);
5317 // A path to nodes[6] does not exist if nodes[2] cannot be routed through.
5318 let scorer = BadNodeScorer { node_id: NodeId::from_pubkey(&nodes[2]) };
5320 &our_id, &payment_params, &network_graph, None, 100, 42,
5321 Arc::clone(&logger), &scorer, &random_seed_bytes
5323 Err(LightningError { err, .. } ) => {
5324 assert_eq!(err, "Failed to find a path to the given destination");
5326 Ok(_) => panic!("Expected error"),
5331 fn total_fees_single_path() {
5335 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5336 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5337 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5340 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5341 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5342 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5345 pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
5346 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5347 short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0
5350 payment_params: None,
5353 assert_eq!(route.get_total_fees(), 250);
5354 assert_eq!(route.get_total_amount(), 225);
5358 fn total_fees_multi_path() {
5362 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5363 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5364 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5367 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5368 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5369 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5373 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5374 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5375 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5378 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5379 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5380 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5383 payment_params: None,
5386 assert_eq!(route.get_total_fees(), 200);
5387 assert_eq!(route.get_total_amount(), 300);
5391 fn total_empty_route_no_panic() {
5392 // In an earlier version of `Route::get_total_fees` and `Route::get_total_amount`, they
5393 // would both panic if the route was completely empty. We test to ensure they return 0
5394 // here, even though its somewhat nonsensical as a route.
5395 let route = Route { paths: Vec::new(), payment_params: None };
5397 assert_eq!(route.get_total_fees(), 0);
5398 assert_eq!(route.get_total_amount(), 0);
5402 fn limits_total_cltv_delta() {
5403 let (secp_ctx, network, _, _, logger) = build_graph();
5404 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5405 let network_graph = network.read_only();
5407 let scorer = test_utils::TestScorer::with_penalty(0);
5409 // Make sure that generally there is at least one route available
5410 let feasible_max_total_cltv_delta = 1008;
5411 let feasible_payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes))
5412 .with_max_total_cltv_expiry_delta(feasible_max_total_cltv_delta);
5413 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5414 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5415 let route = get_route(&our_id, &feasible_payment_params, &network_graph, None, 100, 0, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5416 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5417 assert_ne!(path.len(), 0);
5419 // But not if we exclude all paths on the basis of their accumulated CLTV delta
5420 let fail_max_total_cltv_delta = 23;
5421 let fail_payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes))
5422 .with_max_total_cltv_expiry_delta(fail_max_total_cltv_delta);
5423 match get_route(&our_id, &fail_payment_params, &network_graph, None, 100, 0, Arc::clone(&logger), &scorer, &random_seed_bytes)
5425 Err(LightningError { err, .. } ) => {
5426 assert_eq!(err, "Failed to find a path to the given destination");
5428 Ok(_) => panic!("Expected error"),
5433 fn limits_path_length() {
5434 let (secp_ctx, network, _, _, logger) = build_line_graph();
5435 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5436 let network_graph = network.read_only();
5438 let scorer = test_utils::TestScorer::with_penalty(0);
5439 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5440 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5442 // First check we can actually create a long route on this graph.
5443 let feasible_payment_params = PaymentParameters::from_node_id(nodes[18]);
5444 let route = get_route(&our_id, &feasible_payment_params, &network_graph, None, 100, 0,
5445 Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5446 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5447 assert!(path.len() == MAX_PATH_LENGTH_ESTIMATE.into());
5449 // But we can't create a path surpassing the MAX_PATH_LENGTH_ESTIMATE limit.
5450 let fail_payment_params = PaymentParameters::from_node_id(nodes[19]);
5451 match get_route(&our_id, &fail_payment_params, &network_graph, None, 100, 0,
5452 Arc::clone(&logger), &scorer, &random_seed_bytes)
5454 Err(LightningError { err, .. } ) => {
5455 assert_eq!(err, "Failed to find a path to the given destination");
5457 Ok(_) => panic!("Expected error"),
5462 fn adds_and_limits_cltv_offset() {
5463 let (secp_ctx, network_graph, _, _, logger) = build_graph();
5464 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5466 let scorer = test_utils::TestScorer::with_penalty(0);
5468 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
5469 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5470 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5471 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5472 assert_eq!(route.paths.len(), 1);
5474 let cltv_expiry_deltas_before = route.paths[0].iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5476 // Check whether the offset added to the last hop by default is in [1 .. DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA]
5477 let mut route_default = route.clone();
5478 add_random_cltv_offset(&mut route_default, &payment_params, &network_graph.read_only(), &random_seed_bytes);
5479 let cltv_expiry_deltas_default = route_default.paths[0].iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5480 assert_eq!(cltv_expiry_deltas_before.split_last().unwrap().1, cltv_expiry_deltas_default.split_last().unwrap().1);
5481 assert!(cltv_expiry_deltas_default.last() > cltv_expiry_deltas_before.last());
5482 assert!(cltv_expiry_deltas_default.last().unwrap() <= &DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA);
5484 // Check that no offset is added when we restrict the max_total_cltv_expiry_delta
5485 let mut route_limited = route.clone();
5486 let limited_max_total_cltv_expiry_delta = cltv_expiry_deltas_before.iter().sum();
5487 let limited_payment_params = payment_params.with_max_total_cltv_expiry_delta(limited_max_total_cltv_expiry_delta);
5488 add_random_cltv_offset(&mut route_limited, &limited_payment_params, &network_graph.read_only(), &random_seed_bytes);
5489 let cltv_expiry_deltas_limited = route_limited.paths[0].iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5490 assert_eq!(cltv_expiry_deltas_before, cltv_expiry_deltas_limited);
5494 fn adds_plausible_cltv_offset() {
5495 let (secp_ctx, network, _, _, logger) = build_graph();
5496 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5497 let network_graph = network.read_only();
5498 let network_nodes = network_graph.nodes();
5499 let network_channels = network_graph.channels();
5500 let scorer = test_utils::TestScorer::with_penalty(0);
5501 let payment_params = PaymentParameters::from_node_id(nodes[3]);
5502 let keys_manager = test_utils::TestKeysInterface::new(&[4u8; 32], Network::Testnet);
5503 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5505 let mut route = get_route(&our_id, &payment_params, &network_graph, None, 100, 0,
5506 Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5507 add_random_cltv_offset(&mut route, &payment_params, &network_graph, &random_seed_bytes);
5509 let mut path_plausibility = vec![];
5511 for p in route.paths {
5512 // 1. Select random observation point
5513 let mut prng = ChaCha20::new(&random_seed_bytes, &[0u8; 12]);
5514 let mut random_bytes = [0u8; ::core::mem::size_of::<usize>()];
5516 prng.process_in_place(&mut random_bytes);
5517 let random_path_index = usize::from_be_bytes(random_bytes).wrapping_rem(p.len());
5518 let observation_point = NodeId::from_pubkey(&p.get(random_path_index).unwrap().pubkey);
5520 // 2. Calculate what CLTV expiry delta we would observe there
5521 let observed_cltv_expiry_delta: u32 = p[random_path_index..].iter().map(|h| h.cltv_expiry_delta).sum();
5523 // 3. Starting from the observation point, find candidate paths
5524 let mut candidates: VecDeque<(NodeId, Vec<u32>)> = VecDeque::new();
5525 candidates.push_back((observation_point, vec![]));
5527 let mut found_plausible_candidate = false;
5529 'candidate_loop: while let Some((cur_node_id, cur_path_cltv_deltas)) = candidates.pop_front() {
5530 if let Some(remaining) = observed_cltv_expiry_delta.checked_sub(cur_path_cltv_deltas.iter().sum::<u32>()) {
5531 if remaining == 0 || remaining.wrapping_rem(40) == 0 || remaining.wrapping_rem(144) == 0 {
5532 found_plausible_candidate = true;
5533 break 'candidate_loop;
5537 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
5538 for channel_id in &cur_node.channels {
5539 if let Some(channel_info) = network_channels.get(&channel_id) {
5540 if let Some((dir_info, next_id)) = channel_info.as_directed_from(&cur_node_id) {
5541 if let Some(channel_update_info) = dir_info.direction() {
5542 let next_cltv_expiry_delta = channel_update_info.cltv_expiry_delta as u32;
5543 if cur_path_cltv_deltas.iter().sum::<u32>()
5544 .saturating_add(next_cltv_expiry_delta) <= observed_cltv_expiry_delta {
5545 let mut new_path_cltv_deltas = cur_path_cltv_deltas.clone();
5546 new_path_cltv_deltas.push(next_cltv_expiry_delta);
5547 candidates.push_back((*next_id, new_path_cltv_deltas));
5556 path_plausibility.push(found_plausible_candidate);
5558 assert!(path_plausibility.iter().all(|x| *x));
5562 fn builds_correct_path_from_hops() {
5563 let (secp_ctx, network, _, _, logger) = build_graph();
5564 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5565 let network_graph = network.read_only();
5567 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5568 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5570 let payment_params = PaymentParameters::from_node_id(nodes[3]);
5571 let hops = [nodes[1], nodes[2], nodes[4], nodes[3]];
5572 let route = build_route_from_hops_internal(&our_id, &hops, &payment_params,
5573 &network_graph, 100, 0, Arc::clone(&logger), &random_seed_bytes).unwrap();
5574 let route_hop_pubkeys = route.paths[0].iter().map(|hop| hop.pubkey).collect::<Vec<_>>();
5575 assert_eq!(hops.len(), route.paths[0].len());
5576 for (idx, hop_pubkey) in hops.iter().enumerate() {
5577 assert!(*hop_pubkey == route_hop_pubkeys[idx]);
5581 #[cfg(not(feature = "no-std"))]
5582 pub(super) fn random_init_seed() -> u64 {
5583 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
5584 use core::hash::{BuildHasher, Hasher};
5585 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
5586 println!("Using seed of {}", seed);
5589 #[cfg(not(feature = "no-std"))]
5590 use util::ser::Readable;
5593 #[cfg(not(feature = "no-std"))]
5594 fn generate_routes() {
5595 use routing::scoring::{ProbabilisticScorer, ProbabilisticScoringParameters};
5597 let mut d = match super::test_utils::get_route_file() {
5604 let graph = NetworkGraph::read(&mut d).unwrap();
5605 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5606 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5608 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
5609 let mut seed = random_init_seed() as usize;
5610 let nodes = graph.read_only().nodes().clone();
5611 'load_endpoints: for _ in 0..10 {
5613 seed = seed.overflowing_mul(0xdeadbeef).0;
5614 let src = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5615 seed = seed.overflowing_mul(0xdeadbeef).0;
5616 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5617 let payment_params = PaymentParameters::from_node_id(dst);
5618 let amt = seed as u64 % 200_000_000;
5619 let params = ProbabilisticScoringParameters::default();
5620 let logger = test_utils::TestLogger::new();
5621 let scorer = ProbabilisticScorer::new(params, &graph, &logger);
5622 if get_route(src, &payment_params, &graph.read_only(), None, amt, 42, &logger, &scorer, &random_seed_bytes).is_ok() {
5623 continue 'load_endpoints;
5630 #[cfg(not(feature = "no-std"))]
5631 fn generate_routes_mpp() {
5632 use routing::scoring::{ProbabilisticScorer, ProbabilisticScoringParameters};
5634 let mut d = match super::test_utils::get_route_file() {
5641 let graph = NetworkGraph::read(&mut d).unwrap();
5642 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5643 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5645 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
5646 let mut seed = random_init_seed() as usize;
5647 let nodes = graph.read_only().nodes().clone();
5648 'load_endpoints: for _ in 0..10 {
5650 seed = seed.overflowing_mul(0xdeadbeef).0;
5651 let src = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5652 seed = seed.overflowing_mul(0xdeadbeef).0;
5653 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5654 let payment_params = PaymentParameters::from_node_id(dst).with_features(InvoiceFeatures::known());
5655 let amt = seed as u64 % 200_000_000;
5656 let params = ProbabilisticScoringParameters::default();
5657 let logger = test_utils::TestLogger::new();
5658 let scorer = ProbabilisticScorer::new(params, &graph, &logger);
5659 if get_route(src, &payment_params, &graph.read_only(), None, amt, 42, &logger, &scorer, &random_seed_bytes).is_ok() {
5660 continue 'load_endpoints;
5667 #[cfg(all(test, not(feature = "no-std")))]
5668 pub(crate) mod test_utils {
5670 /// Tries to open a network graph file, or panics with a URL to fetch it.
5671 pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
5672 let res = File::open("net_graph-2021-05-31.bin") // By default we're run in RL/lightning
5673 .or_else(|_| File::open("lightning/net_graph-2021-05-31.bin")) // We may be run manually in RL/
5674 .or_else(|_| { // Fall back to guessing based on the binary location
5675 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
5676 let mut path = std::env::current_exe().unwrap();
5677 path.pop(); // lightning-...
5679 path.pop(); // debug
5680 path.pop(); // target
5681 path.push("lightning");
5682 path.push("net_graph-2021-05-31.bin");
5683 eprintln!("{}", path.to_str().unwrap());
5686 .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");
5687 #[cfg(require_route_graph_test)]
5688 return Ok(res.unwrap());
5689 #[cfg(not(require_route_graph_test))]
5694 #[cfg(all(test, feature = "_bench_unstable", not(feature = "no-std")))]
5697 use bitcoin::hashes::Hash;
5698 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
5699 use chain::transaction::OutPoint;
5700 use chain::keysinterface::{KeysManager,KeysInterface};
5701 use ln::channelmanager::{ChannelCounterparty, ChannelDetails};
5702 use ln::features::{InitFeatures, InvoiceFeatures};
5703 use routing::scoring::{FixedPenaltyScorer, ProbabilisticScorer, ProbabilisticScoringParameters, Scorer};
5704 use util::logger::{Logger, Record};
5705 use util::test_utils::TestLogger;
5709 struct DummyLogger {}
5710 impl Logger for DummyLogger {
5711 fn log(&self, _record: &Record) {}
5714 fn read_network_graph() -> NetworkGraph {
5715 let mut d = test_utils::get_route_file().unwrap();
5716 NetworkGraph::read(&mut d).unwrap()
5719 fn payer_pubkey() -> PublicKey {
5720 let secp_ctx = Secp256k1::new();
5721 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
5725 fn first_hop(node_id: PublicKey) -> ChannelDetails {
5727 channel_id: [0; 32],
5728 counterparty: ChannelCounterparty {
5729 features: InitFeatures::known(),
5731 unspendable_punishment_reserve: 0,
5732 forwarding_info: None,
5733 outbound_htlc_minimum_msat: None,
5734 outbound_htlc_maximum_msat: None,
5736 funding_txo: Some(OutPoint {
5737 txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0
5740 short_channel_id: Some(1),
5741 inbound_scid_alias: None,
5742 outbound_scid_alias: None,
5743 channel_value_satoshis: 10_000_000,
5745 balance_msat: 10_000_000,
5746 outbound_capacity_msat: 10_000_000,
5747 next_outbound_htlc_limit_msat: 10_000_000,
5748 inbound_capacity_msat: 0,
5749 unspendable_punishment_reserve: None,
5750 confirmations_required: None,
5751 force_close_spend_delay: None,
5753 is_channel_ready: true,
5756 inbound_htlc_minimum_msat: None,
5757 inbound_htlc_maximum_msat: None,
5762 fn generate_routes_with_zero_penalty_scorer(bench: &mut Bencher) {
5763 let network_graph = read_network_graph();
5764 let scorer = FixedPenaltyScorer::with_penalty(0);
5765 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::empty());
5769 fn generate_mpp_routes_with_zero_penalty_scorer(bench: &mut Bencher) {
5770 let network_graph = read_network_graph();
5771 let scorer = FixedPenaltyScorer::with_penalty(0);
5772 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::known());
5776 fn generate_routes_with_default_scorer(bench: &mut Bencher) {
5777 let network_graph = read_network_graph();
5778 let scorer = Scorer::default();
5779 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::empty());
5783 fn generate_mpp_routes_with_default_scorer(bench: &mut Bencher) {
5784 let network_graph = read_network_graph();
5785 let scorer = Scorer::default();
5786 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::known());
5790 fn generate_routes_with_probabilistic_scorer(bench: &mut Bencher) {
5791 let logger = TestLogger::new();
5792 let network_graph = read_network_graph();
5793 let params = ProbabilisticScoringParameters::default();
5794 let scorer = ProbabilisticScorer::new(params, &network_graph, &logger);
5795 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::empty());
5799 fn generate_mpp_routes_with_probabilistic_scorer(bench: &mut Bencher) {
5800 let logger = TestLogger::new();
5801 let network_graph = read_network_graph();
5802 let params = ProbabilisticScoringParameters::default();
5803 let scorer = ProbabilisticScorer::new(params, &network_graph, &logger);
5804 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::known());
5807 fn generate_routes<S: Score>(
5808 bench: &mut Bencher, graph: &NetworkGraph, mut scorer: S, features: InvoiceFeatures
5810 let nodes = graph.read_only().nodes().clone();
5811 let payer = payer_pubkey();
5812 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
5813 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5815 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
5816 let mut routes = Vec::new();
5817 let mut route_endpoints = Vec::new();
5818 let mut seed: usize = 0xdeadbeef;
5819 'load_endpoints: for _ in 0..150 {
5822 let src = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5824 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5825 let params = PaymentParameters::from_node_id(dst).with_features(features.clone());
5826 let first_hop = first_hop(src);
5827 let amt = seed as u64 % 1_000_000;
5828 if let Ok(route) = get_route(&payer, ¶ms, &graph.read_only(), Some(&[&first_hop]), amt, 42, &DummyLogger{}, &scorer, &random_seed_bytes) {
5830 route_endpoints.push((first_hop, params, amt));
5831 continue 'load_endpoints;
5836 // ...and seed the scorer with success and failure data...
5837 for route in routes {
5838 let amount = route.get_total_amount();
5839 if amount < 250_000 {
5840 for path in route.paths {
5841 scorer.payment_path_successful(&path.iter().collect::<Vec<_>>());
5843 } else if amount > 750_000 {
5844 for path in route.paths {
5845 let short_channel_id = path[path.len() / 2].short_channel_id;
5846 scorer.payment_path_failed(&path.iter().collect::<Vec<_>>(), short_channel_id);
5851 // Because we've changed channel scores, its possible we'll take different routes to the
5852 // selected destinations, possibly causing us to fail because, eg, the newly-selected path
5853 // requires a too-high CLTV delta.
5854 route_endpoints.retain(|(first_hop, params, amt)| {
5855 get_route(&payer, params, &graph.read_only(), Some(&[first_hop]), *amt, 42, &DummyLogger{}, &scorer, &random_seed_bytes).is_ok()
5857 route_endpoints.truncate(100);
5858 assert_eq!(route_endpoints.len(), 100);
5860 // ...then benchmark finding paths between the nodes we learned.
5863 let (first_hop, params, amt) = &route_endpoints[idx % route_endpoints.len()];
5864 assert!(get_route(&payer, params, &graph.read_only(), Some(&[first_hop]), *amt, 42, &DummyLogger{}, &scorer, &random_seed_bytes).is_ok());