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 P2PGossipSync 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::gossip::{DirectedChannelInfoWithUpdate, EffectiveCapacity, ReadOnlyNetworkGraph, NetworkGraph, NodeId, RoutingFees};
21 use routing::scoring::{ChannelUsage, Score};
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 [`ReadOnlyNetworkGraph`], where the channel capacity may be unknown.
374 info: DirectedChannelInfoWithUpdate<'a>,
375 short_channel_id: u64,
377 /// A hop to the payee found in the payment invoice, though not necessarily a direct channel.
379 hint: &'a RouteHintHop,
383 impl<'a> CandidateRouteHop<'a> {
384 fn short_channel_id(&self) -> u64 {
386 CandidateRouteHop::FirstHop { details } => details.get_outbound_payment_scid().unwrap(),
387 CandidateRouteHop::PublicHop { short_channel_id, .. } => *short_channel_id,
388 CandidateRouteHop::PrivateHop { hint } => hint.short_channel_id,
392 // NOTE: This may alloc memory so avoid calling it in a hot code path.
393 fn features(&self) -> ChannelFeatures {
395 CandidateRouteHop::FirstHop { details } => details.counterparty.features.to_context(),
396 CandidateRouteHop::PublicHop { info, .. } => info.channel().features.clone(),
397 CandidateRouteHop::PrivateHop { .. } => ChannelFeatures::empty(),
401 fn cltv_expiry_delta(&self) -> u32 {
403 CandidateRouteHop::FirstHop { .. } => 0,
404 CandidateRouteHop::PublicHop { info, .. } => info.direction().cltv_expiry_delta as u32,
405 CandidateRouteHop::PrivateHop { hint } => hint.cltv_expiry_delta as u32,
409 fn htlc_minimum_msat(&self) -> u64 {
411 CandidateRouteHop::FirstHop { .. } => 0,
412 CandidateRouteHop::PublicHop { info, .. } => info.direction().htlc_minimum_msat,
413 CandidateRouteHop::PrivateHop { hint } => hint.htlc_minimum_msat.unwrap_or(0),
417 fn htlc_maximum_msat(&self) -> u64 {
419 CandidateRouteHop::FirstHop { details } => details.next_outbound_htlc_limit_msat,
420 CandidateRouteHop::PublicHop { info, .. } => info.htlc_maximum_msat(),
421 CandidateRouteHop::PrivateHop { hint } => {
422 hint.htlc_maximum_msat.unwrap_or(u64::max_value())
427 fn fees(&self) -> RoutingFees {
429 CandidateRouteHop::FirstHop { .. } => RoutingFees {
430 base_msat: 0, proportional_millionths: 0,
432 CandidateRouteHop::PublicHop { info, .. } => info.direction().fees,
433 CandidateRouteHop::PrivateHop { hint } => hint.fees,
437 fn effective_capacity(&self) -> EffectiveCapacity {
439 CandidateRouteHop::FirstHop { details } => EffectiveCapacity::ExactLiquidity {
440 liquidity_msat: details.next_outbound_htlc_limit_msat,
442 CandidateRouteHop::PublicHop { info, .. } => info.effective_capacity(),
443 CandidateRouteHop::PrivateHop { .. } => EffectiveCapacity::Infinite,
448 /// It's useful to keep track of the hops associated with the fees required to use them,
449 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
450 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
451 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
453 struct PathBuildingHop<'a> {
454 // Note that this should be dropped in favor of loading it from CandidateRouteHop, but doing so
455 // is a larger refactor and will require careful performance analysis.
457 candidate: CandidateRouteHop<'a>,
460 /// Minimal fees required to route to the source node of the current hop via any of its inbound channels.
461 src_lowest_inbound_fees: RoutingFees,
462 /// All the fees paid *after* this channel on the way to the destination
463 next_hops_fee_msat: u64,
464 /// Fee paid for the use of the current channel (see candidate.fees()).
465 /// The value will be actually deducted from the counterparty balance on the previous link.
466 hop_use_fee_msat: u64,
467 /// Used to compare channels when choosing the for routing.
468 /// Includes paying for the use of a hop and the following hops, as well as
469 /// an estimated cost of reaching this hop.
470 /// Might get stale when fees are recomputed. Primarily for internal use.
472 /// A mirror of the same field in RouteGraphNode. Note that this is only used during the graph
473 /// walk and may be invalid thereafter.
474 path_htlc_minimum_msat: u64,
475 /// All penalties incurred from this channel on the way to the destination, as calculated using
477 path_penalty_msat: u64,
478 /// If we've already processed a node as the best node, we shouldn't process it again. Normally
479 /// we'd just ignore it if we did as all channels would have a higher new fee, but because we
480 /// may decrease the amounts in use as we walk the graph, the actual calculated fee may
481 /// decrease as well. Thus, we have to explicitly track which nodes have been processed and
482 /// avoid processing them again.
484 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
485 // In tests, we apply further sanity checks on cases where we skip nodes we already processed
486 // to ensure it is specifically in cases where the fee has gone down because of a decrease in
487 // value_contribution_msat, which requires tracking it here. See comments below where it is
488 // used for more info.
489 value_contribution_msat: u64,
492 impl<'a> core::fmt::Debug for PathBuildingHop<'a> {
493 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
494 let mut debug_struct = f.debug_struct("PathBuildingHop");
496 .field("node_id", &self.node_id)
497 .field("short_channel_id", &self.candidate.short_channel_id())
498 .field("total_fee_msat", &self.total_fee_msat)
499 .field("next_hops_fee_msat", &self.next_hops_fee_msat)
500 .field("hop_use_fee_msat", &self.hop_use_fee_msat)
501 .field("total_fee_msat - (next_hops_fee_msat + hop_use_fee_msat)", &(&self.total_fee_msat - (&self.next_hops_fee_msat + &self.hop_use_fee_msat)))
502 .field("path_penalty_msat", &self.path_penalty_msat)
503 .field("path_htlc_minimum_msat", &self.path_htlc_minimum_msat)
504 .field("cltv_expiry_delta", &self.candidate.cltv_expiry_delta());
505 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
506 let debug_struct = debug_struct
507 .field("value_contribution_msat", &self.value_contribution_msat);
508 debug_struct.finish()
512 // Instantiated with a list of hops with correct data in them collected during path finding,
513 // an instance of this struct should be further modified only via given methods.
515 struct PaymentPath<'a> {
516 hops: Vec<(PathBuildingHop<'a>, NodeFeatures)>,
519 impl<'a> PaymentPath<'a> {
520 // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
521 fn get_value_msat(&self) -> u64 {
522 self.hops.last().unwrap().0.fee_msat
525 fn get_path_penalty_msat(&self) -> u64 {
526 self.hops.first().map(|h| h.0.path_penalty_msat).unwrap_or(u64::max_value())
529 fn get_total_fee_paid_msat(&self) -> u64 {
530 if self.hops.len() < 1 {
534 // Can't use next_hops_fee_msat because it gets outdated.
535 for (i, (hop, _)) in self.hops.iter().enumerate() {
536 if i != self.hops.len() - 1 {
537 result += hop.fee_msat;
543 fn get_cost_msat(&self) -> u64 {
544 self.get_total_fee_paid_msat().saturating_add(self.get_path_penalty_msat())
547 // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
548 // to change fees may result in an inconsistency.
550 // Sometimes we call this function right after constructing a path which is inconsistent in
551 // that it the value being transferred has decreased while we were doing path finding, leading
552 // to the fees being paid not lining up with the actual limits.
554 // Note that this function is not aware of the available_liquidity limit, and thus does not
555 // support increasing the value being transferred.
556 fn update_value_and_recompute_fees(&mut self, value_msat: u64) {
557 assert!(value_msat <= self.hops.last().unwrap().0.fee_msat);
559 let mut total_fee_paid_msat = 0 as u64;
560 for i in (0..self.hops.len()).rev() {
561 let last_hop = i == self.hops.len() - 1;
563 // For non-last-hop, this value will represent the fees paid on the current hop. It
564 // will consist of the fees for the use of the next hop, and extra fees to match
565 // htlc_minimum_msat of the current channel. Last hop is handled separately.
566 let mut cur_hop_fees_msat = 0;
568 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().0.hop_use_fee_msat;
571 let mut cur_hop = &mut self.hops.get_mut(i).unwrap().0;
572 cur_hop.next_hops_fee_msat = total_fee_paid_msat;
573 // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
574 // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
575 // set it too high just to maliciously take more fees by exploiting this
576 // match htlc_minimum_msat logic.
577 let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
578 if let Some(extra_fees_msat) = cur_hop.candidate.htlc_minimum_msat().checked_sub(cur_hop_transferred_amount_msat) {
579 // Note that there is a risk that *previous hops* (those closer to us, as we go
580 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
582 // This might make us end up with a broken route, although this should be super-rare
583 // in practice, both because of how healthy channels look like, and how we pick
584 // channels in add_entry.
585 // Also, this can't be exploited more heavily than *announce a free path and fail
587 cur_hop_transferred_amount_msat += extra_fees_msat;
588 total_fee_paid_msat += extra_fees_msat;
589 cur_hop_fees_msat += extra_fees_msat;
593 // Final hop is a special case: it usually has just value_msat (by design), but also
594 // it still could overpay for the htlc_minimum_msat.
595 cur_hop.fee_msat = cur_hop_transferred_amount_msat;
597 // Propagate updated fees for the use of the channels to one hop back, where they
598 // will be actually paid (fee_msat). The last hop is handled above separately.
599 cur_hop.fee_msat = cur_hop_fees_msat;
602 // Fee for the use of the current hop which will be deducted on the previous hop.
603 // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
604 // this channel is free for us.
606 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.candidate.fees()) {
607 cur_hop.hop_use_fee_msat = new_fee;
608 total_fee_paid_msat += new_fee;
610 // It should not be possible because this function is called only to reduce the
611 // value. In that case, compute_fee was already called with the same fees for
612 // larger amount and there was no overflow.
620 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
621 let proportional_fee_millions =
622 amount_msat.checked_mul(channel_fees.proportional_millionths as u64);
623 if let Some(new_fee) = proportional_fee_millions.and_then(|part| {
624 (channel_fees.base_msat as u64).checked_add(part / 1_000_000) }) {
628 // This function may be (indirectly) called without any verification,
629 // with channel_fees provided by a caller. We should handle it gracefully.
634 /// The default `features` we assume for a node in a route, when no `features` are known about that
637 /// Default features are:
638 /// * variable_length_onion_optional
639 fn default_node_features() -> NodeFeatures {
640 let mut features = NodeFeatures::empty();
641 features.set_variable_length_onion_optional();
645 /// Finds a route from us (payer) to the given target node (payee).
647 /// If the payee provided features in their invoice, they should be provided via `params.payee`.
648 /// Without this, MPP will only be used if the payee's features are available in the network graph.
650 /// Private routing paths between a public node and the target may be included in `params.payee`.
652 /// If some channels aren't announced, it may be useful to fill in `first_hops` with the results
653 /// from [`ChannelManager::list_usable_channels`]. If it is filled in, the view of these channels
654 /// from `network_graph` 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 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
674 pub fn find_route<L: Deref, GL: Deref, S: Score>(
675 our_node_pubkey: &PublicKey, route_params: &RouteParameters,
676 network_graph: &NetworkGraph<GL>, first_hops: Option<&[&ChannelDetails]>, logger: L,
677 scorer: &S, random_seed_bytes: &[u8; 32]
678 ) -> Result<Route, LightningError>
679 where L::Target: Logger, GL::Target: Logger {
680 let graph_lock = network_graph.read_only();
681 let mut route = get_route(our_node_pubkey, &route_params.payment_params, &graph_lock, first_hops,
682 route_params.final_value_msat, route_params.final_cltv_expiry_delta, logger, scorer,
684 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
688 pub(crate) fn get_route<L: Deref, S: Score>(
689 our_node_pubkey: &PublicKey, payment_params: &PaymentParameters, network_graph: &ReadOnlyNetworkGraph,
690 first_hops: Option<&[&ChannelDetails]>, final_value_msat: u64, final_cltv_expiry_delta: u32,
691 logger: L, scorer: &S, random_seed_bytes: &[u8; 32]
692 ) -> Result<Route, LightningError>
693 where L::Target: Logger {
694 let payee_node_id = NodeId::from_pubkey(&payment_params.payee_pubkey);
695 let our_node_id = NodeId::from_pubkey(&our_node_pubkey);
697 if payee_node_id == our_node_id {
698 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
701 if final_value_msat > MAX_VALUE_MSAT {
702 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
705 if final_value_msat == 0 {
706 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
709 for route in payment_params.route_hints.iter() {
710 for hop in &route.0 {
711 if hop.src_node_id == payment_params.payee_pubkey {
712 return Err(LightningError{err: "Route hint cannot have the payee as the source.".to_owned(), action: ErrorAction::IgnoreError});
716 if payment_params.max_total_cltv_expiry_delta <= final_cltv_expiry_delta {
717 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});
720 // The general routing idea is the following:
721 // 1. Fill first/last hops communicated by the caller.
722 // 2. Attempt to construct a path from payer to payee for transferring
723 // any ~sufficient (described later) value.
724 // If succeed, remember which channels were used and how much liquidity they have available,
725 // so that future paths don't rely on the same liquidity.
726 // 3. Proceed to the next step if:
727 // - we hit the recommended target value;
728 // - OR if we could not construct a new path. Any next attempt will fail too.
729 // Otherwise, repeat step 2.
730 // 4. See if we managed to collect paths which aggregately are able to transfer target value
731 // (not recommended value).
732 // 5. If yes, proceed. If not, fail routing.
733 // 6. Randomly combine paths into routes having enough to fulfill the payment. (TODO: knapsack)
734 // 7. Of all the found paths, select only those with the lowest total fee.
735 // 8. The last path in every selected route is likely to be more than we need.
736 // Reduce its value-to-transfer and recompute fees.
737 // 9. Choose the best route by the lowest total fee.
739 // As for the actual search algorithm,
740 // we do a payee-to-payer pseudo-Dijkstra's sorting by each node's distance from the payee
741 // plus the minimum per-HTLC fee to get from it to another node (aka "shitty pseudo-A*").
743 // We are not a faithful Dijkstra's implementation because we can change values which impact
744 // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
745 // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) than
746 // the value we are currently attempting to send over a path, we simply reduce the value being
747 // sent along the path for any hops after that channel. This may imply that later fees (which
748 // we've already tabulated) are lower because a smaller value is passing through the channels
749 // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
750 // channels which were selected earlier (and which may still be used for other paths without a
751 // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
754 // One potentially problematic case for this algorithm would be if there are many
755 // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
756 // graph walking), we may never find a path which is not liquidity-limited and has lower
757 // proportional fee (and only lower absolute fee when considering the ultimate value sent).
758 // Because we only consider paths with at least 5% of the total value being sent, the damage
759 // from such a case should be limited, however this could be further reduced in the future by
760 // calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
761 // limits for the purposes of fee calculation.
763 // Alternatively, we could store more detailed path information in the heap (targets, below)
764 // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
765 // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
766 // and practically (as we would need to store dynamically-allocated path information in heap
767 // objects, increasing malloc traffic and indirect memory access significantly). Further, the
768 // results of such an algorithm would likely be biased towards lower-value paths.
770 // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
771 // outside of our current search value, running a path search more times to gather candidate
772 // paths at different values. While this may be acceptable, further path searches may increase
773 // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
774 // graph for candidate paths, calculating the maximum value which can realistically be sent at
775 // the same time, remaining generic across different payment values.
777 // TODO: There are a few tweaks we could do, including possibly pre-calculating more stuff
778 // to use as the A* heuristic beyond just the cost to get one node further than the current
781 let network_channels = network_graph.channels();
782 let network_nodes = network_graph.nodes();
784 // Allow MPP only if we have a features set from somewhere that indicates the payee supports
785 // it. If the payee supports it they're supposed to include it in the invoice, so that should
787 let allow_mpp = if let Some(features) = &payment_params.features {
788 features.supports_basic_mpp()
789 } else if let Some(node) = network_nodes.get(&payee_node_id) {
790 if let Some(node_info) = node.announcement_info.as_ref() {
791 node_info.features.supports_basic_mpp()
794 log_trace!(logger, "Searching for a route from payer {} to payee {} {} MPP and {} first hops {}overriding the network graph", our_node_pubkey,
795 payment_params.payee_pubkey, if allow_mpp { "with" } else { "without" },
796 first_hops.map(|hops| hops.len()).unwrap_or(0), if first_hops.is_some() { "" } else { "not " });
799 // Prepare the data we'll use for payee-to-payer search by
800 // inserting first hops suggested by the caller as targets.
801 // Our search will then attempt to reach them while traversing from the payee node.
802 let mut first_hop_targets: HashMap<_, Vec<&ChannelDetails>> =
803 HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
804 if let Some(hops) = first_hops {
806 if chan.get_outbound_payment_scid().is_none() {
807 panic!("first_hops should be filled in with usable channels, not pending ones");
809 if chan.counterparty.node_id == *our_node_pubkey {
810 return Err(LightningError{err: "First hop cannot have our_node_pubkey as a destination.".to_owned(), action: ErrorAction::IgnoreError});
813 .entry(NodeId::from_pubkey(&chan.counterparty.node_id))
814 .or_insert(Vec::new())
817 if first_hop_targets.is_empty() {
818 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
822 // The main heap containing all candidate next-hops sorted by their score (max(A* fee,
823 // htlc_minimum)). Ideally this would be a heap which allowed cheap score reduction instead of
824 // adding duplicate entries when we find a better path to a given node.
825 let mut targets: BinaryHeap<RouteGraphNode> = BinaryHeap::new();
827 // Map from node_id to information about the best current path to that node, including feerate
829 let mut dist: HashMap<NodeId, PathBuildingHop> = HashMap::with_capacity(network_nodes.len());
831 // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
832 // indicating that we may wish to try again with a higher value, potentially paying to meet an
833 // htlc_minimum with extra fees while still finding a cheaper path.
834 let mut hit_minimum_limit;
836 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
837 // We start with a path_value of the exact amount we want, and if that generates a route we may
838 // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
839 // amount we want in total across paths, selecting the best subset at the end.
840 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
841 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
842 let mut path_value_msat = final_value_msat;
844 // Keep track of how much liquidity has been used in selected channels. Used to determine
845 // if the channel can be used by additional MPP paths or to inform path finding decisions. It is
846 // aware of direction *only* to ensure that the correct htlc_maximum_msat value is used. Hence,
847 // liquidity used in one direction will not offset any used in the opposite direction.
848 let mut used_channel_liquidities: HashMap<(u64, bool), u64> =
849 HashMap::with_capacity(network_nodes.len());
851 // Keeping track of how much value we already collected across other paths. Helps to decide:
852 // - how much a new path should be transferring (upper bound);
853 // - whether a channel should be disregarded because
854 // it's available liquidity is too small comparing to how much more we need to collect;
855 // - when we want to stop looking for new paths.
856 let mut already_collected_value_msat = 0;
858 for (_, channels) in first_hop_targets.iter_mut() {
859 // Sort the first_hops channels to the same node(s) in priority order of which channel we'd
862 // First, if channels are below `recommended_value_msat`, sort them in descending order,
863 // preferring larger channels to avoid splitting the payment into more MPP parts than is
866 // Second, because simply always sorting in descending order would always use our largest
867 // available outbound capacity, needlessly fragmenting our available channel capacities,
868 // sort channels above `recommended_value_msat` in ascending order, preferring channels
869 // which have enough, but not too much, capacity for the payment.
870 channels.sort_unstable_by(|chan_a, chan_b| {
871 if chan_b.next_outbound_htlc_limit_msat < recommended_value_msat || chan_a.next_outbound_htlc_limit_msat < recommended_value_msat {
872 // Sort in descending order
873 chan_b.next_outbound_htlc_limit_msat.cmp(&chan_a.next_outbound_htlc_limit_msat)
875 // Sort in ascending order
876 chan_a.next_outbound_htlc_limit_msat.cmp(&chan_b.next_outbound_htlc_limit_msat)
881 log_trace!(logger, "Building path from {} (payee) to {} (us/payer) for value {} msat.", payment_params.payee_pubkey, our_node_pubkey, final_value_msat);
883 macro_rules! add_entry {
884 // Adds entry which goes from $src_node_id to $dest_node_id over the $candidate hop.
885 // $next_hops_fee_msat represents the fees paid for using all the channels *after* this one,
886 // since that value has to be transferred over this channel.
887 // Returns whether this channel caused an update to `targets`.
888 ( $candidate: expr, $src_node_id: expr, $dest_node_id: expr, $next_hops_fee_msat: expr,
889 $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr,
890 $next_hops_path_penalty_msat: expr, $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => { {
891 // We "return" whether we updated the path at the end, via this:
892 let mut did_add_update_path_to_src_node = false;
893 // Channels to self should not be used. This is more of belt-and-suspenders, because in
894 // practice these cases should be caught earlier:
895 // - for regular channels at channel announcement (TODO)
896 // - for first and last hops early in get_route
897 if $src_node_id != $dest_node_id {
898 let short_channel_id = $candidate.short_channel_id();
899 let htlc_maximum_msat = $candidate.htlc_maximum_msat();
901 // It is tricky to subtract $next_hops_fee_msat from available liquidity here.
902 // It may be misleading because we might later choose to reduce the value transferred
903 // over these channels, and the channel which was insufficient might become sufficient.
904 // Worst case: we drop a good channel here because it can't cover the high following
905 // fees caused by one expensive channel, but then this channel could have been used
906 // if the amount being transferred over this path is lower.
907 // We do this for now, but this is a subject for removal.
908 if let Some(mut available_value_contribution_msat) = htlc_maximum_msat.checked_sub($next_hops_fee_msat) {
909 let used_liquidity_msat = used_channel_liquidities
910 .get(&(short_channel_id, $src_node_id < $dest_node_id))
911 .map_or(0, |used_liquidity_msat| {
912 available_value_contribution_msat = available_value_contribution_msat
913 .saturating_sub(*used_liquidity_msat);
917 // Routing Fragmentation Mitigation heuristic:
919 // Routing fragmentation across many payment paths increases the overall routing
920 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
921 // Taking too many smaller paths also increases the chance of payment failure.
922 // Thus to avoid this effect, we require from our collected links to provide
923 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
925 // This requirement is currently 5% of the remaining-to-be-collected value.
926 // This means as we successfully advance in our collection,
927 // the absolute liquidity contribution is lowered,
928 // thus increasing the number of potential channels to be selected.
930 // Derive the minimal liquidity contribution with a ratio of 20 (5%, rounded up)
931 // or 100% if we're not allowed to do multipath payments.
932 let minimal_value_contribution_msat: u64 = if allow_mpp {
933 (recommended_value_msat - already_collected_value_msat + 19) / 20
937 // Verify the liquidity offered by this channel complies to the minimal contribution.
938 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
939 // Do not consider candidate hops that would exceed the maximum path length.
940 let path_length_to_node = $next_hops_path_length + 1;
941 let doesnt_exceed_max_path_length = path_length_to_node <= MAX_PATH_LENGTH_ESTIMATE;
943 // Do not consider candidates that exceed the maximum total cltv expiry limit.
944 // In order to already account for some of the privacy enhancing random CLTV
945 // expiry delta offset we add on top later, we subtract a rough estimate
946 // (2*MEDIAN_HOP_CLTV_EXPIRY_DELTA) here.
947 let max_total_cltv_expiry_delta = (payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta)
948 .checked_sub(2*MEDIAN_HOP_CLTV_EXPIRY_DELTA)
949 .unwrap_or(payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta);
950 let hop_total_cltv_delta = ($next_hops_cltv_delta as u32)
951 .saturating_add($candidate.cltv_expiry_delta());
952 let doesnt_exceed_cltv_delta_limit = hop_total_cltv_delta <= max_total_cltv_expiry_delta;
954 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
955 // Includes paying fees for the use of the following channels.
956 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
957 Some(result) => result,
958 // Can't overflow due to how the values were computed right above.
959 None => unreachable!(),
961 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
962 let over_path_minimum_msat = amount_to_transfer_over_msat >= $candidate.htlc_minimum_msat() &&
963 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
965 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
966 let may_overpay_to_meet_path_minimum_msat =
967 ((amount_to_transfer_over_msat < $candidate.htlc_minimum_msat() &&
968 recommended_value_msat > $candidate.htlc_minimum_msat()) ||
969 (amount_to_transfer_over_msat < $next_hops_path_htlc_minimum_msat &&
970 recommended_value_msat > $next_hops_path_htlc_minimum_msat));
972 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
973 // bother considering this channel. If retrying with recommended_value_msat may
974 // allow us to hit the HTLC minimum limit, set htlc_minimum_limit so that we go
975 // around again with a higher amount.
976 if contributes_sufficient_value && doesnt_exceed_max_path_length &&
977 doesnt_exceed_cltv_delta_limit && may_overpay_to_meet_path_minimum_msat {
978 hit_minimum_limit = true;
979 } else if contributes_sufficient_value && doesnt_exceed_max_path_length &&
980 doesnt_exceed_cltv_delta_limit && over_path_minimum_msat {
981 // Note that low contribution here (limited by available_liquidity_msat)
982 // might violate htlc_minimum_msat on the hops which are next along the
983 // payment path (upstream to the payee). To avoid that, we recompute
984 // path fees knowing the final path contribution after constructing it.
985 let path_htlc_minimum_msat = compute_fees($next_hops_path_htlc_minimum_msat, $candidate.fees())
986 .and_then(|fee_msat| fee_msat.checked_add($next_hops_path_htlc_minimum_msat))
987 .map(|fee_msat| cmp::max(fee_msat, $candidate.htlc_minimum_msat()))
988 .unwrap_or_else(|| u64::max_value());
989 let hm_entry = dist.entry($src_node_id);
990 let old_entry = hm_entry.or_insert_with(|| {
991 // If there was previously no known way to access the source node
992 // (recall it goes payee-to-payer) of short_channel_id, first add a
993 // semi-dummy record just to compute the fees to reach the source node.
994 // This will affect our decision on selecting short_channel_id
995 // as a way to reach the $dest_node_id.
996 let mut fee_base_msat = 0;
997 let mut fee_proportional_millionths = 0;
998 if let Some(Some(fees)) = network_nodes.get(&$src_node_id).map(|node| node.lowest_inbound_channel_fees) {
999 fee_base_msat = fees.base_msat;
1000 fee_proportional_millionths = fees.proportional_millionths;
1003 node_id: $dest_node_id.clone(),
1004 candidate: $candidate.clone(),
1006 src_lowest_inbound_fees: RoutingFees {
1007 base_msat: fee_base_msat,
1008 proportional_millionths: fee_proportional_millionths,
1010 next_hops_fee_msat: u64::max_value(),
1011 hop_use_fee_msat: u64::max_value(),
1012 total_fee_msat: u64::max_value(),
1013 path_htlc_minimum_msat,
1014 path_penalty_msat: u64::max_value(),
1015 was_processed: false,
1016 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
1017 value_contribution_msat,
1021 #[allow(unused_mut)] // We only use the mut in cfg(test)
1022 let mut should_process = !old_entry.was_processed;
1023 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
1025 // In test/fuzzing builds, we do extra checks to make sure the skipping
1026 // of already-seen nodes only happens in cases we expect (see below).
1027 if !should_process { should_process = true; }
1031 let mut hop_use_fee_msat = 0;
1032 let mut total_fee_msat = $next_hops_fee_msat;
1034 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
1035 // will have the same effective-fee
1036 if $src_node_id != our_node_id {
1037 match compute_fees(amount_to_transfer_over_msat, $candidate.fees()) {
1038 // max_value means we'll always fail
1039 // the old_entry.total_fee_msat > total_fee_msat check
1040 None => total_fee_msat = u64::max_value(),
1042 hop_use_fee_msat = fee_msat;
1043 total_fee_msat += hop_use_fee_msat;
1044 // When calculating the lowest inbound fees to a node, we
1045 // calculate fees here not based on the actual value we think
1046 // will flow over this channel, but on the minimum value that
1047 // we'll accept flowing over it. The minimum accepted value
1048 // is a constant through each path collection run, ensuring
1049 // consistent basis. Otherwise we may later find a
1050 // different path to the source node that is more expensive,
1051 // but which we consider to be cheaper because we are capacity
1052 // constrained and the relative fee becomes lower.
1053 match compute_fees(minimal_value_contribution_msat, old_entry.src_lowest_inbound_fees)
1054 .map(|a| a.checked_add(total_fee_msat)) {
1059 total_fee_msat = u64::max_value();
1066 let channel_usage = ChannelUsage {
1067 amount_msat: amount_to_transfer_over_msat,
1068 inflight_htlc_msat: used_liquidity_msat,
1069 effective_capacity: $candidate.effective_capacity(),
1071 let channel_penalty_msat = scorer.channel_penalty_msat(
1072 short_channel_id, &$src_node_id, &$dest_node_id, channel_usage
1074 let path_penalty_msat = $next_hops_path_penalty_msat
1075 .saturating_add(channel_penalty_msat);
1076 let new_graph_node = RouteGraphNode {
1077 node_id: $src_node_id,
1078 lowest_fee_to_peer_through_node: total_fee_msat,
1079 lowest_fee_to_node: $next_hops_fee_msat as u64 + hop_use_fee_msat,
1080 total_cltv_delta: hop_total_cltv_delta,
1081 value_contribution_msat: value_contribution_msat,
1082 path_htlc_minimum_msat,
1084 path_length_to_node,
1087 // Update the way of reaching $src_node_id with the given short_channel_id (from $dest_node_id),
1088 // if this way is cheaper than the already known
1089 // (considering the cost to "reach" this channel from the route destination,
1090 // the cost of using this channel,
1091 // and the cost of routing to the source node of this channel).
1092 // Also, consider that htlc_minimum_msat_difference, because we might end up
1093 // paying it. Consider the following exploit:
1094 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
1095 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
1096 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
1097 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
1099 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
1100 // but it may require additional tracking - we don't want to double-count
1101 // the fees included in $next_hops_path_htlc_minimum_msat, but also
1102 // can't use something that may decrease on future hops.
1103 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat)
1104 .saturating_add(old_entry.path_penalty_msat);
1105 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat)
1106 .saturating_add(path_penalty_msat);
1108 if !old_entry.was_processed && new_cost < old_cost {
1109 targets.push(new_graph_node);
1110 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
1111 old_entry.hop_use_fee_msat = hop_use_fee_msat;
1112 old_entry.total_fee_msat = total_fee_msat;
1113 old_entry.node_id = $dest_node_id.clone();
1114 old_entry.candidate = $candidate.clone();
1115 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
1116 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
1117 old_entry.path_penalty_msat = path_penalty_msat;
1118 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
1120 old_entry.value_contribution_msat = value_contribution_msat;
1122 did_add_update_path_to_src_node = true;
1123 } else if old_entry.was_processed && new_cost < old_cost {
1124 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
1126 // If we're skipping processing a node which was previously
1127 // processed even though we found another path to it with a
1128 // cheaper fee, check that it was because the second path we
1129 // found (which we are processing now) has a lower value
1130 // contribution due to an HTLC minimum limit.
1132 // e.g. take a graph with two paths from node 1 to node 2, one
1133 // through channel A, and one through channel B. Channel A and
1134 // B are both in the to-process heap, with their scores set by
1135 // a higher htlc_minimum than fee.
1136 // Channel A is processed first, and the channels onwards from
1137 // node 1 are added to the to-process heap. Thereafter, we pop
1138 // Channel B off of the heap, note that it has a much more
1139 // restrictive htlc_maximum_msat, and recalculate the fees for
1140 // all of node 1's channels using the new, reduced, amount.
1142 // This would be bogus - we'd be selecting a higher-fee path
1143 // with a lower htlc_maximum_msat instead of the one we'd
1144 // already decided to use.
1145 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
1147 value_contribution_msat + path_penalty_msat <
1148 old_entry.value_contribution_msat + old_entry.path_penalty_msat
1156 did_add_update_path_to_src_node
1160 let default_node_features = default_node_features();
1162 // Find ways (channels with destination) to reach a given node and store them
1163 // in the corresponding data structures (routing graph etc).
1164 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
1165 // meaning how much will be paid in fees after this node (to the best of our knowledge).
1166 // This data can later be helpful to optimize routing (pay lower fees).
1167 macro_rules! add_entries_to_cheapest_to_target_node {
1168 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr, $next_hops_value_contribution: expr,
1169 $next_hops_path_htlc_minimum_msat: expr, $next_hops_path_penalty_msat: expr,
1170 $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => {
1171 let skip_node = if let Some(elem) = dist.get_mut(&$node_id) {
1172 let was_processed = elem.was_processed;
1173 elem.was_processed = true;
1176 // Entries are added to dist in add_entry!() when there is a channel from a node.
1177 // Because there are no channels from payee, it will not have a dist entry at this point.
1178 // If we're processing any other node, it is always be the result of a channel from it.
1179 assert_eq!($node_id, payee_node_id);
1184 if let Some(first_channels) = first_hop_targets.get(&$node_id) {
1185 for details in first_channels {
1186 let candidate = CandidateRouteHop::FirstHop { details };
1187 add_entry!(candidate, our_node_id, $node_id, $fee_to_target_msat,
1188 $next_hops_value_contribution,
1189 $next_hops_path_htlc_minimum_msat, $next_hops_path_penalty_msat,
1190 $next_hops_cltv_delta, $next_hops_path_length);
1194 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
1197 &default_node_features
1200 if !features.requires_unknown_bits() {
1201 for chan_id in $node.channels.iter() {
1202 let chan = network_channels.get(chan_id).unwrap();
1203 if !chan.features.requires_unknown_bits() {
1204 let (directed_channel, source) =
1205 chan.as_directed_to(&$node_id).expect("inconsistent NetworkGraph");
1206 if first_hops.is_none() || *source != our_node_id {
1207 if let Some(direction) = directed_channel.direction() {
1208 if direction.enabled {
1209 let candidate = CandidateRouteHop::PublicHop {
1210 info: directed_channel.with_update().unwrap(),
1211 short_channel_id: *chan_id,
1213 add_entry!(candidate, *source, $node_id,
1214 $fee_to_target_msat,
1215 $next_hops_value_contribution,
1216 $next_hops_path_htlc_minimum_msat,
1217 $next_hops_path_penalty_msat,
1218 $next_hops_cltv_delta, $next_hops_path_length);
1229 let mut payment_paths = Vec::<PaymentPath>::new();
1231 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
1232 'paths_collection: loop {
1233 // For every new path, start from scratch, except for used_channel_liquidities, which
1234 // helps to avoid reusing previously selected paths in future iterations.
1237 hit_minimum_limit = false;
1239 // If first hop is a private channel and the only way to reach the payee, this is the only
1240 // place where it could be added.
1241 if let Some(first_channels) = first_hop_targets.get(&payee_node_id) {
1242 for details in first_channels {
1243 let candidate = CandidateRouteHop::FirstHop { details };
1244 let added = add_entry!(candidate, our_node_id, payee_node_id, 0, path_value_msat,
1246 log_trace!(logger, "{} direct route to payee via SCID {}",
1247 if added { "Added" } else { "Skipped" }, candidate.short_channel_id());
1251 // Add the payee as a target, so that the payee-to-payer
1252 // search algorithm knows what to start with.
1253 match network_nodes.get(&payee_node_id) {
1254 // The payee is not in our network graph, so nothing to add here.
1255 // There is still a chance of reaching them via last_hops though,
1256 // so don't yet fail the payment here.
1257 // If not, targets.pop() will not even let us enter the loop in step 2.
1260 add_entries_to_cheapest_to_target_node!(node, payee_node_id, 0, path_value_msat, 0, 0u64, 0, 0);
1265 // If a caller provided us with last hops, add them to routing targets. Since this happens
1266 // earlier than general path finding, they will be somewhat prioritized, although currently
1267 // it matters only if the fees are exactly the same.
1268 for route in payment_params.route_hints.iter().filter(|route| !route.0.is_empty()) {
1269 let first_hop_in_route = &(route.0)[0];
1270 let have_hop_src_in_graph =
1271 // Only add the hops in this route to our candidate set if either
1272 // we have a direct channel to the first hop or the first hop is
1273 // in the regular network graph.
1274 first_hop_targets.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some() ||
1275 network_nodes.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some();
1276 if have_hop_src_in_graph {
1277 // We start building the path from reverse, i.e., from payee
1278 // to the first RouteHintHop in the path.
1279 let hop_iter = route.0.iter().rev();
1280 let prev_hop_iter = core::iter::once(&payment_params.payee_pubkey).chain(
1281 route.0.iter().skip(1).rev().map(|hop| &hop.src_node_id));
1282 let mut hop_used = true;
1283 let mut aggregate_next_hops_fee_msat: u64 = 0;
1284 let mut aggregate_next_hops_path_htlc_minimum_msat: u64 = 0;
1285 let mut aggregate_next_hops_path_penalty_msat: u64 = 0;
1286 let mut aggregate_next_hops_cltv_delta: u32 = 0;
1287 let mut aggregate_next_hops_path_length: u8 = 0;
1289 for (idx, (hop, prev_hop_id)) in hop_iter.zip(prev_hop_iter).enumerate() {
1290 let source = NodeId::from_pubkey(&hop.src_node_id);
1291 let target = NodeId::from_pubkey(&prev_hop_id);
1292 let candidate = network_channels
1293 .get(&hop.short_channel_id)
1294 .and_then(|channel| channel.as_directed_to(&target))
1295 .and_then(|(channel, _)| channel.with_update())
1296 .map(|info| CandidateRouteHop::PublicHop {
1298 short_channel_id: hop.short_channel_id,
1300 .unwrap_or_else(|| CandidateRouteHop::PrivateHop { hint: hop });
1302 if !add_entry!(candidate, source, target, aggregate_next_hops_fee_msat,
1303 path_value_msat, aggregate_next_hops_path_htlc_minimum_msat,
1304 aggregate_next_hops_path_penalty_msat,
1305 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length) {
1306 // If this hop was not used then there is no use checking the preceding
1307 // hops in the RouteHint. We can break by just searching for a direct
1308 // channel between last checked hop and first_hop_targets.
1312 let used_liquidity_msat = used_channel_liquidities
1313 .get(&(hop.short_channel_id, source < target)).copied().unwrap_or(0);
1314 let channel_usage = ChannelUsage {
1315 amount_msat: final_value_msat + aggregate_next_hops_fee_msat,
1316 inflight_htlc_msat: used_liquidity_msat,
1317 effective_capacity: candidate.effective_capacity(),
1319 let channel_penalty_msat = scorer.channel_penalty_msat(
1320 hop.short_channel_id, &source, &target, channel_usage
1322 aggregate_next_hops_path_penalty_msat = aggregate_next_hops_path_penalty_msat
1323 .saturating_add(channel_penalty_msat);
1325 aggregate_next_hops_cltv_delta = aggregate_next_hops_cltv_delta
1326 .saturating_add(hop.cltv_expiry_delta as u32);
1328 aggregate_next_hops_path_length = aggregate_next_hops_path_length
1331 // Searching for a direct channel between last checked hop and first_hop_targets
1332 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&prev_hop_id)) {
1333 for details in first_channels {
1334 let candidate = CandidateRouteHop::FirstHop { details };
1335 add_entry!(candidate, our_node_id, NodeId::from_pubkey(&prev_hop_id),
1336 aggregate_next_hops_fee_msat, path_value_msat,
1337 aggregate_next_hops_path_htlc_minimum_msat,
1338 aggregate_next_hops_path_penalty_msat, aggregate_next_hops_cltv_delta,
1339 aggregate_next_hops_path_length);
1347 // In the next values of the iterator, the aggregate fees already reflects
1348 // the sum of value sent from payer (final_value_msat) and routing fees
1349 // for the last node in the RouteHint. We need to just add the fees to
1350 // route through the current node so that the preceding node (next iteration)
1352 let hops_fee = compute_fees(aggregate_next_hops_fee_msat + final_value_msat, hop.fees)
1353 .map_or(None, |inc| inc.checked_add(aggregate_next_hops_fee_msat));
1354 aggregate_next_hops_fee_msat = if let Some(val) = hops_fee { val } else { break; };
1356 let hop_htlc_minimum_msat = candidate.htlc_minimum_msat();
1357 let hop_htlc_minimum_msat_inc = if let Some(val) = compute_fees(aggregate_next_hops_path_htlc_minimum_msat, hop.fees) { val } else { break; };
1358 let hops_path_htlc_minimum = aggregate_next_hops_path_htlc_minimum_msat
1359 .checked_add(hop_htlc_minimum_msat_inc);
1360 aggregate_next_hops_path_htlc_minimum_msat = if let Some(val) = hops_path_htlc_minimum { cmp::max(hop_htlc_minimum_msat, val) } else { break; };
1362 if idx == route.0.len() - 1 {
1363 // The last hop in this iterator is the first hop in
1364 // overall RouteHint.
1365 // If this hop connects to a node with which we have a direct channel,
1366 // ignore the network graph and, if the last hop was added, add our
1367 // direct channel to the candidate set.
1369 // Note that we *must* check if the last hop was added as `add_entry`
1370 // always assumes that the third argument is a node to which we have a
1372 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&hop.src_node_id)) {
1373 for details in first_channels {
1374 let candidate = CandidateRouteHop::FirstHop { details };
1375 add_entry!(candidate, our_node_id,
1376 NodeId::from_pubkey(&hop.src_node_id),
1377 aggregate_next_hops_fee_msat, path_value_msat,
1378 aggregate_next_hops_path_htlc_minimum_msat,
1379 aggregate_next_hops_path_penalty_msat,
1380 aggregate_next_hops_cltv_delta,
1381 aggregate_next_hops_path_length);
1389 log_trace!(logger, "Starting main path collection loop with {} nodes pre-filled from first/last hops.", targets.len());
1391 // At this point, targets are filled with the data from first and
1392 // last hops communicated by the caller, and the payment receiver.
1393 let mut found_new_path = false;
1396 // If this loop terminates due the exhaustion of targets, two situations are possible:
1397 // - not enough outgoing liquidity:
1398 // 0 < already_collected_value_msat < final_value_msat
1399 // - enough outgoing liquidity:
1400 // final_value_msat <= already_collected_value_msat < recommended_value_msat
1401 // Both these cases (and other cases except reaching recommended_value_msat) mean that
1402 // paths_collection will be stopped because found_new_path==false.
1403 // This is not necessarily a routing failure.
1404 '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() {
1406 // Since we're going payee-to-payer, hitting our node as a target means we should stop
1407 // traversing the graph and arrange the path out of what we found.
1408 if node_id == our_node_id {
1409 let mut new_entry = dist.remove(&our_node_id).unwrap();
1410 let mut ordered_hops: Vec<(PathBuildingHop, NodeFeatures)> = vec!((new_entry.clone(), default_node_features.clone()));
1413 let mut features_set = false;
1414 if let Some(first_channels) = first_hop_targets.get(&ordered_hops.last().unwrap().0.node_id) {
1415 for details in first_channels {
1416 if details.get_outbound_payment_scid().unwrap() == ordered_hops.last().unwrap().0.candidate.short_channel_id() {
1417 ordered_hops.last_mut().unwrap().1 = details.counterparty.features.to_context();
1418 features_set = true;
1424 if let Some(node) = network_nodes.get(&ordered_hops.last().unwrap().0.node_id) {
1425 if let Some(node_info) = node.announcement_info.as_ref() {
1426 ordered_hops.last_mut().unwrap().1 = node_info.features.clone();
1428 ordered_hops.last_mut().unwrap().1 = default_node_features.clone();
1431 // We can fill in features for everything except hops which were
1432 // provided via the invoice we're paying. We could guess based on the
1433 // recipient's features but for now we simply avoid guessing at all.
1437 // Means we succesfully traversed from the payer to the payee, now
1438 // save this path for the payment route. Also, update the liquidity
1439 // remaining on the used hops, so that we take them into account
1440 // while looking for more paths.
1441 if ordered_hops.last().unwrap().0.node_id == payee_node_id {
1445 new_entry = match dist.remove(&ordered_hops.last().unwrap().0.node_id) {
1446 Some(payment_hop) => payment_hop,
1447 // We can't arrive at None because, if we ever add an entry to targets,
1448 // we also fill in the entry in dist (see add_entry!).
1449 None => unreachable!(),
1451 // We "propagate" the fees one hop backward (topologically) here,
1452 // so that fees paid for a HTLC forwarding on the current channel are
1453 // associated with the previous channel (where they will be subtracted).
1454 ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
1455 ordered_hops.push((new_entry.clone(), default_node_features.clone()));
1457 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
1458 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
1460 log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: \n {:#?}",
1461 ordered_hops.len(), value_contribution_msat, ordered_hops.iter().map(|h| &(h.0)).collect::<Vec<&PathBuildingHop>>());
1463 let mut payment_path = PaymentPath {hops: ordered_hops};
1465 // We could have possibly constructed a slightly inconsistent path: since we reduce
1466 // value being transferred along the way, we could have violated htlc_minimum_msat
1467 // on some channels we already passed (assuming dest->source direction). Here, we
1468 // recompute the fees again, so that if that's the case, we match the currently
1469 // underpaid htlc_minimum_msat with fees.
1470 payment_path.update_value_and_recompute_fees(cmp::min(value_contribution_msat, final_value_msat));
1472 // Since a path allows to transfer as much value as
1473 // the smallest channel it has ("bottleneck"), we should recompute
1474 // the fees so sender HTLC don't overpay fees when traversing
1475 // larger channels than the bottleneck. This may happen because
1476 // when we were selecting those channels we were not aware how much value
1477 // this path will transfer, and the relative fee for them
1478 // might have been computed considering a larger value.
1479 // Remember that we used these channels so that we don't rely
1480 // on the same liquidity in future paths.
1481 let mut prevented_redundant_path_selection = false;
1482 let prev_hop_iter = core::iter::once(&our_node_id)
1483 .chain(payment_path.hops.iter().map(|(hop, _)| &hop.node_id));
1484 for (prev_hop, (hop, _)) in prev_hop_iter.zip(payment_path.hops.iter()) {
1485 let spent_on_hop_msat = value_contribution_msat + hop.next_hops_fee_msat;
1486 let used_liquidity_msat = used_channel_liquidities
1487 .entry((hop.candidate.short_channel_id(), *prev_hop < hop.node_id))
1488 .and_modify(|used_liquidity_msat| *used_liquidity_msat += spent_on_hop_msat)
1489 .or_insert(spent_on_hop_msat);
1490 if *used_liquidity_msat == hop.candidate.htlc_maximum_msat() {
1491 // If this path used all of this channel's available liquidity, we know
1492 // this path will not be selected again in the next loop iteration.
1493 prevented_redundant_path_selection = true;
1495 debug_assert!(*used_liquidity_msat <= hop.candidate.htlc_maximum_msat());
1497 if !prevented_redundant_path_selection {
1498 // If we weren't capped by hitting a liquidity limit on a channel in the path,
1499 // we'll probably end up picking the same path again on the next iteration.
1500 // Decrease the available liquidity of a hop in the middle of the path.
1501 let victim_scid = payment_path.hops[(payment_path.hops.len()) / 2].0.candidate.short_channel_id();
1502 let exhausted = u64::max_value();
1503 log_trace!(logger, "Disabling channel {} for future path building iterations to avoid duplicates.", victim_scid);
1504 *used_channel_liquidities.entry((victim_scid, false)).or_default() = exhausted;
1505 *used_channel_liquidities.entry((victim_scid, true)).or_default() = exhausted;
1508 // Track the total amount all our collected paths allow to send so that we:
1509 // - know when to stop looking for more paths
1510 // - know which of the hops are useless considering how much more sats we need
1511 // (contributes_sufficient_value)
1512 already_collected_value_msat += value_contribution_msat;
1514 payment_paths.push(payment_path);
1515 found_new_path = true;
1516 break 'path_construction;
1519 // If we found a path back to the payee, we shouldn't try to process it again. This is
1520 // the equivalent of the `elem.was_processed` check in
1521 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
1522 if node_id == payee_node_id { continue 'path_construction; }
1524 // Otherwise, since the current target node is not us,
1525 // keep "unrolling" the payment graph from payee to payer by
1526 // finding a way to reach the current target from the payer side.
1527 match network_nodes.get(&node_id) {
1530 add_entries_to_cheapest_to_target_node!(node, node_id, lowest_fee_to_node,
1531 value_contribution_msat, path_htlc_minimum_msat, path_penalty_msat,
1532 total_cltv_delta, path_length_to_node);
1538 // If we don't support MPP, no use trying to gather more value ever.
1539 break 'paths_collection;
1543 // Stop either when the recommended value is reached or if no new path was found in this
1545 // In the latter case, making another path finding attempt won't help,
1546 // because we deterministically terminated the search due to low liquidity.
1547 if already_collected_value_msat >= recommended_value_msat || !found_new_path {
1548 log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
1549 already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
1550 break 'paths_collection;
1551 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
1552 // Further, if this was our first walk of the graph, and we weren't limited by an
1553 // htlc_minimum_msat, return immediately because this path should suffice. If we were
1554 // limited by an htlc_minimum_msat value, find another path with a higher value,
1555 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
1556 // still keeping a lower total fee than this path.
1557 if !hit_minimum_limit {
1558 log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
1559 break 'paths_collection;
1561 log_trace!(logger, "Collected our payment amount on the first pass, but running again to collect extra paths with a potentially higher limit.");
1562 path_value_msat = recommended_value_msat;
1567 if payment_paths.len() == 0 {
1568 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1571 if already_collected_value_msat < final_value_msat {
1572 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1575 // Sort by total fees and take the best paths.
1576 payment_paths.sort_unstable_by_key(|path| path.get_total_fee_paid_msat());
1577 if payment_paths.len() > 50 {
1578 payment_paths.truncate(50);
1581 // Draw multiple sufficient routes by randomly combining the selected paths.
1582 let mut drawn_routes = Vec::new();
1583 let mut prng = ChaCha20::new(random_seed_bytes, &[0u8; 12]);
1584 let mut random_index_bytes = [0u8; ::core::mem::size_of::<usize>()];
1586 let num_permutations = payment_paths.len();
1587 for _ in 0..num_permutations {
1588 let mut cur_route = Vec::<PaymentPath>::new();
1589 let mut aggregate_route_value_msat = 0;
1592 // Do a Fisher-Yates shuffle to create a random permutation of the payment paths
1593 for cur_index in (1..payment_paths.len()).rev() {
1594 prng.process_in_place(&mut random_index_bytes);
1595 let random_index = usize::from_be_bytes(random_index_bytes).wrapping_rem(cur_index+1);
1596 payment_paths.swap(cur_index, random_index);
1600 for payment_path in &payment_paths {
1601 cur_route.push(payment_path.clone());
1602 aggregate_route_value_msat += payment_path.get_value_msat();
1603 if aggregate_route_value_msat > final_value_msat {
1604 // Last path likely overpaid. Substract it from the most expensive
1605 // (in terms of proportional fee) path in this route and recompute fees.
1606 // This might be not the most economically efficient way, but fewer paths
1607 // also makes routing more reliable.
1608 let mut overpaid_value_msat = aggregate_route_value_msat - final_value_msat;
1610 // First, we drop some expensive low-value paths entirely if possible, since fewer
1611 // paths is better: the payment is less likely to fail. In order to do so, we sort
1612 // by value and fall back to total fees paid, i.e., in case of equal values we
1613 // prefer lower cost paths.
1614 cur_route.sort_unstable_by(|a, b| {
1615 a.get_value_msat().cmp(&b.get_value_msat())
1616 // Reverse ordering for cost, so we drop higher-cost paths first
1617 .then_with(|| b.get_cost_msat().cmp(&a.get_cost_msat()))
1620 // We should make sure that at least 1 path left.
1621 let mut paths_left = cur_route.len();
1622 cur_route.retain(|path| {
1623 if paths_left == 1 {
1626 let mut keep = true;
1627 let path_value_msat = path.get_value_msat();
1628 if path_value_msat <= overpaid_value_msat {
1630 overpaid_value_msat -= path_value_msat;
1636 if overpaid_value_msat == 0 {
1640 assert!(cur_route.len() > 0);
1643 // Now, subtract the overpaid value from the most-expensive path.
1644 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1645 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1646 cur_route.sort_unstable_by_key(|path| { path.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>() });
1647 let expensive_payment_path = cur_route.first_mut().unwrap();
1649 // We already dropped all the small value paths above, meaning all the
1650 // remaining paths are larger than remaining overpaid_value_msat.
1651 // Thus, this can't be negative.
1652 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
1653 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
1657 drawn_routes.push(cur_route);
1661 // Select the best route by lowest total cost.
1662 drawn_routes.sort_unstable_by_key(|paths| paths.iter().map(|path| path.get_cost_msat()).sum::<u64>());
1663 let mut selected_paths = Vec::<Vec<Result<RouteHop, LightningError>>>::new();
1664 for payment_path in drawn_routes.first().unwrap() {
1665 let mut path = payment_path.hops.iter().map(|(payment_hop, node_features)| {
1667 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)})?,
1668 node_features: node_features.clone(),
1669 short_channel_id: payment_hop.candidate.short_channel_id(),
1670 channel_features: payment_hop.candidate.features(),
1671 fee_msat: payment_hop.fee_msat,
1672 cltv_expiry_delta: payment_hop.candidate.cltv_expiry_delta(),
1674 }).collect::<Vec<_>>();
1675 // Propagate the cltv_expiry_delta one hop backwards since the delta from the current hop is
1676 // applicable for the previous hop.
1677 path.iter_mut().rev().fold(final_cltv_expiry_delta, |prev_cltv_expiry_delta, hop| {
1678 core::mem::replace(&mut hop.as_mut().unwrap().cltv_expiry_delta, prev_cltv_expiry_delta)
1680 selected_paths.push(path);
1683 if let Some(features) = &payment_params.features {
1684 for path in selected_paths.iter_mut() {
1685 if let Ok(route_hop) = path.last_mut().unwrap() {
1686 route_hop.node_features = features.to_context();
1692 paths: selected_paths.into_iter().map(|path| path.into_iter().collect()).collect::<Result<Vec<_>, _>>()?,
1693 payment_params: Some(payment_params.clone()),
1695 log_info!(logger, "Got route to {}: {}", payment_params.payee_pubkey, log_route!(route));
1699 // When an adversarial intermediary node observes a payment, it may be able to infer its
1700 // destination, if the remaining CLTV expiry delta exactly matches a feasible path in the network
1701 // graph. In order to improve privacy, this method obfuscates the CLTV expiry deltas along the
1702 // payment path by adding a randomized 'shadow route' offset to the final hop.
1703 fn add_random_cltv_offset(route: &mut Route, payment_params: &PaymentParameters,
1704 network_graph: &ReadOnlyNetworkGraph, random_seed_bytes: &[u8; 32]
1706 let network_channels = network_graph.channels();
1707 let network_nodes = network_graph.nodes();
1709 for path in route.paths.iter_mut() {
1710 let mut shadow_ctlv_expiry_delta_offset: u32 = 0;
1712 // Remember the last three nodes of the random walk and avoid looping back on them.
1713 // Init with the last three nodes from the actual path, if possible.
1714 let mut nodes_to_avoid: [NodeId; 3] = [NodeId::from_pubkey(&path.last().unwrap().pubkey),
1715 NodeId::from_pubkey(&path.get(path.len().saturating_sub(2)).unwrap().pubkey),
1716 NodeId::from_pubkey(&path.get(path.len().saturating_sub(3)).unwrap().pubkey)];
1718 // Choose the last publicly known node as the starting point for the random walk.
1719 let mut cur_hop: Option<NodeId> = None;
1720 let mut path_nonce = [0u8; 12];
1721 if let Some(starting_hop) = path.iter().rev()
1722 .find(|h| network_nodes.contains_key(&NodeId::from_pubkey(&h.pubkey))) {
1723 cur_hop = Some(NodeId::from_pubkey(&starting_hop.pubkey));
1724 path_nonce.copy_from_slice(&cur_hop.unwrap().as_slice()[..12]);
1727 // Init PRNG with the path-dependant nonce, which is static for private paths.
1728 let mut prng = ChaCha20::new(random_seed_bytes, &path_nonce);
1729 let mut random_path_bytes = [0u8; ::core::mem::size_of::<usize>()];
1731 // Pick a random path length in [1 .. 3]
1732 prng.process_in_place(&mut random_path_bytes);
1733 let random_walk_length = usize::from_be_bytes(random_path_bytes).wrapping_rem(3).wrapping_add(1);
1735 for random_hop in 0..random_walk_length {
1736 // If we don't find a suitable offset in the public network graph, we default to
1737 // MEDIAN_HOP_CLTV_EXPIRY_DELTA.
1738 let mut random_hop_offset = MEDIAN_HOP_CLTV_EXPIRY_DELTA;
1740 if let Some(cur_node_id) = cur_hop {
1741 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
1742 // Randomly choose the next unvisited hop.
1743 prng.process_in_place(&mut random_path_bytes);
1744 if let Some(random_channel) = usize::from_be_bytes(random_path_bytes)
1745 .checked_rem(cur_node.channels.len())
1746 .and_then(|index| cur_node.channels.get(index))
1747 .and_then(|id| network_channels.get(id)) {
1748 random_channel.as_directed_from(&cur_node_id).map(|(dir_info, next_id)| {
1749 if !nodes_to_avoid.iter().any(|x| x == next_id) {
1750 nodes_to_avoid[random_hop] = *next_id;
1751 dir_info.direction().map(|channel_update_info| {
1752 random_hop_offset = channel_update_info.cltv_expiry_delta.into();
1753 cur_hop = Some(*next_id);
1761 shadow_ctlv_expiry_delta_offset = shadow_ctlv_expiry_delta_offset
1762 .checked_add(random_hop_offset)
1763 .unwrap_or(shadow_ctlv_expiry_delta_offset);
1766 // Limit the total offset to reduce the worst-case locked liquidity timevalue
1767 const MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET: u32 = 3*144;
1768 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET);
1770 // Limit the offset so we never exceed the max_total_cltv_expiry_delta. To improve plausibility,
1771 // we choose the limit to be the largest possible multiple of MEDIAN_HOP_CLTV_EXPIRY_DELTA.
1772 let path_total_cltv_expiry_delta: u32 = path.iter().map(|h| h.cltv_expiry_delta).sum();
1773 let mut max_path_offset = payment_params.max_total_cltv_expiry_delta - path_total_cltv_expiry_delta;
1774 max_path_offset = cmp::max(
1775 max_path_offset - (max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA),
1776 max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA);
1777 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, max_path_offset);
1779 // Add 'shadow' CLTV offset to the final hop
1780 if let Some(last_hop) = path.last_mut() {
1781 last_hop.cltv_expiry_delta = last_hop.cltv_expiry_delta
1782 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(last_hop.cltv_expiry_delta);
1787 /// Construct a route from us (payer) to the target node (payee) via the given hops (which should
1788 /// exclude the payer, but include the payee). This may be useful, e.g., for probing the chosen path.
1790 /// Re-uses logic from `find_route`, so the restrictions described there also apply here.
1791 pub fn build_route_from_hops<L: Deref, GL: Deref>(
1792 our_node_pubkey: &PublicKey, hops: &[PublicKey], route_params: &RouteParameters,
1793 network_graph: &NetworkGraph<GL>, logger: L, random_seed_bytes: &[u8; 32]
1794 ) -> Result<Route, LightningError>
1795 where L::Target: Logger, GL::Target: Logger {
1796 let graph_lock = network_graph.read_only();
1797 let mut route = build_route_from_hops_internal(
1798 our_node_pubkey, hops, &route_params.payment_params, &graph_lock,
1799 route_params.final_value_msat, route_params.final_cltv_expiry_delta, logger, random_seed_bytes)?;
1800 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
1804 fn build_route_from_hops_internal<L: Deref>(
1805 our_node_pubkey: &PublicKey, hops: &[PublicKey], payment_params: &PaymentParameters,
1806 network_graph: &ReadOnlyNetworkGraph, final_value_msat: u64, final_cltv_expiry_delta: u32,
1807 logger: L, random_seed_bytes: &[u8; 32]
1808 ) -> Result<Route, LightningError> where L::Target: Logger {
1811 our_node_id: NodeId,
1812 hop_ids: [Option<NodeId>; MAX_PATH_LENGTH_ESTIMATE as usize],
1815 impl Score for HopScorer {
1816 fn channel_penalty_msat(&self, _short_channel_id: u64, source: &NodeId, target: &NodeId,
1817 _usage: ChannelUsage) -> u64
1819 let mut cur_id = self.our_node_id;
1820 for i in 0..self.hop_ids.len() {
1821 if let Some(next_id) = self.hop_ids[i] {
1822 if cur_id == *source && next_id == *target {
1833 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
1835 fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
1838 impl<'a> Writeable for HopScorer {
1840 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), io::Error> {
1845 if hops.len() > MAX_PATH_LENGTH_ESTIMATE.into() {
1846 return Err(LightningError{err: "Cannot build a route exceeding the maximum path length.".to_owned(), action: ErrorAction::IgnoreError});
1849 let our_node_id = NodeId::from_pubkey(our_node_pubkey);
1850 let mut hop_ids = [None; MAX_PATH_LENGTH_ESTIMATE as usize];
1851 for i in 0..hops.len() {
1852 hop_ids[i] = Some(NodeId::from_pubkey(&hops[i]));
1855 let scorer = HopScorer { our_node_id, hop_ids };
1857 get_route(our_node_pubkey, payment_params, network_graph, None, final_value_msat,
1858 final_cltv_expiry_delta, logger, &scorer, random_seed_bytes)
1863 use routing::gossip::{NetworkGraph, P2PGossipSync, NodeId};
1864 use routing::router::{get_route, build_route_from_hops_internal, add_random_cltv_offset, default_node_features,
1865 PaymentParameters, Route, RouteHint, RouteHintHop, RouteHop, RoutingFees,
1866 DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA, MAX_PATH_LENGTH_ESTIMATE};
1867 use routing::scoring::{ChannelUsage, Score};
1868 use chain::transaction::OutPoint;
1869 use chain::keysinterface::KeysInterface;
1870 use ln::features::{ChannelFeatures, InitFeatures, InvoiceFeatures, NodeFeatures};
1871 use ln::msgs::{ErrorAction, LightningError, OptionalField, UnsignedChannelAnnouncement, ChannelAnnouncement, RoutingMessageHandler,
1872 NodeAnnouncement, UnsignedNodeAnnouncement, ChannelUpdate, UnsignedChannelUpdate};
1873 use ln::channelmanager;
1874 use util::test_utils;
1875 use util::chacha20::ChaCha20;
1876 use util::ser::Writeable;
1878 use util::ser::Writer;
1880 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
1881 use bitcoin::hashes::Hash;
1882 use bitcoin::network::constants::Network;
1883 use bitcoin::blockdata::constants::genesis_block;
1884 use bitcoin::blockdata::script::Builder;
1885 use bitcoin::blockdata::opcodes;
1886 use bitcoin::blockdata::transaction::TxOut;
1890 use bitcoin::secp256k1::{PublicKey,SecretKey};
1891 use bitcoin::secp256k1::{Secp256k1, All};
1894 use sync::{self, Arc};
1896 fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
1897 features: InitFeatures, outbound_capacity_msat: u64) -> channelmanager::ChannelDetails {
1898 channelmanager::ChannelDetails {
1899 channel_id: [0; 32],
1900 counterparty: channelmanager::ChannelCounterparty {
1903 unspendable_punishment_reserve: 0,
1904 forwarding_info: None,
1905 outbound_htlc_minimum_msat: None,
1906 outbound_htlc_maximum_msat: None,
1908 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
1911 outbound_scid_alias: None,
1912 inbound_scid_alias: None,
1913 channel_value_satoshis: 0,
1916 outbound_capacity_msat,
1917 next_outbound_htlc_limit_msat: outbound_capacity_msat,
1918 inbound_capacity_msat: 42,
1919 unspendable_punishment_reserve: None,
1920 confirmations_required: None,
1921 force_close_spend_delay: None,
1922 is_outbound: true, is_channel_ready: true,
1923 is_usable: true, is_public: true,
1924 inbound_htlc_minimum_msat: None,
1925 inbound_htlc_maximum_msat: None,
1929 // Using the same keys for LN and BTC ids
1931 gossip_sync: &P2PGossipSync<Arc<NetworkGraph<Arc<test_utils::TestLogger>>>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1932 secp_ctx: &Secp256k1<All>, node_1_privkey: &SecretKey, node_2_privkey: &SecretKey, features: ChannelFeatures, short_channel_id: u64
1934 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1935 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1937 let unsigned_announcement = UnsignedChannelAnnouncement {
1939 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1943 bitcoin_key_1: node_id_1,
1944 bitcoin_key_2: node_id_2,
1945 excess_data: Vec::new(),
1948 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1949 let valid_announcement = ChannelAnnouncement {
1950 node_signature_1: secp_ctx.sign_ecdsa(&msghash, node_1_privkey),
1951 node_signature_2: secp_ctx.sign_ecdsa(&msghash, node_2_privkey),
1952 bitcoin_signature_1: secp_ctx.sign_ecdsa(&msghash, node_1_privkey),
1953 bitcoin_signature_2: secp_ctx.sign_ecdsa(&msghash, node_2_privkey),
1954 contents: unsigned_announcement.clone(),
1956 match gossip_sync.handle_channel_announcement(&valid_announcement) {
1957 Ok(res) => assert!(res),
1963 gossip_sync: &P2PGossipSync<Arc<NetworkGraph<Arc<test_utils::TestLogger>>>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1964 secp_ctx: &Secp256k1<All>, node_privkey: &SecretKey, update: UnsignedChannelUpdate
1966 let msghash = hash_to_message!(&Sha256dHash::hash(&update.encode()[..])[..]);
1967 let valid_channel_update = ChannelUpdate {
1968 signature: secp_ctx.sign_ecdsa(&msghash, node_privkey),
1969 contents: update.clone()
1972 match gossip_sync.handle_channel_update(&valid_channel_update) {
1973 Ok(res) => assert!(res),
1978 fn add_or_update_node(
1979 gossip_sync: &P2PGossipSync<Arc<NetworkGraph<Arc<test_utils::TestLogger>>>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1980 secp_ctx: &Secp256k1<All>, node_privkey: &SecretKey, features: NodeFeatures, timestamp: u32
1982 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
1983 let unsigned_announcement = UnsignedNodeAnnouncement {
1989 addresses: Vec::new(),
1990 excess_address_data: Vec::new(),
1991 excess_data: Vec::new(),
1993 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1994 let valid_announcement = NodeAnnouncement {
1995 signature: secp_ctx.sign_ecdsa(&msghash, node_privkey),
1996 contents: unsigned_announcement.clone()
1999 match gossip_sync.handle_node_announcement(&valid_announcement) {
2005 fn get_nodes(secp_ctx: &Secp256k1<All>) -> (SecretKey, PublicKey, Vec<SecretKey>, Vec<PublicKey>) {
2006 let privkeys: Vec<SecretKey> = (2..22).map(|i| {
2007 SecretKey::from_slice(&hex::decode(format!("{:02x}", i).repeat(32)).unwrap()[..]).unwrap()
2010 let pubkeys = privkeys.iter().map(|secret| PublicKey::from_secret_key(&secp_ctx, secret)).collect();
2012 let our_privkey = SecretKey::from_slice(&hex::decode("01".repeat(32)).unwrap()[..]).unwrap();
2013 let our_id = PublicKey::from_secret_key(&secp_ctx, &our_privkey);
2015 (our_privkey, our_id, privkeys, pubkeys)
2018 fn id_to_feature_flags(id: u8) -> Vec<u8> {
2019 // Set the feature flags to the id'th odd (ie non-required) feature bit so that we can
2020 // test for it later.
2021 let idx = (id - 1) * 2 + 1;
2023 vec![1 << (idx - 8*3), 0, 0, 0]
2024 } else if idx > 8*2 {
2025 vec![1 << (idx - 8*2), 0, 0]
2026 } else if idx > 8*1 {
2027 vec![1 << (idx - 8*1), 0]
2033 fn build_line_graph() -> (
2034 Secp256k1<All>, sync::Arc<NetworkGraph<Arc<test_utils::TestLogger>>>,
2035 P2PGossipSync<sync::Arc<NetworkGraph<Arc<test_utils::TestLogger>>>, sync::Arc<test_utils::TestChainSource>, sync::Arc<test_utils::TestLogger>>,
2036 sync::Arc<test_utils::TestChainSource>, sync::Arc<test_utils::TestLogger>,
2038 let secp_ctx = Secp256k1::new();
2039 let logger = Arc::new(test_utils::TestLogger::new());
2040 let chain_monitor = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
2041 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
2042 let network_graph = Arc::new(NetworkGraph::new(genesis_hash, Arc::clone(&logger)));
2043 let gossip_sync = P2PGossipSync::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
2045 // Build network from our_id to node 19:
2046 // our_id -1(1)2- node0 -1(2)2- node1 - ... - node19
2047 let (our_privkey, _, privkeys, _) = get_nodes(&secp_ctx);
2049 for (idx, (cur_privkey, next_privkey)) in core::iter::once(&our_privkey)
2050 .chain(privkeys.iter()).zip(privkeys.iter()).enumerate() {
2051 let cur_short_channel_id = (idx as u64) + 1;
2052 add_channel(&gossip_sync, &secp_ctx, &cur_privkey, &next_privkey,
2053 ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), cur_short_channel_id);
2054 update_channel(&gossip_sync, &secp_ctx, &cur_privkey, UnsignedChannelUpdate {
2055 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2056 short_channel_id: cur_short_channel_id,
2057 timestamp: idx as u32,
2059 cltv_expiry_delta: 0,
2060 htlc_minimum_msat: 0,
2061 htlc_maximum_msat: OptionalField::Absent,
2063 fee_proportional_millionths: 0,
2064 excess_data: Vec::new()
2066 update_channel(&gossip_sync, &secp_ctx, &next_privkey, UnsignedChannelUpdate {
2067 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2068 short_channel_id: cur_short_channel_id,
2069 timestamp: (idx as u32)+1,
2071 cltv_expiry_delta: 0,
2072 htlc_minimum_msat: 0,
2073 htlc_maximum_msat: OptionalField::Absent,
2075 fee_proportional_millionths: 0,
2076 excess_data: Vec::new()
2078 add_or_update_node(&gossip_sync, &secp_ctx, next_privkey,
2079 NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
2082 (secp_ctx, network_graph, gossip_sync, chain_monitor, logger)
2085 fn build_graph() -> (
2087 sync::Arc<NetworkGraph<Arc<test_utils::TestLogger>>>,
2088 P2PGossipSync<sync::Arc<NetworkGraph<Arc<test_utils::TestLogger>>>, sync::Arc<test_utils::TestChainSource>, sync::Arc<test_utils::TestLogger>>,
2089 sync::Arc<test_utils::TestChainSource>,
2090 sync::Arc<test_utils::TestLogger>,
2092 let secp_ctx = Secp256k1::new();
2093 let logger = Arc::new(test_utils::TestLogger::new());
2094 let chain_monitor = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
2095 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
2096 let network_graph = Arc::new(NetworkGraph::new(genesis_hash, Arc::clone(&logger)));
2097 let gossip_sync = P2PGossipSync::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
2098 // Build network from our_id to node6:
2100 // -1(1)2- node0 -1(3)2-
2102 // our_id -1(12)2- node7 -1(13)2--- node2
2104 // -1(2)2- node1 -1(4)2-
2107 // chan1 1-to-2: disabled
2108 // chan1 2-to-1: enabled, 0 fee
2110 // chan2 1-to-2: enabled, ignored fee
2111 // chan2 2-to-1: enabled, 0 fee
2113 // chan3 1-to-2: enabled, 0 fee
2114 // chan3 2-to-1: enabled, 100 msat fee
2116 // chan4 1-to-2: enabled, 100% fee
2117 // chan4 2-to-1: enabled, 0 fee
2119 // chan12 1-to-2: enabled, ignored fee
2120 // chan12 2-to-1: enabled, 0 fee
2122 // chan13 1-to-2: enabled, 200% fee
2123 // chan13 2-to-1: enabled, 0 fee
2126 // -1(5)2- node3 -1(8)2--
2130 // node2--1(6)2- node4 -1(9)2--- node6 (not in global route map)
2132 // -1(7)2- node5 -1(10)2-
2134 // Channels 5, 8, 9 and 10 are private channels.
2136 // chan5 1-to-2: enabled, 100 msat fee
2137 // chan5 2-to-1: enabled, 0 fee
2139 // chan6 1-to-2: enabled, 0 fee
2140 // chan6 2-to-1: enabled, 0 fee
2142 // chan7 1-to-2: enabled, 100% fee
2143 // chan7 2-to-1: enabled, 0 fee
2145 // chan8 1-to-2: enabled, variable fee (0 then 1000 msat)
2146 // chan8 2-to-1: enabled, 0 fee
2148 // chan9 1-to-2: enabled, 1001 msat fee
2149 // chan9 2-to-1: enabled, 0 fee
2151 // chan10 1-to-2: enabled, 0 fee
2152 // chan10 2-to-1: enabled, 0 fee
2154 // chan11 1-to-2: enabled, 0 fee
2155 // chan11 2-to-1: enabled, 0 fee
2157 let (our_privkey, _, privkeys, _) = get_nodes(&secp_ctx);
2159 add_channel(&gossip_sync, &secp_ctx, &our_privkey, &privkeys[0], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
2160 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2161 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2162 short_channel_id: 1,
2165 cltv_expiry_delta: 0,
2166 htlc_minimum_msat: 0,
2167 htlc_maximum_msat: OptionalField::Absent,
2169 fee_proportional_millionths: 0,
2170 excess_data: Vec::new()
2173 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[0], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
2175 add_channel(&gossip_sync, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
2176 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2177 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2178 short_channel_id: 2,
2181 cltv_expiry_delta: (5 << 4) | 3,
2182 htlc_minimum_msat: 0,
2183 htlc_maximum_msat: OptionalField::Absent,
2184 fee_base_msat: u32::max_value(),
2185 fee_proportional_millionths: u32::max_value(),
2186 excess_data: Vec::new()
2188 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2189 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2190 short_channel_id: 2,
2193 cltv_expiry_delta: 0,
2194 htlc_minimum_msat: 0,
2195 htlc_maximum_msat: OptionalField::Absent,
2197 fee_proportional_millionths: 0,
2198 excess_data: Vec::new()
2201 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
2203 add_channel(&gossip_sync, &secp_ctx, &our_privkey, &privkeys[7], ChannelFeatures::from_le_bytes(id_to_feature_flags(12)), 12);
2204 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2205 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2206 short_channel_id: 12,
2209 cltv_expiry_delta: (5 << 4) | 3,
2210 htlc_minimum_msat: 0,
2211 htlc_maximum_msat: OptionalField::Absent,
2212 fee_base_msat: u32::max_value(),
2213 fee_proportional_millionths: u32::max_value(),
2214 excess_data: Vec::new()
2216 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2217 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2218 short_channel_id: 12,
2221 cltv_expiry_delta: 0,
2222 htlc_minimum_msat: 0,
2223 htlc_maximum_msat: OptionalField::Absent,
2225 fee_proportional_millionths: 0,
2226 excess_data: Vec::new()
2229 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[7], NodeFeatures::from_le_bytes(id_to_feature_flags(8)), 0);
2231 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
2232 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2233 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2234 short_channel_id: 3,
2237 cltv_expiry_delta: (3 << 4) | 1,
2238 htlc_minimum_msat: 0,
2239 htlc_maximum_msat: OptionalField::Absent,
2241 fee_proportional_millionths: 0,
2242 excess_data: Vec::new()
2244 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2245 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2246 short_channel_id: 3,
2249 cltv_expiry_delta: (3 << 4) | 2,
2250 htlc_minimum_msat: 0,
2251 htlc_maximum_msat: OptionalField::Absent,
2253 fee_proportional_millionths: 0,
2254 excess_data: Vec::new()
2257 add_channel(&gossip_sync, &secp_ctx, &privkeys[1], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
2258 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2259 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2260 short_channel_id: 4,
2263 cltv_expiry_delta: (4 << 4) | 1,
2264 htlc_minimum_msat: 0,
2265 htlc_maximum_msat: OptionalField::Absent,
2267 fee_proportional_millionths: 1000000,
2268 excess_data: Vec::new()
2270 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2271 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2272 short_channel_id: 4,
2275 cltv_expiry_delta: (4 << 4) | 2,
2276 htlc_minimum_msat: 0,
2277 htlc_maximum_msat: OptionalField::Absent,
2279 fee_proportional_millionths: 0,
2280 excess_data: Vec::new()
2283 add_channel(&gossip_sync, &secp_ctx, &privkeys[7], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(13)), 13);
2284 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2285 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2286 short_channel_id: 13,
2289 cltv_expiry_delta: (13 << 4) | 1,
2290 htlc_minimum_msat: 0,
2291 htlc_maximum_msat: OptionalField::Absent,
2293 fee_proportional_millionths: 2000000,
2294 excess_data: Vec::new()
2296 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2297 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2298 short_channel_id: 13,
2301 cltv_expiry_delta: (13 << 4) | 2,
2302 htlc_minimum_msat: 0,
2303 htlc_maximum_msat: OptionalField::Absent,
2305 fee_proportional_millionths: 0,
2306 excess_data: Vec::new()
2309 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
2311 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
2312 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2313 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2314 short_channel_id: 6,
2317 cltv_expiry_delta: (6 << 4) | 1,
2318 htlc_minimum_msat: 0,
2319 htlc_maximum_msat: OptionalField::Absent,
2321 fee_proportional_millionths: 0,
2322 excess_data: Vec::new()
2324 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
2325 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2326 short_channel_id: 6,
2329 cltv_expiry_delta: (6 << 4) | 2,
2330 htlc_minimum_msat: 0,
2331 htlc_maximum_msat: OptionalField::Absent,
2333 fee_proportional_millionths: 0,
2334 excess_data: Vec::new(),
2337 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(11)), 11);
2338 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
2339 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2340 short_channel_id: 11,
2343 cltv_expiry_delta: (11 << 4) | 1,
2344 htlc_minimum_msat: 0,
2345 htlc_maximum_msat: OptionalField::Absent,
2347 fee_proportional_millionths: 0,
2348 excess_data: Vec::new()
2350 update_channel(&gossip_sync, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
2351 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2352 short_channel_id: 11,
2355 cltv_expiry_delta: (11 << 4) | 2,
2356 htlc_minimum_msat: 0,
2357 htlc_maximum_msat: OptionalField::Absent,
2359 fee_proportional_millionths: 0,
2360 excess_data: Vec::new()
2363 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(5)), 0);
2365 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
2367 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[5], ChannelFeatures::from_le_bytes(id_to_feature_flags(7)), 7);
2368 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2369 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2370 short_channel_id: 7,
2373 cltv_expiry_delta: (7 << 4) | 1,
2374 htlc_minimum_msat: 0,
2375 htlc_maximum_msat: OptionalField::Absent,
2377 fee_proportional_millionths: 1000000,
2378 excess_data: Vec::new()
2380 update_channel(&gossip_sync, &secp_ctx, &privkeys[5], UnsignedChannelUpdate {
2381 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2382 short_channel_id: 7,
2385 cltv_expiry_delta: (7 << 4) | 2,
2386 htlc_minimum_msat: 0,
2387 htlc_maximum_msat: OptionalField::Absent,
2389 fee_proportional_millionths: 0,
2390 excess_data: Vec::new()
2393 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[5], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
2395 (secp_ctx, network_graph, gossip_sync, chain_monitor, logger)
2399 fn simple_route_test() {
2400 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2401 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2402 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2403 let scorer = test_utils::TestScorer::with_penalty(0);
2404 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2405 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2407 // Simple route to 2 via 1
2409 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) {
2410 assert_eq!(err, "Cannot send a payment of 0 msat");
2411 } else { panic!(); }
2413 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2414 assert_eq!(route.paths[0].len(), 2);
2416 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2417 assert_eq!(route.paths[0][0].short_channel_id, 2);
2418 assert_eq!(route.paths[0][0].fee_msat, 100);
2419 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2420 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2421 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2423 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2424 assert_eq!(route.paths[0][1].short_channel_id, 4);
2425 assert_eq!(route.paths[0][1].fee_msat, 100);
2426 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2427 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2428 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2432 fn invalid_first_hop_test() {
2433 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2434 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2435 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2436 let scorer = test_utils::TestScorer::with_penalty(0);
2437 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2438 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2440 // Simple route to 2 via 1
2442 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
2444 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) =
2445 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) {
2446 assert_eq!(err, "First hop cannot have our_node_pubkey as a destination.");
2447 } else { panic!(); }
2449 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2450 assert_eq!(route.paths[0].len(), 2);
2454 fn htlc_minimum_test() {
2455 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2456 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2457 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2458 let scorer = test_utils::TestScorer::with_penalty(0);
2459 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2460 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2462 // Simple route to 2 via 1
2464 // Disable other paths
2465 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2466 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2467 short_channel_id: 12,
2469 flags: 2, // to disable
2470 cltv_expiry_delta: 0,
2471 htlc_minimum_msat: 0,
2472 htlc_maximum_msat: OptionalField::Absent,
2474 fee_proportional_millionths: 0,
2475 excess_data: Vec::new()
2477 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2478 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2479 short_channel_id: 3,
2481 flags: 2, // to disable
2482 cltv_expiry_delta: 0,
2483 htlc_minimum_msat: 0,
2484 htlc_maximum_msat: OptionalField::Absent,
2486 fee_proportional_millionths: 0,
2487 excess_data: Vec::new()
2489 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2490 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2491 short_channel_id: 13,
2493 flags: 2, // to disable
2494 cltv_expiry_delta: 0,
2495 htlc_minimum_msat: 0,
2496 htlc_maximum_msat: OptionalField::Absent,
2498 fee_proportional_millionths: 0,
2499 excess_data: Vec::new()
2501 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2502 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2503 short_channel_id: 6,
2505 flags: 2, // to disable
2506 cltv_expiry_delta: 0,
2507 htlc_minimum_msat: 0,
2508 htlc_maximum_msat: OptionalField::Absent,
2510 fee_proportional_millionths: 0,
2511 excess_data: Vec::new()
2513 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2514 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2515 short_channel_id: 7,
2517 flags: 2, // to disable
2518 cltv_expiry_delta: 0,
2519 htlc_minimum_msat: 0,
2520 htlc_maximum_msat: OptionalField::Absent,
2522 fee_proportional_millionths: 0,
2523 excess_data: Vec::new()
2526 // Check against amount_to_transfer_over_msat.
2527 // Set minimal HTLC of 200_000_000 msat.
2528 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2529 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2530 short_channel_id: 2,
2533 cltv_expiry_delta: 0,
2534 htlc_minimum_msat: 200_000_000,
2535 htlc_maximum_msat: OptionalField::Absent,
2537 fee_proportional_millionths: 0,
2538 excess_data: Vec::new()
2541 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
2543 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2544 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2545 short_channel_id: 4,
2548 cltv_expiry_delta: 0,
2549 htlc_minimum_msat: 0,
2550 htlc_maximum_msat: OptionalField::Present(199_999_999),
2552 fee_proportional_millionths: 0,
2553 excess_data: Vec::new()
2556 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
2557 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) {
2558 assert_eq!(err, "Failed to find a path to the given destination");
2559 } else { panic!(); }
2561 // Lift the restriction on the first hop.
2562 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2563 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2564 short_channel_id: 2,
2567 cltv_expiry_delta: 0,
2568 htlc_minimum_msat: 0,
2569 htlc_maximum_msat: OptionalField::Absent,
2571 fee_proportional_millionths: 0,
2572 excess_data: Vec::new()
2575 // A payment above the minimum should pass
2576 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();
2577 assert_eq!(route.paths[0].len(), 2);
2581 fn htlc_minimum_overpay_test() {
2582 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2583 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2584 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
2585 let scorer = test_utils::TestScorer::with_penalty(0);
2586 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2587 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2589 // A route to node#2 via two paths.
2590 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
2591 // Thus, they can't send 60 without overpaying.
2592 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2593 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2594 short_channel_id: 2,
2597 cltv_expiry_delta: 0,
2598 htlc_minimum_msat: 35_000,
2599 htlc_maximum_msat: OptionalField::Present(40_000),
2601 fee_proportional_millionths: 0,
2602 excess_data: Vec::new()
2604 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2605 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2606 short_channel_id: 12,
2609 cltv_expiry_delta: 0,
2610 htlc_minimum_msat: 35_000,
2611 htlc_maximum_msat: OptionalField::Present(40_000),
2613 fee_proportional_millionths: 0,
2614 excess_data: Vec::new()
2618 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2619 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2620 short_channel_id: 13,
2623 cltv_expiry_delta: 0,
2624 htlc_minimum_msat: 0,
2625 htlc_maximum_msat: OptionalField::Absent,
2627 fee_proportional_millionths: 0,
2628 excess_data: Vec::new()
2630 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2631 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2632 short_channel_id: 4,
2635 cltv_expiry_delta: 0,
2636 htlc_minimum_msat: 0,
2637 htlc_maximum_msat: OptionalField::Absent,
2639 fee_proportional_millionths: 0,
2640 excess_data: Vec::new()
2643 // Disable other paths
2644 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2645 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2646 short_channel_id: 1,
2648 flags: 2, // to disable
2649 cltv_expiry_delta: 0,
2650 htlc_minimum_msat: 0,
2651 htlc_maximum_msat: OptionalField::Absent,
2653 fee_proportional_millionths: 0,
2654 excess_data: Vec::new()
2657 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 60_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2658 // Overpay fees to hit htlc_minimum_msat.
2659 let overpaid_fees = route.paths[0][0].fee_msat + route.paths[1][0].fee_msat;
2660 // TODO: this could be better balanced to overpay 10k and not 15k.
2661 assert_eq!(overpaid_fees, 15_000);
2663 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
2664 // while taking even more fee to match htlc_minimum_msat.
2665 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2666 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2667 short_channel_id: 12,
2670 cltv_expiry_delta: 0,
2671 htlc_minimum_msat: 65_000,
2672 htlc_maximum_msat: OptionalField::Present(80_000),
2674 fee_proportional_millionths: 0,
2675 excess_data: Vec::new()
2677 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2678 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2679 short_channel_id: 2,
2682 cltv_expiry_delta: 0,
2683 htlc_minimum_msat: 0,
2684 htlc_maximum_msat: OptionalField::Absent,
2686 fee_proportional_millionths: 0,
2687 excess_data: Vec::new()
2689 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2690 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2691 short_channel_id: 4,
2694 cltv_expiry_delta: 0,
2695 htlc_minimum_msat: 0,
2696 htlc_maximum_msat: OptionalField::Absent,
2698 fee_proportional_millionths: 100_000,
2699 excess_data: Vec::new()
2702 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 60_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2703 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
2704 assert_eq!(route.paths.len(), 1);
2705 assert_eq!(route.paths[0][0].short_channel_id, 12);
2706 let fees = route.paths[0][0].fee_msat;
2707 assert_eq!(fees, 5_000);
2709 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2710 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
2711 // the other channel.
2712 assert_eq!(route.paths.len(), 1);
2713 assert_eq!(route.paths[0][0].short_channel_id, 2);
2714 let fees = route.paths[0][0].fee_msat;
2715 assert_eq!(fees, 5_000);
2719 fn disable_channels_test() {
2720 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2721 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2722 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2723 let scorer = test_utils::TestScorer::with_penalty(0);
2724 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2725 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2727 // // Disable channels 4 and 12 by flags=2
2728 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2729 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2730 short_channel_id: 4,
2732 flags: 2, // to disable
2733 cltv_expiry_delta: 0,
2734 htlc_minimum_msat: 0,
2735 htlc_maximum_msat: OptionalField::Absent,
2737 fee_proportional_millionths: 0,
2738 excess_data: Vec::new()
2740 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2741 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2742 short_channel_id: 12,
2744 flags: 2, // to disable
2745 cltv_expiry_delta: 0,
2746 htlc_minimum_msat: 0,
2747 htlc_maximum_msat: OptionalField::Absent,
2749 fee_proportional_millionths: 0,
2750 excess_data: Vec::new()
2753 // If all the channels require some features we don't understand, route should fail
2754 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) {
2755 assert_eq!(err, "Failed to find a path to the given destination");
2756 } else { panic!(); }
2758 // If we specify a channel to node7, that overrides our local channel view and that gets used
2759 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2760 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();
2761 assert_eq!(route.paths[0].len(), 2);
2763 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2764 assert_eq!(route.paths[0][0].short_channel_id, 42);
2765 assert_eq!(route.paths[0][0].fee_msat, 200);
2766 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2767 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2768 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2770 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2771 assert_eq!(route.paths[0][1].short_channel_id, 13);
2772 assert_eq!(route.paths[0][1].fee_msat, 100);
2773 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2774 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2775 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2779 fn disable_node_test() {
2780 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2781 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2782 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2783 let scorer = test_utils::TestScorer::with_penalty(0);
2784 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2785 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2787 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
2788 let mut unknown_features = NodeFeatures::known();
2789 unknown_features.set_unknown_feature_required();
2790 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
2791 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
2792 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
2794 // If all nodes require some features we don't understand, route should fail
2795 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) {
2796 assert_eq!(err, "Failed to find a path to the given destination");
2797 } else { panic!(); }
2799 // If we specify a channel to node7, that overrides our local channel view and that gets used
2800 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2801 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();
2802 assert_eq!(route.paths[0].len(), 2);
2804 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2805 assert_eq!(route.paths[0][0].short_channel_id, 42);
2806 assert_eq!(route.paths[0][0].fee_msat, 200);
2807 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2808 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2809 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2811 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2812 assert_eq!(route.paths[0][1].short_channel_id, 13);
2813 assert_eq!(route.paths[0][1].fee_msat, 100);
2814 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2815 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2816 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2818 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
2819 // naively) assume that the user checked the feature bits on the invoice, which override
2820 // the node_announcement.
2824 fn our_chans_test() {
2825 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2826 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2827 let scorer = test_utils::TestScorer::with_penalty(0);
2828 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2829 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2831 // Route to 1 via 2 and 3 because our channel to 1 is disabled
2832 let payment_params = PaymentParameters::from_node_id(nodes[0]);
2833 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2834 assert_eq!(route.paths[0].len(), 3);
2836 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2837 assert_eq!(route.paths[0][0].short_channel_id, 2);
2838 assert_eq!(route.paths[0][0].fee_msat, 200);
2839 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2840 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2841 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2843 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2844 assert_eq!(route.paths[0][1].short_channel_id, 4);
2845 assert_eq!(route.paths[0][1].fee_msat, 100);
2846 assert_eq!(route.paths[0][1].cltv_expiry_delta, (3 << 4) | 2);
2847 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2848 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2850 assert_eq!(route.paths[0][2].pubkey, nodes[0]);
2851 assert_eq!(route.paths[0][2].short_channel_id, 3);
2852 assert_eq!(route.paths[0][2].fee_msat, 100);
2853 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
2854 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(1));
2855 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(3));
2857 // If we specify a channel to node7, that overrides our local channel view and that gets used
2858 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2859 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2860 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();
2861 assert_eq!(route.paths[0].len(), 2);
2863 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2864 assert_eq!(route.paths[0][0].short_channel_id, 42);
2865 assert_eq!(route.paths[0][0].fee_msat, 200);
2866 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2867 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2868 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2870 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2871 assert_eq!(route.paths[0][1].short_channel_id, 13);
2872 assert_eq!(route.paths[0][1].fee_msat, 100);
2873 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2874 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2875 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2878 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2879 let zero_fees = RoutingFees {
2881 proportional_millionths: 0,
2883 vec![RouteHint(vec![RouteHintHop {
2884 src_node_id: nodes[3],
2885 short_channel_id: 8,
2887 cltv_expiry_delta: (8 << 4) | 1,
2888 htlc_minimum_msat: None,
2889 htlc_maximum_msat: None,
2891 ]), RouteHint(vec![RouteHintHop {
2892 src_node_id: nodes[4],
2893 short_channel_id: 9,
2896 proportional_millionths: 0,
2898 cltv_expiry_delta: (9 << 4) | 1,
2899 htlc_minimum_msat: None,
2900 htlc_maximum_msat: None,
2901 }]), RouteHint(vec![RouteHintHop {
2902 src_node_id: nodes[5],
2903 short_channel_id: 10,
2905 cltv_expiry_delta: (10 << 4) | 1,
2906 htlc_minimum_msat: None,
2907 htlc_maximum_msat: None,
2911 fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2912 let zero_fees = RoutingFees {
2914 proportional_millionths: 0,
2916 vec![RouteHint(vec![RouteHintHop {
2917 src_node_id: nodes[2],
2918 short_channel_id: 5,
2921 proportional_millionths: 0,
2923 cltv_expiry_delta: (5 << 4) | 1,
2924 htlc_minimum_msat: None,
2925 htlc_maximum_msat: None,
2927 src_node_id: nodes[3],
2928 short_channel_id: 8,
2930 cltv_expiry_delta: (8 << 4) | 1,
2931 htlc_minimum_msat: None,
2932 htlc_maximum_msat: None,
2934 ]), RouteHint(vec![RouteHintHop {
2935 src_node_id: nodes[4],
2936 short_channel_id: 9,
2939 proportional_millionths: 0,
2941 cltv_expiry_delta: (9 << 4) | 1,
2942 htlc_minimum_msat: None,
2943 htlc_maximum_msat: None,
2944 }]), RouteHint(vec![RouteHintHop {
2945 src_node_id: nodes[5],
2946 short_channel_id: 10,
2948 cltv_expiry_delta: (10 << 4) | 1,
2949 htlc_minimum_msat: None,
2950 htlc_maximum_msat: None,
2955 fn partial_route_hint_test() {
2956 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2957 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2958 let scorer = test_utils::TestScorer::with_penalty(0);
2959 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2960 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2962 // Simple test across 2, 3, 5, and 4 via a last_hop channel
2963 // Tests the behaviour when the RouteHint contains a suboptimal hop.
2964 // RouteHint may be partially used by the algo to build the best path.
2966 // First check that last hop can't have its source as the payee.
2967 let invalid_last_hop = RouteHint(vec![RouteHintHop {
2968 src_node_id: nodes[6],
2969 short_channel_id: 8,
2972 proportional_millionths: 0,
2974 cltv_expiry_delta: (8 << 4) | 1,
2975 htlc_minimum_msat: None,
2976 htlc_maximum_msat: None,
2979 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
2980 invalid_last_hops.push(invalid_last_hop);
2982 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(invalid_last_hops);
2983 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) {
2984 assert_eq!(err, "Route hint cannot have the payee as the source.");
2985 } else { panic!(); }
2988 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops_multi_private_channels(&nodes));
2989 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2990 assert_eq!(route.paths[0].len(), 5);
2992 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2993 assert_eq!(route.paths[0][0].short_channel_id, 2);
2994 assert_eq!(route.paths[0][0].fee_msat, 100);
2995 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2996 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2997 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2999 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3000 assert_eq!(route.paths[0][1].short_channel_id, 4);
3001 assert_eq!(route.paths[0][1].fee_msat, 0);
3002 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
3003 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3004 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3006 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
3007 assert_eq!(route.paths[0][2].short_channel_id, 6);
3008 assert_eq!(route.paths[0][2].fee_msat, 0);
3009 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
3010 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
3011 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
3013 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
3014 assert_eq!(route.paths[0][3].short_channel_id, 11);
3015 assert_eq!(route.paths[0][3].fee_msat, 0);
3016 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
3017 // If we have a peer in the node map, we'll use their features here since we don't have
3018 // a way of figuring out their features from the invoice:
3019 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
3020 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
3022 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
3023 assert_eq!(route.paths[0][4].short_channel_id, 8);
3024 assert_eq!(route.paths[0][4].fee_msat, 100);
3025 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
3026 assert_eq!(route.paths[0][4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3027 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3030 fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3031 let zero_fees = RoutingFees {
3033 proportional_millionths: 0,
3035 vec![RouteHint(vec![RouteHintHop {
3036 src_node_id: nodes[3],
3037 short_channel_id: 8,
3039 cltv_expiry_delta: (8 << 4) | 1,
3040 htlc_minimum_msat: None,
3041 htlc_maximum_msat: None,
3042 }]), RouteHint(vec![
3044 ]), RouteHint(vec![RouteHintHop {
3045 src_node_id: nodes[5],
3046 short_channel_id: 10,
3048 cltv_expiry_delta: (10 << 4) | 1,
3049 htlc_minimum_msat: None,
3050 htlc_maximum_msat: None,
3055 fn ignores_empty_last_hops_test() {
3056 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3057 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3058 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(empty_last_hop(&nodes));
3059 let scorer = test_utils::TestScorer::with_penalty(0);
3060 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3061 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3063 // Test handling of an empty RouteHint passed in Invoice.
3065 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3066 assert_eq!(route.paths[0].len(), 5);
3068 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3069 assert_eq!(route.paths[0][0].short_channel_id, 2);
3070 assert_eq!(route.paths[0][0].fee_msat, 100);
3071 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
3072 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3073 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3075 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3076 assert_eq!(route.paths[0][1].short_channel_id, 4);
3077 assert_eq!(route.paths[0][1].fee_msat, 0);
3078 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
3079 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3080 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3082 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
3083 assert_eq!(route.paths[0][2].short_channel_id, 6);
3084 assert_eq!(route.paths[0][2].fee_msat, 0);
3085 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
3086 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
3087 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
3089 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
3090 assert_eq!(route.paths[0][3].short_channel_id, 11);
3091 assert_eq!(route.paths[0][3].fee_msat, 0);
3092 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
3093 // If we have a peer in the node map, we'll use their features here since we don't have
3094 // a way of figuring out their features from the invoice:
3095 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
3096 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
3098 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
3099 assert_eq!(route.paths[0][4].short_channel_id, 8);
3100 assert_eq!(route.paths[0][4].fee_msat, 100);
3101 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
3102 assert_eq!(route.paths[0][4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3103 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3106 /// Builds a trivial last-hop hint that passes through the two nodes given, with channel 0xff00
3108 fn multi_hop_last_hops_hint(hint_hops: [PublicKey; 2]) -> Vec<RouteHint> {
3109 let zero_fees = RoutingFees {
3111 proportional_millionths: 0,
3113 vec![RouteHint(vec![RouteHintHop {
3114 src_node_id: hint_hops[0],
3115 short_channel_id: 0xff00,
3118 proportional_millionths: 0,
3120 cltv_expiry_delta: (5 << 4) | 1,
3121 htlc_minimum_msat: None,
3122 htlc_maximum_msat: None,
3124 src_node_id: hint_hops[1],
3125 short_channel_id: 0xff01,
3127 cltv_expiry_delta: (8 << 4) | 1,
3128 htlc_minimum_msat: None,
3129 htlc_maximum_msat: None,
3134 fn multi_hint_last_hops_test() {
3135 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3136 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3137 let last_hops = multi_hop_last_hops_hint([nodes[2], nodes[3]]);
3138 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops.clone());
3139 let scorer = test_utils::TestScorer::with_penalty(0);
3140 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3141 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3142 // Test through channels 2, 3, 0xff00, 0xff01.
3143 // Test shows that multiple hop hints are considered.
3145 // Disabling channels 6 & 7 by flags=2
3146 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3147 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3148 short_channel_id: 6,
3150 flags: 2, // to disable
3151 cltv_expiry_delta: 0,
3152 htlc_minimum_msat: 0,
3153 htlc_maximum_msat: OptionalField::Absent,
3155 fee_proportional_millionths: 0,
3156 excess_data: Vec::new()
3158 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3159 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3160 short_channel_id: 7,
3162 flags: 2, // to disable
3163 cltv_expiry_delta: 0,
3164 htlc_minimum_msat: 0,
3165 htlc_maximum_msat: OptionalField::Absent,
3167 fee_proportional_millionths: 0,
3168 excess_data: Vec::new()
3171 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3172 assert_eq!(route.paths[0].len(), 4);
3174 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3175 assert_eq!(route.paths[0][0].short_channel_id, 2);
3176 assert_eq!(route.paths[0][0].fee_msat, 200);
3177 assert_eq!(route.paths[0][0].cltv_expiry_delta, 65);
3178 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3179 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3181 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3182 assert_eq!(route.paths[0][1].short_channel_id, 4);
3183 assert_eq!(route.paths[0][1].fee_msat, 100);
3184 assert_eq!(route.paths[0][1].cltv_expiry_delta, 81);
3185 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3186 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3188 assert_eq!(route.paths[0][2].pubkey, nodes[3]);
3189 assert_eq!(route.paths[0][2].short_channel_id, last_hops[0].0[0].short_channel_id);
3190 assert_eq!(route.paths[0][2].fee_msat, 0);
3191 assert_eq!(route.paths[0][2].cltv_expiry_delta, 129);
3192 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(4));
3193 assert_eq!(route.paths[0][2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3195 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
3196 assert_eq!(route.paths[0][3].short_channel_id, last_hops[0].0[1].short_channel_id);
3197 assert_eq!(route.paths[0][3].fee_msat, 100);
3198 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
3199 assert_eq!(route.paths[0][3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3200 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3204 fn private_multi_hint_last_hops_test() {
3205 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3206 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3208 let non_announced_privkey = SecretKey::from_slice(&hex::decode(format!("{:02x}", 0xf0).repeat(32)).unwrap()[..]).unwrap();
3209 let non_announced_pubkey = PublicKey::from_secret_key(&secp_ctx, &non_announced_privkey);
3211 let last_hops = multi_hop_last_hops_hint([nodes[2], non_announced_pubkey]);
3212 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops.clone());
3213 let scorer = test_utils::TestScorer::with_penalty(0);
3214 // Test through channels 2, 3, 0xff00, 0xff01.
3215 // Test shows that multiple hop hints are considered.
3217 // Disabling channels 6 & 7 by flags=2
3218 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3219 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3220 short_channel_id: 6,
3222 flags: 2, // to disable
3223 cltv_expiry_delta: 0,
3224 htlc_minimum_msat: 0,
3225 htlc_maximum_msat: OptionalField::Absent,
3227 fee_proportional_millionths: 0,
3228 excess_data: Vec::new()
3230 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3231 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3232 short_channel_id: 7,
3234 flags: 2, // to disable
3235 cltv_expiry_delta: 0,
3236 htlc_minimum_msat: 0,
3237 htlc_maximum_msat: OptionalField::Absent,
3239 fee_proportional_millionths: 0,
3240 excess_data: Vec::new()
3243 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &[42u8; 32]).unwrap();
3244 assert_eq!(route.paths[0].len(), 4);
3246 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3247 assert_eq!(route.paths[0][0].short_channel_id, 2);
3248 assert_eq!(route.paths[0][0].fee_msat, 200);
3249 assert_eq!(route.paths[0][0].cltv_expiry_delta, 65);
3250 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3251 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3253 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3254 assert_eq!(route.paths[0][1].short_channel_id, 4);
3255 assert_eq!(route.paths[0][1].fee_msat, 100);
3256 assert_eq!(route.paths[0][1].cltv_expiry_delta, 81);
3257 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3258 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3260 assert_eq!(route.paths[0][2].pubkey, non_announced_pubkey);
3261 assert_eq!(route.paths[0][2].short_channel_id, last_hops[0].0[0].short_channel_id);
3262 assert_eq!(route.paths[0][2].fee_msat, 0);
3263 assert_eq!(route.paths[0][2].cltv_expiry_delta, 129);
3264 assert_eq!(route.paths[0][2].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3265 assert_eq!(route.paths[0][2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3267 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
3268 assert_eq!(route.paths[0][3].short_channel_id, last_hops[0].0[1].short_channel_id);
3269 assert_eq!(route.paths[0][3].fee_msat, 100);
3270 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
3271 assert_eq!(route.paths[0][3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3272 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3275 fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3276 let zero_fees = RoutingFees {
3278 proportional_millionths: 0,
3280 vec![RouteHint(vec![RouteHintHop {
3281 src_node_id: nodes[4],
3282 short_channel_id: 11,
3284 cltv_expiry_delta: (11 << 4) | 1,
3285 htlc_minimum_msat: None,
3286 htlc_maximum_msat: None,
3288 src_node_id: nodes[3],
3289 short_channel_id: 8,
3291 cltv_expiry_delta: (8 << 4) | 1,
3292 htlc_minimum_msat: None,
3293 htlc_maximum_msat: None,
3294 }]), RouteHint(vec![RouteHintHop {
3295 src_node_id: nodes[4],
3296 short_channel_id: 9,
3299 proportional_millionths: 0,
3301 cltv_expiry_delta: (9 << 4) | 1,
3302 htlc_minimum_msat: None,
3303 htlc_maximum_msat: None,
3304 }]), RouteHint(vec![RouteHintHop {
3305 src_node_id: nodes[5],
3306 short_channel_id: 10,
3308 cltv_expiry_delta: (10 << 4) | 1,
3309 htlc_minimum_msat: None,
3310 htlc_maximum_msat: None,
3315 fn last_hops_with_public_channel_test() {
3316 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3317 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3318 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops_with_public_channel(&nodes));
3319 let scorer = test_utils::TestScorer::with_penalty(0);
3320 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3321 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3322 // This test shows that public routes can be present in the invoice
3323 // which would be handled in the same manner.
3325 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3326 assert_eq!(route.paths[0].len(), 5);
3328 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3329 assert_eq!(route.paths[0][0].short_channel_id, 2);
3330 assert_eq!(route.paths[0][0].fee_msat, 100);
3331 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
3332 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3333 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3335 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3336 assert_eq!(route.paths[0][1].short_channel_id, 4);
3337 assert_eq!(route.paths[0][1].fee_msat, 0);
3338 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
3339 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3340 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3342 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
3343 assert_eq!(route.paths[0][2].short_channel_id, 6);
3344 assert_eq!(route.paths[0][2].fee_msat, 0);
3345 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
3346 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
3347 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
3349 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
3350 assert_eq!(route.paths[0][3].short_channel_id, 11);
3351 assert_eq!(route.paths[0][3].fee_msat, 0);
3352 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
3353 // If we have a peer in the node map, we'll use their features here since we don't have
3354 // a way of figuring out their features from the invoice:
3355 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
3356 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
3358 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
3359 assert_eq!(route.paths[0][4].short_channel_id, 8);
3360 assert_eq!(route.paths[0][4].fee_msat, 100);
3361 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
3362 assert_eq!(route.paths[0][4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3363 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3367 fn our_chans_last_hop_connect_test() {
3368 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3369 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3370 let scorer = test_utils::TestScorer::with_penalty(0);
3371 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3372 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3374 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
3375 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3376 let mut last_hops = last_hops(&nodes);
3377 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops.clone());
3378 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();
3379 assert_eq!(route.paths[0].len(), 2);
3381 assert_eq!(route.paths[0][0].pubkey, nodes[3]);
3382 assert_eq!(route.paths[0][0].short_channel_id, 42);
3383 assert_eq!(route.paths[0][0].fee_msat, 0);
3384 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 4) | 1);
3385 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
3386 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3388 assert_eq!(route.paths[0][1].pubkey, nodes[6]);
3389 assert_eq!(route.paths[0][1].short_channel_id, 8);
3390 assert_eq!(route.paths[0][1].fee_msat, 100);
3391 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
3392 assert_eq!(route.paths[0][1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3393 assert_eq!(route.paths[0][1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3395 last_hops[0].0[0].fees.base_msat = 1000;
3397 // Revert to via 6 as the fee on 8 goes up
3398 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops);
3399 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3400 assert_eq!(route.paths[0].len(), 4);
3402 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3403 assert_eq!(route.paths[0][0].short_channel_id, 2);
3404 assert_eq!(route.paths[0][0].fee_msat, 200); // fee increased as its % of value transferred across node
3405 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
3406 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3407 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3409 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3410 assert_eq!(route.paths[0][1].short_channel_id, 4);
3411 assert_eq!(route.paths[0][1].fee_msat, 100);
3412 assert_eq!(route.paths[0][1].cltv_expiry_delta, (7 << 4) | 1);
3413 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3414 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3416 assert_eq!(route.paths[0][2].pubkey, nodes[5]);
3417 assert_eq!(route.paths[0][2].short_channel_id, 7);
3418 assert_eq!(route.paths[0][2].fee_msat, 0);
3419 assert_eq!(route.paths[0][2].cltv_expiry_delta, (10 << 4) | 1);
3420 // If we have a peer in the node map, we'll use their features here since we don't have
3421 // a way of figuring out their features from the invoice:
3422 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
3423 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(7));
3425 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
3426 assert_eq!(route.paths[0][3].short_channel_id, 10);
3427 assert_eq!(route.paths[0][3].fee_msat, 100);
3428 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
3429 assert_eq!(route.paths[0][3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3430 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3432 // ...but still use 8 for larger payments as 6 has a variable feerate
3433 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 2000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3434 assert_eq!(route.paths[0].len(), 5);
3436 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3437 assert_eq!(route.paths[0][0].short_channel_id, 2);
3438 assert_eq!(route.paths[0][0].fee_msat, 3000);
3439 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
3440 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3441 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3443 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3444 assert_eq!(route.paths[0][1].short_channel_id, 4);
3445 assert_eq!(route.paths[0][1].fee_msat, 0);
3446 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
3447 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3448 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3450 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
3451 assert_eq!(route.paths[0][2].short_channel_id, 6);
3452 assert_eq!(route.paths[0][2].fee_msat, 0);
3453 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
3454 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
3455 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
3457 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
3458 assert_eq!(route.paths[0][3].short_channel_id, 11);
3459 assert_eq!(route.paths[0][3].fee_msat, 1000);
3460 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
3461 // If we have a peer in the node map, we'll use their features here since we don't have
3462 // a way of figuring out their features from the invoice:
3463 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
3464 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
3466 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
3467 assert_eq!(route.paths[0][4].short_channel_id, 8);
3468 assert_eq!(route.paths[0][4].fee_msat, 2000);
3469 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
3470 assert_eq!(route.paths[0][4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3471 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3474 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> {
3475 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
3476 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3477 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3479 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
3480 let last_hops = RouteHint(vec![RouteHintHop {
3481 src_node_id: middle_node_id,
3482 short_channel_id: 8,
3485 proportional_millionths: last_hop_fee_prop,
3487 cltv_expiry_delta: (8 << 4) | 1,
3488 htlc_minimum_msat: None,
3489 htlc_maximum_msat: last_hop_htlc_max,
3491 let payment_params = PaymentParameters::from_node_id(target_node_id).with_route_hints(vec![last_hops]);
3492 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
3493 let scorer = test_utils::TestScorer::with_penalty(0);
3494 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3495 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3496 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
3497 let logger = test_utils::TestLogger::new();
3498 let network_graph = NetworkGraph::new(genesis_hash, &logger);
3499 let route = get_route(&source_node_id, &payment_params, &network_graph.read_only(),
3500 Some(&our_chans.iter().collect::<Vec<_>>()), route_val, 42, &logger, &scorer, &random_seed_bytes);
3505 fn unannounced_path_test() {
3506 // We should be able to send a payment to a destination without any help of a routing graph
3507 // if we have a channel with a common counterparty that appears in the first and last hop
3509 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
3511 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3512 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3513 assert_eq!(route.paths[0].len(), 2);
3515 assert_eq!(route.paths[0][0].pubkey, middle_node_id);
3516 assert_eq!(route.paths[0][0].short_channel_id, 42);
3517 assert_eq!(route.paths[0][0].fee_msat, 1001);
3518 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 4) | 1);
3519 assert_eq!(route.paths[0][0].node_features.le_flags(), &[0b11]);
3520 assert_eq!(route.paths[0][0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3522 assert_eq!(route.paths[0][1].pubkey, target_node_id);
3523 assert_eq!(route.paths[0][1].short_channel_id, 8);
3524 assert_eq!(route.paths[0][1].fee_msat, 1000000);
3525 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
3526 assert_eq!(route.paths[0][1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3527 assert_eq!(route.paths[0][1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3531 fn overflow_unannounced_path_test_liquidity_underflow() {
3532 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
3533 // the last-hop had a fee which overflowed a u64, we'd panic.
3534 // This was due to us adding the first-hop from us unconditionally, causing us to think
3535 // we'd built a path (as our node is in the "best candidate" set), when we had not.
3536 // In this test, we previously hit a subtraction underflow due to having less available
3537 // liquidity at the last hop than 0.
3538 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());
3542 fn overflow_unannounced_path_test_feerate_overflow() {
3543 // This tests for the same case as above, except instead of hitting a subtraction
3544 // underflow, we hit a case where the fee charged at a hop overflowed.
3545 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());
3549 fn available_amount_while_routing_test() {
3550 // Tests whether we choose the correct available channel amount while routing.
3552 let (secp_ctx, network_graph, mut gossip_sync, chain_monitor, logger) = build_graph();
3553 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3554 let scorer = test_utils::TestScorer::with_penalty(0);
3555 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3556 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3557 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
3559 // We will use a simple single-path route from
3560 // our node to node2 via node0: channels {1, 3}.
3562 // First disable all other paths.
3563 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3564 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3565 short_channel_id: 2,
3568 cltv_expiry_delta: 0,
3569 htlc_minimum_msat: 0,
3570 htlc_maximum_msat: OptionalField::Present(100_000),
3572 fee_proportional_millionths: 0,
3573 excess_data: Vec::new()
3575 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3576 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3577 short_channel_id: 12,
3580 cltv_expiry_delta: 0,
3581 htlc_minimum_msat: 0,
3582 htlc_maximum_msat: OptionalField::Present(100_000),
3584 fee_proportional_millionths: 0,
3585 excess_data: Vec::new()
3588 // Make the first channel (#1) very permissive,
3589 // and we will be testing all limits on the second channel.
3590 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3591 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3592 short_channel_id: 1,
3595 cltv_expiry_delta: 0,
3596 htlc_minimum_msat: 0,
3597 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3599 fee_proportional_millionths: 0,
3600 excess_data: Vec::new()
3603 // First, let's see if routing works if we have absolutely no idea about the available amount.
3604 // In this case, it should be set to 250_000 sats.
3605 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3606 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3607 short_channel_id: 3,
3610 cltv_expiry_delta: 0,
3611 htlc_minimum_msat: 0,
3612 htlc_maximum_msat: OptionalField::Absent,
3614 fee_proportional_millionths: 0,
3615 excess_data: Vec::new()
3619 // Attempt to route more than available results in a failure.
3620 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3621 &our_id, &payment_params, &network_graph.read_only(), None, 250_000_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3622 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3623 } else { panic!(); }
3627 // Now, attempt to route an exact amount we have should be fine.
3628 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();
3629 assert_eq!(route.paths.len(), 1);
3630 let path = route.paths.last().unwrap();
3631 assert_eq!(path.len(), 2);
3632 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3633 assert_eq!(path.last().unwrap().fee_msat, 250_000_000);
3636 // Check that setting next_outbound_htlc_limit_msat in first_hops limits the channels.
3637 // Disable channel #1 and use another first hop.
3638 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3639 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3640 short_channel_id: 1,
3643 cltv_expiry_delta: 0,
3644 htlc_minimum_msat: 0,
3645 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3647 fee_proportional_millionths: 0,
3648 excess_data: Vec::new()
3651 // Now, limit the first_hop by the next_outbound_htlc_limit_msat of 200_000 sats.
3652 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
3655 // Attempt to route more than available results in a failure.
3656 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3657 &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) {
3658 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3659 } else { panic!(); }
3663 // Now, attempt to route an exact amount we have should be fine.
3664 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();
3665 assert_eq!(route.paths.len(), 1);
3666 let path = route.paths.last().unwrap();
3667 assert_eq!(path.len(), 2);
3668 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3669 assert_eq!(path.last().unwrap().fee_msat, 200_000_000);
3672 // Enable channel #1 back.
3673 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3674 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3675 short_channel_id: 1,
3678 cltv_expiry_delta: 0,
3679 htlc_minimum_msat: 0,
3680 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3682 fee_proportional_millionths: 0,
3683 excess_data: Vec::new()
3687 // Now let's see if routing works if we know only htlc_maximum_msat.
3688 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3689 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3690 short_channel_id: 3,
3693 cltv_expiry_delta: 0,
3694 htlc_minimum_msat: 0,
3695 htlc_maximum_msat: OptionalField::Present(15_000),
3697 fee_proportional_millionths: 0,
3698 excess_data: Vec::new()
3702 // Attempt to route more than available results in a failure.
3703 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3704 &our_id, &payment_params, &network_graph.read_only(), None, 15_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3705 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3706 } else { panic!(); }
3710 // Now, attempt to route an exact amount we have should be fine.
3711 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 15_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3712 assert_eq!(route.paths.len(), 1);
3713 let path = route.paths.last().unwrap();
3714 assert_eq!(path.len(), 2);
3715 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3716 assert_eq!(path.last().unwrap().fee_msat, 15_000);
3719 // Now let's see if routing works if we know only capacity from the UTXO.
3721 // We can't change UTXO capacity on the fly, so we'll disable
3722 // the existing channel and add another one with the capacity we need.
3723 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3724 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3725 short_channel_id: 3,
3728 cltv_expiry_delta: 0,
3729 htlc_minimum_msat: 0,
3730 htlc_maximum_msat: OptionalField::Absent,
3732 fee_proportional_millionths: 0,
3733 excess_data: Vec::new()
3736 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
3737 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
3738 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
3739 .push_opcode(opcodes::all::OP_PUSHNUM_2)
3740 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
3742 *chain_monitor.utxo_ret.lock().unwrap() = Ok(TxOut { value: 15, script_pubkey: good_script.clone() });
3743 gossip_sync.add_chain_access(Some(chain_monitor));
3745 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
3746 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3747 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3748 short_channel_id: 333,
3751 cltv_expiry_delta: (3 << 4) | 1,
3752 htlc_minimum_msat: 0,
3753 htlc_maximum_msat: OptionalField::Absent,
3755 fee_proportional_millionths: 0,
3756 excess_data: Vec::new()
3758 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3759 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3760 short_channel_id: 333,
3763 cltv_expiry_delta: (3 << 4) | 2,
3764 htlc_minimum_msat: 0,
3765 htlc_maximum_msat: OptionalField::Absent,
3767 fee_proportional_millionths: 0,
3768 excess_data: Vec::new()
3772 // Attempt to route more than available results in a failure.
3773 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3774 &our_id, &payment_params, &network_graph.read_only(), None, 15_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3775 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3776 } else { panic!(); }
3780 // Now, attempt to route an exact amount we have should be fine.
3781 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 15_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3782 assert_eq!(route.paths.len(), 1);
3783 let path = route.paths.last().unwrap();
3784 assert_eq!(path.len(), 2);
3785 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3786 assert_eq!(path.last().unwrap().fee_msat, 15_000);
3789 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
3790 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3791 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3792 short_channel_id: 333,
3795 cltv_expiry_delta: 0,
3796 htlc_minimum_msat: 0,
3797 htlc_maximum_msat: OptionalField::Present(10_000),
3799 fee_proportional_millionths: 0,
3800 excess_data: Vec::new()
3804 // Attempt to route more than available results in a failure.
3805 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3806 &our_id, &payment_params, &network_graph.read_only(), None, 10_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3807 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3808 } else { panic!(); }
3812 // Now, attempt to route an exact amount we have should be fine.
3813 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 10_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3814 assert_eq!(route.paths.len(), 1);
3815 let path = route.paths.last().unwrap();
3816 assert_eq!(path.len(), 2);
3817 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3818 assert_eq!(path.last().unwrap().fee_msat, 10_000);
3823 fn available_liquidity_last_hop_test() {
3824 // Check that available liquidity properly limits the path even when only
3825 // one of the latter hops is limited.
3826 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3827 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3828 let scorer = test_utils::TestScorer::with_penalty(0);
3829 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3830 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3831 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
3833 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3834 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
3835 // Total capacity: 50 sats.
3837 // Disable other potential paths.
3838 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3839 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3840 short_channel_id: 2,
3843 cltv_expiry_delta: 0,
3844 htlc_minimum_msat: 0,
3845 htlc_maximum_msat: OptionalField::Present(100_000),
3847 fee_proportional_millionths: 0,
3848 excess_data: Vec::new()
3850 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3851 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3852 short_channel_id: 7,
3855 cltv_expiry_delta: 0,
3856 htlc_minimum_msat: 0,
3857 htlc_maximum_msat: OptionalField::Present(100_000),
3859 fee_proportional_millionths: 0,
3860 excess_data: Vec::new()
3865 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3866 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3867 short_channel_id: 12,
3870 cltv_expiry_delta: 0,
3871 htlc_minimum_msat: 0,
3872 htlc_maximum_msat: OptionalField::Present(100_000),
3874 fee_proportional_millionths: 0,
3875 excess_data: Vec::new()
3877 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3878 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3879 short_channel_id: 13,
3882 cltv_expiry_delta: 0,
3883 htlc_minimum_msat: 0,
3884 htlc_maximum_msat: OptionalField::Present(100_000),
3886 fee_proportional_millionths: 0,
3887 excess_data: Vec::new()
3890 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3891 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3892 short_channel_id: 6,
3895 cltv_expiry_delta: 0,
3896 htlc_minimum_msat: 0,
3897 htlc_maximum_msat: OptionalField::Present(50_000),
3899 fee_proportional_millionths: 0,
3900 excess_data: Vec::new()
3902 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3903 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3904 short_channel_id: 11,
3907 cltv_expiry_delta: 0,
3908 htlc_minimum_msat: 0,
3909 htlc_maximum_msat: OptionalField::Present(100_000),
3911 fee_proportional_millionths: 0,
3912 excess_data: Vec::new()
3915 // Attempt to route more than available results in a failure.
3916 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3917 &our_id, &payment_params, &network_graph.read_only(), None, 60_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3918 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3919 } else { panic!(); }
3923 // Now, attempt to route 49 sats (just a bit below the capacity).
3924 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 49_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3925 assert_eq!(route.paths.len(), 1);
3926 let mut total_amount_paid_msat = 0;
3927 for path in &route.paths {
3928 assert_eq!(path.len(), 4);
3929 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3930 total_amount_paid_msat += path.last().unwrap().fee_msat;
3932 assert_eq!(total_amount_paid_msat, 49_000);
3936 // Attempt to route an exact amount is also fine
3937 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3938 assert_eq!(route.paths.len(), 1);
3939 let mut total_amount_paid_msat = 0;
3940 for path in &route.paths {
3941 assert_eq!(path.len(), 4);
3942 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3943 total_amount_paid_msat += path.last().unwrap().fee_msat;
3945 assert_eq!(total_amount_paid_msat, 50_000);
3950 fn ignore_fee_first_hop_test() {
3951 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3952 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3953 let scorer = test_utils::TestScorer::with_penalty(0);
3954 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3955 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3956 let payment_params = PaymentParameters::from_node_id(nodes[2]);
3958 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3959 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3960 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3961 short_channel_id: 1,
3964 cltv_expiry_delta: 0,
3965 htlc_minimum_msat: 0,
3966 htlc_maximum_msat: OptionalField::Present(100_000),
3967 fee_base_msat: 1_000_000,
3968 fee_proportional_millionths: 0,
3969 excess_data: Vec::new()
3971 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3972 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3973 short_channel_id: 3,
3976 cltv_expiry_delta: 0,
3977 htlc_minimum_msat: 0,
3978 htlc_maximum_msat: OptionalField::Present(50_000),
3980 fee_proportional_millionths: 0,
3981 excess_data: Vec::new()
3985 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3986 assert_eq!(route.paths.len(), 1);
3987 let mut total_amount_paid_msat = 0;
3988 for path in &route.paths {
3989 assert_eq!(path.len(), 2);
3990 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3991 total_amount_paid_msat += path.last().unwrap().fee_msat;
3993 assert_eq!(total_amount_paid_msat, 50_000);
3998 fn simple_mpp_route_test() {
3999 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4000 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4001 let scorer = test_utils::TestScorer::with_penalty(0);
4002 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4003 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4004 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
4006 // We need a route consisting of 3 paths:
4007 // From our node to node2 via node0, node7, node1 (three paths one hop each).
4008 // To achieve this, the amount being transferred should be around
4009 // the total capacity of these 3 paths.
4011 // First, we set limits on these (previously unlimited) channels.
4012 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
4014 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
4015 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4016 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4017 short_channel_id: 1,
4020 cltv_expiry_delta: 0,
4021 htlc_minimum_msat: 0,
4022 htlc_maximum_msat: OptionalField::Present(100_000),
4024 fee_proportional_millionths: 0,
4025 excess_data: Vec::new()
4027 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4028 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4029 short_channel_id: 3,
4032 cltv_expiry_delta: 0,
4033 htlc_minimum_msat: 0,
4034 htlc_maximum_msat: OptionalField::Present(50_000),
4036 fee_proportional_millionths: 0,
4037 excess_data: Vec::new()
4040 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
4041 // (total limit 60).
4042 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4043 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4044 short_channel_id: 12,
4047 cltv_expiry_delta: 0,
4048 htlc_minimum_msat: 0,
4049 htlc_maximum_msat: OptionalField::Present(60_000),
4051 fee_proportional_millionths: 0,
4052 excess_data: Vec::new()
4054 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4055 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4056 short_channel_id: 13,
4059 cltv_expiry_delta: 0,
4060 htlc_minimum_msat: 0,
4061 htlc_maximum_msat: OptionalField::Present(60_000),
4063 fee_proportional_millionths: 0,
4064 excess_data: Vec::new()
4067 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
4068 // (total capacity 180 sats).
4069 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4070 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4071 short_channel_id: 2,
4074 cltv_expiry_delta: 0,
4075 htlc_minimum_msat: 0,
4076 htlc_maximum_msat: OptionalField::Present(200_000),
4078 fee_proportional_millionths: 0,
4079 excess_data: Vec::new()
4081 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4082 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4083 short_channel_id: 4,
4086 cltv_expiry_delta: 0,
4087 htlc_minimum_msat: 0,
4088 htlc_maximum_msat: OptionalField::Present(180_000),
4090 fee_proportional_millionths: 0,
4091 excess_data: Vec::new()
4095 // Attempt to route more than available results in a failure.
4096 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4097 &our_id, &payment_params, &network_graph.read_only(), None, 300_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
4098 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4099 } else { panic!(); }
4103 // Now, attempt to route 250 sats (just a bit below the capacity).
4104 // Our algorithm should provide us with these 3 paths.
4105 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 250_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4106 assert_eq!(route.paths.len(), 3);
4107 let mut total_amount_paid_msat = 0;
4108 for path in &route.paths {
4109 assert_eq!(path.len(), 2);
4110 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4111 total_amount_paid_msat += path.last().unwrap().fee_msat;
4113 assert_eq!(total_amount_paid_msat, 250_000);
4117 // Attempt to route an exact amount is also fine
4118 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 290_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4119 assert_eq!(route.paths.len(), 3);
4120 let mut total_amount_paid_msat = 0;
4121 for path in &route.paths {
4122 assert_eq!(path.len(), 2);
4123 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4124 total_amount_paid_msat += path.last().unwrap().fee_msat;
4126 assert_eq!(total_amount_paid_msat, 290_000);
4131 fn long_mpp_route_test() {
4132 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4133 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4134 let scorer = test_utils::TestScorer::with_penalty(0);
4135 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4136 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4137 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
4139 // We need a route consisting of 3 paths:
4140 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
4141 // Note that these paths overlap (channels 5, 12, 13).
4142 // We will route 300 sats.
4143 // Each path will have 100 sats capacity, those channels which
4144 // are used twice will have 200 sats capacity.
4146 // Disable other potential paths.
4147 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4148 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4149 short_channel_id: 2,
4152 cltv_expiry_delta: 0,
4153 htlc_minimum_msat: 0,
4154 htlc_maximum_msat: OptionalField::Present(100_000),
4156 fee_proportional_millionths: 0,
4157 excess_data: Vec::new()
4159 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4160 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4161 short_channel_id: 7,
4164 cltv_expiry_delta: 0,
4165 htlc_minimum_msat: 0,
4166 htlc_maximum_msat: OptionalField::Present(100_000),
4168 fee_proportional_millionths: 0,
4169 excess_data: Vec::new()
4172 // Path via {node0, node2} is channels {1, 3, 5}.
4173 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4174 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4175 short_channel_id: 1,
4178 cltv_expiry_delta: 0,
4179 htlc_minimum_msat: 0,
4180 htlc_maximum_msat: OptionalField::Present(100_000),
4182 fee_proportional_millionths: 0,
4183 excess_data: Vec::new()
4185 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4186 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4187 short_channel_id: 3,
4190 cltv_expiry_delta: 0,
4191 htlc_minimum_msat: 0,
4192 htlc_maximum_msat: OptionalField::Present(100_000),
4194 fee_proportional_millionths: 0,
4195 excess_data: Vec::new()
4198 // Capacity of 200 sats because this channel will be used by 3rd path as well.
4199 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4200 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4201 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4202 short_channel_id: 5,
4205 cltv_expiry_delta: 0,
4206 htlc_minimum_msat: 0,
4207 htlc_maximum_msat: OptionalField::Present(200_000),
4209 fee_proportional_millionths: 0,
4210 excess_data: Vec::new()
4213 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4214 // Add 100 sats to the capacities of {12, 13}, because these channels
4215 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
4216 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4217 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4218 short_channel_id: 12,
4221 cltv_expiry_delta: 0,
4222 htlc_minimum_msat: 0,
4223 htlc_maximum_msat: OptionalField::Present(200_000),
4225 fee_proportional_millionths: 0,
4226 excess_data: Vec::new()
4228 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4229 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4230 short_channel_id: 13,
4233 cltv_expiry_delta: 0,
4234 htlc_minimum_msat: 0,
4235 htlc_maximum_msat: OptionalField::Present(200_000),
4237 fee_proportional_millionths: 0,
4238 excess_data: Vec::new()
4241 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4242 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4243 short_channel_id: 6,
4246 cltv_expiry_delta: 0,
4247 htlc_minimum_msat: 0,
4248 htlc_maximum_msat: OptionalField::Present(100_000),
4250 fee_proportional_millionths: 0,
4251 excess_data: Vec::new()
4253 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4254 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4255 short_channel_id: 11,
4258 cltv_expiry_delta: 0,
4259 htlc_minimum_msat: 0,
4260 htlc_maximum_msat: OptionalField::Present(100_000),
4262 fee_proportional_millionths: 0,
4263 excess_data: Vec::new()
4266 // Path via {node7, node2} is channels {12, 13, 5}.
4267 // We already limited them to 200 sats (they are used twice for 100 sats).
4268 // Nothing to do here.
4271 // Attempt to route more than available results in a failure.
4272 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4273 &our_id, &payment_params, &network_graph.read_only(), None, 350_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
4274 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4275 } else { panic!(); }
4279 // Now, attempt to route 300 sats (exact amount we can route).
4280 // Our algorithm should provide us with these 3 paths, 100 sats each.
4281 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 300_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4282 assert_eq!(route.paths.len(), 3);
4284 let mut total_amount_paid_msat = 0;
4285 for path in &route.paths {
4286 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
4287 total_amount_paid_msat += path.last().unwrap().fee_msat;
4289 assert_eq!(total_amount_paid_msat, 300_000);
4295 fn mpp_cheaper_route_test() {
4296 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4297 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4298 let scorer = test_utils::TestScorer::with_penalty(0);
4299 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4300 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4301 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
4303 // This test checks that if we have two cheaper paths and one more expensive path,
4304 // so that liquidity-wise any 2 of 3 combination is sufficient,
4305 // two cheaper paths will be taken.
4306 // These paths have equal available liquidity.
4308 // We need a combination of 3 paths:
4309 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
4310 // Note that these paths overlap (channels 5, 12, 13).
4311 // Each path will have 100 sats capacity, those channels which
4312 // are used twice will have 200 sats capacity.
4314 // Disable other potential paths.
4315 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4316 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4317 short_channel_id: 2,
4320 cltv_expiry_delta: 0,
4321 htlc_minimum_msat: 0,
4322 htlc_maximum_msat: OptionalField::Present(100_000),
4324 fee_proportional_millionths: 0,
4325 excess_data: Vec::new()
4327 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4328 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4329 short_channel_id: 7,
4332 cltv_expiry_delta: 0,
4333 htlc_minimum_msat: 0,
4334 htlc_maximum_msat: OptionalField::Present(100_000),
4336 fee_proportional_millionths: 0,
4337 excess_data: Vec::new()
4340 // Path via {node0, node2} is channels {1, 3, 5}.
4341 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4342 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4343 short_channel_id: 1,
4346 cltv_expiry_delta: 0,
4347 htlc_minimum_msat: 0,
4348 htlc_maximum_msat: OptionalField::Present(100_000),
4350 fee_proportional_millionths: 0,
4351 excess_data: Vec::new()
4353 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4354 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4355 short_channel_id: 3,
4358 cltv_expiry_delta: 0,
4359 htlc_minimum_msat: 0,
4360 htlc_maximum_msat: OptionalField::Present(100_000),
4362 fee_proportional_millionths: 0,
4363 excess_data: Vec::new()
4366 // Capacity of 200 sats because this channel will be used by 3rd path as well.
4367 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4368 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4369 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4370 short_channel_id: 5,
4373 cltv_expiry_delta: 0,
4374 htlc_minimum_msat: 0,
4375 htlc_maximum_msat: OptionalField::Present(200_000),
4377 fee_proportional_millionths: 0,
4378 excess_data: Vec::new()
4381 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4382 // Add 100 sats to the capacities of {12, 13}, because these channels
4383 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
4384 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4385 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4386 short_channel_id: 12,
4389 cltv_expiry_delta: 0,
4390 htlc_minimum_msat: 0,
4391 htlc_maximum_msat: OptionalField::Present(200_000),
4393 fee_proportional_millionths: 0,
4394 excess_data: Vec::new()
4396 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4397 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4398 short_channel_id: 13,
4401 cltv_expiry_delta: 0,
4402 htlc_minimum_msat: 0,
4403 htlc_maximum_msat: OptionalField::Present(200_000),
4405 fee_proportional_millionths: 0,
4406 excess_data: Vec::new()
4409 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4410 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4411 short_channel_id: 6,
4414 cltv_expiry_delta: 0,
4415 htlc_minimum_msat: 0,
4416 htlc_maximum_msat: OptionalField::Present(100_000),
4417 fee_base_msat: 1_000,
4418 fee_proportional_millionths: 0,
4419 excess_data: Vec::new()
4421 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4422 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4423 short_channel_id: 11,
4426 cltv_expiry_delta: 0,
4427 htlc_minimum_msat: 0,
4428 htlc_maximum_msat: OptionalField::Present(100_000),
4430 fee_proportional_millionths: 0,
4431 excess_data: Vec::new()
4434 // Path via {node7, node2} is channels {12, 13, 5}.
4435 // We already limited them to 200 sats (they are used twice for 100 sats).
4436 // Nothing to do here.
4439 // Now, attempt to route 180 sats.
4440 // Our algorithm should provide us with these 2 paths.
4441 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 180_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4442 assert_eq!(route.paths.len(), 2);
4444 let mut total_value_transferred_msat = 0;
4445 let mut total_paid_msat = 0;
4446 for path in &route.paths {
4447 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
4448 total_value_transferred_msat += path.last().unwrap().fee_msat;
4450 total_paid_msat += hop.fee_msat;
4453 // If we paid fee, this would be higher.
4454 assert_eq!(total_value_transferred_msat, 180_000);
4455 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
4456 assert_eq!(total_fees_paid, 0);
4461 fn fees_on_mpp_route_test() {
4462 // This test makes sure that MPP algorithm properly takes into account
4463 // fees charged on the channels, by making the fees impactful:
4464 // if the fee is not properly accounted for, the behavior is different.
4465 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4466 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4467 let scorer = test_utils::TestScorer::with_penalty(0);
4468 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4469 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4470 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
4472 // We need a route consisting of 2 paths:
4473 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
4474 // We will route 200 sats, Each path will have 100 sats capacity.
4476 // This test is not particularly stable: e.g.,
4477 // there's a way to route via {node0, node2, node4}.
4478 // It works while pathfinding is deterministic, but can be broken otherwise.
4479 // It's fine to ignore this concern for now.
4481 // Disable other potential paths.
4482 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4483 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4484 short_channel_id: 2,
4487 cltv_expiry_delta: 0,
4488 htlc_minimum_msat: 0,
4489 htlc_maximum_msat: OptionalField::Present(100_000),
4491 fee_proportional_millionths: 0,
4492 excess_data: Vec::new()
4495 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4496 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4497 short_channel_id: 7,
4500 cltv_expiry_delta: 0,
4501 htlc_minimum_msat: 0,
4502 htlc_maximum_msat: OptionalField::Present(100_000),
4504 fee_proportional_millionths: 0,
4505 excess_data: Vec::new()
4508 // Path via {node0, node2} is channels {1, 3, 5}.
4509 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4510 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4511 short_channel_id: 1,
4514 cltv_expiry_delta: 0,
4515 htlc_minimum_msat: 0,
4516 htlc_maximum_msat: OptionalField::Present(100_000),
4518 fee_proportional_millionths: 0,
4519 excess_data: Vec::new()
4521 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4522 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4523 short_channel_id: 3,
4526 cltv_expiry_delta: 0,
4527 htlc_minimum_msat: 0,
4528 htlc_maximum_msat: OptionalField::Present(100_000),
4530 fee_proportional_millionths: 0,
4531 excess_data: Vec::new()
4534 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4535 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4536 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4537 short_channel_id: 5,
4540 cltv_expiry_delta: 0,
4541 htlc_minimum_msat: 0,
4542 htlc_maximum_msat: OptionalField::Present(100_000),
4544 fee_proportional_millionths: 0,
4545 excess_data: Vec::new()
4548 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4549 // All channels should be 100 sats capacity. But for the fee experiment,
4550 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
4551 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
4552 // 100 sats (and pay 150 sats in fees for the use of channel 6),
4553 // so no matter how large are other channels,
4554 // the whole path will be limited by 100 sats with just these 2 conditions:
4555 // - channel 12 capacity is 250 sats
4556 // - fee for channel 6 is 150 sats
4557 // Let's test this by enforcing these 2 conditions and removing other limits.
4558 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4559 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4560 short_channel_id: 12,
4563 cltv_expiry_delta: 0,
4564 htlc_minimum_msat: 0,
4565 htlc_maximum_msat: OptionalField::Present(250_000),
4567 fee_proportional_millionths: 0,
4568 excess_data: Vec::new()
4570 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4571 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4572 short_channel_id: 13,
4575 cltv_expiry_delta: 0,
4576 htlc_minimum_msat: 0,
4577 htlc_maximum_msat: OptionalField::Absent,
4579 fee_proportional_millionths: 0,
4580 excess_data: Vec::new()
4583 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4584 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4585 short_channel_id: 6,
4588 cltv_expiry_delta: 0,
4589 htlc_minimum_msat: 0,
4590 htlc_maximum_msat: OptionalField::Absent,
4591 fee_base_msat: 150_000,
4592 fee_proportional_millionths: 0,
4593 excess_data: Vec::new()
4595 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4596 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4597 short_channel_id: 11,
4600 cltv_expiry_delta: 0,
4601 htlc_minimum_msat: 0,
4602 htlc_maximum_msat: OptionalField::Absent,
4604 fee_proportional_millionths: 0,
4605 excess_data: Vec::new()
4609 // Attempt to route more than available results in a failure.
4610 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4611 &our_id, &payment_params, &network_graph.read_only(), None, 210_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
4612 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4613 } else { panic!(); }
4617 // Now, attempt to route 200 sats (exact amount we can route).
4618 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 200_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4619 assert_eq!(route.paths.len(), 2);
4621 let mut total_amount_paid_msat = 0;
4622 for path in &route.paths {
4623 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
4624 total_amount_paid_msat += path.last().unwrap().fee_msat;
4626 assert_eq!(total_amount_paid_msat, 200_000);
4627 assert_eq!(route.get_total_fees(), 150_000);
4632 fn mpp_with_last_hops() {
4633 // Previously, if we tried to send an MPP payment to a destination which was only reachable
4634 // via a single last-hop route hint, we'd fail to route if we first collected routes
4635 // totaling close but not quite enough to fund the full payment.
4637 // This was because we considered last-hop hints to have exactly the sought payment amount
4638 // instead of the amount we were trying to collect, needlessly limiting our path searching
4639 // at the very first hop.
4641 // Specifically, this interacted with our "all paths must fund at least 5% of total target"
4642 // criterion to cause us to refuse all routes at the last hop hint which would be considered
4643 // to only have the remaining to-collect amount in available liquidity.
4645 // This bug appeared in production in some specific channel configurations.
4646 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4647 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4648 let scorer = test_utils::TestScorer::with_penalty(0);
4649 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4650 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4651 let payment_params = PaymentParameters::from_node_id(PublicKey::from_slice(&[02; 33]).unwrap()).with_features(InvoiceFeatures::known())
4652 .with_route_hints(vec![RouteHint(vec![RouteHintHop {
4653 src_node_id: nodes[2],
4654 short_channel_id: 42,
4655 fees: RoutingFees { base_msat: 0, proportional_millionths: 0 },
4656 cltv_expiry_delta: 42,
4657 htlc_minimum_msat: None,
4658 htlc_maximum_msat: None,
4661 // Keep only two paths from us to nodes[2], both with a 99sat HTLC maximum, with one with
4662 // no fee and one with a 1msat fee. Previously, trying to route 100 sats to nodes[2] here
4663 // would first use the no-fee route and then fail to find a path along the second route as
4664 // we think we can only send up to 1 additional sat over the last-hop but refuse to as its
4665 // under 5% of our payment amount.
4666 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4667 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4668 short_channel_id: 1,
4671 cltv_expiry_delta: (5 << 4) | 5,
4672 htlc_minimum_msat: 0,
4673 htlc_maximum_msat: OptionalField::Present(99_000),
4674 fee_base_msat: u32::max_value(),
4675 fee_proportional_millionths: u32::max_value(),
4676 excess_data: Vec::new()
4678 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4679 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4680 short_channel_id: 2,
4683 cltv_expiry_delta: (5 << 4) | 3,
4684 htlc_minimum_msat: 0,
4685 htlc_maximum_msat: OptionalField::Present(99_000),
4686 fee_base_msat: u32::max_value(),
4687 fee_proportional_millionths: u32::max_value(),
4688 excess_data: Vec::new()
4690 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4691 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4692 short_channel_id: 4,
4695 cltv_expiry_delta: (4 << 4) | 1,
4696 htlc_minimum_msat: 0,
4697 htlc_maximum_msat: OptionalField::Absent,
4699 fee_proportional_millionths: 0,
4700 excess_data: Vec::new()
4702 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4703 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4704 short_channel_id: 13,
4706 flags: 0|2, // Channel disabled
4707 cltv_expiry_delta: (13 << 4) | 1,
4708 htlc_minimum_msat: 0,
4709 htlc_maximum_msat: OptionalField::Absent,
4711 fee_proportional_millionths: 2000000,
4712 excess_data: Vec::new()
4715 // Get a route for 100 sats and check that we found the MPP route no problem and didn't
4717 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4718 assert_eq!(route.paths.len(), 2);
4719 // Paths are somewhat randomly ordered, but:
4720 // * the first is channel 2 (1 msat fee) -> channel 4 -> channel 42
4721 // * the second is channel 1 (0 fee, but 99 sat maximum) -> channel 3 -> channel 42
4722 assert_eq!(route.paths[0][0].short_channel_id, 2);
4723 assert_eq!(route.paths[0][0].fee_msat, 1);
4724 assert_eq!(route.paths[0][2].fee_msat, 1_000);
4725 assert_eq!(route.paths[1][0].short_channel_id, 1);
4726 assert_eq!(route.paths[1][0].fee_msat, 0);
4727 assert_eq!(route.paths[1][2].fee_msat, 99_000);
4728 assert_eq!(route.get_total_fees(), 1);
4729 assert_eq!(route.get_total_amount(), 100_000);
4733 fn drop_lowest_channel_mpp_route_test() {
4734 // This test checks that low-capacity channel is dropped when after
4735 // path finding we realize that we found more capacity than we need.
4736 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4737 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4738 let scorer = test_utils::TestScorer::with_penalty(0);
4739 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4740 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4741 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
4743 // We need a route consisting of 3 paths:
4744 // From our node to node2 via node0, node7, node1 (three paths one hop each).
4746 // The first and the second paths should be sufficient, but the third should be
4747 // cheaper, so that we select it but drop later.
4749 // First, we set limits on these (previously unlimited) channels.
4750 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
4752 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
4753 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4754 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4755 short_channel_id: 1,
4758 cltv_expiry_delta: 0,
4759 htlc_minimum_msat: 0,
4760 htlc_maximum_msat: OptionalField::Present(100_000),
4762 fee_proportional_millionths: 0,
4763 excess_data: Vec::new()
4765 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4766 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4767 short_channel_id: 3,
4770 cltv_expiry_delta: 0,
4771 htlc_minimum_msat: 0,
4772 htlc_maximum_msat: OptionalField::Present(50_000),
4774 fee_proportional_millionths: 0,
4775 excess_data: Vec::new()
4778 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
4779 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4780 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4781 short_channel_id: 12,
4784 cltv_expiry_delta: 0,
4785 htlc_minimum_msat: 0,
4786 htlc_maximum_msat: OptionalField::Present(60_000),
4788 fee_proportional_millionths: 0,
4789 excess_data: Vec::new()
4791 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4792 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4793 short_channel_id: 13,
4796 cltv_expiry_delta: 0,
4797 htlc_minimum_msat: 0,
4798 htlc_maximum_msat: OptionalField::Present(60_000),
4800 fee_proportional_millionths: 0,
4801 excess_data: Vec::new()
4804 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
4805 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4806 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4807 short_channel_id: 2,
4810 cltv_expiry_delta: 0,
4811 htlc_minimum_msat: 0,
4812 htlc_maximum_msat: OptionalField::Present(20_000),
4814 fee_proportional_millionths: 0,
4815 excess_data: Vec::new()
4817 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4818 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4819 short_channel_id: 4,
4822 cltv_expiry_delta: 0,
4823 htlc_minimum_msat: 0,
4824 htlc_maximum_msat: OptionalField::Present(20_000),
4826 fee_proportional_millionths: 0,
4827 excess_data: Vec::new()
4831 // Attempt to route more than available results in a failure.
4832 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4833 &our_id, &payment_params, &network_graph.read_only(), None, 150_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
4834 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4835 } else { panic!(); }
4839 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
4840 // Our algorithm should provide us with these 3 paths.
4841 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 125_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4842 assert_eq!(route.paths.len(), 3);
4843 let mut total_amount_paid_msat = 0;
4844 for path in &route.paths {
4845 assert_eq!(path.len(), 2);
4846 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4847 total_amount_paid_msat += path.last().unwrap().fee_msat;
4849 assert_eq!(total_amount_paid_msat, 125_000);
4853 // Attempt to route without the last small cheap channel
4854 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4855 assert_eq!(route.paths.len(), 2);
4856 let mut total_amount_paid_msat = 0;
4857 for path in &route.paths {
4858 assert_eq!(path.len(), 2);
4859 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4860 total_amount_paid_msat += path.last().unwrap().fee_msat;
4862 assert_eq!(total_amount_paid_msat, 90_000);
4867 fn min_criteria_consistency() {
4868 // Test that we don't use an inconsistent metric between updating and walking nodes during
4869 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
4870 // was updated with a different criterion from the heap sorting, resulting in loops in
4871 // calculated paths. We test for that specific case here.
4873 // We construct a network that looks like this:
4875 // node2 -1(3)2- node3
4879 // node1 -1(5)2- node4 -1(1)2- node6
4885 // We create a loop on the side of our real path - our destination is node 6, with a
4886 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
4887 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
4888 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
4889 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
4890 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
4891 // "previous hop" being set to node 3, creating a loop in the path.
4892 let secp_ctx = Secp256k1::new();
4893 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
4894 let logger = Arc::new(test_utils::TestLogger::new());
4895 let network = Arc::new(NetworkGraph::new(genesis_hash, Arc::clone(&logger)));
4896 let gossip_sync = P2PGossipSync::new(Arc::clone(&network), None, Arc::clone(&logger));
4897 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4898 let scorer = test_utils::TestScorer::with_penalty(0);
4899 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4900 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4901 let payment_params = PaymentParameters::from_node_id(nodes[6]);
4903 add_channel(&gossip_sync, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
4904 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4905 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4906 short_channel_id: 6,
4909 cltv_expiry_delta: (6 << 4) | 0,
4910 htlc_minimum_msat: 0,
4911 htlc_maximum_msat: OptionalField::Absent,
4913 fee_proportional_millionths: 0,
4914 excess_data: Vec::new()
4916 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
4918 add_channel(&gossip_sync, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4919 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4920 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4921 short_channel_id: 5,
4924 cltv_expiry_delta: (5 << 4) | 0,
4925 htlc_minimum_msat: 0,
4926 htlc_maximum_msat: OptionalField::Absent,
4928 fee_proportional_millionths: 0,
4929 excess_data: Vec::new()
4931 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
4933 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
4934 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4935 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4936 short_channel_id: 4,
4939 cltv_expiry_delta: (4 << 4) | 0,
4940 htlc_minimum_msat: 0,
4941 htlc_maximum_msat: OptionalField::Absent,
4943 fee_proportional_millionths: 0,
4944 excess_data: Vec::new()
4946 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
4948 add_channel(&gossip_sync, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
4949 update_channel(&gossip_sync, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
4950 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4951 short_channel_id: 3,
4954 cltv_expiry_delta: (3 << 4) | 0,
4955 htlc_minimum_msat: 0,
4956 htlc_maximum_msat: OptionalField::Absent,
4958 fee_proportional_millionths: 0,
4959 excess_data: Vec::new()
4961 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
4963 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
4964 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4965 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4966 short_channel_id: 2,
4969 cltv_expiry_delta: (2 << 4) | 0,
4970 htlc_minimum_msat: 0,
4971 htlc_maximum_msat: OptionalField::Absent,
4973 fee_proportional_millionths: 0,
4974 excess_data: Vec::new()
4977 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
4978 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4979 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4980 short_channel_id: 1,
4983 cltv_expiry_delta: (1 << 4) | 0,
4984 htlc_minimum_msat: 100,
4985 htlc_maximum_msat: OptionalField::Absent,
4987 fee_proportional_millionths: 0,
4988 excess_data: Vec::new()
4990 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
4993 // Now ensure the route flows simply over nodes 1 and 4 to 6.
4994 let route = get_route(&our_id, &payment_params, &network.read_only(), None, 10_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4995 assert_eq!(route.paths.len(), 1);
4996 assert_eq!(route.paths[0].len(), 3);
4998 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
4999 assert_eq!(route.paths[0][0].short_channel_id, 6);
5000 assert_eq!(route.paths[0][0].fee_msat, 100);
5001 assert_eq!(route.paths[0][0].cltv_expiry_delta, (5 << 4) | 0);
5002 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(1));
5003 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(6));
5005 assert_eq!(route.paths[0][1].pubkey, nodes[4]);
5006 assert_eq!(route.paths[0][1].short_channel_id, 5);
5007 assert_eq!(route.paths[0][1].fee_msat, 0);
5008 assert_eq!(route.paths[0][1].cltv_expiry_delta, (1 << 4) | 0);
5009 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(4));
5010 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(5));
5012 assert_eq!(route.paths[0][2].pubkey, nodes[6]);
5013 assert_eq!(route.paths[0][2].short_channel_id, 1);
5014 assert_eq!(route.paths[0][2].fee_msat, 10_000);
5015 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
5016 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
5017 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(1));
5023 fn exact_fee_liquidity_limit() {
5024 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
5025 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
5026 // we calculated fees on a higher value, resulting in us ignoring such paths.
5027 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5028 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
5029 let scorer = test_utils::TestScorer::with_penalty(0);
5030 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5031 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5032 let payment_params = PaymentParameters::from_node_id(nodes[2]);
5034 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
5036 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5037 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5038 short_channel_id: 2,
5041 cltv_expiry_delta: 0,
5042 htlc_minimum_msat: 0,
5043 htlc_maximum_msat: OptionalField::Present(85_000),
5045 fee_proportional_millionths: 0,
5046 excess_data: Vec::new()
5049 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5050 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5051 short_channel_id: 12,
5054 cltv_expiry_delta: (4 << 4) | 1,
5055 htlc_minimum_msat: 0,
5056 htlc_maximum_msat: OptionalField::Present(270_000),
5058 fee_proportional_millionths: 1000000,
5059 excess_data: Vec::new()
5063 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
5064 // 200% fee charged channel 13 in the 1-to-2 direction.
5065 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5066 assert_eq!(route.paths.len(), 1);
5067 assert_eq!(route.paths[0].len(), 2);
5069 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
5070 assert_eq!(route.paths[0][0].short_channel_id, 12);
5071 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
5072 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
5073 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
5074 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
5076 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
5077 assert_eq!(route.paths[0][1].short_channel_id, 13);
5078 assert_eq!(route.paths[0][1].fee_msat, 90_000);
5079 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
5080 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
5081 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
5086 fn htlc_max_reduction_below_min() {
5087 // Test that if, while walking the graph, we reduce the value being sent to meet an
5088 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
5089 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
5090 // resulting in us thinking there is no possible path, even if other paths exist.
5091 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5092 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5093 let scorer = test_utils::TestScorer::with_penalty(0);
5094 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5095 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5096 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
5098 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
5099 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
5100 // then try to send 90_000.
5101 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5102 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5103 short_channel_id: 2,
5106 cltv_expiry_delta: 0,
5107 htlc_minimum_msat: 0,
5108 htlc_maximum_msat: OptionalField::Present(80_000),
5110 fee_proportional_millionths: 0,
5111 excess_data: Vec::new()
5113 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5114 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5115 short_channel_id: 4,
5118 cltv_expiry_delta: (4 << 4) | 1,
5119 htlc_minimum_msat: 90_000,
5120 htlc_maximum_msat: OptionalField::Absent,
5122 fee_proportional_millionths: 0,
5123 excess_data: Vec::new()
5127 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
5128 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
5129 // expensive) channels 12-13 path.
5130 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5131 assert_eq!(route.paths.len(), 1);
5132 assert_eq!(route.paths[0].len(), 2);
5134 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
5135 assert_eq!(route.paths[0][0].short_channel_id, 12);
5136 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
5137 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
5138 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
5139 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
5141 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
5142 assert_eq!(route.paths[0][1].short_channel_id, 13);
5143 assert_eq!(route.paths[0][1].fee_msat, 90_000);
5144 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
5145 assert_eq!(route.paths[0][1].node_features.le_flags(), InvoiceFeatures::known().le_flags());
5146 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
5151 fn multiple_direct_first_hops() {
5152 // Previously we'd only ever considered one first hop path per counterparty.
5153 // However, as we don't restrict users to one channel per peer, we really need to support
5154 // looking at all first hop paths.
5155 // Here we test that we do not ignore all-but-the-last first hop paths per counterparty (as
5156 // we used to do by overwriting the `first_hop_targets` hashmap entry) and that we can MPP
5157 // route over multiple channels with the same first hop.
5158 let secp_ctx = Secp256k1::new();
5159 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5160 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
5161 let logger = Arc::new(test_utils::TestLogger::new());
5162 let network_graph = NetworkGraph::new(genesis_hash, Arc::clone(&logger));
5163 let scorer = test_utils::TestScorer::with_penalty(0);
5164 let payment_params = PaymentParameters::from_node_id(nodes[0]).with_features(InvoiceFeatures::known());
5165 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5166 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5169 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
5170 &get_channel_details(Some(3), nodes[0], InitFeatures::known(), 200_000),
5171 &get_channel_details(Some(2), nodes[0], InitFeatures::known(), 10_000),
5172 ]), 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5173 assert_eq!(route.paths.len(), 1);
5174 assert_eq!(route.paths[0].len(), 1);
5176 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
5177 assert_eq!(route.paths[0][0].short_channel_id, 3);
5178 assert_eq!(route.paths[0][0].fee_msat, 100_000);
5181 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
5182 &get_channel_details(Some(3), nodes[0], InitFeatures::known(), 50_000),
5183 &get_channel_details(Some(2), nodes[0], InitFeatures::known(), 50_000),
5184 ]), 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5185 assert_eq!(route.paths.len(), 2);
5186 assert_eq!(route.paths[0].len(), 1);
5187 assert_eq!(route.paths[1].len(), 1);
5189 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
5190 assert_eq!(route.paths[0][0].short_channel_id, 3);
5191 assert_eq!(route.paths[0][0].fee_msat, 50_000);
5193 assert_eq!(route.paths[1][0].pubkey, nodes[0]);
5194 assert_eq!(route.paths[1][0].short_channel_id, 2);
5195 assert_eq!(route.paths[1][0].fee_msat, 50_000);
5199 // If we have a bunch of outbound channels to the same node, where most are not
5200 // sufficient to pay the full payment, but one is, we should default to just using the
5201 // one single channel that has sufficient balance, avoiding MPP.
5203 // If we have several options above the 3xpayment value threshold, we should pick the
5204 // smallest of them, avoiding further fragmenting our available outbound balance to
5206 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
5207 &get_channel_details(Some(2), nodes[0], InitFeatures::known(), 50_000),
5208 &get_channel_details(Some(3), nodes[0], InitFeatures::known(), 50_000),
5209 &get_channel_details(Some(5), nodes[0], InitFeatures::known(), 50_000),
5210 &get_channel_details(Some(6), nodes[0], InitFeatures::known(), 300_000),
5211 &get_channel_details(Some(7), nodes[0], InitFeatures::known(), 50_000),
5212 &get_channel_details(Some(8), nodes[0], InitFeatures::known(), 50_000),
5213 &get_channel_details(Some(9), nodes[0], InitFeatures::known(), 50_000),
5214 &get_channel_details(Some(4), nodes[0], InitFeatures::known(), 1_000_000),
5215 ]), 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5216 assert_eq!(route.paths.len(), 1);
5217 assert_eq!(route.paths[0].len(), 1);
5219 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
5220 assert_eq!(route.paths[0][0].short_channel_id, 6);
5221 assert_eq!(route.paths[0][0].fee_msat, 100_000);
5226 fn prefers_shorter_route_with_higher_fees() {
5227 let (secp_ctx, network_graph, _, _, logger) = build_graph();
5228 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5229 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
5231 // Without penalizing each hop 100 msats, a longer path with lower fees is chosen.
5232 let scorer = test_utils::TestScorer::with_penalty(0);
5233 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5234 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5235 let route = get_route(
5236 &our_id, &payment_params, &network_graph.read_only(), None, 100, 42,
5237 Arc::clone(&logger), &scorer, &random_seed_bytes
5239 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5241 assert_eq!(route.get_total_fees(), 100);
5242 assert_eq!(route.get_total_amount(), 100);
5243 assert_eq!(path, vec![2, 4, 6, 11, 8]);
5245 // Applying a 100 msat penalty to each hop results in taking channels 7 and 10 to nodes[6]
5246 // from nodes[2] rather than channel 6, 11, and 8, even though the longer path is cheaper.
5247 let scorer = test_utils::TestScorer::with_penalty(100);
5248 let route = get_route(
5249 &our_id, &payment_params, &network_graph.read_only(), None, 100, 42,
5250 Arc::clone(&logger), &scorer, &random_seed_bytes
5252 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5254 assert_eq!(route.get_total_fees(), 300);
5255 assert_eq!(route.get_total_amount(), 100);
5256 assert_eq!(path, vec![2, 4, 7, 10]);
5259 struct BadChannelScorer {
5260 short_channel_id: u64,
5264 impl Writeable for BadChannelScorer {
5265 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), ::io::Error> { unimplemented!() }
5267 impl Score for BadChannelScorer {
5268 fn channel_penalty_msat(&self, short_channel_id: u64, _: &NodeId, _: &NodeId, _: ChannelUsage) -> u64 {
5269 if short_channel_id == self.short_channel_id { u64::max_value() } else { 0 }
5272 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
5273 fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
5276 struct BadNodeScorer {
5281 impl Writeable for BadNodeScorer {
5282 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), ::io::Error> { unimplemented!() }
5285 impl Score for BadNodeScorer {
5286 fn channel_penalty_msat(&self, _: u64, _: &NodeId, target: &NodeId, _: ChannelUsage) -> u64 {
5287 if *target == self.node_id { u64::max_value() } else { 0 }
5290 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
5291 fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
5295 fn avoids_routing_through_bad_channels_and_nodes() {
5296 let (secp_ctx, network, _, _, logger) = build_graph();
5297 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5298 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
5299 let network_graph = network.read_only();
5301 // A path to nodes[6] exists when no penalties are applied to any channel.
5302 let scorer = test_utils::TestScorer::with_penalty(0);
5303 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5304 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5305 let route = get_route(
5306 &our_id, &payment_params, &network_graph, None, 100, 42,
5307 Arc::clone(&logger), &scorer, &random_seed_bytes
5309 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5311 assert_eq!(route.get_total_fees(), 100);
5312 assert_eq!(route.get_total_amount(), 100);
5313 assert_eq!(path, vec![2, 4, 6, 11, 8]);
5315 // A different path to nodes[6] exists if channel 6 cannot be routed over.
5316 let scorer = BadChannelScorer { short_channel_id: 6 };
5317 let route = get_route(
5318 &our_id, &payment_params, &network_graph, None, 100, 42,
5319 Arc::clone(&logger), &scorer, &random_seed_bytes
5321 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5323 assert_eq!(route.get_total_fees(), 300);
5324 assert_eq!(route.get_total_amount(), 100);
5325 assert_eq!(path, vec![2, 4, 7, 10]);
5327 // A path to nodes[6] does not exist if nodes[2] cannot be routed through.
5328 let scorer = BadNodeScorer { node_id: NodeId::from_pubkey(&nodes[2]) };
5330 &our_id, &payment_params, &network_graph, None, 100, 42,
5331 Arc::clone(&logger), &scorer, &random_seed_bytes
5333 Err(LightningError { err, .. } ) => {
5334 assert_eq!(err, "Failed to find a path to the given destination");
5336 Ok(_) => panic!("Expected error"),
5341 fn total_fees_single_path() {
5345 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5346 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5347 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5350 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5351 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5352 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5355 pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
5356 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5357 short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0
5360 payment_params: None,
5363 assert_eq!(route.get_total_fees(), 250);
5364 assert_eq!(route.get_total_amount(), 225);
5368 fn total_fees_multi_path() {
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
5383 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5384 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5385 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5388 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5389 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5390 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5393 payment_params: None,
5396 assert_eq!(route.get_total_fees(), 200);
5397 assert_eq!(route.get_total_amount(), 300);
5401 fn total_empty_route_no_panic() {
5402 // In an earlier version of `Route::get_total_fees` and `Route::get_total_amount`, they
5403 // would both panic if the route was completely empty. We test to ensure they return 0
5404 // here, even though its somewhat nonsensical as a route.
5405 let route = Route { paths: Vec::new(), payment_params: None };
5407 assert_eq!(route.get_total_fees(), 0);
5408 assert_eq!(route.get_total_amount(), 0);
5412 fn limits_total_cltv_delta() {
5413 let (secp_ctx, network, _, _, logger) = build_graph();
5414 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5415 let network_graph = network.read_only();
5417 let scorer = test_utils::TestScorer::with_penalty(0);
5419 // Make sure that generally there is at least one route available
5420 let feasible_max_total_cltv_delta = 1008;
5421 let feasible_payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes))
5422 .with_max_total_cltv_expiry_delta(feasible_max_total_cltv_delta);
5423 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5424 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5425 let route = get_route(&our_id, &feasible_payment_params, &network_graph, None, 100, 0, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5426 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5427 assert_ne!(path.len(), 0);
5429 // But not if we exclude all paths on the basis of their accumulated CLTV delta
5430 let fail_max_total_cltv_delta = 23;
5431 let fail_payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes))
5432 .with_max_total_cltv_expiry_delta(fail_max_total_cltv_delta);
5433 match get_route(&our_id, &fail_payment_params, &network_graph, None, 100, 0, Arc::clone(&logger), &scorer, &random_seed_bytes)
5435 Err(LightningError { err, .. } ) => {
5436 assert_eq!(err, "Failed to find a path to the given destination");
5438 Ok(_) => panic!("Expected error"),
5443 fn limits_path_length() {
5444 let (secp_ctx, network, _, _, logger) = build_line_graph();
5445 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5446 let network_graph = network.read_only();
5448 let scorer = test_utils::TestScorer::with_penalty(0);
5449 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5450 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5452 // First check we can actually create a long route on this graph.
5453 let feasible_payment_params = PaymentParameters::from_node_id(nodes[18]);
5454 let route = get_route(&our_id, &feasible_payment_params, &network_graph, None, 100, 0,
5455 Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5456 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5457 assert!(path.len() == MAX_PATH_LENGTH_ESTIMATE.into());
5459 // But we can't create a path surpassing the MAX_PATH_LENGTH_ESTIMATE limit.
5460 let fail_payment_params = PaymentParameters::from_node_id(nodes[19]);
5461 match get_route(&our_id, &fail_payment_params, &network_graph, None, 100, 0,
5462 Arc::clone(&logger), &scorer, &random_seed_bytes)
5464 Err(LightningError { err, .. } ) => {
5465 assert_eq!(err, "Failed to find a path to the given destination");
5467 Ok(_) => panic!("Expected error"),
5472 fn adds_and_limits_cltv_offset() {
5473 let (secp_ctx, network_graph, _, _, logger) = build_graph();
5474 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5476 let scorer = test_utils::TestScorer::with_penalty(0);
5478 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
5479 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5480 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5481 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5482 assert_eq!(route.paths.len(), 1);
5484 let cltv_expiry_deltas_before = route.paths[0].iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5486 // Check whether the offset added to the last hop by default is in [1 .. DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA]
5487 let mut route_default = route.clone();
5488 add_random_cltv_offset(&mut route_default, &payment_params, &network_graph.read_only(), &random_seed_bytes);
5489 let cltv_expiry_deltas_default = route_default.paths[0].iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5490 assert_eq!(cltv_expiry_deltas_before.split_last().unwrap().1, cltv_expiry_deltas_default.split_last().unwrap().1);
5491 assert!(cltv_expiry_deltas_default.last() > cltv_expiry_deltas_before.last());
5492 assert!(cltv_expiry_deltas_default.last().unwrap() <= &DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA);
5494 // Check that no offset is added when we restrict the max_total_cltv_expiry_delta
5495 let mut route_limited = route.clone();
5496 let limited_max_total_cltv_expiry_delta = cltv_expiry_deltas_before.iter().sum();
5497 let limited_payment_params = payment_params.with_max_total_cltv_expiry_delta(limited_max_total_cltv_expiry_delta);
5498 add_random_cltv_offset(&mut route_limited, &limited_payment_params, &network_graph.read_only(), &random_seed_bytes);
5499 let cltv_expiry_deltas_limited = route_limited.paths[0].iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5500 assert_eq!(cltv_expiry_deltas_before, cltv_expiry_deltas_limited);
5504 fn adds_plausible_cltv_offset() {
5505 let (secp_ctx, network, _, _, logger) = build_graph();
5506 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5507 let network_graph = network.read_only();
5508 let network_nodes = network_graph.nodes();
5509 let network_channels = network_graph.channels();
5510 let scorer = test_utils::TestScorer::with_penalty(0);
5511 let payment_params = PaymentParameters::from_node_id(nodes[3]);
5512 let keys_manager = test_utils::TestKeysInterface::new(&[4u8; 32], Network::Testnet);
5513 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5515 let mut route = get_route(&our_id, &payment_params, &network_graph, None, 100, 0,
5516 Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5517 add_random_cltv_offset(&mut route, &payment_params, &network_graph, &random_seed_bytes);
5519 let mut path_plausibility = vec![];
5521 for p in route.paths {
5522 // 1. Select random observation point
5523 let mut prng = ChaCha20::new(&random_seed_bytes, &[0u8; 12]);
5524 let mut random_bytes = [0u8; ::core::mem::size_of::<usize>()];
5526 prng.process_in_place(&mut random_bytes);
5527 let random_path_index = usize::from_be_bytes(random_bytes).wrapping_rem(p.len());
5528 let observation_point = NodeId::from_pubkey(&p.get(random_path_index).unwrap().pubkey);
5530 // 2. Calculate what CLTV expiry delta we would observe there
5531 let observed_cltv_expiry_delta: u32 = p[random_path_index..].iter().map(|h| h.cltv_expiry_delta).sum();
5533 // 3. Starting from the observation point, find candidate paths
5534 let mut candidates: VecDeque<(NodeId, Vec<u32>)> = VecDeque::new();
5535 candidates.push_back((observation_point, vec![]));
5537 let mut found_plausible_candidate = false;
5539 'candidate_loop: while let Some((cur_node_id, cur_path_cltv_deltas)) = candidates.pop_front() {
5540 if let Some(remaining) = observed_cltv_expiry_delta.checked_sub(cur_path_cltv_deltas.iter().sum::<u32>()) {
5541 if remaining == 0 || remaining.wrapping_rem(40) == 0 || remaining.wrapping_rem(144) == 0 {
5542 found_plausible_candidate = true;
5543 break 'candidate_loop;
5547 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
5548 for channel_id in &cur_node.channels {
5549 if let Some(channel_info) = network_channels.get(&channel_id) {
5550 if let Some((dir_info, next_id)) = channel_info.as_directed_from(&cur_node_id) {
5551 if let Some(channel_update_info) = dir_info.direction() {
5552 let next_cltv_expiry_delta = channel_update_info.cltv_expiry_delta as u32;
5553 if cur_path_cltv_deltas.iter().sum::<u32>()
5554 .saturating_add(next_cltv_expiry_delta) <= observed_cltv_expiry_delta {
5555 let mut new_path_cltv_deltas = cur_path_cltv_deltas.clone();
5556 new_path_cltv_deltas.push(next_cltv_expiry_delta);
5557 candidates.push_back((*next_id, new_path_cltv_deltas));
5566 path_plausibility.push(found_plausible_candidate);
5568 assert!(path_plausibility.iter().all(|x| *x));
5572 fn builds_correct_path_from_hops() {
5573 let (secp_ctx, network, _, _, logger) = build_graph();
5574 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5575 let network_graph = network.read_only();
5577 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5578 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5580 let payment_params = PaymentParameters::from_node_id(nodes[3]);
5581 let hops = [nodes[1], nodes[2], nodes[4], nodes[3]];
5582 let route = build_route_from_hops_internal(&our_id, &hops, &payment_params,
5583 &network_graph, 100, 0, Arc::clone(&logger), &random_seed_bytes).unwrap();
5584 let route_hop_pubkeys = route.paths[0].iter().map(|hop| hop.pubkey).collect::<Vec<_>>();
5585 assert_eq!(hops.len(), route.paths[0].len());
5586 for (idx, hop_pubkey) in hops.iter().enumerate() {
5587 assert!(*hop_pubkey == route_hop_pubkeys[idx]);
5591 #[cfg(not(feature = "no-std"))]
5592 pub(super) fn random_init_seed() -> u64 {
5593 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
5594 use core::hash::{BuildHasher, Hasher};
5595 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
5596 println!("Using seed of {}", seed);
5599 #[cfg(not(feature = "no-std"))]
5600 use util::ser::ReadableArgs;
5603 #[cfg(not(feature = "no-std"))]
5604 fn generate_routes() {
5605 use routing::scoring::{ProbabilisticScorer, ProbabilisticScoringParameters};
5607 let mut d = match super::test_utils::get_route_file() {
5614 let logger = test_utils::TestLogger::new();
5615 let graph = NetworkGraph::read(&mut d, &logger).unwrap();
5616 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5617 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5619 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
5620 let mut seed = random_init_seed() as usize;
5621 let nodes = graph.read_only().nodes().clone();
5622 'load_endpoints: for _ in 0..10 {
5624 seed = seed.overflowing_mul(0xdeadbeef).0;
5625 let src = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5626 seed = seed.overflowing_mul(0xdeadbeef).0;
5627 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5628 let payment_params = PaymentParameters::from_node_id(dst);
5629 let amt = seed as u64 % 200_000_000;
5630 let params = ProbabilisticScoringParameters::default();
5631 let scorer = ProbabilisticScorer::new(params, &graph, &logger);
5632 if get_route(src, &payment_params, &graph.read_only(), None, amt, 42, &logger, &scorer, &random_seed_bytes).is_ok() {
5633 continue 'load_endpoints;
5640 #[cfg(not(feature = "no-std"))]
5641 fn generate_routes_mpp() {
5642 use routing::scoring::{ProbabilisticScorer, ProbabilisticScoringParameters};
5644 let mut d = match super::test_utils::get_route_file() {
5651 let logger = test_utils::TestLogger::new();
5652 let graph = NetworkGraph::read(&mut d, &logger).unwrap();
5653 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5654 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5656 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
5657 let mut seed = random_init_seed() as usize;
5658 let nodes = graph.read_only().nodes().clone();
5659 'load_endpoints: for _ in 0..10 {
5661 seed = seed.overflowing_mul(0xdeadbeef).0;
5662 let src = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5663 seed = seed.overflowing_mul(0xdeadbeef).0;
5664 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5665 let payment_params = PaymentParameters::from_node_id(dst).with_features(InvoiceFeatures::known());
5666 let amt = seed as u64 % 200_000_000;
5667 let params = ProbabilisticScoringParameters::default();
5668 let scorer = ProbabilisticScorer::new(params, &graph, &logger);
5669 if get_route(src, &payment_params, &graph.read_only(), None, amt, 42, &logger, &scorer, &random_seed_bytes).is_ok() {
5670 continue 'load_endpoints;
5677 #[cfg(all(test, not(feature = "no-std")))]
5678 pub(crate) mod test_utils {
5680 /// Tries to open a network graph file, or panics with a URL to fetch it.
5681 pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
5682 let res = File::open("net_graph-2021-05-31.bin") // By default we're run in RL/lightning
5683 .or_else(|_| File::open("lightning/net_graph-2021-05-31.bin")) // We may be run manually in RL/
5684 .or_else(|_| { // Fall back to guessing based on the binary location
5685 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
5686 let mut path = std::env::current_exe().unwrap();
5687 path.pop(); // lightning-...
5689 path.pop(); // debug
5690 path.pop(); // target
5691 path.push("lightning");
5692 path.push("net_graph-2021-05-31.bin");
5693 eprintln!("{}", path.to_str().unwrap());
5696 .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");
5697 #[cfg(require_route_graph_test)]
5698 return Ok(res.unwrap());
5699 #[cfg(not(require_route_graph_test))]
5704 #[cfg(all(test, feature = "_bench_unstable", not(feature = "no-std")))]
5707 use bitcoin::hashes::Hash;
5708 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
5709 use chain::transaction::OutPoint;
5710 use chain::keysinterface::{KeysManager,KeysInterface};
5711 use ln::channelmanager::{ChannelCounterparty, ChannelDetails};
5712 use ln::features::{InitFeatures, InvoiceFeatures};
5713 use routing::gossip::NetworkGraph;
5714 use routing::scoring::{FixedPenaltyScorer, ProbabilisticScorer, ProbabilisticScoringParameters};
5715 use util::logger::{Logger, Record};
5716 use util::ser::ReadableArgs;
5720 struct DummyLogger {}
5721 impl Logger for DummyLogger {
5722 fn log(&self, _record: &Record) {}
5725 fn read_network_graph(logger: &DummyLogger) -> NetworkGraph<&DummyLogger> {
5726 let mut d = test_utils::get_route_file().unwrap();
5727 NetworkGraph::read(&mut d, logger).unwrap()
5730 fn payer_pubkey() -> PublicKey {
5731 let secp_ctx = Secp256k1::new();
5732 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
5736 fn first_hop(node_id: PublicKey) -> ChannelDetails {
5738 channel_id: [0; 32],
5739 counterparty: ChannelCounterparty {
5740 features: InitFeatures::known(),
5742 unspendable_punishment_reserve: 0,
5743 forwarding_info: None,
5744 outbound_htlc_minimum_msat: None,
5745 outbound_htlc_maximum_msat: None,
5747 funding_txo: Some(OutPoint {
5748 txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0
5751 short_channel_id: Some(1),
5752 inbound_scid_alias: None,
5753 outbound_scid_alias: None,
5754 channel_value_satoshis: 10_000_000,
5756 balance_msat: 10_000_000,
5757 outbound_capacity_msat: 10_000_000,
5758 next_outbound_htlc_limit_msat: 10_000_000,
5759 inbound_capacity_msat: 0,
5760 unspendable_punishment_reserve: None,
5761 confirmations_required: None,
5762 force_close_spend_delay: None,
5764 is_channel_ready: true,
5767 inbound_htlc_minimum_msat: None,
5768 inbound_htlc_maximum_msat: None,
5773 fn generate_routes_with_zero_penalty_scorer(bench: &mut Bencher) {
5774 let logger = DummyLogger {};
5775 let network_graph = read_network_graph(&logger);
5776 let scorer = FixedPenaltyScorer::with_penalty(0);
5777 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::empty());
5781 fn generate_mpp_routes_with_zero_penalty_scorer(bench: &mut Bencher) {
5782 let logger = DummyLogger {};
5783 let network_graph = read_network_graph(&logger);
5784 let scorer = FixedPenaltyScorer::with_penalty(0);
5785 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::known());
5789 fn generate_routes_with_probabilistic_scorer(bench: &mut Bencher) {
5790 let logger = DummyLogger {};
5791 let network_graph = read_network_graph(&logger);
5792 let params = ProbabilisticScoringParameters::default();
5793 let scorer = ProbabilisticScorer::new(params, &network_graph, &logger);
5794 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::empty());
5798 fn generate_mpp_routes_with_probabilistic_scorer(bench: &mut Bencher) {
5799 let logger = DummyLogger {};
5800 let network_graph = read_network_graph(&logger);
5801 let params = ProbabilisticScoringParameters::default();
5802 let scorer = ProbabilisticScorer::new(params, &network_graph, &logger);
5803 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::known());
5806 fn generate_routes<S: Score>(
5807 bench: &mut Bencher, graph: &NetworkGraph<&DummyLogger>, mut scorer: S,
5808 features: InvoiceFeatures
5810 let nodes = graph.read_only().nodes().clone();
5811 let payer = payer_pubkey();
5812 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
5813 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5815 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
5816 let mut routes = Vec::new();
5817 let mut route_endpoints = Vec::new();
5818 let mut seed: usize = 0xdeadbeef;
5819 'load_endpoints: for _ in 0..150 {
5822 let src = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5824 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5825 let params = PaymentParameters::from_node_id(dst).with_features(features.clone());
5826 let first_hop = first_hop(src);
5827 let amt = seed as u64 % 1_000_000;
5828 if let Ok(route) = get_route(&payer, ¶ms, &graph.read_only(), Some(&[&first_hop]), amt, 42, &DummyLogger{}, &scorer, &random_seed_bytes) {
5830 route_endpoints.push((first_hop, params, amt));
5831 continue 'load_endpoints;
5836 // ...and seed the scorer with success and failure data...
5837 for route in routes {
5838 let amount = route.get_total_amount();
5839 if amount < 250_000 {
5840 for path in route.paths {
5841 scorer.payment_path_successful(&path.iter().collect::<Vec<_>>());
5843 } else if amount > 750_000 {
5844 for path in route.paths {
5845 let short_channel_id = path[path.len() / 2].short_channel_id;
5846 scorer.payment_path_failed(&path.iter().collect::<Vec<_>>(), short_channel_id);
5851 // Because we've changed channel scores, its possible we'll take different routes to the
5852 // selected destinations, possibly causing us to fail because, eg, the newly-selected path
5853 // requires a too-high CLTV delta.
5854 route_endpoints.retain(|(first_hop, params, amt)| {
5855 get_route(&payer, params, &graph.read_only(), Some(&[first_hop]), *amt, 42, &DummyLogger{}, &scorer, &random_seed_bytes).is_ok()
5857 route_endpoints.truncate(100);
5858 assert_eq!(route_endpoints.len(), 100);
5860 // ...then benchmark finding paths between the nodes we learned.
5863 let (first_hop, params, amt) = &route_endpoints[idx % route_endpoints.len()];
5864 assert!(get_route(&payer, params, &graph.read_only(), Some(&[first_hop]), *amt, 42, &DummyLogger{}, &scorer, &random_seed_bytes).is_ok());