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.short_channel_id.unwrap(),
387 CandidateRouteHop::PublicHop { short_channel_id, .. } => *short_channel_id,
388 CandidateRouteHop::PrivateHop { hint } => hint.short_channel_id,
392 // NOTE: This may alloc memory so avoid calling it in a hot code path.
393 fn features(&self) -> ChannelFeatures {
395 CandidateRouteHop::FirstHop { details } => details.counterparty.features.to_context(),
396 CandidateRouteHop::PublicHop { info, .. } => info.channel().features.clone(),
397 CandidateRouteHop::PrivateHop { .. } => ChannelFeatures::empty(),
401 fn cltv_expiry_delta(&self) -> u32 {
403 CandidateRouteHop::FirstHop { .. } => 0,
404 CandidateRouteHop::PublicHop { info, .. } => info.direction().cltv_expiry_delta as u32,
405 CandidateRouteHop::PrivateHop { hint } => hint.cltv_expiry_delta as u32,
409 fn htlc_minimum_msat(&self) -> u64 {
411 CandidateRouteHop::FirstHop { .. } => 0,
412 CandidateRouteHop::PublicHop { info, .. } => info.direction().htlc_minimum_msat,
413 CandidateRouteHop::PrivateHop { hint } => hint.htlc_minimum_msat.unwrap_or(0),
417 fn htlc_maximum_msat(&self) -> u64 {
419 CandidateRouteHop::FirstHop { details } => details.next_outbound_htlc_limit_msat,
420 CandidateRouteHop::PublicHop { info, .. } => info.htlc_maximum_msat(),
421 CandidateRouteHop::PrivateHop { hint } => {
422 hint.htlc_maximum_msat.unwrap_or(u64::max_value())
427 fn fees(&self) -> RoutingFees {
429 CandidateRouteHop::FirstHop { .. } => RoutingFees {
430 base_msat: 0, proportional_millionths: 0,
432 CandidateRouteHop::PublicHop { info, .. } => info.direction().fees,
433 CandidateRouteHop::PrivateHop { hint } => hint.fees,
437 fn effective_capacity(&self) -> EffectiveCapacity {
439 CandidateRouteHop::FirstHop { details } => EffectiveCapacity::ExactLiquidity {
440 liquidity_msat: details.next_outbound_htlc_limit_msat,
442 CandidateRouteHop::PublicHop { info, .. } => info.effective_capacity(),
443 CandidateRouteHop::PrivateHop { .. } => EffectiveCapacity::Infinite,
448 /// It's useful to keep track of the hops associated with the fees required to use them,
449 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
450 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
451 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
453 struct PathBuildingHop<'a> {
454 // Note that this should be dropped in favor of loading it from CandidateRouteHop, but doing so
455 // is a larger refactor and will require careful performance analysis.
457 candidate: CandidateRouteHop<'a>,
460 /// Minimal fees required to route to the source node of the current hop via any of its inbound channels.
461 src_lowest_inbound_fees: RoutingFees,
462 /// All the fees paid *after* this channel on the way to the destination
463 next_hops_fee_msat: u64,
464 /// Fee paid for the use of the current channel (see candidate.fees()).
465 /// The value will be actually deducted from the counterparty balance on the previous link.
466 hop_use_fee_msat: u64,
467 /// Used to compare channels when choosing the for routing.
468 /// Includes paying for the use of a hop and the following hops, as well as
469 /// an estimated cost of reaching this hop.
470 /// Might get stale when fees are recomputed. Primarily for internal use.
472 /// A mirror of the same field in RouteGraphNode. Note that this is only used during the graph
473 /// walk and may be invalid thereafter.
474 path_htlc_minimum_msat: u64,
475 /// All penalties incurred from this channel on the way to the destination, as calculated using
477 path_penalty_msat: u64,
478 /// If we've already processed a node as the best node, we shouldn't process it again. Normally
479 /// we'd just ignore it if we did as all channels would have a higher new fee, but because we
480 /// may decrease the amounts in use as we walk the graph, the actual calculated fee may
481 /// decrease as well. Thus, we have to explicitly track which nodes have been processed and
482 /// avoid processing them again.
484 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
485 // In tests, we apply further sanity checks on cases where we skip nodes we already processed
486 // to ensure it is specifically in cases where the fee has gone down because of a decrease in
487 // value_contribution_msat, which requires tracking it here. See comments below where it is
488 // used for more info.
489 value_contribution_msat: u64,
492 impl<'a> core::fmt::Debug for PathBuildingHop<'a> {
493 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
494 let mut debug_struct = f.debug_struct("PathBuildingHop");
496 .field("node_id", &self.node_id)
497 .field("short_channel_id", &self.candidate.short_channel_id())
498 .field("total_fee_msat", &self.total_fee_msat)
499 .field("next_hops_fee_msat", &self.next_hops_fee_msat)
500 .field("hop_use_fee_msat", &self.hop_use_fee_msat)
501 .field("total_fee_msat - (next_hops_fee_msat + hop_use_fee_msat)", &(&self.total_fee_msat - (&self.next_hops_fee_msat + &self.hop_use_fee_msat)))
502 .field("path_penalty_msat", &self.path_penalty_msat)
503 .field("path_htlc_minimum_msat", &self.path_htlc_minimum_msat)
504 .field("cltv_expiry_delta", &self.candidate.cltv_expiry_delta());
505 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
506 let debug_struct = debug_struct
507 .field("value_contribution_msat", &self.value_contribution_msat);
508 debug_struct.finish()
512 // Instantiated with a list of hops with correct data in them collected during path finding,
513 // an instance of this struct should be further modified only via given methods.
515 struct PaymentPath<'a> {
516 hops: Vec<(PathBuildingHop<'a>, NodeFeatures)>,
519 impl<'a> PaymentPath<'a> {
520 // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
521 fn get_value_msat(&self) -> u64 {
522 self.hops.last().unwrap().0.fee_msat
525 fn get_path_penalty_msat(&self) -> u64 {
526 self.hops.first().map(|h| h.0.path_penalty_msat).unwrap_or(u64::max_value())
529 fn get_total_fee_paid_msat(&self) -> u64 {
530 if self.hops.len() < 1 {
534 // Can't use next_hops_fee_msat because it gets outdated.
535 for (i, (hop, _)) in self.hops.iter().enumerate() {
536 if i != self.hops.len() - 1 {
537 result += hop.fee_msat;
543 fn get_cost_msat(&self) -> u64 {
544 self.get_total_fee_paid_msat().saturating_add(self.get_path_penalty_msat())
547 // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
548 // to change fees may result in an inconsistency.
550 // Sometimes we call this function right after constructing a path which is inconsistent in
551 // that it the value being transferred has decreased while we were doing path finding, leading
552 // to the fees being paid not lining up with the actual limits.
554 // Note that this function is not aware of the available_liquidity limit, and thus does not
555 // support increasing the value being transferred.
556 fn update_value_and_recompute_fees(&mut self, value_msat: u64) {
557 assert!(value_msat <= self.hops.last().unwrap().0.fee_msat);
559 let mut total_fee_paid_msat = 0 as u64;
560 for i in (0..self.hops.len()).rev() {
561 let last_hop = i == self.hops.len() - 1;
563 // For non-last-hop, this value will represent the fees paid on the current hop. It
564 // will consist of the fees for the use of the next hop, and extra fees to match
565 // htlc_minimum_msat of the current channel. Last hop is handled separately.
566 let mut cur_hop_fees_msat = 0;
568 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().0.hop_use_fee_msat;
571 let mut cur_hop = &mut self.hops.get_mut(i).unwrap().0;
572 cur_hop.next_hops_fee_msat = total_fee_paid_msat;
573 // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
574 // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
575 // set it too high just to maliciously take more fees by exploiting this
576 // match htlc_minimum_msat logic.
577 let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
578 if let Some(extra_fees_msat) = cur_hop.candidate.htlc_minimum_msat().checked_sub(cur_hop_transferred_amount_msat) {
579 // Note that there is a risk that *previous hops* (those closer to us, as we go
580 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
582 // This might make us end up with a broken route, although this should be super-rare
583 // in practice, both because of how healthy channels look like, and how we pick
584 // channels in add_entry.
585 // Also, this can't be exploited more heavily than *announce a free path and fail
587 cur_hop_transferred_amount_msat += extra_fees_msat;
588 total_fee_paid_msat += extra_fees_msat;
589 cur_hop_fees_msat += extra_fees_msat;
593 // Final hop is a special case: it usually has just value_msat (by design), but also
594 // it still could overpay for the htlc_minimum_msat.
595 cur_hop.fee_msat = cur_hop_transferred_amount_msat;
597 // Propagate updated fees for the use of the channels to one hop back, where they
598 // will be actually paid (fee_msat). The last hop is handled above separately.
599 cur_hop.fee_msat = cur_hop_fees_msat;
602 // Fee for the use of the current hop which will be deducted on the previous hop.
603 // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
604 // this channel is free for us.
606 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.candidate.fees()) {
607 cur_hop.hop_use_fee_msat = new_fee;
608 total_fee_paid_msat += new_fee;
610 // It should not be possible because this function is called only to reduce the
611 // value. In that case, compute_fee was already called with the same fees for
612 // larger amount and there was no overflow.
620 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
621 let proportional_fee_millions =
622 amount_msat.checked_mul(channel_fees.proportional_millionths as u64);
623 if let Some(new_fee) = proportional_fee_millions.and_then(|part| {
624 (channel_fees.base_msat as u64).checked_add(part / 1_000_000) }) {
628 // This function may be (indirectly) called without any verification,
629 // with channel_fees provided by a caller. We should handle it gracefully.
634 /// The default `features` we assume for a node in a route, when no `features` are known about that
637 /// Default features are:
638 /// * variable_length_onion_optional
639 fn default_node_features() -> NodeFeatures {
640 let mut features = NodeFeatures::empty();
641 features.set_variable_length_onion_optional();
645 /// Finds a route from us (payer) to the given target node (payee).
647 /// If the payee provided features in their invoice, they should be provided via `params.payee`.
648 /// Without this, MPP will only be used if the payee's features are available in the network graph.
650 /// Private routing paths between a public node and the target may be included in `params.payee`.
652 /// If some channels aren't announced, it may be useful to fill in `first_hops` with the results
653 /// from [`ChannelManager::list_usable_channels`]. If it is filled in, the view of our local
654 /// channels from [`NetworkGraph`] will be ignored, and only those in `first_hops` will be used.
656 /// The fees on channels from us to the next hop are ignored as they are assumed to all be equal.
657 /// However, the enabled/disabled bit on such channels as well as the `htlc_minimum_msat` /
658 /// `htlc_maximum_msat` *are* checked as they may change based on the receiving node.
662 /// May be used to re-compute a [`Route`] when handling a [`Event::PaymentPathFailed`]. Any
663 /// adjustments to the [`NetworkGraph`] and channel scores should be made prior to calling this
668 /// Panics if first_hops contains channels without short_channel_ids;
669 /// [`ChannelManager::list_usable_channels`] will never include such channels.
671 /// [`ChannelManager::list_usable_channels`]: crate::ln::channelmanager::ChannelManager::list_usable_channels
672 /// [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed
673 pub fn find_route<L: Deref, S: Score>(
674 our_node_pubkey: &PublicKey, route_params: &RouteParameters, network: &NetworkGraph,
675 first_hops: Option<&[&ChannelDetails]>, logger: L, scorer: &S, random_seed_bytes: &[u8; 32]
676 ) -> Result<Route, LightningError>
677 where L::Target: Logger {
678 let network_graph = network.read_only();
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.short_channel_id.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.short_channel_id.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 inbound_scid_alias: None,
1910 channel_value_satoshis: 0,
1913 outbound_capacity_msat,
1914 next_outbound_htlc_limit_msat: outbound_capacity_msat,
1915 inbound_capacity_msat: 42,
1916 unspendable_punishment_reserve: None,
1917 confirmations_required: None,
1918 force_close_spend_delay: None,
1919 is_outbound: true, is_funding_locked: true,
1920 is_usable: true, is_public: true,
1921 inbound_htlc_minimum_msat: None,
1922 inbound_htlc_maximum_msat: None,
1926 // Using the same keys for LN and BTC ids
1928 net_graph_msg_handler: &NetGraphMsgHandler<Arc<NetworkGraph>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1929 secp_ctx: &Secp256k1<All>, node_1_privkey: &SecretKey, node_2_privkey: &SecretKey, features: ChannelFeatures, short_channel_id: u64
1931 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1932 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1934 let unsigned_announcement = UnsignedChannelAnnouncement {
1936 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1940 bitcoin_key_1: node_id_1,
1941 bitcoin_key_2: node_id_2,
1942 excess_data: Vec::new(),
1945 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1946 let valid_announcement = ChannelAnnouncement {
1947 node_signature_1: secp_ctx.sign_ecdsa(&msghash, node_1_privkey),
1948 node_signature_2: secp_ctx.sign_ecdsa(&msghash, node_2_privkey),
1949 bitcoin_signature_1: secp_ctx.sign_ecdsa(&msghash, node_1_privkey),
1950 bitcoin_signature_2: secp_ctx.sign_ecdsa(&msghash, node_2_privkey),
1951 contents: unsigned_announcement.clone(),
1953 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1954 Ok(res) => assert!(res),
1960 net_graph_msg_handler: &NetGraphMsgHandler<Arc<NetworkGraph>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1961 secp_ctx: &Secp256k1<All>, node_privkey: &SecretKey, update: UnsignedChannelUpdate
1963 let msghash = hash_to_message!(&Sha256dHash::hash(&update.encode()[..])[..]);
1964 let valid_channel_update = ChannelUpdate {
1965 signature: secp_ctx.sign_ecdsa(&msghash, node_privkey),
1966 contents: update.clone()
1969 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1970 Ok(res) => assert!(res),
1975 fn add_or_update_node(
1976 net_graph_msg_handler: &NetGraphMsgHandler<Arc<NetworkGraph>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1977 secp_ctx: &Secp256k1<All>, node_privkey: &SecretKey, features: NodeFeatures, timestamp: u32
1979 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
1980 let unsigned_announcement = UnsignedNodeAnnouncement {
1986 addresses: Vec::new(),
1987 excess_address_data: Vec::new(),
1988 excess_data: Vec::new(),
1990 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1991 let valid_announcement = NodeAnnouncement {
1992 signature: secp_ctx.sign_ecdsa(&msghash, node_privkey),
1993 contents: unsigned_announcement.clone()
1996 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
2002 fn get_nodes(secp_ctx: &Secp256k1<All>) -> (SecretKey, PublicKey, Vec<SecretKey>, Vec<PublicKey>) {
2003 let privkeys: Vec<SecretKey> = (2..22).map(|i| {
2004 SecretKey::from_slice(&hex::decode(format!("{:02x}", i).repeat(32)).unwrap()[..]).unwrap()
2007 let pubkeys = privkeys.iter().map(|secret| PublicKey::from_secret_key(&secp_ctx, secret)).collect();
2009 let our_privkey = SecretKey::from_slice(&hex::decode("01".repeat(32)).unwrap()[..]).unwrap();
2010 let our_id = PublicKey::from_secret_key(&secp_ctx, &our_privkey);
2012 (our_privkey, our_id, privkeys, pubkeys)
2015 fn id_to_feature_flags(id: u8) -> Vec<u8> {
2016 // Set the feature flags to the id'th odd (ie non-required) feature bit so that we can
2017 // test for it later.
2018 let idx = (id - 1) * 2 + 1;
2020 vec![1 << (idx - 8*3), 0, 0, 0]
2021 } else if idx > 8*2 {
2022 vec![1 << (idx - 8*2), 0, 0]
2023 } else if idx > 8*1 {
2024 vec![1 << (idx - 8*1), 0]
2030 fn build_line_graph() -> (
2031 Secp256k1<All>, sync::Arc<NetworkGraph>, NetGraphMsgHandler<sync::Arc<NetworkGraph>,
2032 sync::Arc<test_utils::TestChainSource>, sync::Arc<crate::util::test_utils::TestLogger>>,
2033 sync::Arc<test_utils::TestChainSource>, sync::Arc<test_utils::TestLogger>,
2035 let secp_ctx = Secp256k1::new();
2036 let logger = Arc::new(test_utils::TestLogger::new());
2037 let chain_monitor = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
2038 let network_graph = Arc::new(NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash()));
2039 let net_graph_msg_handler = NetGraphMsgHandler::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
2041 // Build network from our_id to node 19:
2042 // our_id -1(1)2- node0 -1(2)2- node1 - ... - node19
2043 let (our_privkey, _, privkeys, _) = get_nodes(&secp_ctx);
2045 for (idx, (cur_privkey, next_privkey)) in core::iter::once(&our_privkey)
2046 .chain(privkeys.iter()).zip(privkeys.iter()).enumerate() {
2047 let cur_short_channel_id = (idx as u64) + 1;
2048 add_channel(&net_graph_msg_handler, &secp_ctx, &cur_privkey, &next_privkey,
2049 ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), cur_short_channel_id);
2050 update_channel(&net_graph_msg_handler, &secp_ctx, &cur_privkey, UnsignedChannelUpdate {
2051 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2052 short_channel_id: cur_short_channel_id,
2053 timestamp: idx as u32,
2055 cltv_expiry_delta: 0,
2056 htlc_minimum_msat: 0,
2057 htlc_maximum_msat: OptionalField::Absent,
2059 fee_proportional_millionths: 0,
2060 excess_data: Vec::new()
2062 update_channel(&net_graph_msg_handler, &secp_ctx, &next_privkey, UnsignedChannelUpdate {
2063 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2064 short_channel_id: cur_short_channel_id,
2065 timestamp: (idx as u32)+1,
2067 cltv_expiry_delta: 0,
2068 htlc_minimum_msat: 0,
2069 htlc_maximum_msat: OptionalField::Absent,
2071 fee_proportional_millionths: 0,
2072 excess_data: Vec::new()
2074 add_or_update_node(&net_graph_msg_handler, &secp_ctx, next_privkey,
2075 NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
2078 (secp_ctx, network_graph, net_graph_msg_handler, chain_monitor, logger)
2081 fn build_graph() -> (
2083 sync::Arc<NetworkGraph>,
2084 NetGraphMsgHandler<sync::Arc<NetworkGraph>, sync::Arc<test_utils::TestChainSource>, sync::Arc<crate::util::test_utils::TestLogger>>,
2085 sync::Arc<test_utils::TestChainSource>,
2086 sync::Arc<test_utils::TestLogger>,
2088 let secp_ctx = Secp256k1::new();
2089 let logger = Arc::new(test_utils::TestLogger::new());
2090 let chain_monitor = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
2091 let network_graph = Arc::new(NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash()));
2092 let net_graph_msg_handler = NetGraphMsgHandler::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
2093 // Build network from our_id to node6:
2095 // -1(1)2- node0 -1(3)2-
2097 // our_id -1(12)2- node7 -1(13)2--- node2
2099 // -1(2)2- node1 -1(4)2-
2102 // chan1 1-to-2: disabled
2103 // chan1 2-to-1: enabled, 0 fee
2105 // chan2 1-to-2: enabled, ignored fee
2106 // chan2 2-to-1: enabled, 0 fee
2108 // chan3 1-to-2: enabled, 0 fee
2109 // chan3 2-to-1: enabled, 100 msat fee
2111 // chan4 1-to-2: enabled, 100% fee
2112 // chan4 2-to-1: enabled, 0 fee
2114 // chan12 1-to-2: enabled, ignored fee
2115 // chan12 2-to-1: enabled, 0 fee
2117 // chan13 1-to-2: enabled, 200% fee
2118 // chan13 2-to-1: enabled, 0 fee
2121 // -1(5)2- node3 -1(8)2--
2125 // node2--1(6)2- node4 -1(9)2--- node6 (not in global route map)
2127 // -1(7)2- node5 -1(10)2-
2129 // Channels 5, 8, 9 and 10 are private channels.
2131 // chan5 1-to-2: enabled, 100 msat fee
2132 // chan5 2-to-1: enabled, 0 fee
2134 // chan6 1-to-2: enabled, 0 fee
2135 // chan6 2-to-1: enabled, 0 fee
2137 // chan7 1-to-2: enabled, 100% fee
2138 // chan7 2-to-1: enabled, 0 fee
2140 // chan8 1-to-2: enabled, variable fee (0 then 1000 msat)
2141 // chan8 2-to-1: enabled, 0 fee
2143 // chan9 1-to-2: enabled, 1001 msat fee
2144 // chan9 2-to-1: enabled, 0 fee
2146 // chan10 1-to-2: enabled, 0 fee
2147 // chan10 2-to-1: enabled, 0 fee
2149 // chan11 1-to-2: enabled, 0 fee
2150 // chan11 2-to-1: enabled, 0 fee
2152 let (our_privkey, _, privkeys, _) = get_nodes(&secp_ctx);
2154 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[0], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
2155 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2156 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2157 short_channel_id: 1,
2160 cltv_expiry_delta: 0,
2161 htlc_minimum_msat: 0,
2162 htlc_maximum_msat: OptionalField::Absent,
2164 fee_proportional_millionths: 0,
2165 excess_data: Vec::new()
2168 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
2170 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
2171 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2172 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2173 short_channel_id: 2,
2176 cltv_expiry_delta: (5 << 4) | 3,
2177 htlc_minimum_msat: 0,
2178 htlc_maximum_msat: OptionalField::Absent,
2179 fee_base_msat: u32::max_value(),
2180 fee_proportional_millionths: u32::max_value(),
2181 excess_data: Vec::new()
2183 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2184 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2185 short_channel_id: 2,
2188 cltv_expiry_delta: 0,
2189 htlc_minimum_msat: 0,
2190 htlc_maximum_msat: OptionalField::Absent,
2192 fee_proportional_millionths: 0,
2193 excess_data: Vec::new()
2196 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
2198 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[7], ChannelFeatures::from_le_bytes(id_to_feature_flags(12)), 12);
2199 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2200 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2201 short_channel_id: 12,
2204 cltv_expiry_delta: (5 << 4) | 3,
2205 htlc_minimum_msat: 0,
2206 htlc_maximum_msat: OptionalField::Absent,
2207 fee_base_msat: u32::max_value(),
2208 fee_proportional_millionths: u32::max_value(),
2209 excess_data: Vec::new()
2211 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2212 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2213 short_channel_id: 12,
2216 cltv_expiry_delta: 0,
2217 htlc_minimum_msat: 0,
2218 htlc_maximum_msat: OptionalField::Absent,
2220 fee_proportional_millionths: 0,
2221 excess_data: Vec::new()
2224 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], NodeFeatures::from_le_bytes(id_to_feature_flags(8)), 0);
2226 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
2227 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2228 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2229 short_channel_id: 3,
2232 cltv_expiry_delta: (3 << 4) | 1,
2233 htlc_minimum_msat: 0,
2234 htlc_maximum_msat: OptionalField::Absent,
2236 fee_proportional_millionths: 0,
2237 excess_data: Vec::new()
2239 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2240 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2241 short_channel_id: 3,
2244 cltv_expiry_delta: (3 << 4) | 2,
2245 htlc_minimum_msat: 0,
2246 htlc_maximum_msat: OptionalField::Absent,
2248 fee_proportional_millionths: 0,
2249 excess_data: Vec::new()
2252 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
2253 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2254 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2255 short_channel_id: 4,
2258 cltv_expiry_delta: (4 << 4) | 1,
2259 htlc_minimum_msat: 0,
2260 htlc_maximum_msat: OptionalField::Absent,
2262 fee_proportional_millionths: 1000000,
2263 excess_data: Vec::new()
2265 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2266 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2267 short_channel_id: 4,
2270 cltv_expiry_delta: (4 << 4) | 2,
2271 htlc_minimum_msat: 0,
2272 htlc_maximum_msat: OptionalField::Absent,
2274 fee_proportional_millionths: 0,
2275 excess_data: Vec::new()
2278 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(13)), 13);
2279 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2280 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2281 short_channel_id: 13,
2284 cltv_expiry_delta: (13 << 4) | 1,
2285 htlc_minimum_msat: 0,
2286 htlc_maximum_msat: OptionalField::Absent,
2288 fee_proportional_millionths: 2000000,
2289 excess_data: Vec::new()
2291 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2292 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2293 short_channel_id: 13,
2296 cltv_expiry_delta: (13 << 4) | 2,
2297 htlc_minimum_msat: 0,
2298 htlc_maximum_msat: OptionalField::Absent,
2300 fee_proportional_millionths: 0,
2301 excess_data: Vec::new()
2304 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
2306 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
2307 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2308 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2309 short_channel_id: 6,
2312 cltv_expiry_delta: (6 << 4) | 1,
2313 htlc_minimum_msat: 0,
2314 htlc_maximum_msat: OptionalField::Absent,
2316 fee_proportional_millionths: 0,
2317 excess_data: Vec::new()
2319 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
2320 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2321 short_channel_id: 6,
2324 cltv_expiry_delta: (6 << 4) | 2,
2325 htlc_minimum_msat: 0,
2326 htlc_maximum_msat: OptionalField::Absent,
2328 fee_proportional_millionths: 0,
2329 excess_data: Vec::new(),
2332 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(11)), 11);
2333 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
2334 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2335 short_channel_id: 11,
2338 cltv_expiry_delta: (11 << 4) | 1,
2339 htlc_minimum_msat: 0,
2340 htlc_maximum_msat: OptionalField::Absent,
2342 fee_proportional_millionths: 0,
2343 excess_data: Vec::new()
2345 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
2346 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2347 short_channel_id: 11,
2350 cltv_expiry_delta: (11 << 4) | 2,
2351 htlc_minimum_msat: 0,
2352 htlc_maximum_msat: OptionalField::Absent,
2354 fee_proportional_millionths: 0,
2355 excess_data: Vec::new()
2358 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(5)), 0);
2360 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
2362 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[5], ChannelFeatures::from_le_bytes(id_to_feature_flags(7)), 7);
2363 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2364 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2365 short_channel_id: 7,
2368 cltv_expiry_delta: (7 << 4) | 1,
2369 htlc_minimum_msat: 0,
2370 htlc_maximum_msat: OptionalField::Absent,
2372 fee_proportional_millionths: 1000000,
2373 excess_data: Vec::new()
2375 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[5], UnsignedChannelUpdate {
2376 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2377 short_channel_id: 7,
2380 cltv_expiry_delta: (7 << 4) | 2,
2381 htlc_minimum_msat: 0,
2382 htlc_maximum_msat: OptionalField::Absent,
2384 fee_proportional_millionths: 0,
2385 excess_data: Vec::new()
2388 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[5], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
2390 (secp_ctx, network_graph, net_graph_msg_handler, chain_monitor, logger)
2394 fn simple_route_test() {
2395 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2396 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2397 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2398 let scorer = test_utils::TestScorer::with_penalty(0);
2399 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2400 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2402 // Simple route to 2 via 1
2404 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) {
2405 assert_eq!(err, "Cannot send a payment of 0 msat");
2406 } else { panic!(); }
2408 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2409 assert_eq!(route.paths[0].len(), 2);
2411 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2412 assert_eq!(route.paths[0][0].short_channel_id, 2);
2413 assert_eq!(route.paths[0][0].fee_msat, 100);
2414 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2415 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2416 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2418 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2419 assert_eq!(route.paths[0][1].short_channel_id, 4);
2420 assert_eq!(route.paths[0][1].fee_msat, 100);
2421 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2422 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2423 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2427 fn invalid_first_hop_test() {
2428 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2429 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2430 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2431 let scorer = test_utils::TestScorer::with_penalty(0);
2432 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2433 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2435 // Simple route to 2 via 1
2437 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
2439 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) =
2440 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) {
2441 assert_eq!(err, "First hop cannot have our_node_pubkey as a destination.");
2442 } else { panic!(); }
2444 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2445 assert_eq!(route.paths[0].len(), 2);
2449 fn htlc_minimum_test() {
2450 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2451 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2452 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2453 let scorer = test_utils::TestScorer::with_penalty(0);
2454 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2455 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2457 // Simple route to 2 via 1
2459 // Disable other paths
2460 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2461 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2462 short_channel_id: 12,
2464 flags: 2, // to disable
2465 cltv_expiry_delta: 0,
2466 htlc_minimum_msat: 0,
2467 htlc_maximum_msat: OptionalField::Absent,
2469 fee_proportional_millionths: 0,
2470 excess_data: Vec::new()
2472 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2473 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2474 short_channel_id: 3,
2476 flags: 2, // to disable
2477 cltv_expiry_delta: 0,
2478 htlc_minimum_msat: 0,
2479 htlc_maximum_msat: OptionalField::Absent,
2481 fee_proportional_millionths: 0,
2482 excess_data: Vec::new()
2484 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2485 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2486 short_channel_id: 13,
2488 flags: 2, // to disable
2489 cltv_expiry_delta: 0,
2490 htlc_minimum_msat: 0,
2491 htlc_maximum_msat: OptionalField::Absent,
2493 fee_proportional_millionths: 0,
2494 excess_data: Vec::new()
2496 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2497 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2498 short_channel_id: 6,
2500 flags: 2, // to disable
2501 cltv_expiry_delta: 0,
2502 htlc_minimum_msat: 0,
2503 htlc_maximum_msat: OptionalField::Absent,
2505 fee_proportional_millionths: 0,
2506 excess_data: Vec::new()
2508 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2509 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2510 short_channel_id: 7,
2512 flags: 2, // to disable
2513 cltv_expiry_delta: 0,
2514 htlc_minimum_msat: 0,
2515 htlc_maximum_msat: OptionalField::Absent,
2517 fee_proportional_millionths: 0,
2518 excess_data: Vec::new()
2521 // Check against amount_to_transfer_over_msat.
2522 // Set minimal HTLC of 200_000_000 msat.
2523 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2524 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2525 short_channel_id: 2,
2528 cltv_expiry_delta: 0,
2529 htlc_minimum_msat: 200_000_000,
2530 htlc_maximum_msat: OptionalField::Absent,
2532 fee_proportional_millionths: 0,
2533 excess_data: Vec::new()
2536 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
2538 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2539 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2540 short_channel_id: 4,
2543 cltv_expiry_delta: 0,
2544 htlc_minimum_msat: 0,
2545 htlc_maximum_msat: OptionalField::Present(199_999_999),
2547 fee_proportional_millionths: 0,
2548 excess_data: Vec::new()
2551 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
2552 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) {
2553 assert_eq!(err, "Failed to find a path to the given destination");
2554 } else { panic!(); }
2556 // Lift the restriction on the first hop.
2557 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2558 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2559 short_channel_id: 2,
2562 cltv_expiry_delta: 0,
2563 htlc_minimum_msat: 0,
2564 htlc_maximum_msat: OptionalField::Absent,
2566 fee_proportional_millionths: 0,
2567 excess_data: Vec::new()
2570 // A payment above the minimum should pass
2571 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();
2572 assert_eq!(route.paths[0].len(), 2);
2576 fn htlc_minimum_overpay_test() {
2577 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2578 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2579 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
2580 let scorer = test_utils::TestScorer::with_penalty(0);
2581 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2582 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2584 // A route to node#2 via two paths.
2585 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
2586 // Thus, they can't send 60 without overpaying.
2587 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2588 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2589 short_channel_id: 2,
2592 cltv_expiry_delta: 0,
2593 htlc_minimum_msat: 35_000,
2594 htlc_maximum_msat: OptionalField::Present(40_000),
2596 fee_proportional_millionths: 0,
2597 excess_data: Vec::new()
2599 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2600 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2601 short_channel_id: 12,
2604 cltv_expiry_delta: 0,
2605 htlc_minimum_msat: 35_000,
2606 htlc_maximum_msat: OptionalField::Present(40_000),
2608 fee_proportional_millionths: 0,
2609 excess_data: Vec::new()
2613 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2614 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2615 short_channel_id: 13,
2618 cltv_expiry_delta: 0,
2619 htlc_minimum_msat: 0,
2620 htlc_maximum_msat: OptionalField::Absent,
2622 fee_proportional_millionths: 0,
2623 excess_data: Vec::new()
2625 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2626 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2627 short_channel_id: 4,
2630 cltv_expiry_delta: 0,
2631 htlc_minimum_msat: 0,
2632 htlc_maximum_msat: OptionalField::Absent,
2634 fee_proportional_millionths: 0,
2635 excess_data: Vec::new()
2638 // Disable other paths
2639 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2640 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2641 short_channel_id: 1,
2643 flags: 2, // to disable
2644 cltv_expiry_delta: 0,
2645 htlc_minimum_msat: 0,
2646 htlc_maximum_msat: OptionalField::Absent,
2648 fee_proportional_millionths: 0,
2649 excess_data: Vec::new()
2652 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 60_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2653 // Overpay fees to hit htlc_minimum_msat.
2654 let overpaid_fees = route.paths[0][0].fee_msat + route.paths[1][0].fee_msat;
2655 // TODO: this could be better balanced to overpay 10k and not 15k.
2656 assert_eq!(overpaid_fees, 15_000);
2658 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
2659 // while taking even more fee to match htlc_minimum_msat.
2660 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2661 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2662 short_channel_id: 12,
2665 cltv_expiry_delta: 0,
2666 htlc_minimum_msat: 65_000,
2667 htlc_maximum_msat: OptionalField::Present(80_000),
2669 fee_proportional_millionths: 0,
2670 excess_data: Vec::new()
2672 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2673 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2674 short_channel_id: 2,
2677 cltv_expiry_delta: 0,
2678 htlc_minimum_msat: 0,
2679 htlc_maximum_msat: OptionalField::Absent,
2681 fee_proportional_millionths: 0,
2682 excess_data: Vec::new()
2684 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2685 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2686 short_channel_id: 4,
2689 cltv_expiry_delta: 0,
2690 htlc_minimum_msat: 0,
2691 htlc_maximum_msat: OptionalField::Absent,
2693 fee_proportional_millionths: 100_000,
2694 excess_data: Vec::new()
2697 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 60_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2698 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
2699 assert_eq!(route.paths.len(), 1);
2700 assert_eq!(route.paths[0][0].short_channel_id, 12);
2701 let fees = route.paths[0][0].fee_msat;
2702 assert_eq!(fees, 5_000);
2704 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2705 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
2706 // the other channel.
2707 assert_eq!(route.paths.len(), 1);
2708 assert_eq!(route.paths[0][0].short_channel_id, 2);
2709 let fees = route.paths[0][0].fee_msat;
2710 assert_eq!(fees, 5_000);
2714 fn disable_channels_test() {
2715 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2716 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2717 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2718 let scorer = test_utils::TestScorer::with_penalty(0);
2719 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2720 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2722 // // Disable channels 4 and 12 by flags=2
2723 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2724 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2725 short_channel_id: 4,
2727 flags: 2, // to disable
2728 cltv_expiry_delta: 0,
2729 htlc_minimum_msat: 0,
2730 htlc_maximum_msat: OptionalField::Absent,
2732 fee_proportional_millionths: 0,
2733 excess_data: Vec::new()
2735 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2736 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2737 short_channel_id: 12,
2739 flags: 2, // to disable
2740 cltv_expiry_delta: 0,
2741 htlc_minimum_msat: 0,
2742 htlc_maximum_msat: OptionalField::Absent,
2744 fee_proportional_millionths: 0,
2745 excess_data: Vec::new()
2748 // If all the channels require some features we don't understand, route should fail
2749 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) {
2750 assert_eq!(err, "Failed to find a path to the given destination");
2751 } else { panic!(); }
2753 // If we specify a channel to node7, that overrides our local channel view and that gets used
2754 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2755 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();
2756 assert_eq!(route.paths[0].len(), 2);
2758 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2759 assert_eq!(route.paths[0][0].short_channel_id, 42);
2760 assert_eq!(route.paths[0][0].fee_msat, 200);
2761 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2762 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2763 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2765 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2766 assert_eq!(route.paths[0][1].short_channel_id, 13);
2767 assert_eq!(route.paths[0][1].fee_msat, 100);
2768 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2769 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2770 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2774 fn disable_node_test() {
2775 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2776 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2777 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2778 let scorer = test_utils::TestScorer::with_penalty(0);
2779 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2780 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2782 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
2783 let mut unknown_features = NodeFeatures::known();
2784 unknown_features.set_unknown_feature_required();
2785 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
2786 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
2787 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
2789 // If all nodes require some features we don't understand, route should fail
2790 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) {
2791 assert_eq!(err, "Failed to find a path to the given destination");
2792 } else { panic!(); }
2794 // If we specify a channel to node7, that overrides our local channel view and that gets used
2795 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2796 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();
2797 assert_eq!(route.paths[0].len(), 2);
2799 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2800 assert_eq!(route.paths[0][0].short_channel_id, 42);
2801 assert_eq!(route.paths[0][0].fee_msat, 200);
2802 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2803 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2804 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2806 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2807 assert_eq!(route.paths[0][1].short_channel_id, 13);
2808 assert_eq!(route.paths[0][1].fee_msat, 100);
2809 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2810 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2811 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2813 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
2814 // naively) assume that the user checked the feature bits on the invoice, which override
2815 // the node_announcement.
2819 fn our_chans_test() {
2820 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2821 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2822 let scorer = test_utils::TestScorer::with_penalty(0);
2823 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2824 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2826 // Route to 1 via 2 and 3 because our channel to 1 is disabled
2827 let payment_params = PaymentParameters::from_node_id(nodes[0]);
2828 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2829 assert_eq!(route.paths[0].len(), 3);
2831 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2832 assert_eq!(route.paths[0][0].short_channel_id, 2);
2833 assert_eq!(route.paths[0][0].fee_msat, 200);
2834 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2835 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2836 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2838 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2839 assert_eq!(route.paths[0][1].short_channel_id, 4);
2840 assert_eq!(route.paths[0][1].fee_msat, 100);
2841 assert_eq!(route.paths[0][1].cltv_expiry_delta, (3 << 4) | 2);
2842 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2843 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2845 assert_eq!(route.paths[0][2].pubkey, nodes[0]);
2846 assert_eq!(route.paths[0][2].short_channel_id, 3);
2847 assert_eq!(route.paths[0][2].fee_msat, 100);
2848 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
2849 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(1));
2850 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(3));
2852 // If we specify a channel to node7, that overrides our local channel view and that gets used
2853 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2854 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2855 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();
2856 assert_eq!(route.paths[0].len(), 2);
2858 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2859 assert_eq!(route.paths[0][0].short_channel_id, 42);
2860 assert_eq!(route.paths[0][0].fee_msat, 200);
2861 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2862 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2863 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2865 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2866 assert_eq!(route.paths[0][1].short_channel_id, 13);
2867 assert_eq!(route.paths[0][1].fee_msat, 100);
2868 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2869 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2870 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2873 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2874 let zero_fees = RoutingFees {
2876 proportional_millionths: 0,
2878 vec![RouteHint(vec![RouteHintHop {
2879 src_node_id: nodes[3],
2880 short_channel_id: 8,
2882 cltv_expiry_delta: (8 << 4) | 1,
2883 htlc_minimum_msat: None,
2884 htlc_maximum_msat: None,
2886 ]), RouteHint(vec![RouteHintHop {
2887 src_node_id: nodes[4],
2888 short_channel_id: 9,
2891 proportional_millionths: 0,
2893 cltv_expiry_delta: (9 << 4) | 1,
2894 htlc_minimum_msat: None,
2895 htlc_maximum_msat: None,
2896 }]), RouteHint(vec![RouteHintHop {
2897 src_node_id: nodes[5],
2898 short_channel_id: 10,
2900 cltv_expiry_delta: (10 << 4) | 1,
2901 htlc_minimum_msat: None,
2902 htlc_maximum_msat: None,
2906 fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2907 let zero_fees = RoutingFees {
2909 proportional_millionths: 0,
2911 vec![RouteHint(vec![RouteHintHop {
2912 src_node_id: nodes[2],
2913 short_channel_id: 5,
2916 proportional_millionths: 0,
2918 cltv_expiry_delta: (5 << 4) | 1,
2919 htlc_minimum_msat: None,
2920 htlc_maximum_msat: None,
2922 src_node_id: nodes[3],
2923 short_channel_id: 8,
2925 cltv_expiry_delta: (8 << 4) | 1,
2926 htlc_minimum_msat: None,
2927 htlc_maximum_msat: None,
2929 ]), RouteHint(vec![RouteHintHop {
2930 src_node_id: nodes[4],
2931 short_channel_id: 9,
2934 proportional_millionths: 0,
2936 cltv_expiry_delta: (9 << 4) | 1,
2937 htlc_minimum_msat: None,
2938 htlc_maximum_msat: None,
2939 }]), RouteHint(vec![RouteHintHop {
2940 src_node_id: nodes[5],
2941 short_channel_id: 10,
2943 cltv_expiry_delta: (10 << 4) | 1,
2944 htlc_minimum_msat: None,
2945 htlc_maximum_msat: None,
2950 fn partial_route_hint_test() {
2951 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2952 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2953 let scorer = test_utils::TestScorer::with_penalty(0);
2954 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2955 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2957 // Simple test across 2, 3, 5, and 4 via a last_hop channel
2958 // Tests the behaviour when the RouteHint contains a suboptimal hop.
2959 // RouteHint may be partially used by the algo to build the best path.
2961 // First check that last hop can't have its source as the payee.
2962 let invalid_last_hop = RouteHint(vec![RouteHintHop {
2963 src_node_id: nodes[6],
2964 short_channel_id: 8,
2967 proportional_millionths: 0,
2969 cltv_expiry_delta: (8 << 4) | 1,
2970 htlc_minimum_msat: None,
2971 htlc_maximum_msat: None,
2974 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
2975 invalid_last_hops.push(invalid_last_hop);
2977 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(invalid_last_hops);
2978 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) {
2979 assert_eq!(err, "Route hint cannot have the payee as the source.");
2980 } else { panic!(); }
2983 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops_multi_private_channels(&nodes));
2984 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2985 assert_eq!(route.paths[0].len(), 5);
2987 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2988 assert_eq!(route.paths[0][0].short_channel_id, 2);
2989 assert_eq!(route.paths[0][0].fee_msat, 100);
2990 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2991 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2992 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2994 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2995 assert_eq!(route.paths[0][1].short_channel_id, 4);
2996 assert_eq!(route.paths[0][1].fee_msat, 0);
2997 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
2998 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2999 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3001 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
3002 assert_eq!(route.paths[0][2].short_channel_id, 6);
3003 assert_eq!(route.paths[0][2].fee_msat, 0);
3004 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
3005 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
3006 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
3008 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
3009 assert_eq!(route.paths[0][3].short_channel_id, 11);
3010 assert_eq!(route.paths[0][3].fee_msat, 0);
3011 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
3012 // If we have a peer in the node map, we'll use their features here since we don't have
3013 // a way of figuring out their features from the invoice:
3014 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
3015 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
3017 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
3018 assert_eq!(route.paths[0][4].short_channel_id, 8);
3019 assert_eq!(route.paths[0][4].fee_msat, 100);
3020 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
3021 assert_eq!(route.paths[0][4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3022 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3025 fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3026 let zero_fees = RoutingFees {
3028 proportional_millionths: 0,
3030 vec![RouteHint(vec![RouteHintHop {
3031 src_node_id: nodes[3],
3032 short_channel_id: 8,
3034 cltv_expiry_delta: (8 << 4) | 1,
3035 htlc_minimum_msat: None,
3036 htlc_maximum_msat: None,
3037 }]), RouteHint(vec![
3039 ]), RouteHint(vec![RouteHintHop {
3040 src_node_id: nodes[5],
3041 short_channel_id: 10,
3043 cltv_expiry_delta: (10 << 4) | 1,
3044 htlc_minimum_msat: None,
3045 htlc_maximum_msat: None,
3050 fn ignores_empty_last_hops_test() {
3051 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3052 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3053 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(empty_last_hop(&nodes));
3054 let scorer = test_utils::TestScorer::with_penalty(0);
3055 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3056 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3058 // Test handling of an empty RouteHint passed in Invoice.
3060 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3061 assert_eq!(route.paths[0].len(), 5);
3063 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3064 assert_eq!(route.paths[0][0].short_channel_id, 2);
3065 assert_eq!(route.paths[0][0].fee_msat, 100);
3066 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
3067 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3068 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3070 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3071 assert_eq!(route.paths[0][1].short_channel_id, 4);
3072 assert_eq!(route.paths[0][1].fee_msat, 0);
3073 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
3074 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3075 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3077 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
3078 assert_eq!(route.paths[0][2].short_channel_id, 6);
3079 assert_eq!(route.paths[0][2].fee_msat, 0);
3080 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
3081 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
3082 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
3084 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
3085 assert_eq!(route.paths[0][3].short_channel_id, 11);
3086 assert_eq!(route.paths[0][3].fee_msat, 0);
3087 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
3088 // If we have a peer in the node map, we'll use their features here since we don't have
3089 // a way of figuring out their features from the invoice:
3090 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
3091 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
3093 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
3094 assert_eq!(route.paths[0][4].short_channel_id, 8);
3095 assert_eq!(route.paths[0][4].fee_msat, 100);
3096 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
3097 assert_eq!(route.paths[0][4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3098 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3101 /// Builds a trivial last-hop hint that passes through the two nodes given, with channel 0xff00
3103 fn multi_hop_last_hops_hint(hint_hops: [PublicKey; 2]) -> Vec<RouteHint> {
3104 let zero_fees = RoutingFees {
3106 proportional_millionths: 0,
3108 vec![RouteHint(vec![RouteHintHop {
3109 src_node_id: hint_hops[0],
3110 short_channel_id: 0xff00,
3113 proportional_millionths: 0,
3115 cltv_expiry_delta: (5 << 4) | 1,
3116 htlc_minimum_msat: None,
3117 htlc_maximum_msat: None,
3119 src_node_id: hint_hops[1],
3120 short_channel_id: 0xff01,
3122 cltv_expiry_delta: (8 << 4) | 1,
3123 htlc_minimum_msat: None,
3124 htlc_maximum_msat: None,
3129 fn multi_hint_last_hops_test() {
3130 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3131 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3132 let last_hops = multi_hop_last_hops_hint([nodes[2], nodes[3]]);
3133 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops.clone());
3134 let scorer = test_utils::TestScorer::with_penalty(0);
3135 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3136 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3137 // Test through channels 2, 3, 0xff00, 0xff01.
3138 // Test shows that multiple hop hints are considered.
3140 // Disabling channels 6 & 7 by flags=2
3141 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3142 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3143 short_channel_id: 6,
3145 flags: 2, // to disable
3146 cltv_expiry_delta: 0,
3147 htlc_minimum_msat: 0,
3148 htlc_maximum_msat: OptionalField::Absent,
3150 fee_proportional_millionths: 0,
3151 excess_data: Vec::new()
3153 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3154 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3155 short_channel_id: 7,
3157 flags: 2, // to disable
3158 cltv_expiry_delta: 0,
3159 htlc_minimum_msat: 0,
3160 htlc_maximum_msat: OptionalField::Absent,
3162 fee_proportional_millionths: 0,
3163 excess_data: Vec::new()
3166 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3167 assert_eq!(route.paths[0].len(), 4);
3169 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3170 assert_eq!(route.paths[0][0].short_channel_id, 2);
3171 assert_eq!(route.paths[0][0].fee_msat, 200);
3172 assert_eq!(route.paths[0][0].cltv_expiry_delta, 65);
3173 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3174 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3176 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3177 assert_eq!(route.paths[0][1].short_channel_id, 4);
3178 assert_eq!(route.paths[0][1].fee_msat, 100);
3179 assert_eq!(route.paths[0][1].cltv_expiry_delta, 81);
3180 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3181 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3183 assert_eq!(route.paths[0][2].pubkey, nodes[3]);
3184 assert_eq!(route.paths[0][2].short_channel_id, last_hops[0].0[0].short_channel_id);
3185 assert_eq!(route.paths[0][2].fee_msat, 0);
3186 assert_eq!(route.paths[0][2].cltv_expiry_delta, 129);
3187 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(4));
3188 assert_eq!(route.paths[0][2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3190 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
3191 assert_eq!(route.paths[0][3].short_channel_id, last_hops[0].0[1].short_channel_id);
3192 assert_eq!(route.paths[0][3].fee_msat, 100);
3193 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
3194 assert_eq!(route.paths[0][3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3195 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3199 fn private_multi_hint_last_hops_test() {
3200 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3201 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3203 let non_announced_privkey = SecretKey::from_slice(&hex::decode(format!("{:02x}", 0xf0).repeat(32)).unwrap()[..]).unwrap();
3204 let non_announced_pubkey = PublicKey::from_secret_key(&secp_ctx, &non_announced_privkey);
3206 let last_hops = multi_hop_last_hops_hint([nodes[2], non_announced_pubkey]);
3207 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops.clone());
3208 let scorer = test_utils::TestScorer::with_penalty(0);
3209 // Test through channels 2, 3, 0xff00, 0xff01.
3210 // Test shows that multiple hop hints are considered.
3212 // Disabling channels 6 & 7 by flags=2
3213 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3214 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3215 short_channel_id: 6,
3217 flags: 2, // to disable
3218 cltv_expiry_delta: 0,
3219 htlc_minimum_msat: 0,
3220 htlc_maximum_msat: OptionalField::Absent,
3222 fee_proportional_millionths: 0,
3223 excess_data: Vec::new()
3225 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3226 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3227 short_channel_id: 7,
3229 flags: 2, // to disable
3230 cltv_expiry_delta: 0,
3231 htlc_minimum_msat: 0,
3232 htlc_maximum_msat: OptionalField::Absent,
3234 fee_proportional_millionths: 0,
3235 excess_data: Vec::new()
3238 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &[42u8; 32]).unwrap();
3239 assert_eq!(route.paths[0].len(), 4);
3241 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3242 assert_eq!(route.paths[0][0].short_channel_id, 2);
3243 assert_eq!(route.paths[0][0].fee_msat, 200);
3244 assert_eq!(route.paths[0][0].cltv_expiry_delta, 65);
3245 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3246 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3248 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3249 assert_eq!(route.paths[0][1].short_channel_id, 4);
3250 assert_eq!(route.paths[0][1].fee_msat, 100);
3251 assert_eq!(route.paths[0][1].cltv_expiry_delta, 81);
3252 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3253 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3255 assert_eq!(route.paths[0][2].pubkey, non_announced_pubkey);
3256 assert_eq!(route.paths[0][2].short_channel_id, last_hops[0].0[0].short_channel_id);
3257 assert_eq!(route.paths[0][2].fee_msat, 0);
3258 assert_eq!(route.paths[0][2].cltv_expiry_delta, 129);
3259 assert_eq!(route.paths[0][2].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3260 assert_eq!(route.paths[0][2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3262 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
3263 assert_eq!(route.paths[0][3].short_channel_id, last_hops[0].0[1].short_channel_id);
3264 assert_eq!(route.paths[0][3].fee_msat, 100);
3265 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
3266 assert_eq!(route.paths[0][3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3267 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3270 fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3271 let zero_fees = RoutingFees {
3273 proportional_millionths: 0,
3275 vec![RouteHint(vec![RouteHintHop {
3276 src_node_id: nodes[4],
3277 short_channel_id: 11,
3279 cltv_expiry_delta: (11 << 4) | 1,
3280 htlc_minimum_msat: None,
3281 htlc_maximum_msat: None,
3283 src_node_id: nodes[3],
3284 short_channel_id: 8,
3286 cltv_expiry_delta: (8 << 4) | 1,
3287 htlc_minimum_msat: None,
3288 htlc_maximum_msat: None,
3289 }]), RouteHint(vec![RouteHintHop {
3290 src_node_id: nodes[4],
3291 short_channel_id: 9,
3294 proportional_millionths: 0,
3296 cltv_expiry_delta: (9 << 4) | 1,
3297 htlc_minimum_msat: None,
3298 htlc_maximum_msat: None,
3299 }]), RouteHint(vec![RouteHintHop {
3300 src_node_id: nodes[5],
3301 short_channel_id: 10,
3303 cltv_expiry_delta: (10 << 4) | 1,
3304 htlc_minimum_msat: None,
3305 htlc_maximum_msat: None,
3310 fn last_hops_with_public_channel_test() {
3311 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3312 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3313 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops_with_public_channel(&nodes));
3314 let scorer = test_utils::TestScorer::with_penalty(0);
3315 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3316 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3317 // This test shows that public routes can be present in the invoice
3318 // which would be handled in the same manner.
3320 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3321 assert_eq!(route.paths[0].len(), 5);
3323 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3324 assert_eq!(route.paths[0][0].short_channel_id, 2);
3325 assert_eq!(route.paths[0][0].fee_msat, 100);
3326 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
3327 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3328 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3330 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3331 assert_eq!(route.paths[0][1].short_channel_id, 4);
3332 assert_eq!(route.paths[0][1].fee_msat, 0);
3333 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
3334 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3335 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3337 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
3338 assert_eq!(route.paths[0][2].short_channel_id, 6);
3339 assert_eq!(route.paths[0][2].fee_msat, 0);
3340 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
3341 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
3342 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
3344 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
3345 assert_eq!(route.paths[0][3].short_channel_id, 11);
3346 assert_eq!(route.paths[0][3].fee_msat, 0);
3347 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
3348 // If we have a peer in the node map, we'll use their features here since we don't have
3349 // a way of figuring out their features from the invoice:
3350 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
3351 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
3353 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
3354 assert_eq!(route.paths[0][4].short_channel_id, 8);
3355 assert_eq!(route.paths[0][4].fee_msat, 100);
3356 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
3357 assert_eq!(route.paths[0][4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3358 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3362 fn our_chans_last_hop_connect_test() {
3363 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3364 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3365 let scorer = test_utils::TestScorer::with_penalty(0);
3366 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3367 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3369 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
3370 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3371 let mut last_hops = last_hops(&nodes);
3372 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops.clone());
3373 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();
3374 assert_eq!(route.paths[0].len(), 2);
3376 assert_eq!(route.paths[0][0].pubkey, nodes[3]);
3377 assert_eq!(route.paths[0][0].short_channel_id, 42);
3378 assert_eq!(route.paths[0][0].fee_msat, 0);
3379 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 4) | 1);
3380 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
3381 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3383 assert_eq!(route.paths[0][1].pubkey, nodes[6]);
3384 assert_eq!(route.paths[0][1].short_channel_id, 8);
3385 assert_eq!(route.paths[0][1].fee_msat, 100);
3386 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
3387 assert_eq!(route.paths[0][1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3388 assert_eq!(route.paths[0][1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3390 last_hops[0].0[0].fees.base_msat = 1000;
3392 // Revert to via 6 as the fee on 8 goes up
3393 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops);
3394 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3395 assert_eq!(route.paths[0].len(), 4);
3397 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3398 assert_eq!(route.paths[0][0].short_channel_id, 2);
3399 assert_eq!(route.paths[0][0].fee_msat, 200); // fee increased as its % of value transferred across node
3400 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
3401 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3402 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3404 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3405 assert_eq!(route.paths[0][1].short_channel_id, 4);
3406 assert_eq!(route.paths[0][1].fee_msat, 100);
3407 assert_eq!(route.paths[0][1].cltv_expiry_delta, (7 << 4) | 1);
3408 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3409 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3411 assert_eq!(route.paths[0][2].pubkey, nodes[5]);
3412 assert_eq!(route.paths[0][2].short_channel_id, 7);
3413 assert_eq!(route.paths[0][2].fee_msat, 0);
3414 assert_eq!(route.paths[0][2].cltv_expiry_delta, (10 << 4) | 1);
3415 // If we have a peer in the node map, we'll use their features here since we don't have
3416 // a way of figuring out their features from the invoice:
3417 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
3418 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(7));
3420 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
3421 assert_eq!(route.paths[0][3].short_channel_id, 10);
3422 assert_eq!(route.paths[0][3].fee_msat, 100);
3423 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
3424 assert_eq!(route.paths[0][3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3425 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3427 // ...but still use 8 for larger payments as 6 has a variable feerate
3428 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 2000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3429 assert_eq!(route.paths[0].len(), 5);
3431 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3432 assert_eq!(route.paths[0][0].short_channel_id, 2);
3433 assert_eq!(route.paths[0][0].fee_msat, 3000);
3434 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
3435 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3436 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3438 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3439 assert_eq!(route.paths[0][1].short_channel_id, 4);
3440 assert_eq!(route.paths[0][1].fee_msat, 0);
3441 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
3442 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3443 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3445 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
3446 assert_eq!(route.paths[0][2].short_channel_id, 6);
3447 assert_eq!(route.paths[0][2].fee_msat, 0);
3448 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
3449 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
3450 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
3452 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
3453 assert_eq!(route.paths[0][3].short_channel_id, 11);
3454 assert_eq!(route.paths[0][3].fee_msat, 1000);
3455 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
3456 // If we have a peer in the node map, we'll use their features here since we don't have
3457 // a way of figuring out their features from the invoice:
3458 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
3459 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
3461 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
3462 assert_eq!(route.paths[0][4].short_channel_id, 8);
3463 assert_eq!(route.paths[0][4].fee_msat, 2000);
3464 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
3465 assert_eq!(route.paths[0][4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3466 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3469 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> {
3470 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
3471 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3472 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3474 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
3475 let last_hops = RouteHint(vec![RouteHintHop {
3476 src_node_id: middle_node_id,
3477 short_channel_id: 8,
3480 proportional_millionths: last_hop_fee_prop,
3482 cltv_expiry_delta: (8 << 4) | 1,
3483 htlc_minimum_msat: None,
3484 htlc_maximum_msat: last_hop_htlc_max,
3486 let payment_params = PaymentParameters::from_node_id(target_node_id).with_route_hints(vec![last_hops]);
3487 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
3488 let scorer = test_utils::TestScorer::with_penalty(0);
3489 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3490 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3491 get_route(&source_node_id, &payment_params, &NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash()).read_only(),
3492 Some(&our_chans.iter().collect::<Vec<_>>()), route_val, 42, &test_utils::TestLogger::new(), &scorer, &random_seed_bytes)
3496 fn unannounced_path_test() {
3497 // We should be able to send a payment to a destination without any help of a routing graph
3498 // if we have a channel with a common counterparty that appears in the first and last hop
3500 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
3502 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3503 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3504 assert_eq!(route.paths[0].len(), 2);
3506 assert_eq!(route.paths[0][0].pubkey, middle_node_id);
3507 assert_eq!(route.paths[0][0].short_channel_id, 42);
3508 assert_eq!(route.paths[0][0].fee_msat, 1001);
3509 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 4) | 1);
3510 assert_eq!(route.paths[0][0].node_features.le_flags(), &[0b11]);
3511 assert_eq!(route.paths[0][0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3513 assert_eq!(route.paths[0][1].pubkey, target_node_id);
3514 assert_eq!(route.paths[0][1].short_channel_id, 8);
3515 assert_eq!(route.paths[0][1].fee_msat, 1000000);
3516 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
3517 assert_eq!(route.paths[0][1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3518 assert_eq!(route.paths[0][1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3522 fn overflow_unannounced_path_test_liquidity_underflow() {
3523 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
3524 // the last-hop had a fee which overflowed a u64, we'd panic.
3525 // This was due to us adding the first-hop from us unconditionally, causing us to think
3526 // we'd built a path (as our node is in the "best candidate" set), when we had not.
3527 // In this test, we previously hit a subtraction underflow due to having less available
3528 // liquidity at the last hop than 0.
3529 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());
3533 fn overflow_unannounced_path_test_feerate_overflow() {
3534 // This tests for the same case as above, except instead of hitting a subtraction
3535 // underflow, we hit a case where the fee charged at a hop overflowed.
3536 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());
3540 fn available_amount_while_routing_test() {
3541 // Tests whether we choose the correct available channel amount while routing.
3543 let (secp_ctx, network_graph, mut net_graph_msg_handler, chain_monitor, logger) = build_graph();
3544 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3545 let scorer = test_utils::TestScorer::with_penalty(0);
3546 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3547 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3548 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
3550 // We will use a simple single-path route from
3551 // our node to node2 via node0: channels {1, 3}.
3553 // First disable all other paths.
3554 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3555 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3556 short_channel_id: 2,
3559 cltv_expiry_delta: 0,
3560 htlc_minimum_msat: 0,
3561 htlc_maximum_msat: OptionalField::Present(100_000),
3563 fee_proportional_millionths: 0,
3564 excess_data: Vec::new()
3566 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3567 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3568 short_channel_id: 12,
3571 cltv_expiry_delta: 0,
3572 htlc_minimum_msat: 0,
3573 htlc_maximum_msat: OptionalField::Present(100_000),
3575 fee_proportional_millionths: 0,
3576 excess_data: Vec::new()
3579 // Make the first channel (#1) very permissive,
3580 // and we will be testing all limits on the second channel.
3581 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3582 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3583 short_channel_id: 1,
3586 cltv_expiry_delta: 0,
3587 htlc_minimum_msat: 0,
3588 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3590 fee_proportional_millionths: 0,
3591 excess_data: Vec::new()
3594 // First, let's see if routing works if we have absolutely no idea about the available amount.
3595 // In this case, it should be set to 250_000 sats.
3596 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3597 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3598 short_channel_id: 3,
3601 cltv_expiry_delta: 0,
3602 htlc_minimum_msat: 0,
3603 htlc_maximum_msat: OptionalField::Absent,
3605 fee_proportional_millionths: 0,
3606 excess_data: Vec::new()
3610 // Attempt to route more than available results in a failure.
3611 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3612 &our_id, &payment_params, &network_graph.read_only(), None, 250_000_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3613 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3614 } else { panic!(); }
3618 // Now, attempt to route an exact amount we have should be fine.
3619 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();
3620 assert_eq!(route.paths.len(), 1);
3621 let path = route.paths.last().unwrap();
3622 assert_eq!(path.len(), 2);
3623 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3624 assert_eq!(path.last().unwrap().fee_msat, 250_000_000);
3627 // Check that setting next_outbound_htlc_limit_msat in first_hops limits the channels.
3628 // Disable channel #1 and use another first hop.
3629 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3630 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3631 short_channel_id: 1,
3634 cltv_expiry_delta: 0,
3635 htlc_minimum_msat: 0,
3636 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3638 fee_proportional_millionths: 0,
3639 excess_data: Vec::new()
3642 // Now, limit the first_hop by the next_outbound_htlc_limit_msat of 200_000 sats.
3643 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
3646 // Attempt to route more than available results in a failure.
3647 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3648 &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) {
3649 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3650 } else { panic!(); }
3654 // Now, attempt to route an exact amount we have should be fine.
3655 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();
3656 assert_eq!(route.paths.len(), 1);
3657 let path = route.paths.last().unwrap();
3658 assert_eq!(path.len(), 2);
3659 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3660 assert_eq!(path.last().unwrap().fee_msat, 200_000_000);
3663 // Enable channel #1 back.
3664 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3665 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3666 short_channel_id: 1,
3669 cltv_expiry_delta: 0,
3670 htlc_minimum_msat: 0,
3671 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3673 fee_proportional_millionths: 0,
3674 excess_data: Vec::new()
3678 // Now let's see if routing works if we know only htlc_maximum_msat.
3679 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3680 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3681 short_channel_id: 3,
3684 cltv_expiry_delta: 0,
3685 htlc_minimum_msat: 0,
3686 htlc_maximum_msat: OptionalField::Present(15_000),
3688 fee_proportional_millionths: 0,
3689 excess_data: Vec::new()
3693 // Attempt to route more than available results in a failure.
3694 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3695 &our_id, &payment_params, &network_graph.read_only(), None, 15_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3696 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3697 } else { panic!(); }
3701 // Now, attempt to route an exact amount we have should be fine.
3702 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 15_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3703 assert_eq!(route.paths.len(), 1);
3704 let path = route.paths.last().unwrap();
3705 assert_eq!(path.len(), 2);
3706 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3707 assert_eq!(path.last().unwrap().fee_msat, 15_000);
3710 // Now let's see if routing works if we know only capacity from the UTXO.
3712 // We can't change UTXO capacity on the fly, so we'll disable
3713 // the existing channel and add another one with the capacity we need.
3714 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3715 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3716 short_channel_id: 3,
3719 cltv_expiry_delta: 0,
3720 htlc_minimum_msat: 0,
3721 htlc_maximum_msat: OptionalField::Absent,
3723 fee_proportional_millionths: 0,
3724 excess_data: Vec::new()
3727 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
3728 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
3729 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
3730 .push_opcode(opcodes::all::OP_PUSHNUM_2)
3731 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
3733 *chain_monitor.utxo_ret.lock().unwrap() = Ok(TxOut { value: 15, script_pubkey: good_script.clone() });
3734 net_graph_msg_handler.add_chain_access(Some(chain_monitor));
3736 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
3737 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3738 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3739 short_channel_id: 333,
3742 cltv_expiry_delta: (3 << 4) | 1,
3743 htlc_minimum_msat: 0,
3744 htlc_maximum_msat: OptionalField::Absent,
3746 fee_proportional_millionths: 0,
3747 excess_data: Vec::new()
3749 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3750 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3751 short_channel_id: 333,
3754 cltv_expiry_delta: (3 << 4) | 2,
3755 htlc_minimum_msat: 0,
3756 htlc_maximum_msat: OptionalField::Absent,
3758 fee_proportional_millionths: 0,
3759 excess_data: Vec::new()
3763 // Attempt to route more than available results in a failure.
3764 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3765 &our_id, &payment_params, &network_graph.read_only(), None, 15_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3766 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3767 } else { panic!(); }
3771 // Now, attempt to route an exact amount we have should be fine.
3772 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 15_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3773 assert_eq!(route.paths.len(), 1);
3774 let path = route.paths.last().unwrap();
3775 assert_eq!(path.len(), 2);
3776 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3777 assert_eq!(path.last().unwrap().fee_msat, 15_000);
3780 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
3781 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3782 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3783 short_channel_id: 333,
3786 cltv_expiry_delta: 0,
3787 htlc_minimum_msat: 0,
3788 htlc_maximum_msat: OptionalField::Present(10_000),
3790 fee_proportional_millionths: 0,
3791 excess_data: Vec::new()
3795 // Attempt to route more than available results in a failure.
3796 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3797 &our_id, &payment_params, &network_graph.read_only(), None, 10_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3798 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3799 } else { panic!(); }
3803 // Now, attempt to route an exact amount we have should be fine.
3804 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 10_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3805 assert_eq!(route.paths.len(), 1);
3806 let path = route.paths.last().unwrap();
3807 assert_eq!(path.len(), 2);
3808 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3809 assert_eq!(path.last().unwrap().fee_msat, 10_000);
3814 fn available_liquidity_last_hop_test() {
3815 // Check that available liquidity properly limits the path even when only
3816 // one of the latter hops is limited.
3817 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3818 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3819 let scorer = test_utils::TestScorer::with_penalty(0);
3820 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3821 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3822 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
3824 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3825 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
3826 // Total capacity: 50 sats.
3828 // Disable other potential paths.
3829 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3830 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3831 short_channel_id: 2,
3834 cltv_expiry_delta: 0,
3835 htlc_minimum_msat: 0,
3836 htlc_maximum_msat: OptionalField::Present(100_000),
3838 fee_proportional_millionths: 0,
3839 excess_data: Vec::new()
3841 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3842 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3843 short_channel_id: 7,
3846 cltv_expiry_delta: 0,
3847 htlc_minimum_msat: 0,
3848 htlc_maximum_msat: OptionalField::Present(100_000),
3850 fee_proportional_millionths: 0,
3851 excess_data: Vec::new()
3856 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3857 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3858 short_channel_id: 12,
3861 cltv_expiry_delta: 0,
3862 htlc_minimum_msat: 0,
3863 htlc_maximum_msat: OptionalField::Present(100_000),
3865 fee_proportional_millionths: 0,
3866 excess_data: Vec::new()
3868 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3869 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3870 short_channel_id: 13,
3873 cltv_expiry_delta: 0,
3874 htlc_minimum_msat: 0,
3875 htlc_maximum_msat: OptionalField::Present(100_000),
3877 fee_proportional_millionths: 0,
3878 excess_data: Vec::new()
3881 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3882 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3883 short_channel_id: 6,
3886 cltv_expiry_delta: 0,
3887 htlc_minimum_msat: 0,
3888 htlc_maximum_msat: OptionalField::Present(50_000),
3890 fee_proportional_millionths: 0,
3891 excess_data: Vec::new()
3893 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3894 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3895 short_channel_id: 11,
3898 cltv_expiry_delta: 0,
3899 htlc_minimum_msat: 0,
3900 htlc_maximum_msat: OptionalField::Present(100_000),
3902 fee_proportional_millionths: 0,
3903 excess_data: Vec::new()
3906 // Attempt to route more than available results in a failure.
3907 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3908 &our_id, &payment_params, &network_graph.read_only(), None, 60_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3909 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3910 } else { panic!(); }
3914 // Now, attempt to route 49 sats (just a bit below the capacity).
3915 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 49_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3916 assert_eq!(route.paths.len(), 1);
3917 let mut total_amount_paid_msat = 0;
3918 for path in &route.paths {
3919 assert_eq!(path.len(), 4);
3920 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3921 total_amount_paid_msat += path.last().unwrap().fee_msat;
3923 assert_eq!(total_amount_paid_msat, 49_000);
3927 // Attempt to route an exact amount is also fine
3928 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3929 assert_eq!(route.paths.len(), 1);
3930 let mut total_amount_paid_msat = 0;
3931 for path in &route.paths {
3932 assert_eq!(path.len(), 4);
3933 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3934 total_amount_paid_msat += path.last().unwrap().fee_msat;
3936 assert_eq!(total_amount_paid_msat, 50_000);
3941 fn ignore_fee_first_hop_test() {
3942 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3943 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3944 let scorer = test_utils::TestScorer::with_penalty(0);
3945 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3946 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3947 let payment_params = PaymentParameters::from_node_id(nodes[2]);
3949 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3950 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3951 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3952 short_channel_id: 1,
3955 cltv_expiry_delta: 0,
3956 htlc_minimum_msat: 0,
3957 htlc_maximum_msat: OptionalField::Present(100_000),
3958 fee_base_msat: 1_000_000,
3959 fee_proportional_millionths: 0,
3960 excess_data: Vec::new()
3962 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3963 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3964 short_channel_id: 3,
3967 cltv_expiry_delta: 0,
3968 htlc_minimum_msat: 0,
3969 htlc_maximum_msat: OptionalField::Present(50_000),
3971 fee_proportional_millionths: 0,
3972 excess_data: Vec::new()
3976 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3977 assert_eq!(route.paths.len(), 1);
3978 let mut total_amount_paid_msat = 0;
3979 for path in &route.paths {
3980 assert_eq!(path.len(), 2);
3981 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3982 total_amount_paid_msat += path.last().unwrap().fee_msat;
3984 assert_eq!(total_amount_paid_msat, 50_000);
3989 fn simple_mpp_route_test() {
3990 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3991 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3992 let scorer = test_utils::TestScorer::with_penalty(0);
3993 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3994 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3995 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
3997 // We need a route consisting of 3 paths:
3998 // From our node to node2 via node0, node7, node1 (three paths one hop each).
3999 // To achieve this, the amount being transferred should be around
4000 // the total capacity of these 3 paths.
4002 // First, we set limits on these (previously unlimited) channels.
4003 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
4005 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
4006 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4007 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4008 short_channel_id: 1,
4011 cltv_expiry_delta: 0,
4012 htlc_minimum_msat: 0,
4013 htlc_maximum_msat: OptionalField::Present(100_000),
4015 fee_proportional_millionths: 0,
4016 excess_data: Vec::new()
4018 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4019 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4020 short_channel_id: 3,
4023 cltv_expiry_delta: 0,
4024 htlc_minimum_msat: 0,
4025 htlc_maximum_msat: OptionalField::Present(50_000),
4027 fee_proportional_millionths: 0,
4028 excess_data: Vec::new()
4031 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
4032 // (total limit 60).
4033 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4034 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4035 short_channel_id: 12,
4038 cltv_expiry_delta: 0,
4039 htlc_minimum_msat: 0,
4040 htlc_maximum_msat: OptionalField::Present(60_000),
4042 fee_proportional_millionths: 0,
4043 excess_data: Vec::new()
4045 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4046 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4047 short_channel_id: 13,
4050 cltv_expiry_delta: 0,
4051 htlc_minimum_msat: 0,
4052 htlc_maximum_msat: OptionalField::Present(60_000),
4054 fee_proportional_millionths: 0,
4055 excess_data: Vec::new()
4058 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
4059 // (total capacity 180 sats).
4060 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4061 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4062 short_channel_id: 2,
4065 cltv_expiry_delta: 0,
4066 htlc_minimum_msat: 0,
4067 htlc_maximum_msat: OptionalField::Present(200_000),
4069 fee_proportional_millionths: 0,
4070 excess_data: Vec::new()
4072 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4073 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4074 short_channel_id: 4,
4077 cltv_expiry_delta: 0,
4078 htlc_minimum_msat: 0,
4079 htlc_maximum_msat: OptionalField::Present(180_000),
4081 fee_proportional_millionths: 0,
4082 excess_data: Vec::new()
4086 // Attempt to route more than available results in a failure.
4087 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4088 &our_id, &payment_params, &network_graph.read_only(), None, 300_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
4089 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4090 } else { panic!(); }
4094 // Now, attempt to route 250 sats (just a bit below the capacity).
4095 // Our algorithm should provide us with these 3 paths.
4096 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 250_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4097 assert_eq!(route.paths.len(), 3);
4098 let mut total_amount_paid_msat = 0;
4099 for path in &route.paths {
4100 assert_eq!(path.len(), 2);
4101 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4102 total_amount_paid_msat += path.last().unwrap().fee_msat;
4104 assert_eq!(total_amount_paid_msat, 250_000);
4108 // Attempt to route an exact amount is also fine
4109 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 290_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4110 assert_eq!(route.paths.len(), 3);
4111 let mut total_amount_paid_msat = 0;
4112 for path in &route.paths {
4113 assert_eq!(path.len(), 2);
4114 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4115 total_amount_paid_msat += path.last().unwrap().fee_msat;
4117 assert_eq!(total_amount_paid_msat, 290_000);
4122 fn long_mpp_route_test() {
4123 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4124 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4125 let scorer = test_utils::TestScorer::with_penalty(0);
4126 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4127 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4128 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
4130 // We need a route consisting of 3 paths:
4131 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
4132 // Note that these paths overlap (channels 5, 12, 13).
4133 // We will route 300 sats.
4134 // Each path will have 100 sats capacity, those channels which
4135 // are used twice will have 200 sats capacity.
4137 // Disable other potential paths.
4138 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4139 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4140 short_channel_id: 2,
4143 cltv_expiry_delta: 0,
4144 htlc_minimum_msat: 0,
4145 htlc_maximum_msat: OptionalField::Present(100_000),
4147 fee_proportional_millionths: 0,
4148 excess_data: Vec::new()
4150 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4151 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4152 short_channel_id: 7,
4155 cltv_expiry_delta: 0,
4156 htlc_minimum_msat: 0,
4157 htlc_maximum_msat: OptionalField::Present(100_000),
4159 fee_proportional_millionths: 0,
4160 excess_data: Vec::new()
4163 // Path via {node0, node2} is channels {1, 3, 5}.
4164 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4165 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4166 short_channel_id: 1,
4169 cltv_expiry_delta: 0,
4170 htlc_minimum_msat: 0,
4171 htlc_maximum_msat: OptionalField::Present(100_000),
4173 fee_proportional_millionths: 0,
4174 excess_data: Vec::new()
4176 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4177 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4178 short_channel_id: 3,
4181 cltv_expiry_delta: 0,
4182 htlc_minimum_msat: 0,
4183 htlc_maximum_msat: OptionalField::Present(100_000),
4185 fee_proportional_millionths: 0,
4186 excess_data: Vec::new()
4189 // Capacity of 200 sats because this channel will be used by 3rd path as well.
4190 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4191 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4192 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4193 short_channel_id: 5,
4196 cltv_expiry_delta: 0,
4197 htlc_minimum_msat: 0,
4198 htlc_maximum_msat: OptionalField::Present(200_000),
4200 fee_proportional_millionths: 0,
4201 excess_data: Vec::new()
4204 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4205 // Add 100 sats to the capacities of {12, 13}, because these channels
4206 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
4207 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4208 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4209 short_channel_id: 12,
4212 cltv_expiry_delta: 0,
4213 htlc_minimum_msat: 0,
4214 htlc_maximum_msat: OptionalField::Present(200_000),
4216 fee_proportional_millionths: 0,
4217 excess_data: Vec::new()
4219 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4220 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4221 short_channel_id: 13,
4224 cltv_expiry_delta: 0,
4225 htlc_minimum_msat: 0,
4226 htlc_maximum_msat: OptionalField::Present(200_000),
4228 fee_proportional_millionths: 0,
4229 excess_data: Vec::new()
4232 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4233 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4234 short_channel_id: 6,
4237 cltv_expiry_delta: 0,
4238 htlc_minimum_msat: 0,
4239 htlc_maximum_msat: OptionalField::Present(100_000),
4241 fee_proportional_millionths: 0,
4242 excess_data: Vec::new()
4244 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4245 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4246 short_channel_id: 11,
4249 cltv_expiry_delta: 0,
4250 htlc_minimum_msat: 0,
4251 htlc_maximum_msat: OptionalField::Present(100_000),
4253 fee_proportional_millionths: 0,
4254 excess_data: Vec::new()
4257 // Path via {node7, node2} is channels {12, 13, 5}.
4258 // We already limited them to 200 sats (they are used twice for 100 sats).
4259 // Nothing to do here.
4262 // Attempt to route more than available results in a failure.
4263 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4264 &our_id, &payment_params, &network_graph.read_only(), None, 350_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
4265 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4266 } else { panic!(); }
4270 // Now, attempt to route 300 sats (exact amount we can route).
4271 // Our algorithm should provide us with these 3 paths, 100 sats each.
4272 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 300_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4273 assert_eq!(route.paths.len(), 3);
4275 let mut total_amount_paid_msat = 0;
4276 for path in &route.paths {
4277 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
4278 total_amount_paid_msat += path.last().unwrap().fee_msat;
4280 assert_eq!(total_amount_paid_msat, 300_000);
4286 fn mpp_cheaper_route_test() {
4287 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4288 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4289 let scorer = test_utils::TestScorer::with_penalty(0);
4290 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4291 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4292 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
4294 // This test checks that if we have two cheaper paths and one more expensive path,
4295 // so that liquidity-wise any 2 of 3 combination is sufficient,
4296 // two cheaper paths will be taken.
4297 // These paths have equal available liquidity.
4299 // We need a combination of 3 paths:
4300 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
4301 // Note that these paths overlap (channels 5, 12, 13).
4302 // Each path will have 100 sats capacity, those channels which
4303 // are used twice will have 200 sats capacity.
4305 // Disable other potential paths.
4306 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4307 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4308 short_channel_id: 2,
4311 cltv_expiry_delta: 0,
4312 htlc_minimum_msat: 0,
4313 htlc_maximum_msat: OptionalField::Present(100_000),
4315 fee_proportional_millionths: 0,
4316 excess_data: Vec::new()
4318 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4319 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4320 short_channel_id: 7,
4323 cltv_expiry_delta: 0,
4324 htlc_minimum_msat: 0,
4325 htlc_maximum_msat: OptionalField::Present(100_000),
4327 fee_proportional_millionths: 0,
4328 excess_data: Vec::new()
4331 // Path via {node0, node2} is channels {1, 3, 5}.
4332 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4333 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4334 short_channel_id: 1,
4337 cltv_expiry_delta: 0,
4338 htlc_minimum_msat: 0,
4339 htlc_maximum_msat: OptionalField::Present(100_000),
4341 fee_proportional_millionths: 0,
4342 excess_data: Vec::new()
4344 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4345 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4346 short_channel_id: 3,
4349 cltv_expiry_delta: 0,
4350 htlc_minimum_msat: 0,
4351 htlc_maximum_msat: OptionalField::Present(100_000),
4353 fee_proportional_millionths: 0,
4354 excess_data: Vec::new()
4357 // Capacity of 200 sats because this channel will be used by 3rd path as well.
4358 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4359 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4360 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4361 short_channel_id: 5,
4364 cltv_expiry_delta: 0,
4365 htlc_minimum_msat: 0,
4366 htlc_maximum_msat: OptionalField::Present(200_000),
4368 fee_proportional_millionths: 0,
4369 excess_data: Vec::new()
4372 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4373 // Add 100 sats to the capacities of {12, 13}, because these channels
4374 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
4375 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4376 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4377 short_channel_id: 12,
4380 cltv_expiry_delta: 0,
4381 htlc_minimum_msat: 0,
4382 htlc_maximum_msat: OptionalField::Present(200_000),
4384 fee_proportional_millionths: 0,
4385 excess_data: Vec::new()
4387 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4388 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4389 short_channel_id: 13,
4392 cltv_expiry_delta: 0,
4393 htlc_minimum_msat: 0,
4394 htlc_maximum_msat: OptionalField::Present(200_000),
4396 fee_proportional_millionths: 0,
4397 excess_data: Vec::new()
4400 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4401 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4402 short_channel_id: 6,
4405 cltv_expiry_delta: 0,
4406 htlc_minimum_msat: 0,
4407 htlc_maximum_msat: OptionalField::Present(100_000),
4408 fee_base_msat: 1_000,
4409 fee_proportional_millionths: 0,
4410 excess_data: Vec::new()
4412 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4413 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4414 short_channel_id: 11,
4417 cltv_expiry_delta: 0,
4418 htlc_minimum_msat: 0,
4419 htlc_maximum_msat: OptionalField::Present(100_000),
4421 fee_proportional_millionths: 0,
4422 excess_data: Vec::new()
4425 // Path via {node7, node2} is channels {12, 13, 5}.
4426 // We already limited them to 200 sats (they are used twice for 100 sats).
4427 // Nothing to do here.
4430 // Now, attempt to route 180 sats.
4431 // Our algorithm should provide us with these 2 paths.
4432 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 180_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4433 assert_eq!(route.paths.len(), 2);
4435 let mut total_value_transferred_msat = 0;
4436 let mut total_paid_msat = 0;
4437 for path in &route.paths {
4438 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
4439 total_value_transferred_msat += path.last().unwrap().fee_msat;
4441 total_paid_msat += hop.fee_msat;
4444 // If we paid fee, this would be higher.
4445 assert_eq!(total_value_transferred_msat, 180_000);
4446 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
4447 assert_eq!(total_fees_paid, 0);
4452 fn fees_on_mpp_route_test() {
4453 // This test makes sure that MPP algorithm properly takes into account
4454 // fees charged on the channels, by making the fees impactful:
4455 // if the fee is not properly accounted for, the behavior is different.
4456 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4457 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4458 let scorer = test_utils::TestScorer::with_penalty(0);
4459 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4460 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4461 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
4463 // We need a route consisting of 2 paths:
4464 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
4465 // We will route 200 sats, Each path will have 100 sats capacity.
4467 // This test is not particularly stable: e.g.,
4468 // there's a way to route via {node0, node2, node4}.
4469 // It works while pathfinding is deterministic, but can be broken otherwise.
4470 // It's fine to ignore this concern for now.
4472 // Disable other potential paths.
4473 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4474 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4475 short_channel_id: 2,
4478 cltv_expiry_delta: 0,
4479 htlc_minimum_msat: 0,
4480 htlc_maximum_msat: OptionalField::Present(100_000),
4482 fee_proportional_millionths: 0,
4483 excess_data: Vec::new()
4486 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4487 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4488 short_channel_id: 7,
4491 cltv_expiry_delta: 0,
4492 htlc_minimum_msat: 0,
4493 htlc_maximum_msat: OptionalField::Present(100_000),
4495 fee_proportional_millionths: 0,
4496 excess_data: Vec::new()
4499 // Path via {node0, node2} is channels {1, 3, 5}.
4500 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4501 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4502 short_channel_id: 1,
4505 cltv_expiry_delta: 0,
4506 htlc_minimum_msat: 0,
4507 htlc_maximum_msat: OptionalField::Present(100_000),
4509 fee_proportional_millionths: 0,
4510 excess_data: Vec::new()
4512 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4513 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4514 short_channel_id: 3,
4517 cltv_expiry_delta: 0,
4518 htlc_minimum_msat: 0,
4519 htlc_maximum_msat: OptionalField::Present(100_000),
4521 fee_proportional_millionths: 0,
4522 excess_data: Vec::new()
4525 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4526 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4527 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4528 short_channel_id: 5,
4531 cltv_expiry_delta: 0,
4532 htlc_minimum_msat: 0,
4533 htlc_maximum_msat: OptionalField::Present(100_000),
4535 fee_proportional_millionths: 0,
4536 excess_data: Vec::new()
4539 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4540 // All channels should be 100 sats capacity. But for the fee experiment,
4541 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
4542 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
4543 // 100 sats (and pay 150 sats in fees for the use of channel 6),
4544 // so no matter how large are other channels,
4545 // the whole path will be limited by 100 sats with just these 2 conditions:
4546 // - channel 12 capacity is 250 sats
4547 // - fee for channel 6 is 150 sats
4548 // Let's test this by enforcing these 2 conditions and removing other limits.
4549 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4550 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4551 short_channel_id: 12,
4554 cltv_expiry_delta: 0,
4555 htlc_minimum_msat: 0,
4556 htlc_maximum_msat: OptionalField::Present(250_000),
4558 fee_proportional_millionths: 0,
4559 excess_data: Vec::new()
4561 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4562 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4563 short_channel_id: 13,
4566 cltv_expiry_delta: 0,
4567 htlc_minimum_msat: 0,
4568 htlc_maximum_msat: OptionalField::Absent,
4570 fee_proportional_millionths: 0,
4571 excess_data: Vec::new()
4574 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4575 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4576 short_channel_id: 6,
4579 cltv_expiry_delta: 0,
4580 htlc_minimum_msat: 0,
4581 htlc_maximum_msat: OptionalField::Absent,
4582 fee_base_msat: 150_000,
4583 fee_proportional_millionths: 0,
4584 excess_data: Vec::new()
4586 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4587 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4588 short_channel_id: 11,
4591 cltv_expiry_delta: 0,
4592 htlc_minimum_msat: 0,
4593 htlc_maximum_msat: OptionalField::Absent,
4595 fee_proportional_millionths: 0,
4596 excess_data: Vec::new()
4600 // Attempt to route more than available results in a failure.
4601 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4602 &our_id, &payment_params, &network_graph.read_only(), None, 210_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
4603 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4604 } else { panic!(); }
4608 // Now, attempt to route 200 sats (exact amount we can route).
4609 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 200_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4610 assert_eq!(route.paths.len(), 2);
4612 let mut total_amount_paid_msat = 0;
4613 for path in &route.paths {
4614 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
4615 total_amount_paid_msat += path.last().unwrap().fee_msat;
4617 assert_eq!(total_amount_paid_msat, 200_000);
4618 assert_eq!(route.get_total_fees(), 150_000);
4623 fn mpp_with_last_hops() {
4624 // Previously, if we tried to send an MPP payment to a destination which was only reachable
4625 // via a single last-hop route hint, we'd fail to route if we first collected routes
4626 // totaling close but not quite enough to fund the full payment.
4628 // This was because we considered last-hop hints to have exactly the sought payment amount
4629 // instead of the amount we were trying to collect, needlessly limiting our path searching
4630 // at the very first hop.
4632 // Specifically, this interacted with our "all paths must fund at least 5% of total target"
4633 // criterion to cause us to refuse all routes at the last hop hint which would be considered
4634 // to only have the remaining to-collect amount in available liquidity.
4636 // This bug appeared in production in some specific channel configurations.
4637 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4638 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4639 let scorer = test_utils::TestScorer::with_penalty(0);
4640 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4641 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4642 let payment_params = PaymentParameters::from_node_id(PublicKey::from_slice(&[02; 33]).unwrap()).with_features(InvoiceFeatures::known())
4643 .with_route_hints(vec![RouteHint(vec![RouteHintHop {
4644 src_node_id: nodes[2],
4645 short_channel_id: 42,
4646 fees: RoutingFees { base_msat: 0, proportional_millionths: 0 },
4647 cltv_expiry_delta: 42,
4648 htlc_minimum_msat: None,
4649 htlc_maximum_msat: None,
4652 // Keep only two paths from us to nodes[2], both with a 99sat HTLC maximum, with one with
4653 // no fee and one with a 1msat fee. Previously, trying to route 100 sats to nodes[2] here
4654 // would first use the no-fee route and then fail to find a path along the second route as
4655 // we think we can only send up to 1 additional sat over the last-hop but refuse to as its
4656 // under 5% of our payment amount.
4657 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4658 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4659 short_channel_id: 1,
4662 cltv_expiry_delta: (5 << 4) | 5,
4663 htlc_minimum_msat: 0,
4664 htlc_maximum_msat: OptionalField::Present(99_000),
4665 fee_base_msat: u32::max_value(),
4666 fee_proportional_millionths: u32::max_value(),
4667 excess_data: Vec::new()
4669 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4670 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4671 short_channel_id: 2,
4674 cltv_expiry_delta: (5 << 4) | 3,
4675 htlc_minimum_msat: 0,
4676 htlc_maximum_msat: OptionalField::Present(99_000),
4677 fee_base_msat: u32::max_value(),
4678 fee_proportional_millionths: u32::max_value(),
4679 excess_data: Vec::new()
4681 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4682 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4683 short_channel_id: 4,
4686 cltv_expiry_delta: (4 << 4) | 1,
4687 htlc_minimum_msat: 0,
4688 htlc_maximum_msat: OptionalField::Absent,
4690 fee_proportional_millionths: 0,
4691 excess_data: Vec::new()
4693 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4694 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4695 short_channel_id: 13,
4697 flags: 0|2, // Channel disabled
4698 cltv_expiry_delta: (13 << 4) | 1,
4699 htlc_minimum_msat: 0,
4700 htlc_maximum_msat: OptionalField::Absent,
4702 fee_proportional_millionths: 2000000,
4703 excess_data: Vec::new()
4706 // Get a route for 100 sats and check that we found the MPP route no problem and didn't
4708 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4709 assert_eq!(route.paths.len(), 2);
4710 // Paths are somewhat randomly ordered, but:
4711 // * the first is channel 2 (1 msat fee) -> channel 4 -> channel 42
4712 // * the second is channel 1 (0 fee, but 99 sat maximum) -> channel 3 -> channel 42
4713 assert_eq!(route.paths[0][0].short_channel_id, 2);
4714 assert_eq!(route.paths[0][0].fee_msat, 1);
4715 assert_eq!(route.paths[0][2].fee_msat, 1_000);
4716 assert_eq!(route.paths[1][0].short_channel_id, 1);
4717 assert_eq!(route.paths[1][0].fee_msat, 0);
4718 assert_eq!(route.paths[1][2].fee_msat, 99_000);
4719 assert_eq!(route.get_total_fees(), 1);
4720 assert_eq!(route.get_total_amount(), 100_000);
4724 fn drop_lowest_channel_mpp_route_test() {
4725 // This test checks that low-capacity channel is dropped when after
4726 // path finding we realize that we found more capacity than we need.
4727 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4728 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4729 let scorer = test_utils::TestScorer::with_penalty(0);
4730 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4731 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4732 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
4734 // We need a route consisting of 3 paths:
4735 // From our node to node2 via node0, node7, node1 (three paths one hop each).
4737 // The first and the second paths should be sufficient, but the third should be
4738 // cheaper, so that we select it but drop later.
4740 // First, we set limits on these (previously unlimited) channels.
4741 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
4743 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
4744 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4745 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4746 short_channel_id: 1,
4749 cltv_expiry_delta: 0,
4750 htlc_minimum_msat: 0,
4751 htlc_maximum_msat: OptionalField::Present(100_000),
4753 fee_proportional_millionths: 0,
4754 excess_data: Vec::new()
4756 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4757 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4758 short_channel_id: 3,
4761 cltv_expiry_delta: 0,
4762 htlc_minimum_msat: 0,
4763 htlc_maximum_msat: OptionalField::Present(50_000),
4765 fee_proportional_millionths: 0,
4766 excess_data: Vec::new()
4769 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
4770 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4771 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4772 short_channel_id: 12,
4775 cltv_expiry_delta: 0,
4776 htlc_minimum_msat: 0,
4777 htlc_maximum_msat: OptionalField::Present(60_000),
4779 fee_proportional_millionths: 0,
4780 excess_data: Vec::new()
4782 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4783 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4784 short_channel_id: 13,
4787 cltv_expiry_delta: 0,
4788 htlc_minimum_msat: 0,
4789 htlc_maximum_msat: OptionalField::Present(60_000),
4791 fee_proportional_millionths: 0,
4792 excess_data: Vec::new()
4795 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
4796 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4797 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4798 short_channel_id: 2,
4801 cltv_expiry_delta: 0,
4802 htlc_minimum_msat: 0,
4803 htlc_maximum_msat: OptionalField::Present(20_000),
4805 fee_proportional_millionths: 0,
4806 excess_data: Vec::new()
4808 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4809 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4810 short_channel_id: 4,
4813 cltv_expiry_delta: 0,
4814 htlc_minimum_msat: 0,
4815 htlc_maximum_msat: OptionalField::Present(20_000),
4817 fee_proportional_millionths: 0,
4818 excess_data: Vec::new()
4822 // Attempt to route more than available results in a failure.
4823 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4824 &our_id, &payment_params, &network_graph.read_only(), None, 150_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
4825 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4826 } else { panic!(); }
4830 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
4831 // Our algorithm should provide us with these 3 paths.
4832 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 125_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4833 assert_eq!(route.paths.len(), 3);
4834 let mut total_amount_paid_msat = 0;
4835 for path in &route.paths {
4836 assert_eq!(path.len(), 2);
4837 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4838 total_amount_paid_msat += path.last().unwrap().fee_msat;
4840 assert_eq!(total_amount_paid_msat, 125_000);
4844 // Attempt to route without the last small cheap channel
4845 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4846 assert_eq!(route.paths.len(), 2);
4847 let mut total_amount_paid_msat = 0;
4848 for path in &route.paths {
4849 assert_eq!(path.len(), 2);
4850 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4851 total_amount_paid_msat += path.last().unwrap().fee_msat;
4853 assert_eq!(total_amount_paid_msat, 90_000);
4858 fn min_criteria_consistency() {
4859 // Test that we don't use an inconsistent metric between updating and walking nodes during
4860 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
4861 // was updated with a different criterion from the heap sorting, resulting in loops in
4862 // calculated paths. We test for that specific case here.
4864 // We construct a network that looks like this:
4866 // node2 -1(3)2- node3
4870 // node1 -1(5)2- node4 -1(1)2- node6
4876 // We create a loop on the side of our real path - our destination is node 6, with a
4877 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
4878 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
4879 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
4880 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
4881 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
4882 // "previous hop" being set to node 3, creating a loop in the path.
4883 let secp_ctx = Secp256k1::new();
4884 let logger = Arc::new(test_utils::TestLogger::new());
4885 let network = Arc::new(NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash()));
4886 let net_graph_msg_handler = NetGraphMsgHandler::new(Arc::clone(&network), None, Arc::clone(&logger));
4887 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4888 let scorer = test_utils::TestScorer::with_penalty(0);
4889 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4890 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4891 let payment_params = PaymentParameters::from_node_id(nodes[6]);
4893 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
4894 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4895 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4896 short_channel_id: 6,
4899 cltv_expiry_delta: (6 << 4) | 0,
4900 htlc_minimum_msat: 0,
4901 htlc_maximum_msat: OptionalField::Absent,
4903 fee_proportional_millionths: 0,
4904 excess_data: Vec::new()
4906 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
4908 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4909 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4910 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4911 short_channel_id: 5,
4914 cltv_expiry_delta: (5 << 4) | 0,
4915 htlc_minimum_msat: 0,
4916 htlc_maximum_msat: OptionalField::Absent,
4918 fee_proportional_millionths: 0,
4919 excess_data: Vec::new()
4921 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
4923 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
4924 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4925 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4926 short_channel_id: 4,
4929 cltv_expiry_delta: (4 << 4) | 0,
4930 htlc_minimum_msat: 0,
4931 htlc_maximum_msat: OptionalField::Absent,
4933 fee_proportional_millionths: 0,
4934 excess_data: Vec::new()
4936 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
4938 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
4939 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
4940 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4941 short_channel_id: 3,
4944 cltv_expiry_delta: (3 << 4) | 0,
4945 htlc_minimum_msat: 0,
4946 htlc_maximum_msat: OptionalField::Absent,
4948 fee_proportional_millionths: 0,
4949 excess_data: Vec::new()
4951 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
4953 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
4954 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4955 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4956 short_channel_id: 2,
4959 cltv_expiry_delta: (2 << 4) | 0,
4960 htlc_minimum_msat: 0,
4961 htlc_maximum_msat: OptionalField::Absent,
4963 fee_proportional_millionths: 0,
4964 excess_data: Vec::new()
4967 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
4968 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4969 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4970 short_channel_id: 1,
4973 cltv_expiry_delta: (1 << 4) | 0,
4974 htlc_minimum_msat: 100,
4975 htlc_maximum_msat: OptionalField::Absent,
4977 fee_proportional_millionths: 0,
4978 excess_data: Vec::new()
4980 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
4983 // Now ensure the route flows simply over nodes 1 and 4 to 6.
4984 let route = get_route(&our_id, &payment_params, &network.read_only(), None, 10_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4985 assert_eq!(route.paths.len(), 1);
4986 assert_eq!(route.paths[0].len(), 3);
4988 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
4989 assert_eq!(route.paths[0][0].short_channel_id, 6);
4990 assert_eq!(route.paths[0][0].fee_msat, 100);
4991 assert_eq!(route.paths[0][0].cltv_expiry_delta, (5 << 4) | 0);
4992 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(1));
4993 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(6));
4995 assert_eq!(route.paths[0][1].pubkey, nodes[4]);
4996 assert_eq!(route.paths[0][1].short_channel_id, 5);
4997 assert_eq!(route.paths[0][1].fee_msat, 0);
4998 assert_eq!(route.paths[0][1].cltv_expiry_delta, (1 << 4) | 0);
4999 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(4));
5000 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(5));
5002 assert_eq!(route.paths[0][2].pubkey, nodes[6]);
5003 assert_eq!(route.paths[0][2].short_channel_id, 1);
5004 assert_eq!(route.paths[0][2].fee_msat, 10_000);
5005 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
5006 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
5007 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(1));
5013 fn exact_fee_liquidity_limit() {
5014 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
5015 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
5016 // we calculated fees on a higher value, resulting in us ignoring such paths.
5017 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
5018 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
5019 let scorer = test_utils::TestScorer::with_penalty(0);
5020 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5021 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5022 let payment_params = PaymentParameters::from_node_id(nodes[2]);
5024 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
5026 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5027 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5028 short_channel_id: 2,
5031 cltv_expiry_delta: 0,
5032 htlc_minimum_msat: 0,
5033 htlc_maximum_msat: OptionalField::Present(85_000),
5035 fee_proportional_millionths: 0,
5036 excess_data: Vec::new()
5039 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5040 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5041 short_channel_id: 12,
5044 cltv_expiry_delta: (4 << 4) | 1,
5045 htlc_minimum_msat: 0,
5046 htlc_maximum_msat: OptionalField::Present(270_000),
5048 fee_proportional_millionths: 1000000,
5049 excess_data: Vec::new()
5053 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
5054 // 200% fee charged channel 13 in the 1-to-2 direction.
5055 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5056 assert_eq!(route.paths.len(), 1);
5057 assert_eq!(route.paths[0].len(), 2);
5059 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
5060 assert_eq!(route.paths[0][0].short_channel_id, 12);
5061 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
5062 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
5063 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
5064 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
5066 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
5067 assert_eq!(route.paths[0][1].short_channel_id, 13);
5068 assert_eq!(route.paths[0][1].fee_msat, 90_000);
5069 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
5070 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
5071 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
5076 fn htlc_max_reduction_below_min() {
5077 // Test that if, while walking the graph, we reduce the value being sent to meet an
5078 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
5079 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
5080 // resulting in us thinking there is no possible path, even if other paths exist.
5081 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
5082 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5083 let scorer = test_utils::TestScorer::with_penalty(0);
5084 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5085 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5086 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
5088 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
5089 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
5090 // then try to send 90_000.
5091 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5092 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5093 short_channel_id: 2,
5096 cltv_expiry_delta: 0,
5097 htlc_minimum_msat: 0,
5098 htlc_maximum_msat: OptionalField::Present(80_000),
5100 fee_proportional_millionths: 0,
5101 excess_data: Vec::new()
5103 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5104 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5105 short_channel_id: 4,
5108 cltv_expiry_delta: (4 << 4) | 1,
5109 htlc_minimum_msat: 90_000,
5110 htlc_maximum_msat: OptionalField::Absent,
5112 fee_proportional_millionths: 0,
5113 excess_data: Vec::new()
5117 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
5118 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
5119 // expensive) channels 12-13 path.
5120 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5121 assert_eq!(route.paths.len(), 1);
5122 assert_eq!(route.paths[0].len(), 2);
5124 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
5125 assert_eq!(route.paths[0][0].short_channel_id, 12);
5126 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
5127 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
5128 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
5129 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
5131 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
5132 assert_eq!(route.paths[0][1].short_channel_id, 13);
5133 assert_eq!(route.paths[0][1].fee_msat, 90_000);
5134 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
5135 assert_eq!(route.paths[0][1].node_features.le_flags(), InvoiceFeatures::known().le_flags());
5136 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
5141 fn multiple_direct_first_hops() {
5142 // Previously we'd only ever considered one first hop path per counterparty.
5143 // However, as we don't restrict users to one channel per peer, we really need to support
5144 // looking at all first hop paths.
5145 // Here we test that we do not ignore all-but-the-last first hop paths per counterparty (as
5146 // we used to do by overwriting the `first_hop_targets` hashmap entry) and that we can MPP
5147 // route over multiple channels with the same first hop.
5148 let secp_ctx = Secp256k1::new();
5149 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5150 let logger = Arc::new(test_utils::TestLogger::new());
5151 let network_graph = NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash());
5152 let scorer = test_utils::TestScorer::with_penalty(0);
5153 let payment_params = PaymentParameters::from_node_id(nodes[0]).with_features(InvoiceFeatures::known());
5154 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5155 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5158 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
5159 &get_channel_details(Some(3), nodes[0], InitFeatures::known(), 200_000),
5160 &get_channel_details(Some(2), nodes[0], InitFeatures::known(), 10_000),
5161 ]), 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5162 assert_eq!(route.paths.len(), 1);
5163 assert_eq!(route.paths[0].len(), 1);
5165 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
5166 assert_eq!(route.paths[0][0].short_channel_id, 3);
5167 assert_eq!(route.paths[0][0].fee_msat, 100_000);
5170 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
5171 &get_channel_details(Some(3), nodes[0], InitFeatures::known(), 50_000),
5172 &get_channel_details(Some(2), nodes[0], InitFeatures::known(), 50_000),
5173 ]), 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5174 assert_eq!(route.paths.len(), 2);
5175 assert_eq!(route.paths[0].len(), 1);
5176 assert_eq!(route.paths[1].len(), 1);
5178 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
5179 assert_eq!(route.paths[0][0].short_channel_id, 3);
5180 assert_eq!(route.paths[0][0].fee_msat, 50_000);
5182 assert_eq!(route.paths[1][0].pubkey, nodes[0]);
5183 assert_eq!(route.paths[1][0].short_channel_id, 2);
5184 assert_eq!(route.paths[1][0].fee_msat, 50_000);
5188 // If we have a bunch of outbound channels to the same node, where most are not
5189 // sufficient to pay the full payment, but one is, we should default to just using the
5190 // one single channel that has sufficient balance, avoiding MPP.
5192 // If we have several options above the 3xpayment value threshold, we should pick the
5193 // smallest of them, avoiding further fragmenting our available outbound balance to
5195 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
5196 &get_channel_details(Some(2), nodes[0], InitFeatures::known(), 50_000),
5197 &get_channel_details(Some(3), nodes[0], InitFeatures::known(), 50_000),
5198 &get_channel_details(Some(5), nodes[0], InitFeatures::known(), 50_000),
5199 &get_channel_details(Some(6), nodes[0], InitFeatures::known(), 300_000),
5200 &get_channel_details(Some(7), nodes[0], InitFeatures::known(), 50_000),
5201 &get_channel_details(Some(8), nodes[0], InitFeatures::known(), 50_000),
5202 &get_channel_details(Some(9), nodes[0], InitFeatures::known(), 50_000),
5203 &get_channel_details(Some(4), nodes[0], InitFeatures::known(), 1_000_000),
5204 ]), 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5205 assert_eq!(route.paths.len(), 1);
5206 assert_eq!(route.paths[0].len(), 1);
5208 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
5209 assert_eq!(route.paths[0][0].short_channel_id, 6);
5210 assert_eq!(route.paths[0][0].fee_msat, 100_000);
5215 fn prefers_shorter_route_with_higher_fees() {
5216 let (secp_ctx, network_graph, _, _, logger) = build_graph();
5217 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5218 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
5220 // Without penalizing each hop 100 msats, a longer path with lower fees is chosen.
5221 let scorer = test_utils::TestScorer::with_penalty(0);
5222 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5223 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5224 let route = get_route(
5225 &our_id, &payment_params, &network_graph.read_only(), None, 100, 42,
5226 Arc::clone(&logger), &scorer, &random_seed_bytes
5228 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5230 assert_eq!(route.get_total_fees(), 100);
5231 assert_eq!(route.get_total_amount(), 100);
5232 assert_eq!(path, vec![2, 4, 6, 11, 8]);
5234 // Applying a 100 msat penalty to each hop results in taking channels 7 and 10 to nodes[6]
5235 // from nodes[2] rather than channel 6, 11, and 8, even though the longer path is cheaper.
5236 let scorer = test_utils::TestScorer::with_penalty(100);
5237 let route = get_route(
5238 &our_id, &payment_params, &network_graph.read_only(), None, 100, 42,
5239 Arc::clone(&logger), &scorer, &random_seed_bytes
5241 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5243 assert_eq!(route.get_total_fees(), 300);
5244 assert_eq!(route.get_total_amount(), 100);
5245 assert_eq!(path, vec![2, 4, 7, 10]);
5248 struct BadChannelScorer {
5249 short_channel_id: u64,
5253 impl Writeable for BadChannelScorer {
5254 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), ::io::Error> { unimplemented!() }
5256 impl Score for BadChannelScorer {
5257 fn channel_penalty_msat(&self, short_channel_id: u64, _: &NodeId, _: &NodeId, _: ChannelUsage) -> u64 {
5258 if short_channel_id == self.short_channel_id { u64::max_value() } else { 0 }
5261 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
5262 fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
5265 struct BadNodeScorer {
5270 impl Writeable for BadNodeScorer {
5271 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), ::io::Error> { unimplemented!() }
5274 impl Score for BadNodeScorer {
5275 fn channel_penalty_msat(&self, _: u64, _: &NodeId, target: &NodeId, _: ChannelUsage) -> u64 {
5276 if *target == self.node_id { u64::max_value() } else { 0 }
5279 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
5280 fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
5284 fn avoids_routing_through_bad_channels_and_nodes() {
5285 let (secp_ctx, network, _, _, logger) = build_graph();
5286 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5287 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
5288 let network_graph = network.read_only();
5290 // A path to nodes[6] exists when no penalties are applied to any channel.
5291 let scorer = test_utils::TestScorer::with_penalty(0);
5292 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5293 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5294 let route = get_route(
5295 &our_id, &payment_params, &network_graph, None, 100, 42,
5296 Arc::clone(&logger), &scorer, &random_seed_bytes
5298 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5300 assert_eq!(route.get_total_fees(), 100);
5301 assert_eq!(route.get_total_amount(), 100);
5302 assert_eq!(path, vec![2, 4, 6, 11, 8]);
5304 // A different path to nodes[6] exists if channel 6 cannot be routed over.
5305 let scorer = BadChannelScorer { short_channel_id: 6 };
5306 let route = get_route(
5307 &our_id, &payment_params, &network_graph, None, 100, 42,
5308 Arc::clone(&logger), &scorer, &random_seed_bytes
5310 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5312 assert_eq!(route.get_total_fees(), 300);
5313 assert_eq!(route.get_total_amount(), 100);
5314 assert_eq!(path, vec![2, 4, 7, 10]);
5316 // A path to nodes[6] does not exist if nodes[2] cannot be routed through.
5317 let scorer = BadNodeScorer { node_id: NodeId::from_pubkey(&nodes[2]) };
5319 &our_id, &payment_params, &network_graph, None, 100, 42,
5320 Arc::clone(&logger), &scorer, &random_seed_bytes
5322 Err(LightningError { err, .. } ) => {
5323 assert_eq!(err, "Failed to find a path to the given destination");
5325 Ok(_) => panic!("Expected error"),
5330 fn total_fees_single_path() {
5334 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5335 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5336 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5339 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5340 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5341 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5344 pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
5345 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5346 short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0
5349 payment_params: None,
5352 assert_eq!(route.get_total_fees(), 250);
5353 assert_eq!(route.get_total_amount(), 225);
5357 fn total_fees_multi_path() {
5361 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5362 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5363 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5366 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5367 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5368 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5372 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5373 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5374 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5377 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5378 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5379 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5382 payment_params: None,
5385 assert_eq!(route.get_total_fees(), 200);
5386 assert_eq!(route.get_total_amount(), 300);
5390 fn total_empty_route_no_panic() {
5391 // In an earlier version of `Route::get_total_fees` and `Route::get_total_amount`, they
5392 // would both panic if the route was completely empty. We test to ensure they return 0
5393 // here, even though its somewhat nonsensical as a route.
5394 let route = Route { paths: Vec::new(), payment_params: None };
5396 assert_eq!(route.get_total_fees(), 0);
5397 assert_eq!(route.get_total_amount(), 0);
5401 fn limits_total_cltv_delta() {
5402 let (secp_ctx, network, _, _, logger) = build_graph();
5403 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5404 let network_graph = network.read_only();
5406 let scorer = test_utils::TestScorer::with_penalty(0);
5408 // Make sure that generally there is at least one route available
5409 let feasible_max_total_cltv_delta = 1008;
5410 let feasible_payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes))
5411 .with_max_total_cltv_expiry_delta(feasible_max_total_cltv_delta);
5412 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5413 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5414 let route = get_route(&our_id, &feasible_payment_params, &network_graph, None, 100, 0, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5415 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5416 assert_ne!(path.len(), 0);
5418 // But not if we exclude all paths on the basis of their accumulated CLTV delta
5419 let fail_max_total_cltv_delta = 23;
5420 let fail_payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes))
5421 .with_max_total_cltv_expiry_delta(fail_max_total_cltv_delta);
5422 match get_route(&our_id, &fail_payment_params, &network_graph, None, 100, 0, Arc::clone(&logger), &scorer, &random_seed_bytes)
5424 Err(LightningError { err, .. } ) => {
5425 assert_eq!(err, "Failed to find a path to the given destination");
5427 Ok(_) => panic!("Expected error"),
5432 fn limits_path_length() {
5433 let (secp_ctx, network, _, _, logger) = build_line_graph();
5434 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5435 let network_graph = network.read_only();
5437 let scorer = test_utils::TestScorer::with_penalty(0);
5438 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5439 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5441 // First check we can actually create a long route on this graph.
5442 let feasible_payment_params = PaymentParameters::from_node_id(nodes[18]);
5443 let route = get_route(&our_id, &feasible_payment_params, &network_graph, None, 100, 0,
5444 Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5445 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5446 assert!(path.len() == MAX_PATH_LENGTH_ESTIMATE.into());
5448 // But we can't create a path surpassing the MAX_PATH_LENGTH_ESTIMATE limit.
5449 let fail_payment_params = PaymentParameters::from_node_id(nodes[19]);
5450 match get_route(&our_id, &fail_payment_params, &network_graph, None, 100, 0,
5451 Arc::clone(&logger), &scorer, &random_seed_bytes)
5453 Err(LightningError { err, .. } ) => {
5454 assert_eq!(err, "Failed to find a path to the given destination");
5456 Ok(_) => panic!("Expected error"),
5461 fn adds_and_limits_cltv_offset() {
5462 let (secp_ctx, network_graph, _, _, logger) = build_graph();
5463 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5465 let scorer = test_utils::TestScorer::with_penalty(0);
5467 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
5468 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5469 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5470 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5471 assert_eq!(route.paths.len(), 1);
5473 let cltv_expiry_deltas_before = route.paths[0].iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5475 // Check whether the offset added to the last hop by default is in [1 .. DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA]
5476 let mut route_default = route.clone();
5477 add_random_cltv_offset(&mut route_default, &payment_params, &network_graph.read_only(), &random_seed_bytes);
5478 let cltv_expiry_deltas_default = route_default.paths[0].iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5479 assert_eq!(cltv_expiry_deltas_before.split_last().unwrap().1, cltv_expiry_deltas_default.split_last().unwrap().1);
5480 assert!(cltv_expiry_deltas_default.last() > cltv_expiry_deltas_before.last());
5481 assert!(cltv_expiry_deltas_default.last().unwrap() <= &DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA);
5483 // Check that no offset is added when we restrict the max_total_cltv_expiry_delta
5484 let mut route_limited = route.clone();
5485 let limited_max_total_cltv_expiry_delta = cltv_expiry_deltas_before.iter().sum();
5486 let limited_payment_params = payment_params.with_max_total_cltv_expiry_delta(limited_max_total_cltv_expiry_delta);
5487 add_random_cltv_offset(&mut route_limited, &limited_payment_params, &network_graph.read_only(), &random_seed_bytes);
5488 let cltv_expiry_deltas_limited = route_limited.paths[0].iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5489 assert_eq!(cltv_expiry_deltas_before, cltv_expiry_deltas_limited);
5493 fn adds_plausible_cltv_offset() {
5494 let (secp_ctx, network, _, _, logger) = build_graph();
5495 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5496 let network_graph = network.read_only();
5497 let network_nodes = network_graph.nodes();
5498 let network_channels = network_graph.channels();
5499 let scorer = test_utils::TestScorer::with_penalty(0);
5500 let payment_params = PaymentParameters::from_node_id(nodes[3]);
5501 let keys_manager = test_utils::TestKeysInterface::new(&[4u8; 32], Network::Testnet);
5502 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5504 let mut route = get_route(&our_id, &payment_params, &network_graph, None, 100, 0,
5505 Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5506 add_random_cltv_offset(&mut route, &payment_params, &network_graph, &random_seed_bytes);
5508 let mut path_plausibility = vec![];
5510 for p in route.paths {
5511 // 1. Select random observation point
5512 let mut prng = ChaCha20::new(&random_seed_bytes, &[0u8; 12]);
5513 let mut random_bytes = [0u8; ::core::mem::size_of::<usize>()];
5515 prng.process_in_place(&mut random_bytes);
5516 let random_path_index = usize::from_be_bytes(random_bytes).wrapping_rem(p.len());
5517 let observation_point = NodeId::from_pubkey(&p.get(random_path_index).unwrap().pubkey);
5519 // 2. Calculate what CLTV expiry delta we would observe there
5520 let observed_cltv_expiry_delta: u32 = p[random_path_index..].iter().map(|h| h.cltv_expiry_delta).sum();
5522 // 3. Starting from the observation point, find candidate paths
5523 let mut candidates: VecDeque<(NodeId, Vec<u32>)> = VecDeque::new();
5524 candidates.push_back((observation_point, vec![]));
5526 let mut found_plausible_candidate = false;
5528 'candidate_loop: while let Some((cur_node_id, cur_path_cltv_deltas)) = candidates.pop_front() {
5529 if let Some(remaining) = observed_cltv_expiry_delta.checked_sub(cur_path_cltv_deltas.iter().sum::<u32>()) {
5530 if remaining == 0 || remaining.wrapping_rem(40) == 0 || remaining.wrapping_rem(144) == 0 {
5531 found_plausible_candidate = true;
5532 break 'candidate_loop;
5536 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
5537 for channel_id in &cur_node.channels {
5538 if let Some(channel_info) = network_channels.get(&channel_id) {
5539 if let Some((dir_info, next_id)) = channel_info.as_directed_from(&cur_node_id) {
5540 if let Some(channel_update_info) = dir_info.direction() {
5541 let next_cltv_expiry_delta = channel_update_info.cltv_expiry_delta as u32;
5542 if cur_path_cltv_deltas.iter().sum::<u32>()
5543 .saturating_add(next_cltv_expiry_delta) <= observed_cltv_expiry_delta {
5544 let mut new_path_cltv_deltas = cur_path_cltv_deltas.clone();
5545 new_path_cltv_deltas.push(next_cltv_expiry_delta);
5546 candidates.push_back((*next_id, new_path_cltv_deltas));
5555 path_plausibility.push(found_plausible_candidate);
5557 assert!(path_plausibility.iter().all(|x| *x));
5561 fn builds_correct_path_from_hops() {
5562 let (secp_ctx, network, _, _, logger) = build_graph();
5563 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5564 let network_graph = network.read_only();
5566 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5567 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5569 let payment_params = PaymentParameters::from_node_id(nodes[3]);
5570 let hops = [nodes[1], nodes[2], nodes[4], nodes[3]];
5571 let route = build_route_from_hops_internal(&our_id, &hops, &payment_params,
5572 &network_graph, 100, 0, Arc::clone(&logger), &random_seed_bytes).unwrap();
5573 let route_hop_pubkeys = route.paths[0].iter().map(|hop| hop.pubkey).collect::<Vec<_>>();
5574 assert_eq!(hops.len(), route.paths[0].len());
5575 for (idx, hop_pubkey) in hops.iter().enumerate() {
5576 assert!(*hop_pubkey == route_hop_pubkeys[idx]);
5580 #[cfg(not(feature = "no-std"))]
5581 pub(super) fn random_init_seed() -> u64 {
5582 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
5583 use core::hash::{BuildHasher, Hasher};
5584 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
5585 println!("Using seed of {}", seed);
5588 #[cfg(not(feature = "no-std"))]
5589 use util::ser::Readable;
5592 #[cfg(not(feature = "no-std"))]
5593 fn generate_routes() {
5594 use routing::scoring::{ProbabilisticScorer, ProbabilisticScoringParameters};
5596 let mut d = match super::test_utils::get_route_file() {
5603 let graph = NetworkGraph::read(&mut d).unwrap();
5604 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5605 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5607 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
5608 let mut seed = random_init_seed() as usize;
5609 let nodes = graph.read_only().nodes().clone();
5610 'load_endpoints: for _ in 0..10 {
5612 seed = seed.overflowing_mul(0xdeadbeef).0;
5613 let src = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5614 seed = seed.overflowing_mul(0xdeadbeef).0;
5615 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5616 let payment_params = PaymentParameters::from_node_id(dst);
5617 let amt = seed as u64 % 200_000_000;
5618 let params = ProbabilisticScoringParameters::default();
5619 let logger = test_utils::TestLogger::new();
5620 let scorer = ProbabilisticScorer::new(params, &graph, &logger);
5621 if get_route(src, &payment_params, &graph.read_only(), None, amt, 42, &logger, &scorer, &random_seed_bytes).is_ok() {
5622 continue 'load_endpoints;
5629 #[cfg(not(feature = "no-std"))]
5630 fn generate_routes_mpp() {
5631 use routing::scoring::{ProbabilisticScorer, ProbabilisticScoringParameters};
5633 let mut d = match super::test_utils::get_route_file() {
5640 let graph = NetworkGraph::read(&mut d).unwrap();
5641 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5642 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5644 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
5645 let mut seed = random_init_seed() as usize;
5646 let nodes = graph.read_only().nodes().clone();
5647 'load_endpoints: for _ in 0..10 {
5649 seed = seed.overflowing_mul(0xdeadbeef).0;
5650 let src = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5651 seed = seed.overflowing_mul(0xdeadbeef).0;
5652 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5653 let payment_params = PaymentParameters::from_node_id(dst).with_features(InvoiceFeatures::known());
5654 let amt = seed as u64 % 200_000_000;
5655 let params = ProbabilisticScoringParameters::default();
5656 let logger = test_utils::TestLogger::new();
5657 let scorer = ProbabilisticScorer::new(params, &graph, &logger);
5658 if get_route(src, &payment_params, &graph.read_only(), None, amt, 42, &logger, &scorer, &random_seed_bytes).is_ok() {
5659 continue 'load_endpoints;
5666 #[cfg(all(test, not(feature = "no-std")))]
5667 pub(crate) mod test_utils {
5669 /// Tries to open a network graph file, or panics with a URL to fetch it.
5670 pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
5671 let res = File::open("net_graph-2021-05-31.bin") // By default we're run in RL/lightning
5672 .or_else(|_| File::open("lightning/net_graph-2021-05-31.bin")) // We may be run manually in RL/
5673 .or_else(|_| { // Fall back to guessing based on the binary location
5674 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
5675 let mut path = std::env::current_exe().unwrap();
5676 path.pop(); // lightning-...
5678 path.pop(); // debug
5679 path.pop(); // target
5680 path.push("lightning");
5681 path.push("net_graph-2021-05-31.bin");
5682 eprintln!("{}", path.to_str().unwrap());
5685 .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");
5686 #[cfg(require_route_graph_test)]
5687 return Ok(res.unwrap());
5688 #[cfg(not(require_route_graph_test))]
5693 #[cfg(all(test, feature = "_bench_unstable", not(feature = "no-std")))]
5696 use bitcoin::hashes::Hash;
5697 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
5698 use chain::transaction::OutPoint;
5699 use chain::keysinterface::{KeysManager,KeysInterface};
5700 use ln::channelmanager::{ChannelCounterparty, ChannelDetails};
5701 use ln::features::{InitFeatures, InvoiceFeatures};
5702 use routing::scoring::{FixedPenaltyScorer, ProbabilisticScorer, ProbabilisticScoringParameters, Scorer};
5703 use util::logger::{Logger, Record};
5704 use util::test_utils::TestLogger;
5708 struct DummyLogger {}
5709 impl Logger for DummyLogger {
5710 fn log(&self, _record: &Record) {}
5713 fn read_network_graph() -> NetworkGraph {
5714 let mut d = test_utils::get_route_file().unwrap();
5715 NetworkGraph::read(&mut d).unwrap()
5718 fn payer_pubkey() -> PublicKey {
5719 let secp_ctx = Secp256k1::new();
5720 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
5724 fn first_hop(node_id: PublicKey) -> ChannelDetails {
5726 channel_id: [0; 32],
5727 counterparty: ChannelCounterparty {
5728 features: InitFeatures::known(),
5730 unspendable_punishment_reserve: 0,
5731 forwarding_info: None,
5732 outbound_htlc_minimum_msat: None,
5733 outbound_htlc_maximum_msat: None,
5735 funding_txo: Some(OutPoint {
5736 txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0
5739 short_channel_id: Some(1),
5740 inbound_scid_alias: None,
5741 channel_value_satoshis: 10_000_000,
5743 balance_msat: 10_000_000,
5744 outbound_capacity_msat: 10_000_000,
5745 next_outbound_htlc_limit_msat: 10_000_000,
5746 inbound_capacity_msat: 0,
5747 unspendable_punishment_reserve: None,
5748 confirmations_required: None,
5749 force_close_spend_delay: None,
5751 is_funding_locked: true,
5754 inbound_htlc_minimum_msat: None,
5755 inbound_htlc_maximum_msat: None,
5760 fn generate_routes_with_zero_penalty_scorer(bench: &mut Bencher) {
5761 let network_graph = read_network_graph();
5762 let scorer = FixedPenaltyScorer::with_penalty(0);
5763 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::empty());
5767 fn generate_mpp_routes_with_zero_penalty_scorer(bench: &mut Bencher) {
5768 let network_graph = read_network_graph();
5769 let scorer = FixedPenaltyScorer::with_penalty(0);
5770 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::known());
5774 fn generate_routes_with_default_scorer(bench: &mut Bencher) {
5775 let network_graph = read_network_graph();
5776 let scorer = Scorer::default();
5777 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::empty());
5781 fn generate_mpp_routes_with_default_scorer(bench: &mut Bencher) {
5782 let network_graph = read_network_graph();
5783 let scorer = Scorer::default();
5784 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::known());
5788 fn generate_routes_with_probabilistic_scorer(bench: &mut Bencher) {
5789 let logger = TestLogger::new();
5790 let network_graph = read_network_graph();
5791 let params = ProbabilisticScoringParameters::default();
5792 let scorer = ProbabilisticScorer::new(params, &network_graph, &logger);
5793 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::empty());
5797 fn generate_mpp_routes_with_probabilistic_scorer(bench: &mut Bencher) {
5798 let logger = TestLogger::new();
5799 let network_graph = read_network_graph();
5800 let params = ProbabilisticScoringParameters::default();
5801 let scorer = ProbabilisticScorer::new(params, &network_graph, &logger);
5802 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::known());
5805 fn generate_routes<S: Score>(
5806 bench: &mut Bencher, graph: &NetworkGraph, mut scorer: S, features: InvoiceFeatures
5808 let nodes = graph.read_only().nodes().clone();
5809 let payer = payer_pubkey();
5810 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
5811 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5813 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
5814 let mut routes = Vec::new();
5815 let mut route_endpoints = Vec::new();
5816 let mut seed: usize = 0xdeadbeef;
5817 'load_endpoints: for _ in 0..150 {
5820 let src = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5822 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5823 let params = PaymentParameters::from_node_id(dst).with_features(features.clone());
5824 let first_hop = first_hop(src);
5825 let amt = seed as u64 % 1_000_000;
5826 if let Ok(route) = get_route(&payer, ¶ms, &graph.read_only(), Some(&[&first_hop]), amt, 42, &DummyLogger{}, &scorer, &random_seed_bytes) {
5828 route_endpoints.push((first_hop, params, amt));
5829 continue 'load_endpoints;
5834 // ...and seed the scorer with success and failure data...
5835 for route in routes {
5836 let amount = route.get_total_amount();
5837 if amount < 250_000 {
5838 for path in route.paths {
5839 scorer.payment_path_successful(&path.iter().collect::<Vec<_>>());
5841 } else if amount > 750_000 {
5842 for path in route.paths {
5843 let short_channel_id = path[path.len() / 2].short_channel_id;
5844 scorer.payment_path_failed(&path.iter().collect::<Vec<_>>(), short_channel_id);
5849 // Because we've changed channel scores, its possible we'll take different routes to the
5850 // selected destinations, possibly causing us to fail because, eg, the newly-selected path
5851 // requires a too-high CLTV delta.
5852 route_endpoints.retain(|(first_hop, params, amt)| {
5853 get_route(&payer, params, &graph.read_only(), Some(&[first_hop]), *amt, 42, &DummyLogger{}, &scorer, &random_seed_bytes).is_ok()
5855 route_endpoints.truncate(100);
5856 assert_eq!(route_endpoints.len(), 100);
5858 // ...then benchmark finding paths between the nodes we learned.
5861 let (first_hop, params, amt) = &route_endpoints[idx % route_endpoints.len()];
5862 assert!(get_route(&payer, params, &graph.read_only(), Some(&[first_hop]), *amt, 42, &DummyLogger{}, &scorer, &random_seed_bytes).is_ok());