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 /// Maximum number of paths we allow an (MPP) payment to have.
180 // The default limit is currently set rather arbitrary - there aren't any real fundamental path-count
181 // limits, but for now more than 10 paths likely carries too much one-path failure.
182 pub const DEFAULT_MAX_PATH_COUNT: u8 = 10;
184 // The median hop CLTV expiry delta currently seen in the network.
185 const MEDIAN_HOP_CLTV_EXPIRY_DELTA: u32 = 40;
187 // During routing, we only consider paths shorter than our maximum length estimate.
188 // In the legacy onion format, the maximum number of hops used to be a fixed value of 20.
189 // However, in the TLV onion format, there is no fixed maximum length, but the `hop_payloads`
190 // field is always 1300 bytes. As the `tlv_payload` for each hop may vary in length, we have to
191 // estimate how many hops the route may have so that it actually fits the `hop_payloads` field.
193 // We estimate 3+32 (payload length and HMAC) + 2+8 (amt_to_forward) + 2+4 (outgoing_cltv_value) +
194 // 2+8 (short_channel_id) = 61 bytes for each intermediate hop and 3+32
195 // (payload length and HMAC) + 2+8 (amt_to_forward) + 2+4 (outgoing_cltv_value) + 2+32+8
196 // (payment_secret and total_msat) = 93 bytes for the final hop.
197 // Since the length of the potentially included `payment_metadata` is unknown to us, we round
198 // down from (1300-93) / 61 = 19.78... to arrive at a conservative estimate of 19.
199 const MAX_PATH_LENGTH_ESTIMATE: u8 = 19;
201 /// The recipient of a payment.
202 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
203 pub struct PaymentParameters {
204 /// The node id of the payee.
205 pub payee_pubkey: PublicKey,
207 /// Features supported by the payee.
209 /// May be set from the payee's invoice or via [`for_keysend`]. May be `None` if the invoice
210 /// does not contain any features.
212 /// [`for_keysend`]: Self::for_keysend
213 pub features: Option<InvoiceFeatures>,
215 /// Hints for routing to the payee, containing channels connecting the payee to public nodes.
216 pub route_hints: Vec<RouteHint>,
218 /// Expiration of a payment to the payee, in seconds relative to the UNIX epoch.
219 pub expiry_time: Option<u64>,
221 /// The maximum total CLTV delta we accept for the route.
222 /// Defaults to [`DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA`].
223 pub max_total_cltv_expiry_delta: u32,
225 /// The maximum number of paths that may be used by (MPP) payments.
226 /// Defaults to [`DEFAULT_MAX_PATH_COUNT`].
227 pub max_path_count: u8,
229 /// Selects the maximum share of a channel's total capacity which will be sent over a channel,
230 /// as a power of 1/2. A higher value prefers to send the payment using more MPP parts whereas
231 /// a lower value prefers to send larger MPP parts, potentially saturating channels and
232 /// increasing failure probability for those paths.
234 /// A value of 0 will allow payments up to and including a channel's total announced usable
235 /// capacity, a value of one will only use up to half its capacity, two 1/4, etc.
238 pub max_channel_saturation_power_of_half: u8,
241 impl_writeable_tlv_based!(PaymentParameters, {
242 (0, payee_pubkey, required),
243 (1, max_total_cltv_expiry_delta, (default_value, DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA)),
244 (2, features, option),
245 (3, max_path_count, (default_value, DEFAULT_MAX_PATH_COUNT)),
246 (4, route_hints, vec_type),
247 (5, max_channel_saturation_power_of_half, (default_value, 1)),
248 (6, expiry_time, option),
251 impl PaymentParameters {
252 /// Creates a payee with the node id of the given `pubkey`.
253 pub fn from_node_id(payee_pubkey: PublicKey) -> Self {
259 max_total_cltv_expiry_delta: DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA,
260 max_path_count: DEFAULT_MAX_PATH_COUNT,
261 #[cfg(test)] // Many tests were written prior to the introduction of this parameter, so
262 // we leave it as 0 by default in tests, and change it for a few.
263 max_channel_saturation_power_of_half: 0,
265 max_channel_saturation_power_of_half: 1,
269 /// Creates a payee with the node id of the given `pubkey` to use for keysend payments.
270 pub fn for_keysend(payee_pubkey: PublicKey) -> Self {
271 Self::from_node_id(payee_pubkey).with_features(InvoiceFeatures::for_keysend())
274 /// Includes the payee's features.
276 /// (C-not exported) since bindings don't support move semantics
277 pub fn with_features(self, features: InvoiceFeatures) -> Self {
278 Self { features: Some(features), ..self }
281 /// Includes hints for routing to the payee.
283 /// (C-not exported) since bindings don't support move semantics
284 pub fn with_route_hints(self, route_hints: Vec<RouteHint>) -> Self {
285 Self { route_hints, ..self }
288 /// Includes a payment expiration in seconds relative to the UNIX epoch.
290 /// (C-not exported) since bindings don't support move semantics
291 pub fn with_expiry_time(self, expiry_time: u64) -> Self {
292 Self { expiry_time: Some(expiry_time), ..self }
295 /// Includes a limit for the total CLTV expiry delta which is considered during routing
297 /// (C-not exported) since bindings don't support move semantics
298 pub fn with_max_total_cltv_expiry_delta(self, max_total_cltv_expiry_delta: u32) -> Self {
299 Self { max_total_cltv_expiry_delta, ..self }
302 /// Includes a limit for the maximum number of payment paths that may be used.
304 /// (C-not exported) since bindings don't support move semantics
305 pub fn with_max_path_count(self, max_path_count: u8) -> Self {
306 Self { max_path_count, ..self }
310 /// A list of hops along a payment path terminating with a channel to the recipient.
311 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
312 pub struct RouteHint(pub Vec<RouteHintHop>);
314 impl Writeable for RouteHint {
315 fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
316 (self.0.len() as u64).write(writer)?;
317 for hop in self.0.iter() {
324 impl Readable for RouteHint {
325 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
326 let hop_count: u64 = Readable::read(reader)?;
327 let mut hops = Vec::with_capacity(cmp::min(hop_count, 16) as usize);
328 for _ in 0..hop_count {
329 hops.push(Readable::read(reader)?);
335 /// A channel descriptor for a hop along a payment path.
336 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
337 pub struct RouteHintHop {
338 /// The node_id of the non-target end of the route
339 pub src_node_id: PublicKey,
340 /// The short_channel_id of this channel
341 pub short_channel_id: u64,
342 /// The fees which must be paid to use this channel
343 pub fees: RoutingFees,
344 /// The difference in CLTV values between this node and the next node.
345 pub cltv_expiry_delta: u16,
346 /// The minimum value, in msat, which must be relayed to the next hop.
347 pub htlc_minimum_msat: Option<u64>,
348 /// The maximum value in msat available for routing with a single HTLC.
349 pub htlc_maximum_msat: Option<u64>,
352 impl_writeable_tlv_based!(RouteHintHop, {
353 (0, src_node_id, required),
354 (1, htlc_minimum_msat, option),
355 (2, short_channel_id, required),
356 (3, htlc_maximum_msat, option),
358 (6, cltv_expiry_delta, required),
361 #[derive(Eq, PartialEq)]
362 struct RouteGraphNode {
364 lowest_fee_to_peer_through_node: u64,
365 lowest_fee_to_node: u64,
366 total_cltv_delta: u32,
367 // The maximum value a yet-to-be-constructed payment path might flow through this node.
368 // This value is upper-bounded by us by:
369 // - how much is needed for a path being constructed
370 // - how much value can channels following this node (up to the destination) can contribute,
371 // considering their capacity and fees
372 value_contribution_msat: u64,
373 /// The effective htlc_minimum_msat at this hop. If a later hop on the path had a higher HTLC
374 /// minimum, we use it, plus the fees required at each earlier hop to meet it.
375 path_htlc_minimum_msat: u64,
376 /// All penalties incurred from this hop on the way to the destination, as calculated using
378 path_penalty_msat: u64,
379 /// The number of hops walked up to this node.
380 path_length_to_node: u8,
383 impl cmp::Ord for RouteGraphNode {
384 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
385 let other_score = cmp::max(other.lowest_fee_to_peer_through_node, other.path_htlc_minimum_msat)
386 .saturating_add(other.path_penalty_msat);
387 let self_score = cmp::max(self.lowest_fee_to_peer_through_node, self.path_htlc_minimum_msat)
388 .saturating_add(self.path_penalty_msat);
389 other_score.cmp(&self_score).then_with(|| other.node_id.cmp(&self.node_id))
393 impl cmp::PartialOrd for RouteGraphNode {
394 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
395 Some(self.cmp(other))
399 /// A wrapper around the various hop representations.
401 /// Used to construct a [`PathBuildingHop`] and to estimate [`EffectiveCapacity`].
402 #[derive(Clone, Debug)]
403 enum CandidateRouteHop<'a> {
404 /// A hop from the payer, where the outbound liquidity is known.
406 details: &'a ChannelDetails,
408 /// A hop found in the [`ReadOnlyNetworkGraph`], where the channel capacity may be unknown.
410 info: DirectedChannelInfoWithUpdate<'a>,
411 short_channel_id: u64,
413 /// A hop to the payee found in the payment invoice, though not necessarily a direct channel.
415 hint: &'a RouteHintHop,
419 impl<'a> CandidateRouteHop<'a> {
420 fn short_channel_id(&self) -> u64 {
422 CandidateRouteHop::FirstHop { details } => details.get_outbound_payment_scid().unwrap(),
423 CandidateRouteHop::PublicHop { short_channel_id, .. } => *short_channel_id,
424 CandidateRouteHop::PrivateHop { hint } => hint.short_channel_id,
428 // NOTE: This may alloc memory so avoid calling it in a hot code path.
429 fn features(&self) -> ChannelFeatures {
431 CandidateRouteHop::FirstHop { details } => details.counterparty.features.to_context(),
432 CandidateRouteHop::PublicHop { info, .. } => info.channel().features.clone(),
433 CandidateRouteHop::PrivateHop { .. } => ChannelFeatures::empty(),
437 fn cltv_expiry_delta(&self) -> u32 {
439 CandidateRouteHop::FirstHop { .. } => 0,
440 CandidateRouteHop::PublicHop { info, .. } => info.direction().cltv_expiry_delta as u32,
441 CandidateRouteHop::PrivateHop { hint } => hint.cltv_expiry_delta as u32,
445 fn htlc_minimum_msat(&self) -> u64 {
447 CandidateRouteHop::FirstHop { .. } => 0,
448 CandidateRouteHop::PublicHop { info, .. } => info.direction().htlc_minimum_msat,
449 CandidateRouteHop::PrivateHop { hint } => hint.htlc_minimum_msat.unwrap_or(0),
453 fn fees(&self) -> RoutingFees {
455 CandidateRouteHop::FirstHop { .. } => RoutingFees {
456 base_msat: 0, proportional_millionths: 0,
458 CandidateRouteHop::PublicHop { info, .. } => info.direction().fees,
459 CandidateRouteHop::PrivateHop { hint } => hint.fees,
463 fn effective_capacity(&self) -> EffectiveCapacity {
465 CandidateRouteHop::FirstHop { details } => EffectiveCapacity::ExactLiquidity {
466 liquidity_msat: details.next_outbound_htlc_limit_msat,
468 CandidateRouteHop::PublicHop { info, .. } => info.effective_capacity(),
469 CandidateRouteHop::PrivateHop { .. } => EffectiveCapacity::Infinite,
475 fn max_htlc_from_capacity(capacity: EffectiveCapacity, max_channel_saturation_power_of_half: u8) -> u64 {
476 let saturation_shift: u32 = max_channel_saturation_power_of_half as u32;
478 EffectiveCapacity::ExactLiquidity { liquidity_msat } => liquidity_msat,
479 EffectiveCapacity::Infinite => u64::max_value(),
480 EffectiveCapacity::Unknown => EffectiveCapacity::Unknown.as_msat(),
481 EffectiveCapacity::MaximumHTLC { amount_msat } =>
482 amount_msat.checked_shr(saturation_shift).unwrap_or(0),
483 EffectiveCapacity::Total { capacity_msat, htlc_maximum_msat: None } =>
484 capacity_msat.checked_shr(saturation_shift).unwrap_or(0),
485 EffectiveCapacity::Total { capacity_msat, htlc_maximum_msat: Some(htlc_max) } =>
486 cmp::min(capacity_msat.checked_shr(saturation_shift).unwrap_or(0), htlc_max),
490 /// It's useful to keep track of the hops associated with the fees required to use them,
491 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
492 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
493 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
495 struct PathBuildingHop<'a> {
496 // Note that this should be dropped in favor of loading it from CandidateRouteHop, but doing so
497 // is a larger refactor and will require careful performance analysis.
499 candidate: CandidateRouteHop<'a>,
502 /// Minimal fees required to route to the source node of the current hop via any of its inbound channels.
503 src_lowest_inbound_fees: RoutingFees,
504 /// All the fees paid *after* this channel on the way to the destination
505 next_hops_fee_msat: u64,
506 /// Fee paid for the use of the current channel (see candidate.fees()).
507 /// The value will be actually deducted from the counterparty balance on the previous link.
508 hop_use_fee_msat: u64,
509 /// Used to compare channels when choosing the for routing.
510 /// Includes paying for the use of a hop and the following hops, as well as
511 /// an estimated cost of reaching this hop.
512 /// Might get stale when fees are recomputed. Primarily for internal use.
514 /// A mirror of the same field in RouteGraphNode. Note that this is only used during the graph
515 /// walk and may be invalid thereafter.
516 path_htlc_minimum_msat: u64,
517 /// All penalties incurred from this channel on the way to the destination, as calculated using
519 path_penalty_msat: u64,
520 /// If we've already processed a node as the best node, we shouldn't process it again. Normally
521 /// we'd just ignore it if we did as all channels would have a higher new fee, but because we
522 /// may decrease the amounts in use as we walk the graph, the actual calculated fee may
523 /// decrease as well. Thus, we have to explicitly track which nodes have been processed and
524 /// avoid processing them again.
526 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
527 // In tests, we apply further sanity checks on cases where we skip nodes we already processed
528 // to ensure it is specifically in cases where the fee has gone down because of a decrease in
529 // value_contribution_msat, which requires tracking it here. See comments below where it is
530 // used for more info.
531 value_contribution_msat: u64,
534 impl<'a> core::fmt::Debug for PathBuildingHop<'a> {
535 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
536 let mut debug_struct = f.debug_struct("PathBuildingHop");
538 .field("node_id", &self.node_id)
539 .field("short_channel_id", &self.candidate.short_channel_id())
540 .field("total_fee_msat", &self.total_fee_msat)
541 .field("next_hops_fee_msat", &self.next_hops_fee_msat)
542 .field("hop_use_fee_msat", &self.hop_use_fee_msat)
543 .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)))
544 .field("path_penalty_msat", &self.path_penalty_msat)
545 .field("path_htlc_minimum_msat", &self.path_htlc_minimum_msat)
546 .field("cltv_expiry_delta", &self.candidate.cltv_expiry_delta());
547 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
548 let debug_struct = debug_struct
549 .field("value_contribution_msat", &self.value_contribution_msat);
550 debug_struct.finish()
554 // Instantiated with a list of hops with correct data in them collected during path finding,
555 // an instance of this struct should be further modified only via given methods.
557 struct PaymentPath<'a> {
558 hops: Vec<(PathBuildingHop<'a>, NodeFeatures)>,
561 impl<'a> PaymentPath<'a> {
562 // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
563 fn get_value_msat(&self) -> u64 {
564 self.hops.last().unwrap().0.fee_msat
567 fn get_path_penalty_msat(&self) -> u64 {
568 self.hops.first().map(|h| h.0.path_penalty_msat).unwrap_or(u64::max_value())
571 fn get_total_fee_paid_msat(&self) -> u64 {
572 if self.hops.len() < 1 {
576 // Can't use next_hops_fee_msat because it gets outdated.
577 for (i, (hop, _)) in self.hops.iter().enumerate() {
578 if i != self.hops.len() - 1 {
579 result += hop.fee_msat;
585 fn get_cost_msat(&self) -> u64 {
586 self.get_total_fee_paid_msat().saturating_add(self.get_path_penalty_msat())
589 // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
590 // to change fees may result in an inconsistency.
592 // Sometimes we call this function right after constructing a path which is inconsistent in
593 // that it the value being transferred has decreased while we were doing path finding, leading
594 // to the fees being paid not lining up with the actual limits.
596 // Note that this function is not aware of the available_liquidity limit, and thus does not
597 // support increasing the value being transferred.
598 fn update_value_and_recompute_fees(&mut self, value_msat: u64) {
599 assert!(value_msat <= self.hops.last().unwrap().0.fee_msat);
601 let mut total_fee_paid_msat = 0 as u64;
602 for i in (0..self.hops.len()).rev() {
603 let last_hop = i == self.hops.len() - 1;
605 // For non-last-hop, this value will represent the fees paid on the current hop. It
606 // will consist of the fees for the use of the next hop, and extra fees to match
607 // htlc_minimum_msat of the current channel. Last hop is handled separately.
608 let mut cur_hop_fees_msat = 0;
610 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().0.hop_use_fee_msat;
613 let mut cur_hop = &mut self.hops.get_mut(i).unwrap().0;
614 cur_hop.next_hops_fee_msat = total_fee_paid_msat;
615 // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
616 // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
617 // set it too high just to maliciously take more fees by exploiting this
618 // match htlc_minimum_msat logic.
619 let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
620 if let Some(extra_fees_msat) = cur_hop.candidate.htlc_minimum_msat().checked_sub(cur_hop_transferred_amount_msat) {
621 // Note that there is a risk that *previous hops* (those closer to us, as we go
622 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
624 // This might make us end up with a broken route, although this should be super-rare
625 // in practice, both because of how healthy channels look like, and how we pick
626 // channels in add_entry.
627 // Also, this can't be exploited more heavily than *announce a free path and fail
629 cur_hop_transferred_amount_msat += extra_fees_msat;
630 total_fee_paid_msat += extra_fees_msat;
631 cur_hop_fees_msat += extra_fees_msat;
635 // Final hop is a special case: it usually has just value_msat (by design), but also
636 // it still could overpay for the htlc_minimum_msat.
637 cur_hop.fee_msat = cur_hop_transferred_amount_msat;
639 // Propagate updated fees for the use of the channels to one hop back, where they
640 // will be actually paid (fee_msat). The last hop is handled above separately.
641 cur_hop.fee_msat = cur_hop_fees_msat;
644 // Fee for the use of the current hop which will be deducted on the previous hop.
645 // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
646 // this channel is free for us.
648 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.candidate.fees()) {
649 cur_hop.hop_use_fee_msat = new_fee;
650 total_fee_paid_msat += new_fee;
652 // It should not be possible because this function is called only to reduce the
653 // value. In that case, compute_fee was already called with the same fees for
654 // larger amount and there was no overflow.
662 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
663 let proportional_fee_millions =
664 amount_msat.checked_mul(channel_fees.proportional_millionths as u64);
665 if let Some(new_fee) = proportional_fee_millions.and_then(|part| {
666 (channel_fees.base_msat as u64).checked_add(part / 1_000_000) }) {
670 // This function may be (indirectly) called without any verification,
671 // with channel_fees provided by a caller. We should handle it gracefully.
676 /// The default `features` we assume for a node in a route, when no `features` are known about that
679 /// Default features are:
680 /// * variable_length_onion_optional
681 fn default_node_features() -> NodeFeatures {
682 let mut features = NodeFeatures::empty();
683 features.set_variable_length_onion_optional();
687 /// Finds a route from us (payer) to the given target node (payee).
689 /// If the payee provided features in their invoice, they should be provided via `params.payee`.
690 /// Without this, MPP will only be used if the payee's features are available in the network graph.
692 /// Private routing paths between a public node and the target may be included in `params.payee`.
694 /// If some channels aren't announced, it may be useful to fill in `first_hops` with the results
695 /// from [`ChannelManager::list_usable_channels`]. If it is filled in, the view of these channels
696 /// from `network_graph` will be ignored, and only those in `first_hops` will be used.
698 /// The fees on channels from us to the next hop are ignored as they are assumed to all be equal.
699 /// However, the enabled/disabled bit on such channels as well as the `htlc_minimum_msat` /
700 /// `htlc_maximum_msat` *are* checked as they may change based on the receiving node.
704 /// May be used to re-compute a [`Route`] when handling a [`Event::PaymentPathFailed`]. Any
705 /// adjustments to the [`NetworkGraph`] and channel scores should be made prior to calling this
710 /// Panics if first_hops contains channels without short_channel_ids;
711 /// [`ChannelManager::list_usable_channels`] will never include such channels.
713 /// [`ChannelManager::list_usable_channels`]: crate::ln::channelmanager::ChannelManager::list_usable_channels
714 /// [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed
715 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
716 pub fn find_route<L: Deref, GL: Deref, S: Score>(
717 our_node_pubkey: &PublicKey, route_params: &RouteParameters,
718 network_graph: &NetworkGraph<GL>, first_hops: Option<&[&ChannelDetails]>, logger: L,
719 scorer: &S, random_seed_bytes: &[u8; 32]
720 ) -> Result<Route, LightningError>
721 where L::Target: Logger, GL::Target: Logger {
722 let graph_lock = network_graph.read_only();
723 let mut route = get_route(our_node_pubkey, &route_params.payment_params, &graph_lock, first_hops,
724 route_params.final_value_msat, route_params.final_cltv_expiry_delta, logger, scorer,
726 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
730 pub(crate) fn get_route<L: Deref, S: Score>(
731 our_node_pubkey: &PublicKey, payment_params: &PaymentParameters, network_graph: &ReadOnlyNetworkGraph,
732 first_hops: Option<&[&ChannelDetails]>, final_value_msat: u64, final_cltv_expiry_delta: u32,
733 logger: L, scorer: &S, random_seed_bytes: &[u8; 32]
734 ) -> Result<Route, LightningError>
735 where L::Target: Logger {
736 let payee_node_id = NodeId::from_pubkey(&payment_params.payee_pubkey);
737 let our_node_id = NodeId::from_pubkey(&our_node_pubkey);
739 if payee_node_id == our_node_id {
740 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
743 if final_value_msat > MAX_VALUE_MSAT {
744 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
747 if final_value_msat == 0 {
748 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
751 for route in payment_params.route_hints.iter() {
752 for hop in &route.0 {
753 if hop.src_node_id == payment_params.payee_pubkey {
754 return Err(LightningError{err: "Route hint cannot have the payee as the source.".to_owned(), action: ErrorAction::IgnoreError});
758 if payment_params.max_total_cltv_expiry_delta <= final_cltv_expiry_delta {
759 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});
762 // The general routing idea is the following:
763 // 1. Fill first/last hops communicated by the caller.
764 // 2. Attempt to construct a path from payer to payee for transferring
765 // any ~sufficient (described later) value.
766 // If succeed, remember which channels were used and how much liquidity they have available,
767 // so that future paths don't rely on the same liquidity.
768 // 3. Proceed to the next step if:
769 // - we hit the recommended target value;
770 // - OR if we could not construct a new path. Any next attempt will fail too.
771 // Otherwise, repeat step 2.
772 // 4. See if we managed to collect paths which aggregately are able to transfer target value
773 // (not recommended value).
774 // 5. If yes, proceed. If not, fail routing.
775 // 6. Randomly combine paths into routes having enough to fulfill the payment. (TODO: knapsack)
776 // 7. Of all the found paths, select only those with the lowest total fee.
777 // 8. The last path in every selected route is likely to be more than we need.
778 // Reduce its value-to-transfer and recompute fees.
779 // 9. Choose the best route by the lowest total fee.
781 // As for the actual search algorithm,
782 // we do a payee-to-payer pseudo-Dijkstra's sorting by each node's distance from the payee
783 // plus the minimum per-HTLC fee to get from it to another node (aka "shitty pseudo-A*").
785 // We are not a faithful Dijkstra's implementation because we can change values which impact
786 // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
787 // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) than
788 // the value we are currently attempting to send over a path, we simply reduce the value being
789 // sent along the path for any hops after that channel. This may imply that later fees (which
790 // we've already tabulated) are lower because a smaller value is passing through the channels
791 // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
792 // channels which were selected earlier (and which may still be used for other paths without a
793 // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
796 // One potentially problematic case for this algorithm would be if there are many
797 // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
798 // graph walking), we may never find a path which is not liquidity-limited and has lower
799 // proportional fee (and only lower absolute fee when considering the ultimate value sent).
800 // Because we only consider paths with at least 5% of the total value being sent, the damage
801 // from such a case should be limited, however this could be further reduced in the future by
802 // calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
803 // limits for the purposes of fee calculation.
805 // Alternatively, we could store more detailed path information in the heap (targets, below)
806 // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
807 // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
808 // and practically (as we would need to store dynamically-allocated path information in heap
809 // objects, increasing malloc traffic and indirect memory access significantly). Further, the
810 // results of such an algorithm would likely be biased towards lower-value paths.
812 // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
813 // outside of our current search value, running a path search more times to gather candidate
814 // paths at different values. While this may be acceptable, further path searches may increase
815 // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
816 // graph for candidate paths, calculating the maximum value which can realistically be sent at
817 // the same time, remaining generic across different payment values.
819 // TODO: There are a few tweaks we could do, including possibly pre-calculating more stuff
820 // to use as the A* heuristic beyond just the cost to get one node further than the current
823 let network_channels = network_graph.channels();
824 let network_nodes = network_graph.nodes();
826 if payment_params.max_path_count == 0 {
827 return Err(LightningError{err: "Can't find a route with no paths allowed.".to_owned(), action: ErrorAction::IgnoreError});
830 // Allow MPP only if we have a features set from somewhere that indicates the payee supports
831 // it. If the payee supports it they're supposed to include it in the invoice, so that should
833 let allow_mpp = if payment_params.max_path_count == 1 {
835 } else if let Some(features) = &payment_params.features {
836 features.supports_basic_mpp()
837 } else if let Some(node) = network_nodes.get(&payee_node_id) {
838 if let Some(node_info) = node.announcement_info.as_ref() {
839 node_info.features.supports_basic_mpp()
843 log_trace!(logger, "Searching for a route from payer {} to payee {} {} MPP and {} first hops {}overriding the network graph", our_node_pubkey,
844 payment_params.payee_pubkey, if allow_mpp { "with" } else { "without" },
845 first_hops.map(|hops| hops.len()).unwrap_or(0), if first_hops.is_some() { "" } else { "not " });
848 // Prepare the data we'll use for payee-to-payer search by
849 // inserting first hops suggested by the caller as targets.
850 // Our search will then attempt to reach them while traversing from the payee node.
851 let mut first_hop_targets: HashMap<_, Vec<&ChannelDetails>> =
852 HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
853 if let Some(hops) = first_hops {
855 if chan.get_outbound_payment_scid().is_none() {
856 panic!("first_hops should be filled in with usable channels, not pending ones");
858 if chan.counterparty.node_id == *our_node_pubkey {
859 return Err(LightningError{err: "First hop cannot have our_node_pubkey as a destination.".to_owned(), action: ErrorAction::IgnoreError});
862 .entry(NodeId::from_pubkey(&chan.counterparty.node_id))
863 .or_insert(Vec::new())
866 if first_hop_targets.is_empty() {
867 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
871 // The main heap containing all candidate next-hops sorted by their score (max(A* fee,
872 // htlc_minimum)). Ideally this would be a heap which allowed cheap score reduction instead of
873 // adding duplicate entries when we find a better path to a given node.
874 let mut targets: BinaryHeap<RouteGraphNode> = BinaryHeap::new();
876 // Map from node_id to information about the best current path to that node, including feerate
878 let mut dist: HashMap<NodeId, PathBuildingHop> = HashMap::with_capacity(network_nodes.len());
880 // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
881 // indicating that we may wish to try again with a higher value, potentially paying to meet an
882 // htlc_minimum with extra fees while still finding a cheaper path.
883 let mut hit_minimum_limit;
885 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
886 // We start with a path_value of the exact amount we want, and if that generates a route we may
887 // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
888 // amount we want in total across paths, selecting the best subset at the end.
889 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
890 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
891 let mut path_value_msat = final_value_msat;
893 // Routing Fragmentation Mitigation heuristic:
895 // Routing fragmentation across many payment paths increases the overall routing
896 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
897 // Taking too many smaller paths also increases the chance of payment failure.
898 // Thus to avoid this effect, we require from our collected links to provide
899 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
900 // This requirement is currently set to be 1/max_path_count of the payment
901 // value to ensure we only ever return routes that do not violate this limit.
902 let minimal_value_contribution_msat: u64 = if allow_mpp {
903 (final_value_msat + (payment_params.max_path_count as u64 - 1)) / payment_params.max_path_count as u64
908 // Keep track of how much liquidity has been used in selected channels. Used to determine
909 // if the channel can be used by additional MPP paths or to inform path finding decisions. It is
910 // aware of direction *only* to ensure that the correct htlc_maximum_msat value is used. Hence,
911 // liquidity used in one direction will not offset any used in the opposite direction.
912 let mut used_channel_liquidities: HashMap<(u64, bool), u64> =
913 HashMap::with_capacity(network_nodes.len());
915 // Keeping track of how much value we already collected across other paths. Helps to decide
916 // when we want to stop looking for new paths.
917 let mut already_collected_value_msat = 0;
919 for (_, channels) in first_hop_targets.iter_mut() {
920 // Sort the first_hops channels to the same node(s) in priority order of which channel we'd
923 // First, if channels are below `recommended_value_msat`, sort them in descending order,
924 // preferring larger channels to avoid splitting the payment into more MPP parts than is
927 // Second, because simply always sorting in descending order would always use our largest
928 // available outbound capacity, needlessly fragmenting our available channel capacities,
929 // sort channels above `recommended_value_msat` in ascending order, preferring channels
930 // which have enough, but not too much, capacity for the payment.
931 channels.sort_unstable_by(|chan_a, chan_b| {
932 if chan_b.next_outbound_htlc_limit_msat < recommended_value_msat || chan_a.next_outbound_htlc_limit_msat < recommended_value_msat {
933 // Sort in descending order
934 chan_b.next_outbound_htlc_limit_msat.cmp(&chan_a.next_outbound_htlc_limit_msat)
936 // Sort in ascending order
937 chan_a.next_outbound_htlc_limit_msat.cmp(&chan_b.next_outbound_htlc_limit_msat)
942 log_trace!(logger, "Building path from {} (payee) to {} (us/payer) for value {} msat.", payment_params.payee_pubkey, our_node_pubkey, final_value_msat);
944 macro_rules! add_entry {
945 // Adds entry which goes from $src_node_id to $dest_node_id over the $candidate hop.
946 // $next_hops_fee_msat represents the fees paid for using all the channels *after* this one,
947 // since that value has to be transferred over this channel.
948 // Returns whether this channel caused an update to `targets`.
949 ( $candidate: expr, $src_node_id: expr, $dest_node_id: expr, $next_hops_fee_msat: expr,
950 $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr,
951 $next_hops_path_penalty_msat: expr, $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => { {
952 // We "return" whether we updated the path at the end, via this:
953 let mut did_add_update_path_to_src_node = false;
954 // Channels to self should not be used. This is more of belt-and-suspenders, because in
955 // practice these cases should be caught earlier:
956 // - for regular channels at channel announcement (TODO)
957 // - for first and last hops early in get_route
958 if $src_node_id != $dest_node_id {
959 let short_channel_id = $candidate.short_channel_id();
960 let effective_capacity = $candidate.effective_capacity();
961 let htlc_maximum_msat = max_htlc_from_capacity(effective_capacity, payment_params.max_channel_saturation_power_of_half);
963 // It is tricky to subtract $next_hops_fee_msat from available liquidity here.
964 // It may be misleading because we might later choose to reduce the value transferred
965 // over these channels, and the channel which was insufficient might become sufficient.
966 // Worst case: we drop a good channel here because it can't cover the high following
967 // fees caused by one expensive channel, but then this channel could have been used
968 // if the amount being transferred over this path is lower.
969 // We do this for now, but this is a subject for removal.
970 if let Some(mut available_value_contribution_msat) = htlc_maximum_msat.checked_sub($next_hops_fee_msat) {
971 let used_liquidity_msat = used_channel_liquidities
972 .get(&(short_channel_id, $src_node_id < $dest_node_id))
973 .map_or(0, |used_liquidity_msat| {
974 available_value_contribution_msat = available_value_contribution_msat
975 .saturating_sub(*used_liquidity_msat);
979 // Verify the liquidity offered by this channel complies to the minimal contribution.
980 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
981 // Do not consider candidate hops that would exceed the maximum path length.
982 let path_length_to_node = $next_hops_path_length + 1;
983 let doesnt_exceed_max_path_length = path_length_to_node <= MAX_PATH_LENGTH_ESTIMATE;
985 // Do not consider candidates that exceed the maximum total cltv expiry limit.
986 // In order to already account for some of the privacy enhancing random CLTV
987 // expiry delta offset we add on top later, we subtract a rough estimate
988 // (2*MEDIAN_HOP_CLTV_EXPIRY_DELTA) here.
989 let max_total_cltv_expiry_delta = (payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta)
990 .checked_sub(2*MEDIAN_HOP_CLTV_EXPIRY_DELTA)
991 .unwrap_or(payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta);
992 let hop_total_cltv_delta = ($next_hops_cltv_delta as u32)
993 .saturating_add($candidate.cltv_expiry_delta());
994 let doesnt_exceed_cltv_delta_limit = hop_total_cltv_delta <= max_total_cltv_expiry_delta;
996 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
997 // Includes paying fees for the use of the following channels.
998 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
999 Some(result) => result,
1000 // Can't overflow due to how the values were computed right above.
1001 None => unreachable!(),
1003 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
1004 let over_path_minimum_msat = amount_to_transfer_over_msat >= $candidate.htlc_minimum_msat() &&
1005 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
1007 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
1008 let may_overpay_to_meet_path_minimum_msat =
1009 ((amount_to_transfer_over_msat < $candidate.htlc_minimum_msat() &&
1010 recommended_value_msat > $candidate.htlc_minimum_msat()) ||
1011 (amount_to_transfer_over_msat < $next_hops_path_htlc_minimum_msat &&
1012 recommended_value_msat > $next_hops_path_htlc_minimum_msat));
1014 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
1015 // bother considering this channel. If retrying with recommended_value_msat may
1016 // allow us to hit the HTLC minimum limit, set htlc_minimum_limit so that we go
1017 // around again with a higher amount.
1018 if contributes_sufficient_value && doesnt_exceed_max_path_length &&
1019 doesnt_exceed_cltv_delta_limit && may_overpay_to_meet_path_minimum_msat {
1020 hit_minimum_limit = true;
1021 } else if contributes_sufficient_value && doesnt_exceed_max_path_length &&
1022 doesnt_exceed_cltv_delta_limit && over_path_minimum_msat {
1023 // Note that low contribution here (limited by available_liquidity_msat)
1024 // might violate htlc_minimum_msat on the hops which are next along the
1025 // payment path (upstream to the payee). To avoid that, we recompute
1026 // path fees knowing the final path contribution after constructing it.
1027 let path_htlc_minimum_msat = compute_fees($next_hops_path_htlc_minimum_msat, $candidate.fees())
1028 .and_then(|fee_msat| fee_msat.checked_add($next_hops_path_htlc_minimum_msat))
1029 .map(|fee_msat| cmp::max(fee_msat, $candidate.htlc_minimum_msat()))
1030 .unwrap_or_else(|| u64::max_value());
1031 let hm_entry = dist.entry($src_node_id);
1032 let old_entry = hm_entry.or_insert_with(|| {
1033 // If there was previously no known way to access the source node
1034 // (recall it goes payee-to-payer) of short_channel_id, first add a
1035 // semi-dummy record just to compute the fees to reach the source node.
1036 // This will affect our decision on selecting short_channel_id
1037 // as a way to reach the $dest_node_id.
1038 let mut fee_base_msat = 0;
1039 let mut fee_proportional_millionths = 0;
1040 if let Some(Some(fees)) = network_nodes.get(&$src_node_id).map(|node| node.lowest_inbound_channel_fees) {
1041 fee_base_msat = fees.base_msat;
1042 fee_proportional_millionths = fees.proportional_millionths;
1045 node_id: $dest_node_id.clone(),
1046 candidate: $candidate.clone(),
1048 src_lowest_inbound_fees: RoutingFees {
1049 base_msat: fee_base_msat,
1050 proportional_millionths: fee_proportional_millionths,
1052 next_hops_fee_msat: u64::max_value(),
1053 hop_use_fee_msat: u64::max_value(),
1054 total_fee_msat: u64::max_value(),
1055 path_htlc_minimum_msat,
1056 path_penalty_msat: u64::max_value(),
1057 was_processed: false,
1058 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
1059 value_contribution_msat,
1063 #[allow(unused_mut)] // We only use the mut in cfg(test)
1064 let mut should_process = !old_entry.was_processed;
1065 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
1067 // In test/fuzzing builds, we do extra checks to make sure the skipping
1068 // of already-seen nodes only happens in cases we expect (see below).
1069 if !should_process { should_process = true; }
1073 let mut hop_use_fee_msat = 0;
1074 let mut total_fee_msat = $next_hops_fee_msat;
1076 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
1077 // will have the same effective-fee
1078 if $src_node_id != our_node_id {
1079 match compute_fees(amount_to_transfer_over_msat, $candidate.fees()) {
1080 // max_value means we'll always fail
1081 // the old_entry.total_fee_msat > total_fee_msat check
1082 None => total_fee_msat = u64::max_value(),
1084 hop_use_fee_msat = fee_msat;
1085 total_fee_msat += hop_use_fee_msat;
1086 // When calculating the lowest inbound fees to a node, we
1087 // calculate fees here not based on the actual value we think
1088 // will flow over this channel, but on the minimum value that
1089 // we'll accept flowing over it. The minimum accepted value
1090 // is a constant through each path collection run, ensuring
1091 // consistent basis. Otherwise we may later find a
1092 // different path to the source node that is more expensive,
1093 // but which we consider to be cheaper because we are capacity
1094 // constrained and the relative fee becomes lower.
1095 match compute_fees(minimal_value_contribution_msat, old_entry.src_lowest_inbound_fees)
1096 .map(|a| a.checked_add(total_fee_msat)) {
1101 total_fee_msat = u64::max_value();
1108 let channel_usage = ChannelUsage {
1109 amount_msat: amount_to_transfer_over_msat,
1110 inflight_htlc_msat: used_liquidity_msat,
1113 let channel_penalty_msat = scorer.channel_penalty_msat(
1114 short_channel_id, &$src_node_id, &$dest_node_id, channel_usage
1116 let path_penalty_msat = $next_hops_path_penalty_msat
1117 .saturating_add(channel_penalty_msat);
1118 let new_graph_node = RouteGraphNode {
1119 node_id: $src_node_id,
1120 lowest_fee_to_peer_through_node: total_fee_msat,
1121 lowest_fee_to_node: $next_hops_fee_msat as u64 + hop_use_fee_msat,
1122 total_cltv_delta: hop_total_cltv_delta,
1123 value_contribution_msat: value_contribution_msat,
1124 path_htlc_minimum_msat,
1126 path_length_to_node,
1129 // Update the way of reaching $src_node_id with the given short_channel_id (from $dest_node_id),
1130 // if this way is cheaper than the already known
1131 // (considering the cost to "reach" this channel from the route destination,
1132 // the cost of using this channel,
1133 // and the cost of routing to the source node of this channel).
1134 // Also, consider that htlc_minimum_msat_difference, because we might end up
1135 // paying it. Consider the following exploit:
1136 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
1137 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
1138 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
1139 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
1141 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
1142 // but it may require additional tracking - we don't want to double-count
1143 // the fees included in $next_hops_path_htlc_minimum_msat, but also
1144 // can't use something that may decrease on future hops.
1145 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat)
1146 .saturating_add(old_entry.path_penalty_msat);
1147 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat)
1148 .saturating_add(path_penalty_msat);
1150 if !old_entry.was_processed && new_cost < old_cost {
1151 targets.push(new_graph_node);
1152 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
1153 old_entry.hop_use_fee_msat = hop_use_fee_msat;
1154 old_entry.total_fee_msat = total_fee_msat;
1155 old_entry.node_id = $dest_node_id.clone();
1156 old_entry.candidate = $candidate.clone();
1157 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
1158 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
1159 old_entry.path_penalty_msat = path_penalty_msat;
1160 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
1162 old_entry.value_contribution_msat = value_contribution_msat;
1164 did_add_update_path_to_src_node = true;
1165 } else if old_entry.was_processed && new_cost < old_cost {
1166 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
1168 // If we're skipping processing a node which was previously
1169 // processed even though we found another path to it with a
1170 // cheaper fee, check that it was because the second path we
1171 // found (which we are processing now) has a lower value
1172 // contribution due to an HTLC minimum limit.
1174 // e.g. take a graph with two paths from node 1 to node 2, one
1175 // through channel A, and one through channel B. Channel A and
1176 // B are both in the to-process heap, with their scores set by
1177 // a higher htlc_minimum than fee.
1178 // Channel A is processed first, and the channels onwards from
1179 // node 1 are added to the to-process heap. Thereafter, we pop
1180 // Channel B off of the heap, note that it has a much more
1181 // restrictive htlc_maximum_msat, and recalculate the fees for
1182 // all of node 1's channels using the new, reduced, amount.
1184 // This would be bogus - we'd be selecting a higher-fee path
1185 // with a lower htlc_maximum_msat instead of the one we'd
1186 // already decided to use.
1187 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
1189 value_contribution_msat + path_penalty_msat <
1190 old_entry.value_contribution_msat + old_entry.path_penalty_msat
1198 did_add_update_path_to_src_node
1202 let default_node_features = default_node_features();
1204 // Find ways (channels with destination) to reach a given node and store them
1205 // in the corresponding data structures (routing graph etc).
1206 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
1207 // meaning how much will be paid in fees after this node (to the best of our knowledge).
1208 // This data can later be helpful to optimize routing (pay lower fees).
1209 macro_rules! add_entries_to_cheapest_to_target_node {
1210 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr, $next_hops_value_contribution: expr,
1211 $next_hops_path_htlc_minimum_msat: expr, $next_hops_path_penalty_msat: expr,
1212 $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => {
1213 let skip_node = if let Some(elem) = dist.get_mut(&$node_id) {
1214 let was_processed = elem.was_processed;
1215 elem.was_processed = true;
1218 // Entries are added to dist in add_entry!() when there is a channel from a node.
1219 // Because there are no channels from payee, it will not have a dist entry at this point.
1220 // If we're processing any other node, it is always be the result of a channel from it.
1221 assert_eq!($node_id, payee_node_id);
1226 if let Some(first_channels) = first_hop_targets.get(&$node_id) {
1227 for details in first_channels {
1228 let candidate = CandidateRouteHop::FirstHop { details };
1229 add_entry!(candidate, our_node_id, $node_id, $fee_to_target_msat,
1230 $next_hops_value_contribution,
1231 $next_hops_path_htlc_minimum_msat, $next_hops_path_penalty_msat,
1232 $next_hops_cltv_delta, $next_hops_path_length);
1236 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
1239 &default_node_features
1242 if !features.requires_unknown_bits() {
1243 for chan_id in $node.channels.iter() {
1244 let chan = network_channels.get(chan_id).unwrap();
1245 if !chan.features.requires_unknown_bits() {
1246 let (directed_channel, source) =
1247 chan.as_directed_to(&$node_id).expect("inconsistent NetworkGraph");
1248 if first_hops.is_none() || *source != our_node_id {
1249 if let Some(direction) = directed_channel.direction() {
1250 if direction.enabled {
1251 let candidate = CandidateRouteHop::PublicHop {
1252 info: directed_channel.with_update().unwrap(),
1253 short_channel_id: *chan_id,
1255 add_entry!(candidate, *source, $node_id,
1256 $fee_to_target_msat,
1257 $next_hops_value_contribution,
1258 $next_hops_path_htlc_minimum_msat,
1259 $next_hops_path_penalty_msat,
1260 $next_hops_cltv_delta, $next_hops_path_length);
1271 let mut payment_paths = Vec::<PaymentPath>::new();
1273 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
1274 'paths_collection: loop {
1275 // For every new path, start from scratch, except for used_channel_liquidities, which
1276 // helps to avoid reusing previously selected paths in future iterations.
1279 hit_minimum_limit = false;
1281 // If first hop is a private channel and the only way to reach the payee, this is the only
1282 // place where it could be added.
1283 if let Some(first_channels) = first_hop_targets.get(&payee_node_id) {
1284 for details in first_channels {
1285 let candidate = CandidateRouteHop::FirstHop { details };
1286 let added = add_entry!(candidate, our_node_id, payee_node_id, 0, path_value_msat,
1288 log_trace!(logger, "{} direct route to payee via SCID {}",
1289 if added { "Added" } else { "Skipped" }, candidate.short_channel_id());
1293 // Add the payee as a target, so that the payee-to-payer
1294 // search algorithm knows what to start with.
1295 match network_nodes.get(&payee_node_id) {
1296 // The payee is not in our network graph, so nothing to add here.
1297 // There is still a chance of reaching them via last_hops though,
1298 // so don't yet fail the payment here.
1299 // If not, targets.pop() will not even let us enter the loop in step 2.
1302 add_entries_to_cheapest_to_target_node!(node, payee_node_id, 0, path_value_msat, 0, 0u64, 0, 0);
1307 // If a caller provided us with last hops, add them to routing targets. Since this happens
1308 // earlier than general path finding, they will be somewhat prioritized, although currently
1309 // it matters only if the fees are exactly the same.
1310 for route in payment_params.route_hints.iter().filter(|route| !route.0.is_empty()) {
1311 let first_hop_in_route = &(route.0)[0];
1312 let have_hop_src_in_graph =
1313 // Only add the hops in this route to our candidate set if either
1314 // we have a direct channel to the first hop or the first hop is
1315 // in the regular network graph.
1316 first_hop_targets.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some() ||
1317 network_nodes.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some();
1318 if have_hop_src_in_graph {
1319 // We start building the path from reverse, i.e., from payee
1320 // to the first RouteHintHop in the path.
1321 let hop_iter = route.0.iter().rev();
1322 let prev_hop_iter = core::iter::once(&payment_params.payee_pubkey).chain(
1323 route.0.iter().skip(1).rev().map(|hop| &hop.src_node_id));
1324 let mut hop_used = true;
1325 let mut aggregate_next_hops_fee_msat: u64 = 0;
1326 let mut aggregate_next_hops_path_htlc_minimum_msat: u64 = 0;
1327 let mut aggregate_next_hops_path_penalty_msat: u64 = 0;
1328 let mut aggregate_next_hops_cltv_delta: u32 = 0;
1329 let mut aggregate_next_hops_path_length: u8 = 0;
1331 for (idx, (hop, prev_hop_id)) in hop_iter.zip(prev_hop_iter).enumerate() {
1332 let source = NodeId::from_pubkey(&hop.src_node_id);
1333 let target = NodeId::from_pubkey(&prev_hop_id);
1334 let candidate = network_channels
1335 .get(&hop.short_channel_id)
1336 .and_then(|channel| channel.as_directed_to(&target))
1337 .and_then(|(channel, _)| channel.with_update())
1338 .map(|info| CandidateRouteHop::PublicHop {
1340 short_channel_id: hop.short_channel_id,
1342 .unwrap_or_else(|| CandidateRouteHop::PrivateHop { hint: hop });
1344 if !add_entry!(candidate, source, target, aggregate_next_hops_fee_msat,
1345 path_value_msat, aggregate_next_hops_path_htlc_minimum_msat,
1346 aggregate_next_hops_path_penalty_msat,
1347 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length) {
1348 // If this hop was not used then there is no use checking the preceding
1349 // hops in the RouteHint. We can break by just searching for a direct
1350 // channel between last checked hop and first_hop_targets.
1354 let used_liquidity_msat = used_channel_liquidities
1355 .get(&(hop.short_channel_id, source < target)).copied().unwrap_or(0);
1356 let channel_usage = ChannelUsage {
1357 amount_msat: final_value_msat + aggregate_next_hops_fee_msat,
1358 inflight_htlc_msat: used_liquidity_msat,
1359 effective_capacity: candidate.effective_capacity(),
1361 let channel_penalty_msat = scorer.channel_penalty_msat(
1362 hop.short_channel_id, &source, &target, channel_usage
1364 aggregate_next_hops_path_penalty_msat = aggregate_next_hops_path_penalty_msat
1365 .saturating_add(channel_penalty_msat);
1367 aggregate_next_hops_cltv_delta = aggregate_next_hops_cltv_delta
1368 .saturating_add(hop.cltv_expiry_delta as u32);
1370 aggregate_next_hops_path_length = aggregate_next_hops_path_length
1373 // Searching for a direct channel between last checked hop and first_hop_targets
1374 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&prev_hop_id)) {
1375 for details in first_channels {
1376 let candidate = CandidateRouteHop::FirstHop { details };
1377 add_entry!(candidate, our_node_id, NodeId::from_pubkey(&prev_hop_id),
1378 aggregate_next_hops_fee_msat, path_value_msat,
1379 aggregate_next_hops_path_htlc_minimum_msat,
1380 aggregate_next_hops_path_penalty_msat, aggregate_next_hops_cltv_delta,
1381 aggregate_next_hops_path_length);
1389 // In the next values of the iterator, the aggregate fees already reflects
1390 // the sum of value sent from payer (final_value_msat) and routing fees
1391 // for the last node in the RouteHint. We need to just add the fees to
1392 // route through the current node so that the preceding node (next iteration)
1394 let hops_fee = compute_fees(aggregate_next_hops_fee_msat + final_value_msat, hop.fees)
1395 .map_or(None, |inc| inc.checked_add(aggregate_next_hops_fee_msat));
1396 aggregate_next_hops_fee_msat = if let Some(val) = hops_fee { val } else { break; };
1398 let hop_htlc_minimum_msat = candidate.htlc_minimum_msat();
1399 let hop_htlc_minimum_msat_inc = if let Some(val) = compute_fees(aggregate_next_hops_path_htlc_minimum_msat, hop.fees) { val } else { break; };
1400 let hops_path_htlc_minimum = aggregate_next_hops_path_htlc_minimum_msat
1401 .checked_add(hop_htlc_minimum_msat_inc);
1402 aggregate_next_hops_path_htlc_minimum_msat = if let Some(val) = hops_path_htlc_minimum { cmp::max(hop_htlc_minimum_msat, val) } else { break; };
1404 if idx == route.0.len() - 1 {
1405 // The last hop in this iterator is the first hop in
1406 // overall RouteHint.
1407 // If this hop connects to a node with which we have a direct channel,
1408 // ignore the network graph and, if the last hop was added, add our
1409 // direct channel to the candidate set.
1411 // Note that we *must* check if the last hop was added as `add_entry`
1412 // always assumes that the third argument is a node to which we have a
1414 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&hop.src_node_id)) {
1415 for details in first_channels {
1416 let candidate = CandidateRouteHop::FirstHop { details };
1417 add_entry!(candidate, our_node_id,
1418 NodeId::from_pubkey(&hop.src_node_id),
1419 aggregate_next_hops_fee_msat, path_value_msat,
1420 aggregate_next_hops_path_htlc_minimum_msat,
1421 aggregate_next_hops_path_penalty_msat,
1422 aggregate_next_hops_cltv_delta,
1423 aggregate_next_hops_path_length);
1431 log_trace!(logger, "Starting main path collection loop with {} nodes pre-filled from first/last hops.", targets.len());
1433 // At this point, targets are filled with the data from first and
1434 // last hops communicated by the caller, and the payment receiver.
1435 let mut found_new_path = false;
1438 // If this loop terminates due the exhaustion of targets, two situations are possible:
1439 // - not enough outgoing liquidity:
1440 // 0 < already_collected_value_msat < final_value_msat
1441 // - enough outgoing liquidity:
1442 // final_value_msat <= already_collected_value_msat < recommended_value_msat
1443 // Both these cases (and other cases except reaching recommended_value_msat) mean that
1444 // paths_collection will be stopped because found_new_path==false.
1445 // This is not necessarily a routing failure.
1446 '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() {
1448 // Since we're going payee-to-payer, hitting our node as a target means we should stop
1449 // traversing the graph and arrange the path out of what we found.
1450 if node_id == our_node_id {
1451 let mut new_entry = dist.remove(&our_node_id).unwrap();
1452 let mut ordered_hops: Vec<(PathBuildingHop, NodeFeatures)> = vec!((new_entry.clone(), default_node_features.clone()));
1455 let mut features_set = false;
1456 if let Some(first_channels) = first_hop_targets.get(&ordered_hops.last().unwrap().0.node_id) {
1457 for details in first_channels {
1458 if details.get_outbound_payment_scid().unwrap() == ordered_hops.last().unwrap().0.candidate.short_channel_id() {
1459 ordered_hops.last_mut().unwrap().1 = details.counterparty.features.to_context();
1460 features_set = true;
1466 if let Some(node) = network_nodes.get(&ordered_hops.last().unwrap().0.node_id) {
1467 if let Some(node_info) = node.announcement_info.as_ref() {
1468 ordered_hops.last_mut().unwrap().1 = node_info.features.clone();
1470 ordered_hops.last_mut().unwrap().1 = default_node_features.clone();
1473 // We can fill in features for everything except hops which were
1474 // provided via the invoice we're paying. We could guess based on the
1475 // recipient's features but for now we simply avoid guessing at all.
1479 // Means we succesfully traversed from the payer to the payee, now
1480 // save this path for the payment route. Also, update the liquidity
1481 // remaining on the used hops, so that we take them into account
1482 // while looking for more paths.
1483 if ordered_hops.last().unwrap().0.node_id == payee_node_id {
1487 new_entry = match dist.remove(&ordered_hops.last().unwrap().0.node_id) {
1488 Some(payment_hop) => payment_hop,
1489 // We can't arrive at None because, if we ever add an entry to targets,
1490 // we also fill in the entry in dist (see add_entry!).
1491 None => unreachable!(),
1493 // We "propagate" the fees one hop backward (topologically) here,
1494 // so that fees paid for a HTLC forwarding on the current channel are
1495 // associated with the previous channel (where they will be subtracted).
1496 ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
1497 ordered_hops.push((new_entry.clone(), default_node_features.clone()));
1499 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
1500 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
1502 log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: \n {:#?}",
1503 ordered_hops.len(), value_contribution_msat, ordered_hops.iter().map(|h| &(h.0)).collect::<Vec<&PathBuildingHop>>());
1505 let mut payment_path = PaymentPath {hops: ordered_hops};
1507 // We could have possibly constructed a slightly inconsistent path: since we reduce
1508 // value being transferred along the way, we could have violated htlc_minimum_msat
1509 // on some channels we already passed (assuming dest->source direction). Here, we
1510 // recompute the fees again, so that if that's the case, we match the currently
1511 // underpaid htlc_minimum_msat with fees.
1512 payment_path.update_value_and_recompute_fees(cmp::min(value_contribution_msat, final_value_msat));
1514 // Since a path allows to transfer as much value as
1515 // the smallest channel it has ("bottleneck"), we should recompute
1516 // the fees so sender HTLC don't overpay fees when traversing
1517 // larger channels than the bottleneck. This may happen because
1518 // when we were selecting those channels we were not aware how much value
1519 // this path will transfer, and the relative fee for them
1520 // might have been computed considering a larger value.
1521 // Remember that we used these channels so that we don't rely
1522 // on the same liquidity in future paths.
1523 let mut prevented_redundant_path_selection = false;
1524 let prev_hop_iter = core::iter::once(&our_node_id)
1525 .chain(payment_path.hops.iter().map(|(hop, _)| &hop.node_id));
1526 for (prev_hop, (hop, _)) in prev_hop_iter.zip(payment_path.hops.iter()) {
1527 let spent_on_hop_msat = value_contribution_msat + hop.next_hops_fee_msat;
1528 let used_liquidity_msat = used_channel_liquidities
1529 .entry((hop.candidate.short_channel_id(), *prev_hop < hop.node_id))
1530 .and_modify(|used_liquidity_msat| *used_liquidity_msat += spent_on_hop_msat)
1531 .or_insert(spent_on_hop_msat);
1532 let hop_capacity = hop.candidate.effective_capacity();
1533 let hop_max_msat = max_htlc_from_capacity(hop_capacity,
1534 payment_params.max_channel_saturation_power_of_half);
1535 if *used_liquidity_msat == hop_max_msat {
1536 // If this path used all of this channel's available liquidity, we know
1537 // this path will not be selected again in the next loop iteration.
1538 prevented_redundant_path_selection = true;
1540 debug_assert!(*used_liquidity_msat <= hop_max_msat);
1542 if !prevented_redundant_path_selection {
1543 // If we weren't capped by hitting a liquidity limit on a channel in the path,
1544 // we'll probably end up picking the same path again on the next iteration.
1545 // Decrease the available liquidity of a hop in the middle of the path.
1546 let victim_scid = payment_path.hops[(payment_path.hops.len()) / 2].0.candidate.short_channel_id();
1547 let exhausted = u64::max_value();
1548 log_trace!(logger, "Disabling channel {} for future path building iterations to avoid duplicates.", victim_scid);
1549 *used_channel_liquidities.entry((victim_scid, false)).or_default() = exhausted;
1550 *used_channel_liquidities.entry((victim_scid, true)).or_default() = exhausted;
1553 // Track the total amount all our collected paths allow to send so that we know
1554 // when to stop looking for more paths
1555 already_collected_value_msat += value_contribution_msat;
1557 payment_paths.push(payment_path);
1558 found_new_path = true;
1559 break 'path_construction;
1562 // If we found a path back to the payee, we shouldn't try to process it again. This is
1563 // the equivalent of the `elem.was_processed` check in
1564 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
1565 if node_id == payee_node_id { continue 'path_construction; }
1567 // Otherwise, since the current target node is not us,
1568 // keep "unrolling" the payment graph from payee to payer by
1569 // finding a way to reach the current target from the payer side.
1570 match network_nodes.get(&node_id) {
1573 add_entries_to_cheapest_to_target_node!(node, node_id, lowest_fee_to_node,
1574 value_contribution_msat, path_htlc_minimum_msat, path_penalty_msat,
1575 total_cltv_delta, path_length_to_node);
1581 // If we don't support MPP, no use trying to gather more value ever.
1582 break 'paths_collection;
1586 // Stop either when the recommended value is reached or if no new path was found in this
1588 // In the latter case, making another path finding attempt won't help,
1589 // because we deterministically terminated the search due to low liquidity.
1590 if already_collected_value_msat >= recommended_value_msat || !found_new_path {
1591 log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
1592 already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
1593 break 'paths_collection;
1594 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
1595 // Further, if this was our first walk of the graph, and we weren't limited by an
1596 // htlc_minimum_msat, return immediately because this path should suffice. If we were
1597 // limited by an htlc_minimum_msat value, find another path with a higher value,
1598 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
1599 // still keeping a lower total fee than this path.
1600 if !hit_minimum_limit {
1601 log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
1602 break 'paths_collection;
1604 log_trace!(logger, "Collected our payment amount on the first pass, but running again to collect extra paths with a potentially higher limit.");
1605 path_value_msat = recommended_value_msat;
1610 if payment_paths.len() == 0 {
1611 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1614 if already_collected_value_msat < final_value_msat {
1615 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1618 // Sort by total fees and take the best paths.
1619 payment_paths.sort_unstable_by_key(|path| path.get_total_fee_paid_msat());
1620 if payment_paths.len() > 50 {
1621 payment_paths.truncate(50);
1624 // Draw multiple sufficient routes by randomly combining the selected paths.
1625 let mut drawn_routes = Vec::new();
1626 let mut prng = ChaCha20::new(random_seed_bytes, &[0u8; 12]);
1627 let mut random_index_bytes = [0u8; ::core::mem::size_of::<usize>()];
1629 let num_permutations = payment_paths.len();
1630 for _ in 0..num_permutations {
1631 let mut cur_route = Vec::<PaymentPath>::new();
1632 let mut aggregate_route_value_msat = 0;
1635 // Do a Fisher-Yates shuffle to create a random permutation of the payment paths
1636 for cur_index in (1..payment_paths.len()).rev() {
1637 prng.process_in_place(&mut random_index_bytes);
1638 let random_index = usize::from_be_bytes(random_index_bytes).wrapping_rem(cur_index+1);
1639 payment_paths.swap(cur_index, random_index);
1643 for payment_path in &payment_paths {
1644 cur_route.push(payment_path.clone());
1645 aggregate_route_value_msat += payment_path.get_value_msat();
1646 if aggregate_route_value_msat > final_value_msat {
1647 // Last path likely overpaid. Substract it from the most expensive
1648 // (in terms of proportional fee) path in this route and recompute fees.
1649 // This might be not the most economically efficient way, but fewer paths
1650 // also makes routing more reliable.
1651 let mut overpaid_value_msat = aggregate_route_value_msat - final_value_msat;
1653 // First, we drop some expensive low-value paths entirely if possible, since fewer
1654 // paths is better: the payment is less likely to fail. In order to do so, we sort
1655 // by value and fall back to total fees paid, i.e., in case of equal values we
1656 // prefer lower cost paths.
1657 cur_route.sort_unstable_by(|a, b| {
1658 a.get_value_msat().cmp(&b.get_value_msat())
1659 // Reverse ordering for cost, so we drop higher-cost paths first
1660 .then_with(|| b.get_cost_msat().cmp(&a.get_cost_msat()))
1663 // We should make sure that at least 1 path left.
1664 let mut paths_left = cur_route.len();
1665 cur_route.retain(|path| {
1666 if paths_left == 1 {
1669 let mut keep = true;
1670 let path_value_msat = path.get_value_msat();
1671 if path_value_msat <= overpaid_value_msat {
1673 overpaid_value_msat -= path_value_msat;
1679 if overpaid_value_msat == 0 {
1683 assert!(cur_route.len() > 0);
1686 // Now, subtract the overpaid value from the most-expensive path.
1687 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1688 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1689 cur_route.sort_unstable_by_key(|path| { path.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>() });
1690 let expensive_payment_path = cur_route.first_mut().unwrap();
1692 // We already dropped all the small value paths above, meaning all the
1693 // remaining paths are larger than remaining overpaid_value_msat.
1694 // Thus, this can't be negative.
1695 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
1696 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
1700 drawn_routes.push(cur_route);
1704 // Select the best route by lowest total cost.
1705 drawn_routes.sort_unstable_by_key(|paths| paths.iter().map(|path| path.get_cost_msat()).sum::<u64>());
1706 let mut selected_paths = Vec::<Vec<Result<RouteHop, LightningError>>>::new();
1707 for payment_path in drawn_routes.first().unwrap() {
1708 let mut path = payment_path.hops.iter().map(|(payment_hop, node_features)| {
1710 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)})?,
1711 node_features: node_features.clone(),
1712 short_channel_id: payment_hop.candidate.short_channel_id(),
1713 channel_features: payment_hop.candidate.features(),
1714 fee_msat: payment_hop.fee_msat,
1715 cltv_expiry_delta: payment_hop.candidate.cltv_expiry_delta(),
1717 }).collect::<Vec<_>>();
1718 // Propagate the cltv_expiry_delta one hop backwards since the delta from the current hop is
1719 // applicable for the previous hop.
1720 path.iter_mut().rev().fold(final_cltv_expiry_delta, |prev_cltv_expiry_delta, hop| {
1721 core::mem::replace(&mut hop.as_mut().unwrap().cltv_expiry_delta, prev_cltv_expiry_delta)
1723 selected_paths.push(path);
1725 // Make sure we would never create a route with more paths than we allow.
1726 debug_assert!(selected_paths.len() <= payment_params.max_path_count.into());
1728 if let Some(features) = &payment_params.features {
1729 for path in selected_paths.iter_mut() {
1730 if let Ok(route_hop) = path.last_mut().unwrap() {
1731 route_hop.node_features = features.to_context();
1737 paths: selected_paths.into_iter().map(|path| path.into_iter().collect()).collect::<Result<Vec<_>, _>>()?,
1738 payment_params: Some(payment_params.clone()),
1740 log_info!(logger, "Got route to {}: {}", payment_params.payee_pubkey, log_route!(route));
1744 // When an adversarial intermediary node observes a payment, it may be able to infer its
1745 // destination, if the remaining CLTV expiry delta exactly matches a feasible path in the network
1746 // graph. In order to improve privacy, this method obfuscates the CLTV expiry deltas along the
1747 // payment path by adding a randomized 'shadow route' offset to the final hop.
1748 fn add_random_cltv_offset(route: &mut Route, payment_params: &PaymentParameters,
1749 network_graph: &ReadOnlyNetworkGraph, random_seed_bytes: &[u8; 32]
1751 let network_channels = network_graph.channels();
1752 let network_nodes = network_graph.nodes();
1754 for path in route.paths.iter_mut() {
1755 let mut shadow_ctlv_expiry_delta_offset: u32 = 0;
1757 // Remember the last three nodes of the random walk and avoid looping back on them.
1758 // Init with the last three nodes from the actual path, if possible.
1759 let mut nodes_to_avoid: [NodeId; 3] = [NodeId::from_pubkey(&path.last().unwrap().pubkey),
1760 NodeId::from_pubkey(&path.get(path.len().saturating_sub(2)).unwrap().pubkey),
1761 NodeId::from_pubkey(&path.get(path.len().saturating_sub(3)).unwrap().pubkey)];
1763 // Choose the last publicly known node as the starting point for the random walk.
1764 let mut cur_hop: Option<NodeId> = None;
1765 let mut path_nonce = [0u8; 12];
1766 if let Some(starting_hop) = path.iter().rev()
1767 .find(|h| network_nodes.contains_key(&NodeId::from_pubkey(&h.pubkey))) {
1768 cur_hop = Some(NodeId::from_pubkey(&starting_hop.pubkey));
1769 path_nonce.copy_from_slice(&cur_hop.unwrap().as_slice()[..12]);
1772 // Init PRNG with the path-dependant nonce, which is static for private paths.
1773 let mut prng = ChaCha20::new(random_seed_bytes, &path_nonce);
1774 let mut random_path_bytes = [0u8; ::core::mem::size_of::<usize>()];
1776 // Pick a random path length in [1 .. 3]
1777 prng.process_in_place(&mut random_path_bytes);
1778 let random_walk_length = usize::from_be_bytes(random_path_bytes).wrapping_rem(3).wrapping_add(1);
1780 for random_hop in 0..random_walk_length {
1781 // If we don't find a suitable offset in the public network graph, we default to
1782 // MEDIAN_HOP_CLTV_EXPIRY_DELTA.
1783 let mut random_hop_offset = MEDIAN_HOP_CLTV_EXPIRY_DELTA;
1785 if let Some(cur_node_id) = cur_hop {
1786 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
1787 // Randomly choose the next unvisited hop.
1788 prng.process_in_place(&mut random_path_bytes);
1789 if let Some(random_channel) = usize::from_be_bytes(random_path_bytes)
1790 .checked_rem(cur_node.channels.len())
1791 .and_then(|index| cur_node.channels.get(index))
1792 .and_then(|id| network_channels.get(id)) {
1793 random_channel.as_directed_from(&cur_node_id).map(|(dir_info, next_id)| {
1794 if !nodes_to_avoid.iter().any(|x| x == next_id) {
1795 nodes_to_avoid[random_hop] = *next_id;
1796 dir_info.direction().map(|channel_update_info| {
1797 random_hop_offset = channel_update_info.cltv_expiry_delta.into();
1798 cur_hop = Some(*next_id);
1806 shadow_ctlv_expiry_delta_offset = shadow_ctlv_expiry_delta_offset
1807 .checked_add(random_hop_offset)
1808 .unwrap_or(shadow_ctlv_expiry_delta_offset);
1811 // Limit the total offset to reduce the worst-case locked liquidity timevalue
1812 const MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET: u32 = 3*144;
1813 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET);
1815 // Limit the offset so we never exceed the max_total_cltv_expiry_delta. To improve plausibility,
1816 // we choose the limit to be the largest possible multiple of MEDIAN_HOP_CLTV_EXPIRY_DELTA.
1817 let path_total_cltv_expiry_delta: u32 = path.iter().map(|h| h.cltv_expiry_delta).sum();
1818 let mut max_path_offset = payment_params.max_total_cltv_expiry_delta - path_total_cltv_expiry_delta;
1819 max_path_offset = cmp::max(
1820 max_path_offset - (max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA),
1821 max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA);
1822 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, max_path_offset);
1824 // Add 'shadow' CLTV offset to the final hop
1825 if let Some(last_hop) = path.last_mut() {
1826 last_hop.cltv_expiry_delta = last_hop.cltv_expiry_delta
1827 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(last_hop.cltv_expiry_delta);
1832 /// Construct a route from us (payer) to the target node (payee) via the given hops (which should
1833 /// exclude the payer, but include the payee). This may be useful, e.g., for probing the chosen path.
1835 /// Re-uses logic from `find_route`, so the restrictions described there also apply here.
1836 pub fn build_route_from_hops<L: Deref, GL: Deref>(
1837 our_node_pubkey: &PublicKey, hops: &[PublicKey], route_params: &RouteParameters,
1838 network_graph: &NetworkGraph<GL>, logger: L, random_seed_bytes: &[u8; 32]
1839 ) -> Result<Route, LightningError>
1840 where L::Target: Logger, GL::Target: Logger {
1841 let graph_lock = network_graph.read_only();
1842 let mut route = build_route_from_hops_internal(
1843 our_node_pubkey, hops, &route_params.payment_params, &graph_lock,
1844 route_params.final_value_msat, route_params.final_cltv_expiry_delta, logger, random_seed_bytes)?;
1845 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
1849 fn build_route_from_hops_internal<L: Deref>(
1850 our_node_pubkey: &PublicKey, hops: &[PublicKey], payment_params: &PaymentParameters,
1851 network_graph: &ReadOnlyNetworkGraph, final_value_msat: u64, final_cltv_expiry_delta: u32,
1852 logger: L, random_seed_bytes: &[u8; 32]
1853 ) -> Result<Route, LightningError> where L::Target: Logger {
1856 our_node_id: NodeId,
1857 hop_ids: [Option<NodeId>; MAX_PATH_LENGTH_ESTIMATE as usize],
1860 impl Score for HopScorer {
1861 fn channel_penalty_msat(&self, _short_channel_id: u64, source: &NodeId, target: &NodeId,
1862 _usage: ChannelUsage) -> u64
1864 let mut cur_id = self.our_node_id;
1865 for i in 0..self.hop_ids.len() {
1866 if let Some(next_id) = self.hop_ids[i] {
1867 if cur_id == *source && next_id == *target {
1878 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
1880 fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
1882 fn probe_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
1884 fn probe_successful(&mut self, _path: &[&RouteHop]) {}
1887 impl<'a> Writeable for HopScorer {
1889 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), io::Error> {
1894 if hops.len() > MAX_PATH_LENGTH_ESTIMATE.into() {
1895 return Err(LightningError{err: "Cannot build a route exceeding the maximum path length.".to_owned(), action: ErrorAction::IgnoreError});
1898 let our_node_id = NodeId::from_pubkey(our_node_pubkey);
1899 let mut hop_ids = [None; MAX_PATH_LENGTH_ESTIMATE as usize];
1900 for i in 0..hops.len() {
1901 hop_ids[i] = Some(NodeId::from_pubkey(&hops[i]));
1904 let scorer = HopScorer { our_node_id, hop_ids };
1906 get_route(our_node_pubkey, payment_params, network_graph, None, final_value_msat,
1907 final_cltv_expiry_delta, logger, &scorer, random_seed_bytes)
1912 use routing::gossip::{NetworkGraph, P2PGossipSync, NodeId};
1913 use routing::router::{get_route, build_route_from_hops_internal, add_random_cltv_offset, default_node_features,
1914 PaymentParameters, Route, RouteHint, RouteHintHop, RouteHop, RoutingFees,
1915 DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA, MAX_PATH_LENGTH_ESTIMATE};
1916 use routing::scoring::{ChannelUsage, Score, ProbabilisticScorer, ProbabilisticScoringParameters};
1917 use chain::transaction::OutPoint;
1918 use chain::keysinterface::KeysInterface;
1919 use ln::features::{ChannelFeatures, InitFeatures, InvoiceFeatures, NodeFeatures};
1920 use ln::msgs::{ErrorAction, LightningError, OptionalField, UnsignedChannelAnnouncement, ChannelAnnouncement, RoutingMessageHandler,
1921 NodeAnnouncement, UnsignedNodeAnnouncement, ChannelUpdate, UnsignedChannelUpdate};
1922 use ln::channelmanager;
1923 use util::test_utils;
1924 use util::chacha20::ChaCha20;
1925 use util::ser::Writeable;
1927 use util::ser::Writer;
1929 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
1930 use bitcoin::hashes::Hash;
1931 use bitcoin::network::constants::Network;
1932 use bitcoin::blockdata::constants::genesis_block;
1933 use bitcoin::blockdata::script::Builder;
1934 use bitcoin::blockdata::opcodes;
1935 use bitcoin::blockdata::transaction::TxOut;
1939 use bitcoin::secp256k1::{PublicKey,SecretKey};
1940 use bitcoin::secp256k1::{Secp256k1, All};
1943 use sync::{self, Arc};
1945 fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
1946 features: InitFeatures, outbound_capacity_msat: u64) -> channelmanager::ChannelDetails {
1947 channelmanager::ChannelDetails {
1948 channel_id: [0; 32],
1949 counterparty: channelmanager::ChannelCounterparty {
1952 unspendable_punishment_reserve: 0,
1953 forwarding_info: None,
1954 outbound_htlc_minimum_msat: None,
1955 outbound_htlc_maximum_msat: None,
1957 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
1960 outbound_scid_alias: None,
1961 inbound_scid_alias: None,
1962 channel_value_satoshis: 0,
1965 outbound_capacity_msat,
1966 next_outbound_htlc_limit_msat: outbound_capacity_msat,
1967 inbound_capacity_msat: 42,
1968 unspendable_punishment_reserve: None,
1969 confirmations_required: None,
1970 force_close_spend_delay: None,
1971 is_outbound: true, is_channel_ready: true,
1972 is_usable: true, is_public: true,
1973 inbound_htlc_minimum_msat: None,
1974 inbound_htlc_maximum_msat: None,
1979 // Using the same keys for LN and BTC ids
1981 gossip_sync: &P2PGossipSync<Arc<NetworkGraph<Arc<test_utils::TestLogger>>>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1982 secp_ctx: &Secp256k1<All>, node_1_privkey: &SecretKey, node_2_privkey: &SecretKey, features: ChannelFeatures, short_channel_id: u64
1984 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1985 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1987 let unsigned_announcement = UnsignedChannelAnnouncement {
1989 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1993 bitcoin_key_1: node_id_1,
1994 bitcoin_key_2: node_id_2,
1995 excess_data: Vec::new(),
1998 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1999 let valid_announcement = ChannelAnnouncement {
2000 node_signature_1: secp_ctx.sign_ecdsa(&msghash, node_1_privkey),
2001 node_signature_2: secp_ctx.sign_ecdsa(&msghash, node_2_privkey),
2002 bitcoin_signature_1: secp_ctx.sign_ecdsa(&msghash, node_1_privkey),
2003 bitcoin_signature_2: secp_ctx.sign_ecdsa(&msghash, node_2_privkey),
2004 contents: unsigned_announcement.clone(),
2006 match gossip_sync.handle_channel_announcement(&valid_announcement) {
2007 Ok(res) => assert!(res),
2013 gossip_sync: &P2PGossipSync<Arc<NetworkGraph<Arc<test_utils::TestLogger>>>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
2014 secp_ctx: &Secp256k1<All>, node_privkey: &SecretKey, update: UnsignedChannelUpdate
2016 let msghash = hash_to_message!(&Sha256dHash::hash(&update.encode()[..])[..]);
2017 let valid_channel_update = ChannelUpdate {
2018 signature: secp_ctx.sign_ecdsa(&msghash, node_privkey),
2019 contents: update.clone()
2022 match gossip_sync.handle_channel_update(&valid_channel_update) {
2023 Ok(res) => assert!(res),
2028 fn add_or_update_node(
2029 gossip_sync: &P2PGossipSync<Arc<NetworkGraph<Arc<test_utils::TestLogger>>>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
2030 secp_ctx: &Secp256k1<All>, node_privkey: &SecretKey, features: NodeFeatures, timestamp: u32
2032 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
2033 let unsigned_announcement = UnsignedNodeAnnouncement {
2039 addresses: Vec::new(),
2040 excess_address_data: Vec::new(),
2041 excess_data: Vec::new(),
2043 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
2044 let valid_announcement = NodeAnnouncement {
2045 signature: secp_ctx.sign_ecdsa(&msghash, node_privkey),
2046 contents: unsigned_announcement.clone()
2049 match gossip_sync.handle_node_announcement(&valid_announcement) {
2055 fn get_nodes(secp_ctx: &Secp256k1<All>) -> (SecretKey, PublicKey, Vec<SecretKey>, Vec<PublicKey>) {
2056 let privkeys: Vec<SecretKey> = (2..22).map(|i| {
2057 SecretKey::from_slice(&hex::decode(format!("{:02x}", i).repeat(32)).unwrap()[..]).unwrap()
2060 let pubkeys = privkeys.iter().map(|secret| PublicKey::from_secret_key(&secp_ctx, secret)).collect();
2062 let our_privkey = SecretKey::from_slice(&hex::decode("01".repeat(32)).unwrap()[..]).unwrap();
2063 let our_id = PublicKey::from_secret_key(&secp_ctx, &our_privkey);
2065 (our_privkey, our_id, privkeys, pubkeys)
2068 fn id_to_feature_flags(id: u8) -> Vec<u8> {
2069 // Set the feature flags to the id'th odd (ie non-required) feature bit so that we can
2070 // test for it later.
2071 let idx = (id - 1) * 2 + 1;
2073 vec![1 << (idx - 8*3), 0, 0, 0]
2074 } else if idx > 8*2 {
2075 vec![1 << (idx - 8*2), 0, 0]
2076 } else if idx > 8*1 {
2077 vec![1 << (idx - 8*1), 0]
2083 fn build_line_graph() -> (
2084 Secp256k1<All>, sync::Arc<NetworkGraph<Arc<test_utils::TestLogger>>>,
2085 P2PGossipSync<sync::Arc<NetworkGraph<Arc<test_utils::TestLogger>>>, sync::Arc<test_utils::TestChainSource>, sync::Arc<test_utils::TestLogger>>,
2086 sync::Arc<test_utils::TestChainSource>, sync::Arc<test_utils::TestLogger>,
2088 let secp_ctx = Secp256k1::new();
2089 let logger = Arc::new(test_utils::TestLogger::new());
2090 let chain_monitor = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
2091 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
2092 let network_graph = Arc::new(NetworkGraph::new(genesis_hash, Arc::clone(&logger)));
2093 let gossip_sync = P2PGossipSync::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
2095 // Build network from our_id to node 19:
2096 // our_id -1(1)2- node0 -1(2)2- node1 - ... - node19
2097 let (our_privkey, _, privkeys, _) = get_nodes(&secp_ctx);
2099 for (idx, (cur_privkey, next_privkey)) in core::iter::once(&our_privkey)
2100 .chain(privkeys.iter()).zip(privkeys.iter()).enumerate() {
2101 let cur_short_channel_id = (idx as u64) + 1;
2102 add_channel(&gossip_sync, &secp_ctx, &cur_privkey, &next_privkey,
2103 ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), cur_short_channel_id);
2104 update_channel(&gossip_sync, &secp_ctx, &cur_privkey, UnsignedChannelUpdate {
2105 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2106 short_channel_id: cur_short_channel_id,
2107 timestamp: idx as u32,
2109 cltv_expiry_delta: 0,
2110 htlc_minimum_msat: 0,
2111 htlc_maximum_msat: OptionalField::Absent,
2113 fee_proportional_millionths: 0,
2114 excess_data: Vec::new()
2116 update_channel(&gossip_sync, &secp_ctx, &next_privkey, UnsignedChannelUpdate {
2117 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2118 short_channel_id: cur_short_channel_id,
2119 timestamp: (idx as u32)+1,
2121 cltv_expiry_delta: 0,
2122 htlc_minimum_msat: 0,
2123 htlc_maximum_msat: OptionalField::Absent,
2125 fee_proportional_millionths: 0,
2126 excess_data: Vec::new()
2128 add_or_update_node(&gossip_sync, &secp_ctx, next_privkey,
2129 NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
2132 (secp_ctx, network_graph, gossip_sync, chain_monitor, logger)
2135 fn build_graph() -> (
2137 sync::Arc<NetworkGraph<Arc<test_utils::TestLogger>>>,
2138 P2PGossipSync<sync::Arc<NetworkGraph<Arc<test_utils::TestLogger>>>, sync::Arc<test_utils::TestChainSource>, sync::Arc<test_utils::TestLogger>>,
2139 sync::Arc<test_utils::TestChainSource>,
2140 sync::Arc<test_utils::TestLogger>,
2142 let secp_ctx = Secp256k1::new();
2143 let logger = Arc::new(test_utils::TestLogger::new());
2144 let chain_monitor = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
2145 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
2146 let network_graph = Arc::new(NetworkGraph::new(genesis_hash, Arc::clone(&logger)));
2147 let gossip_sync = P2PGossipSync::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
2148 // Build network from our_id to node6:
2150 // -1(1)2- node0 -1(3)2-
2152 // our_id -1(12)2- node7 -1(13)2--- node2
2154 // -1(2)2- node1 -1(4)2-
2157 // chan1 1-to-2: disabled
2158 // chan1 2-to-1: enabled, 0 fee
2160 // chan2 1-to-2: enabled, ignored fee
2161 // chan2 2-to-1: enabled, 0 fee
2163 // chan3 1-to-2: enabled, 0 fee
2164 // chan3 2-to-1: enabled, 100 msat fee
2166 // chan4 1-to-2: enabled, 100% fee
2167 // chan4 2-to-1: enabled, 0 fee
2169 // chan12 1-to-2: enabled, ignored fee
2170 // chan12 2-to-1: enabled, 0 fee
2172 // chan13 1-to-2: enabled, 200% fee
2173 // chan13 2-to-1: enabled, 0 fee
2176 // -1(5)2- node3 -1(8)2--
2180 // node2--1(6)2- node4 -1(9)2--- node6 (not in global route map)
2182 // -1(7)2- node5 -1(10)2-
2184 // Channels 5, 8, 9 and 10 are private channels.
2186 // chan5 1-to-2: enabled, 100 msat fee
2187 // chan5 2-to-1: enabled, 0 fee
2189 // chan6 1-to-2: enabled, 0 fee
2190 // chan6 2-to-1: enabled, 0 fee
2192 // chan7 1-to-2: enabled, 100% fee
2193 // chan7 2-to-1: enabled, 0 fee
2195 // chan8 1-to-2: enabled, variable fee (0 then 1000 msat)
2196 // chan8 2-to-1: enabled, 0 fee
2198 // chan9 1-to-2: enabled, 1001 msat fee
2199 // chan9 2-to-1: enabled, 0 fee
2201 // chan10 1-to-2: enabled, 0 fee
2202 // chan10 2-to-1: enabled, 0 fee
2204 // chan11 1-to-2: enabled, 0 fee
2205 // chan11 2-to-1: enabled, 0 fee
2207 let (our_privkey, _, privkeys, _) = get_nodes(&secp_ctx);
2209 add_channel(&gossip_sync, &secp_ctx, &our_privkey, &privkeys[0], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
2210 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2211 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2212 short_channel_id: 1,
2215 cltv_expiry_delta: 0,
2216 htlc_minimum_msat: 0,
2217 htlc_maximum_msat: OptionalField::Absent,
2219 fee_proportional_millionths: 0,
2220 excess_data: Vec::new()
2223 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[0], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
2225 add_channel(&gossip_sync, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
2226 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2227 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2228 short_channel_id: 2,
2231 cltv_expiry_delta: (5 << 4) | 3,
2232 htlc_minimum_msat: 0,
2233 htlc_maximum_msat: OptionalField::Absent,
2234 fee_base_msat: u32::max_value(),
2235 fee_proportional_millionths: u32::max_value(),
2236 excess_data: Vec::new()
2238 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2239 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2240 short_channel_id: 2,
2243 cltv_expiry_delta: 0,
2244 htlc_minimum_msat: 0,
2245 htlc_maximum_msat: OptionalField::Absent,
2247 fee_proportional_millionths: 0,
2248 excess_data: Vec::new()
2251 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
2253 add_channel(&gossip_sync, &secp_ctx, &our_privkey, &privkeys[7], ChannelFeatures::from_le_bytes(id_to_feature_flags(12)), 12);
2254 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2255 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2256 short_channel_id: 12,
2259 cltv_expiry_delta: (5 << 4) | 3,
2260 htlc_minimum_msat: 0,
2261 htlc_maximum_msat: OptionalField::Absent,
2262 fee_base_msat: u32::max_value(),
2263 fee_proportional_millionths: u32::max_value(),
2264 excess_data: Vec::new()
2266 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2267 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2268 short_channel_id: 12,
2271 cltv_expiry_delta: 0,
2272 htlc_minimum_msat: 0,
2273 htlc_maximum_msat: OptionalField::Absent,
2275 fee_proportional_millionths: 0,
2276 excess_data: Vec::new()
2279 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[7], NodeFeatures::from_le_bytes(id_to_feature_flags(8)), 0);
2281 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
2282 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2283 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2284 short_channel_id: 3,
2287 cltv_expiry_delta: (3 << 4) | 1,
2288 htlc_minimum_msat: 0,
2289 htlc_maximum_msat: OptionalField::Absent,
2291 fee_proportional_millionths: 0,
2292 excess_data: Vec::new()
2294 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2295 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2296 short_channel_id: 3,
2299 cltv_expiry_delta: (3 << 4) | 2,
2300 htlc_minimum_msat: 0,
2301 htlc_maximum_msat: OptionalField::Absent,
2303 fee_proportional_millionths: 0,
2304 excess_data: Vec::new()
2307 add_channel(&gossip_sync, &secp_ctx, &privkeys[1], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
2308 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2309 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2310 short_channel_id: 4,
2313 cltv_expiry_delta: (4 << 4) | 1,
2314 htlc_minimum_msat: 0,
2315 htlc_maximum_msat: OptionalField::Absent,
2317 fee_proportional_millionths: 1000000,
2318 excess_data: Vec::new()
2320 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2321 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2322 short_channel_id: 4,
2325 cltv_expiry_delta: (4 << 4) | 2,
2326 htlc_minimum_msat: 0,
2327 htlc_maximum_msat: OptionalField::Absent,
2329 fee_proportional_millionths: 0,
2330 excess_data: Vec::new()
2333 add_channel(&gossip_sync, &secp_ctx, &privkeys[7], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(13)), 13);
2334 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2335 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2336 short_channel_id: 13,
2339 cltv_expiry_delta: (13 << 4) | 1,
2340 htlc_minimum_msat: 0,
2341 htlc_maximum_msat: OptionalField::Absent,
2343 fee_proportional_millionths: 2000000,
2344 excess_data: Vec::new()
2346 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2347 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2348 short_channel_id: 13,
2351 cltv_expiry_delta: (13 << 4) | 2,
2352 htlc_minimum_msat: 0,
2353 htlc_maximum_msat: OptionalField::Absent,
2355 fee_proportional_millionths: 0,
2356 excess_data: Vec::new()
2359 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
2361 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
2362 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2363 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2364 short_channel_id: 6,
2367 cltv_expiry_delta: (6 << 4) | 1,
2368 htlc_minimum_msat: 0,
2369 htlc_maximum_msat: OptionalField::Absent,
2371 fee_proportional_millionths: 0,
2372 excess_data: Vec::new()
2374 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
2375 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2376 short_channel_id: 6,
2379 cltv_expiry_delta: (6 << 4) | 2,
2380 htlc_minimum_msat: 0,
2381 htlc_maximum_msat: OptionalField::Absent,
2383 fee_proportional_millionths: 0,
2384 excess_data: Vec::new(),
2387 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(11)), 11);
2388 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
2389 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2390 short_channel_id: 11,
2393 cltv_expiry_delta: (11 << 4) | 1,
2394 htlc_minimum_msat: 0,
2395 htlc_maximum_msat: OptionalField::Absent,
2397 fee_proportional_millionths: 0,
2398 excess_data: Vec::new()
2400 update_channel(&gossip_sync, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
2401 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2402 short_channel_id: 11,
2405 cltv_expiry_delta: (11 << 4) | 2,
2406 htlc_minimum_msat: 0,
2407 htlc_maximum_msat: OptionalField::Absent,
2409 fee_proportional_millionths: 0,
2410 excess_data: Vec::new()
2413 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(5)), 0);
2415 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
2417 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[5], ChannelFeatures::from_le_bytes(id_to_feature_flags(7)), 7);
2418 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2419 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2420 short_channel_id: 7,
2423 cltv_expiry_delta: (7 << 4) | 1,
2424 htlc_minimum_msat: 0,
2425 htlc_maximum_msat: OptionalField::Absent,
2427 fee_proportional_millionths: 1000000,
2428 excess_data: Vec::new()
2430 update_channel(&gossip_sync, &secp_ctx, &privkeys[5], UnsignedChannelUpdate {
2431 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2432 short_channel_id: 7,
2435 cltv_expiry_delta: (7 << 4) | 2,
2436 htlc_minimum_msat: 0,
2437 htlc_maximum_msat: OptionalField::Absent,
2439 fee_proportional_millionths: 0,
2440 excess_data: Vec::new()
2443 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[5], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
2445 (secp_ctx, network_graph, gossip_sync, chain_monitor, logger)
2449 fn simple_route_test() {
2450 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2451 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2452 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2453 let scorer = test_utils::TestScorer::with_penalty(0);
2454 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2455 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2457 // Simple route to 2 via 1
2459 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) {
2460 assert_eq!(err, "Cannot send a payment of 0 msat");
2461 } else { panic!(); }
2463 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2464 assert_eq!(route.paths[0].len(), 2);
2466 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2467 assert_eq!(route.paths[0][0].short_channel_id, 2);
2468 assert_eq!(route.paths[0][0].fee_msat, 100);
2469 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2470 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2471 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2473 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2474 assert_eq!(route.paths[0][1].short_channel_id, 4);
2475 assert_eq!(route.paths[0][1].fee_msat, 100);
2476 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2477 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2478 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2482 fn invalid_first_hop_test() {
2483 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2484 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2485 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2486 let scorer = test_utils::TestScorer::with_penalty(0);
2487 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2488 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2490 // Simple route to 2 via 1
2492 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
2494 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) =
2495 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) {
2496 assert_eq!(err, "First hop cannot have our_node_pubkey as a destination.");
2497 } else { panic!(); }
2499 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2500 assert_eq!(route.paths[0].len(), 2);
2504 fn htlc_minimum_test() {
2505 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2506 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2507 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2508 let scorer = test_utils::TestScorer::with_penalty(0);
2509 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2510 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2512 // Simple route to 2 via 1
2514 // Disable other paths
2515 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2516 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2517 short_channel_id: 12,
2519 flags: 2, // to disable
2520 cltv_expiry_delta: 0,
2521 htlc_minimum_msat: 0,
2522 htlc_maximum_msat: OptionalField::Absent,
2524 fee_proportional_millionths: 0,
2525 excess_data: Vec::new()
2527 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2528 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2529 short_channel_id: 3,
2531 flags: 2, // to disable
2532 cltv_expiry_delta: 0,
2533 htlc_minimum_msat: 0,
2534 htlc_maximum_msat: OptionalField::Absent,
2536 fee_proportional_millionths: 0,
2537 excess_data: Vec::new()
2539 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2540 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2541 short_channel_id: 13,
2543 flags: 2, // to disable
2544 cltv_expiry_delta: 0,
2545 htlc_minimum_msat: 0,
2546 htlc_maximum_msat: OptionalField::Absent,
2548 fee_proportional_millionths: 0,
2549 excess_data: Vec::new()
2551 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2552 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2553 short_channel_id: 6,
2555 flags: 2, // to disable
2556 cltv_expiry_delta: 0,
2557 htlc_minimum_msat: 0,
2558 htlc_maximum_msat: OptionalField::Absent,
2560 fee_proportional_millionths: 0,
2561 excess_data: Vec::new()
2563 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2564 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2565 short_channel_id: 7,
2567 flags: 2, // to disable
2568 cltv_expiry_delta: 0,
2569 htlc_minimum_msat: 0,
2570 htlc_maximum_msat: OptionalField::Absent,
2572 fee_proportional_millionths: 0,
2573 excess_data: Vec::new()
2576 // Check against amount_to_transfer_over_msat.
2577 // Set minimal HTLC of 200_000_000 msat.
2578 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2579 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2580 short_channel_id: 2,
2583 cltv_expiry_delta: 0,
2584 htlc_minimum_msat: 200_000_000,
2585 htlc_maximum_msat: OptionalField::Absent,
2587 fee_proportional_millionths: 0,
2588 excess_data: Vec::new()
2591 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
2593 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2594 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2595 short_channel_id: 4,
2598 cltv_expiry_delta: 0,
2599 htlc_minimum_msat: 0,
2600 htlc_maximum_msat: OptionalField::Present(199_999_999),
2602 fee_proportional_millionths: 0,
2603 excess_data: Vec::new()
2606 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
2607 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) {
2608 assert_eq!(err, "Failed to find a path to the given destination");
2609 } else { panic!(); }
2611 // Lift the restriction on the first hop.
2612 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2613 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2614 short_channel_id: 2,
2617 cltv_expiry_delta: 0,
2618 htlc_minimum_msat: 0,
2619 htlc_maximum_msat: OptionalField::Absent,
2621 fee_proportional_millionths: 0,
2622 excess_data: Vec::new()
2625 // A payment above the minimum should pass
2626 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();
2627 assert_eq!(route.paths[0].len(), 2);
2631 fn htlc_minimum_overpay_test() {
2632 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2633 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2634 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
2635 let scorer = test_utils::TestScorer::with_penalty(0);
2636 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2637 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2639 // A route to node#2 via two paths.
2640 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
2641 // Thus, they can't send 60 without overpaying.
2642 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2643 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2644 short_channel_id: 2,
2647 cltv_expiry_delta: 0,
2648 htlc_minimum_msat: 35_000,
2649 htlc_maximum_msat: OptionalField::Present(40_000),
2651 fee_proportional_millionths: 0,
2652 excess_data: Vec::new()
2654 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2655 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2656 short_channel_id: 12,
2659 cltv_expiry_delta: 0,
2660 htlc_minimum_msat: 35_000,
2661 htlc_maximum_msat: OptionalField::Present(40_000),
2663 fee_proportional_millionths: 0,
2664 excess_data: Vec::new()
2668 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2669 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2670 short_channel_id: 13,
2673 cltv_expiry_delta: 0,
2674 htlc_minimum_msat: 0,
2675 htlc_maximum_msat: OptionalField::Absent,
2677 fee_proportional_millionths: 0,
2678 excess_data: Vec::new()
2680 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2681 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2682 short_channel_id: 4,
2685 cltv_expiry_delta: 0,
2686 htlc_minimum_msat: 0,
2687 htlc_maximum_msat: OptionalField::Absent,
2689 fee_proportional_millionths: 0,
2690 excess_data: Vec::new()
2693 // Disable other paths
2694 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2695 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2696 short_channel_id: 1,
2698 flags: 2, // to disable
2699 cltv_expiry_delta: 0,
2700 htlc_minimum_msat: 0,
2701 htlc_maximum_msat: OptionalField::Absent,
2703 fee_proportional_millionths: 0,
2704 excess_data: Vec::new()
2707 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 60_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2708 // Overpay fees to hit htlc_minimum_msat.
2709 let overpaid_fees = route.paths[0][0].fee_msat + route.paths[1][0].fee_msat;
2710 // TODO: this could be better balanced to overpay 10k and not 15k.
2711 assert_eq!(overpaid_fees, 15_000);
2713 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
2714 // while taking even more fee to match htlc_minimum_msat.
2715 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2716 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2717 short_channel_id: 12,
2720 cltv_expiry_delta: 0,
2721 htlc_minimum_msat: 65_000,
2722 htlc_maximum_msat: OptionalField::Present(80_000),
2724 fee_proportional_millionths: 0,
2725 excess_data: Vec::new()
2727 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2728 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2729 short_channel_id: 2,
2732 cltv_expiry_delta: 0,
2733 htlc_minimum_msat: 0,
2734 htlc_maximum_msat: OptionalField::Absent,
2736 fee_proportional_millionths: 0,
2737 excess_data: Vec::new()
2739 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2740 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2741 short_channel_id: 4,
2744 cltv_expiry_delta: 0,
2745 htlc_minimum_msat: 0,
2746 htlc_maximum_msat: OptionalField::Absent,
2748 fee_proportional_millionths: 100_000,
2749 excess_data: Vec::new()
2752 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 60_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2753 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
2754 assert_eq!(route.paths.len(), 1);
2755 assert_eq!(route.paths[0][0].short_channel_id, 12);
2756 let fees = route.paths[0][0].fee_msat;
2757 assert_eq!(fees, 5_000);
2759 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2760 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
2761 // the other channel.
2762 assert_eq!(route.paths.len(), 1);
2763 assert_eq!(route.paths[0][0].short_channel_id, 2);
2764 let fees = route.paths[0][0].fee_msat;
2765 assert_eq!(fees, 5_000);
2769 fn disable_channels_test() {
2770 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2771 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2772 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2773 let scorer = test_utils::TestScorer::with_penalty(0);
2774 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2775 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2777 // // Disable channels 4 and 12 by flags=2
2778 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2779 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2780 short_channel_id: 4,
2782 flags: 2, // to disable
2783 cltv_expiry_delta: 0,
2784 htlc_minimum_msat: 0,
2785 htlc_maximum_msat: OptionalField::Absent,
2787 fee_proportional_millionths: 0,
2788 excess_data: Vec::new()
2790 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2791 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2792 short_channel_id: 12,
2794 flags: 2, // to disable
2795 cltv_expiry_delta: 0,
2796 htlc_minimum_msat: 0,
2797 htlc_maximum_msat: OptionalField::Absent,
2799 fee_proportional_millionths: 0,
2800 excess_data: Vec::new()
2803 // If all the channels require some features we don't understand, route should fail
2804 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) {
2805 assert_eq!(err, "Failed to find a path to the given destination");
2806 } else { panic!(); }
2808 // If we specify a channel to node7, that overrides our local channel view and that gets used
2809 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2810 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();
2811 assert_eq!(route.paths[0].len(), 2);
2813 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2814 assert_eq!(route.paths[0][0].short_channel_id, 42);
2815 assert_eq!(route.paths[0][0].fee_msat, 200);
2816 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2817 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2818 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2820 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2821 assert_eq!(route.paths[0][1].short_channel_id, 13);
2822 assert_eq!(route.paths[0][1].fee_msat, 100);
2823 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2824 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2825 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2829 fn disable_node_test() {
2830 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2831 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2832 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2833 let scorer = test_utils::TestScorer::with_penalty(0);
2834 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2835 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2837 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
2838 let mut unknown_features = NodeFeatures::known();
2839 unknown_features.set_unknown_feature_required();
2840 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
2841 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
2842 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
2844 // If all nodes require some features we don't understand, route should fail
2845 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) {
2846 assert_eq!(err, "Failed to find a path to the given destination");
2847 } else { panic!(); }
2849 // If we specify a channel to node7, that overrides our local channel view and that gets used
2850 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2851 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();
2852 assert_eq!(route.paths[0].len(), 2);
2854 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2855 assert_eq!(route.paths[0][0].short_channel_id, 42);
2856 assert_eq!(route.paths[0][0].fee_msat, 200);
2857 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2858 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2859 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2861 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2862 assert_eq!(route.paths[0][1].short_channel_id, 13);
2863 assert_eq!(route.paths[0][1].fee_msat, 100);
2864 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2865 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2866 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2868 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
2869 // naively) assume that the user checked the feature bits on the invoice, which override
2870 // the node_announcement.
2874 fn our_chans_test() {
2875 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2876 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2877 let scorer = test_utils::TestScorer::with_penalty(0);
2878 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2879 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2881 // Route to 1 via 2 and 3 because our channel to 1 is disabled
2882 let payment_params = PaymentParameters::from_node_id(nodes[0]);
2883 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2884 assert_eq!(route.paths[0].len(), 3);
2886 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2887 assert_eq!(route.paths[0][0].short_channel_id, 2);
2888 assert_eq!(route.paths[0][0].fee_msat, 200);
2889 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2890 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2891 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2893 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2894 assert_eq!(route.paths[0][1].short_channel_id, 4);
2895 assert_eq!(route.paths[0][1].fee_msat, 100);
2896 assert_eq!(route.paths[0][1].cltv_expiry_delta, (3 << 4) | 2);
2897 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2898 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2900 assert_eq!(route.paths[0][2].pubkey, nodes[0]);
2901 assert_eq!(route.paths[0][2].short_channel_id, 3);
2902 assert_eq!(route.paths[0][2].fee_msat, 100);
2903 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
2904 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(1));
2905 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(3));
2907 // If we specify a channel to node7, that overrides our local channel view and that gets used
2908 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2909 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2910 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();
2911 assert_eq!(route.paths[0].len(), 2);
2913 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2914 assert_eq!(route.paths[0][0].short_channel_id, 42);
2915 assert_eq!(route.paths[0][0].fee_msat, 200);
2916 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2917 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2918 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2920 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2921 assert_eq!(route.paths[0][1].short_channel_id, 13);
2922 assert_eq!(route.paths[0][1].fee_msat, 100);
2923 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2924 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2925 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2928 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2929 let zero_fees = RoutingFees {
2931 proportional_millionths: 0,
2933 vec![RouteHint(vec![RouteHintHop {
2934 src_node_id: nodes[3],
2935 short_channel_id: 8,
2937 cltv_expiry_delta: (8 << 4) | 1,
2938 htlc_minimum_msat: None,
2939 htlc_maximum_msat: None,
2941 ]), RouteHint(vec![RouteHintHop {
2942 src_node_id: nodes[4],
2943 short_channel_id: 9,
2946 proportional_millionths: 0,
2948 cltv_expiry_delta: (9 << 4) | 1,
2949 htlc_minimum_msat: None,
2950 htlc_maximum_msat: None,
2951 }]), RouteHint(vec![RouteHintHop {
2952 src_node_id: nodes[5],
2953 short_channel_id: 10,
2955 cltv_expiry_delta: (10 << 4) | 1,
2956 htlc_minimum_msat: None,
2957 htlc_maximum_msat: None,
2961 fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2962 let zero_fees = RoutingFees {
2964 proportional_millionths: 0,
2966 vec![RouteHint(vec![RouteHintHop {
2967 src_node_id: nodes[2],
2968 short_channel_id: 5,
2971 proportional_millionths: 0,
2973 cltv_expiry_delta: (5 << 4) | 1,
2974 htlc_minimum_msat: None,
2975 htlc_maximum_msat: None,
2977 src_node_id: nodes[3],
2978 short_channel_id: 8,
2980 cltv_expiry_delta: (8 << 4) | 1,
2981 htlc_minimum_msat: None,
2982 htlc_maximum_msat: None,
2984 ]), RouteHint(vec![RouteHintHop {
2985 src_node_id: nodes[4],
2986 short_channel_id: 9,
2989 proportional_millionths: 0,
2991 cltv_expiry_delta: (9 << 4) | 1,
2992 htlc_minimum_msat: None,
2993 htlc_maximum_msat: None,
2994 }]), RouteHint(vec![RouteHintHop {
2995 src_node_id: nodes[5],
2996 short_channel_id: 10,
2998 cltv_expiry_delta: (10 << 4) | 1,
2999 htlc_minimum_msat: None,
3000 htlc_maximum_msat: None,
3005 fn partial_route_hint_test() {
3006 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3007 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3008 let scorer = test_utils::TestScorer::with_penalty(0);
3009 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3010 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3012 // Simple test across 2, 3, 5, and 4 via a last_hop channel
3013 // Tests the behaviour when the RouteHint contains a suboptimal hop.
3014 // RouteHint may be partially used by the algo to build the best path.
3016 // First check that last hop can't have its source as the payee.
3017 let invalid_last_hop = RouteHint(vec![RouteHintHop {
3018 src_node_id: nodes[6],
3019 short_channel_id: 8,
3022 proportional_millionths: 0,
3024 cltv_expiry_delta: (8 << 4) | 1,
3025 htlc_minimum_msat: None,
3026 htlc_maximum_msat: None,
3029 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
3030 invalid_last_hops.push(invalid_last_hop);
3032 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(invalid_last_hops);
3033 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) {
3034 assert_eq!(err, "Route hint cannot have the payee as the source.");
3035 } else { panic!(); }
3038 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops_multi_private_channels(&nodes));
3039 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3040 assert_eq!(route.paths[0].len(), 5);
3042 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3043 assert_eq!(route.paths[0][0].short_channel_id, 2);
3044 assert_eq!(route.paths[0][0].fee_msat, 100);
3045 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
3046 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3047 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3049 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3050 assert_eq!(route.paths[0][1].short_channel_id, 4);
3051 assert_eq!(route.paths[0][1].fee_msat, 0);
3052 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
3053 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3054 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3056 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
3057 assert_eq!(route.paths[0][2].short_channel_id, 6);
3058 assert_eq!(route.paths[0][2].fee_msat, 0);
3059 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
3060 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
3061 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
3063 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
3064 assert_eq!(route.paths[0][3].short_channel_id, 11);
3065 assert_eq!(route.paths[0][3].fee_msat, 0);
3066 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
3067 // If we have a peer in the node map, we'll use their features here since we don't have
3068 // a way of figuring out their features from the invoice:
3069 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
3070 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
3072 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
3073 assert_eq!(route.paths[0][4].short_channel_id, 8);
3074 assert_eq!(route.paths[0][4].fee_msat, 100);
3075 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
3076 assert_eq!(route.paths[0][4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3077 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3080 fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3081 let zero_fees = RoutingFees {
3083 proportional_millionths: 0,
3085 vec![RouteHint(vec![RouteHintHop {
3086 src_node_id: nodes[3],
3087 short_channel_id: 8,
3089 cltv_expiry_delta: (8 << 4) | 1,
3090 htlc_minimum_msat: None,
3091 htlc_maximum_msat: None,
3092 }]), RouteHint(vec![
3094 ]), RouteHint(vec![RouteHintHop {
3095 src_node_id: nodes[5],
3096 short_channel_id: 10,
3098 cltv_expiry_delta: (10 << 4) | 1,
3099 htlc_minimum_msat: None,
3100 htlc_maximum_msat: None,
3105 fn ignores_empty_last_hops_test() {
3106 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3107 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3108 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(empty_last_hop(&nodes));
3109 let scorer = test_utils::TestScorer::with_penalty(0);
3110 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3111 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3113 // Test handling of an empty RouteHint passed in Invoice.
3115 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3116 assert_eq!(route.paths[0].len(), 5);
3118 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3119 assert_eq!(route.paths[0][0].short_channel_id, 2);
3120 assert_eq!(route.paths[0][0].fee_msat, 100);
3121 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
3122 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3123 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3125 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3126 assert_eq!(route.paths[0][1].short_channel_id, 4);
3127 assert_eq!(route.paths[0][1].fee_msat, 0);
3128 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
3129 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3130 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3132 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
3133 assert_eq!(route.paths[0][2].short_channel_id, 6);
3134 assert_eq!(route.paths[0][2].fee_msat, 0);
3135 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
3136 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
3137 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
3139 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
3140 assert_eq!(route.paths[0][3].short_channel_id, 11);
3141 assert_eq!(route.paths[0][3].fee_msat, 0);
3142 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
3143 // If we have a peer in the node map, we'll use their features here since we don't have
3144 // a way of figuring out their features from the invoice:
3145 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
3146 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
3148 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
3149 assert_eq!(route.paths[0][4].short_channel_id, 8);
3150 assert_eq!(route.paths[0][4].fee_msat, 100);
3151 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
3152 assert_eq!(route.paths[0][4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3153 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3156 /// Builds a trivial last-hop hint that passes through the two nodes given, with channel 0xff00
3158 fn multi_hop_last_hops_hint(hint_hops: [PublicKey; 2]) -> Vec<RouteHint> {
3159 let zero_fees = RoutingFees {
3161 proportional_millionths: 0,
3163 vec![RouteHint(vec![RouteHintHop {
3164 src_node_id: hint_hops[0],
3165 short_channel_id: 0xff00,
3168 proportional_millionths: 0,
3170 cltv_expiry_delta: (5 << 4) | 1,
3171 htlc_minimum_msat: None,
3172 htlc_maximum_msat: None,
3174 src_node_id: hint_hops[1],
3175 short_channel_id: 0xff01,
3177 cltv_expiry_delta: (8 << 4) | 1,
3178 htlc_minimum_msat: None,
3179 htlc_maximum_msat: None,
3184 fn multi_hint_last_hops_test() {
3185 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3186 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3187 let last_hops = multi_hop_last_hops_hint([nodes[2], nodes[3]]);
3188 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops.clone());
3189 let scorer = test_utils::TestScorer::with_penalty(0);
3190 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3191 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3192 // Test through channels 2, 3, 0xff00, 0xff01.
3193 // Test shows that multiple hop hints are considered.
3195 // Disabling channels 6 & 7 by flags=2
3196 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3197 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3198 short_channel_id: 6,
3200 flags: 2, // to disable
3201 cltv_expiry_delta: 0,
3202 htlc_minimum_msat: 0,
3203 htlc_maximum_msat: OptionalField::Absent,
3205 fee_proportional_millionths: 0,
3206 excess_data: Vec::new()
3208 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3209 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3210 short_channel_id: 7,
3212 flags: 2, // to disable
3213 cltv_expiry_delta: 0,
3214 htlc_minimum_msat: 0,
3215 htlc_maximum_msat: OptionalField::Absent,
3217 fee_proportional_millionths: 0,
3218 excess_data: Vec::new()
3221 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3222 assert_eq!(route.paths[0].len(), 4);
3224 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3225 assert_eq!(route.paths[0][0].short_channel_id, 2);
3226 assert_eq!(route.paths[0][0].fee_msat, 200);
3227 assert_eq!(route.paths[0][0].cltv_expiry_delta, 65);
3228 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3229 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3231 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3232 assert_eq!(route.paths[0][1].short_channel_id, 4);
3233 assert_eq!(route.paths[0][1].fee_msat, 100);
3234 assert_eq!(route.paths[0][1].cltv_expiry_delta, 81);
3235 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3236 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3238 assert_eq!(route.paths[0][2].pubkey, nodes[3]);
3239 assert_eq!(route.paths[0][2].short_channel_id, last_hops[0].0[0].short_channel_id);
3240 assert_eq!(route.paths[0][2].fee_msat, 0);
3241 assert_eq!(route.paths[0][2].cltv_expiry_delta, 129);
3242 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(4));
3243 assert_eq!(route.paths[0][2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3245 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
3246 assert_eq!(route.paths[0][3].short_channel_id, last_hops[0].0[1].short_channel_id);
3247 assert_eq!(route.paths[0][3].fee_msat, 100);
3248 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
3249 assert_eq!(route.paths[0][3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3250 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3254 fn private_multi_hint_last_hops_test() {
3255 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3256 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3258 let non_announced_privkey = SecretKey::from_slice(&hex::decode(format!("{:02x}", 0xf0).repeat(32)).unwrap()[..]).unwrap();
3259 let non_announced_pubkey = PublicKey::from_secret_key(&secp_ctx, &non_announced_privkey);
3261 let last_hops = multi_hop_last_hops_hint([nodes[2], non_announced_pubkey]);
3262 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops.clone());
3263 let scorer = test_utils::TestScorer::with_penalty(0);
3264 // Test through channels 2, 3, 0xff00, 0xff01.
3265 // Test shows that multiple hop hints are considered.
3267 // Disabling channels 6 & 7 by flags=2
3268 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3269 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3270 short_channel_id: 6,
3272 flags: 2, // to disable
3273 cltv_expiry_delta: 0,
3274 htlc_minimum_msat: 0,
3275 htlc_maximum_msat: OptionalField::Absent,
3277 fee_proportional_millionths: 0,
3278 excess_data: Vec::new()
3280 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3281 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3282 short_channel_id: 7,
3284 flags: 2, // to disable
3285 cltv_expiry_delta: 0,
3286 htlc_minimum_msat: 0,
3287 htlc_maximum_msat: OptionalField::Absent,
3289 fee_proportional_millionths: 0,
3290 excess_data: Vec::new()
3293 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &[42u8; 32]).unwrap();
3294 assert_eq!(route.paths[0].len(), 4);
3296 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3297 assert_eq!(route.paths[0][0].short_channel_id, 2);
3298 assert_eq!(route.paths[0][0].fee_msat, 200);
3299 assert_eq!(route.paths[0][0].cltv_expiry_delta, 65);
3300 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3301 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3303 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3304 assert_eq!(route.paths[0][1].short_channel_id, 4);
3305 assert_eq!(route.paths[0][1].fee_msat, 100);
3306 assert_eq!(route.paths[0][1].cltv_expiry_delta, 81);
3307 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3308 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3310 assert_eq!(route.paths[0][2].pubkey, non_announced_pubkey);
3311 assert_eq!(route.paths[0][2].short_channel_id, last_hops[0].0[0].short_channel_id);
3312 assert_eq!(route.paths[0][2].fee_msat, 0);
3313 assert_eq!(route.paths[0][2].cltv_expiry_delta, 129);
3314 assert_eq!(route.paths[0][2].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3315 assert_eq!(route.paths[0][2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3317 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
3318 assert_eq!(route.paths[0][3].short_channel_id, last_hops[0].0[1].short_channel_id);
3319 assert_eq!(route.paths[0][3].fee_msat, 100);
3320 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
3321 assert_eq!(route.paths[0][3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3322 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3325 fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3326 let zero_fees = RoutingFees {
3328 proportional_millionths: 0,
3330 vec![RouteHint(vec![RouteHintHop {
3331 src_node_id: nodes[4],
3332 short_channel_id: 11,
3334 cltv_expiry_delta: (11 << 4) | 1,
3335 htlc_minimum_msat: None,
3336 htlc_maximum_msat: None,
3338 src_node_id: nodes[3],
3339 short_channel_id: 8,
3341 cltv_expiry_delta: (8 << 4) | 1,
3342 htlc_minimum_msat: None,
3343 htlc_maximum_msat: None,
3344 }]), RouteHint(vec![RouteHintHop {
3345 src_node_id: nodes[4],
3346 short_channel_id: 9,
3349 proportional_millionths: 0,
3351 cltv_expiry_delta: (9 << 4) | 1,
3352 htlc_minimum_msat: None,
3353 htlc_maximum_msat: None,
3354 }]), RouteHint(vec![RouteHintHop {
3355 src_node_id: nodes[5],
3356 short_channel_id: 10,
3358 cltv_expiry_delta: (10 << 4) | 1,
3359 htlc_minimum_msat: None,
3360 htlc_maximum_msat: None,
3365 fn last_hops_with_public_channel_test() {
3366 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3367 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3368 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops_with_public_channel(&nodes));
3369 let scorer = test_utils::TestScorer::with_penalty(0);
3370 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3371 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3372 // This test shows that public routes can be present in the invoice
3373 // which would be handled in the same manner.
3375 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3376 assert_eq!(route.paths[0].len(), 5);
3378 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3379 assert_eq!(route.paths[0][0].short_channel_id, 2);
3380 assert_eq!(route.paths[0][0].fee_msat, 100);
3381 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
3382 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3383 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3385 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3386 assert_eq!(route.paths[0][1].short_channel_id, 4);
3387 assert_eq!(route.paths[0][1].fee_msat, 0);
3388 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
3389 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3390 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3392 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
3393 assert_eq!(route.paths[0][2].short_channel_id, 6);
3394 assert_eq!(route.paths[0][2].fee_msat, 0);
3395 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
3396 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
3397 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
3399 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
3400 assert_eq!(route.paths[0][3].short_channel_id, 11);
3401 assert_eq!(route.paths[0][3].fee_msat, 0);
3402 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
3403 // If we have a peer in the node map, we'll use their features here since we don't have
3404 // a way of figuring out their features from the invoice:
3405 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
3406 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
3408 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
3409 assert_eq!(route.paths[0][4].short_channel_id, 8);
3410 assert_eq!(route.paths[0][4].fee_msat, 100);
3411 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
3412 assert_eq!(route.paths[0][4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3413 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3417 fn our_chans_last_hop_connect_test() {
3418 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3419 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3420 let scorer = test_utils::TestScorer::with_penalty(0);
3421 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3422 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3424 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
3425 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3426 let mut last_hops = last_hops(&nodes);
3427 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops.clone());
3428 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();
3429 assert_eq!(route.paths[0].len(), 2);
3431 assert_eq!(route.paths[0][0].pubkey, nodes[3]);
3432 assert_eq!(route.paths[0][0].short_channel_id, 42);
3433 assert_eq!(route.paths[0][0].fee_msat, 0);
3434 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 4) | 1);
3435 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
3436 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3438 assert_eq!(route.paths[0][1].pubkey, nodes[6]);
3439 assert_eq!(route.paths[0][1].short_channel_id, 8);
3440 assert_eq!(route.paths[0][1].fee_msat, 100);
3441 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
3442 assert_eq!(route.paths[0][1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3443 assert_eq!(route.paths[0][1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3445 last_hops[0].0[0].fees.base_msat = 1000;
3447 // Revert to via 6 as the fee on 8 goes up
3448 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops);
3449 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3450 assert_eq!(route.paths[0].len(), 4);
3452 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3453 assert_eq!(route.paths[0][0].short_channel_id, 2);
3454 assert_eq!(route.paths[0][0].fee_msat, 200); // fee increased as its % of value transferred across node
3455 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
3456 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3457 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3459 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3460 assert_eq!(route.paths[0][1].short_channel_id, 4);
3461 assert_eq!(route.paths[0][1].fee_msat, 100);
3462 assert_eq!(route.paths[0][1].cltv_expiry_delta, (7 << 4) | 1);
3463 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3464 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3466 assert_eq!(route.paths[0][2].pubkey, nodes[5]);
3467 assert_eq!(route.paths[0][2].short_channel_id, 7);
3468 assert_eq!(route.paths[0][2].fee_msat, 0);
3469 assert_eq!(route.paths[0][2].cltv_expiry_delta, (10 << 4) | 1);
3470 // If we have a peer in the node map, we'll use their features here since we don't have
3471 // a way of figuring out their features from the invoice:
3472 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
3473 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(7));
3475 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
3476 assert_eq!(route.paths[0][3].short_channel_id, 10);
3477 assert_eq!(route.paths[0][3].fee_msat, 100);
3478 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
3479 assert_eq!(route.paths[0][3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3480 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3482 // ...but still use 8 for larger payments as 6 has a variable feerate
3483 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 2000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3484 assert_eq!(route.paths[0].len(), 5);
3486 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3487 assert_eq!(route.paths[0][0].short_channel_id, 2);
3488 assert_eq!(route.paths[0][0].fee_msat, 3000);
3489 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
3490 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3491 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3493 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3494 assert_eq!(route.paths[0][1].short_channel_id, 4);
3495 assert_eq!(route.paths[0][1].fee_msat, 0);
3496 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
3497 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3498 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3500 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
3501 assert_eq!(route.paths[0][2].short_channel_id, 6);
3502 assert_eq!(route.paths[0][2].fee_msat, 0);
3503 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
3504 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
3505 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
3507 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
3508 assert_eq!(route.paths[0][3].short_channel_id, 11);
3509 assert_eq!(route.paths[0][3].fee_msat, 1000);
3510 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
3511 // If we have a peer in the node map, we'll use their features here since we don't have
3512 // a way of figuring out their features from the invoice:
3513 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
3514 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
3516 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
3517 assert_eq!(route.paths[0][4].short_channel_id, 8);
3518 assert_eq!(route.paths[0][4].fee_msat, 2000);
3519 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
3520 assert_eq!(route.paths[0][4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3521 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3524 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> {
3525 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
3526 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3527 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3529 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
3530 let last_hops = RouteHint(vec![RouteHintHop {
3531 src_node_id: middle_node_id,
3532 short_channel_id: 8,
3535 proportional_millionths: last_hop_fee_prop,
3537 cltv_expiry_delta: (8 << 4) | 1,
3538 htlc_minimum_msat: None,
3539 htlc_maximum_msat: last_hop_htlc_max,
3541 let payment_params = PaymentParameters::from_node_id(target_node_id).with_route_hints(vec![last_hops]);
3542 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
3543 let scorer = test_utils::TestScorer::with_penalty(0);
3544 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3545 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3546 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
3547 let logger = test_utils::TestLogger::new();
3548 let network_graph = NetworkGraph::new(genesis_hash, &logger);
3549 let route = get_route(&source_node_id, &payment_params, &network_graph.read_only(),
3550 Some(&our_chans.iter().collect::<Vec<_>>()), route_val, 42, &logger, &scorer, &random_seed_bytes);
3555 fn unannounced_path_test() {
3556 // We should be able to send a payment to a destination without any help of a routing graph
3557 // if we have a channel with a common counterparty that appears in the first and last hop
3559 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
3561 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3562 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3563 assert_eq!(route.paths[0].len(), 2);
3565 assert_eq!(route.paths[0][0].pubkey, middle_node_id);
3566 assert_eq!(route.paths[0][0].short_channel_id, 42);
3567 assert_eq!(route.paths[0][0].fee_msat, 1001);
3568 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 4) | 1);
3569 assert_eq!(route.paths[0][0].node_features.le_flags(), &[0b11]);
3570 assert_eq!(route.paths[0][0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3572 assert_eq!(route.paths[0][1].pubkey, target_node_id);
3573 assert_eq!(route.paths[0][1].short_channel_id, 8);
3574 assert_eq!(route.paths[0][1].fee_msat, 1000000);
3575 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
3576 assert_eq!(route.paths[0][1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3577 assert_eq!(route.paths[0][1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3581 fn overflow_unannounced_path_test_liquidity_underflow() {
3582 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
3583 // the last-hop had a fee which overflowed a u64, we'd panic.
3584 // This was due to us adding the first-hop from us unconditionally, causing us to think
3585 // we'd built a path (as our node is in the "best candidate" set), when we had not.
3586 // In this test, we previously hit a subtraction underflow due to having less available
3587 // liquidity at the last hop than 0.
3588 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());
3592 fn overflow_unannounced_path_test_feerate_overflow() {
3593 // This tests for the same case as above, except instead of hitting a subtraction
3594 // underflow, we hit a case where the fee charged at a hop overflowed.
3595 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());
3599 fn available_amount_while_routing_test() {
3600 // Tests whether we choose the correct available channel amount while routing.
3602 let (secp_ctx, network_graph, mut gossip_sync, chain_monitor, logger) = build_graph();
3603 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3604 let scorer = test_utils::TestScorer::with_penalty(0);
3605 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3606 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3607 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
3609 // We will use a simple single-path route from
3610 // our node to node2 via node0: channels {1, 3}.
3612 // First disable all other paths.
3613 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3614 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3615 short_channel_id: 2,
3618 cltv_expiry_delta: 0,
3619 htlc_minimum_msat: 0,
3620 htlc_maximum_msat: OptionalField::Present(100_000),
3622 fee_proportional_millionths: 0,
3623 excess_data: Vec::new()
3625 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3626 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3627 short_channel_id: 12,
3630 cltv_expiry_delta: 0,
3631 htlc_minimum_msat: 0,
3632 htlc_maximum_msat: OptionalField::Present(100_000),
3634 fee_proportional_millionths: 0,
3635 excess_data: Vec::new()
3638 // Make the first channel (#1) very permissive,
3639 // and we will be testing all limits on the second channel.
3640 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3641 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3642 short_channel_id: 1,
3645 cltv_expiry_delta: 0,
3646 htlc_minimum_msat: 0,
3647 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3649 fee_proportional_millionths: 0,
3650 excess_data: Vec::new()
3653 // First, let's see if routing works if we have absolutely no idea about the available amount.
3654 // In this case, it should be set to 250_000 sats.
3655 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3656 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3657 short_channel_id: 3,
3660 cltv_expiry_delta: 0,
3661 htlc_minimum_msat: 0,
3662 htlc_maximum_msat: OptionalField::Absent,
3664 fee_proportional_millionths: 0,
3665 excess_data: Vec::new()
3669 // Attempt to route more than available results in a failure.
3670 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3671 &our_id, &payment_params, &network_graph.read_only(), None, 250_000_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3672 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3673 } else { panic!(); }
3677 // Now, attempt to route an exact amount we have should be fine.
3678 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();
3679 assert_eq!(route.paths.len(), 1);
3680 let path = route.paths.last().unwrap();
3681 assert_eq!(path.len(), 2);
3682 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3683 assert_eq!(path.last().unwrap().fee_msat, 250_000_000);
3686 // Check that setting next_outbound_htlc_limit_msat in first_hops limits the channels.
3687 // Disable channel #1 and use another first hop.
3688 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3689 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3690 short_channel_id: 1,
3693 cltv_expiry_delta: 0,
3694 htlc_minimum_msat: 0,
3695 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3697 fee_proportional_millionths: 0,
3698 excess_data: Vec::new()
3701 // Now, limit the first_hop by the next_outbound_htlc_limit_msat of 200_000 sats.
3702 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
3705 // Attempt to route more than available results in a failure.
3706 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3707 &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) {
3708 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3709 } else { panic!(); }
3713 // Now, attempt to route an exact amount we have should be fine.
3714 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();
3715 assert_eq!(route.paths.len(), 1);
3716 let path = route.paths.last().unwrap();
3717 assert_eq!(path.len(), 2);
3718 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3719 assert_eq!(path.last().unwrap().fee_msat, 200_000_000);
3722 // Enable channel #1 back.
3723 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3724 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3725 short_channel_id: 1,
3728 cltv_expiry_delta: 0,
3729 htlc_minimum_msat: 0,
3730 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3732 fee_proportional_millionths: 0,
3733 excess_data: Vec::new()
3737 // Now let's see if routing works if we know only htlc_maximum_msat.
3738 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3739 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3740 short_channel_id: 3,
3743 cltv_expiry_delta: 0,
3744 htlc_minimum_msat: 0,
3745 htlc_maximum_msat: OptionalField::Present(15_000),
3747 fee_proportional_millionths: 0,
3748 excess_data: Vec::new()
3752 // Attempt to route more than available results in a failure.
3753 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3754 &our_id, &payment_params, &network_graph.read_only(), None, 15_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3755 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3756 } else { panic!(); }
3760 // Now, attempt to route an exact amount we have should be fine.
3761 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 15_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3762 assert_eq!(route.paths.len(), 1);
3763 let path = route.paths.last().unwrap();
3764 assert_eq!(path.len(), 2);
3765 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3766 assert_eq!(path.last().unwrap().fee_msat, 15_000);
3769 // Now let's see if routing works if we know only capacity from the UTXO.
3771 // We can't change UTXO capacity on the fly, so we'll disable
3772 // the existing channel and add another one with the capacity we need.
3773 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3774 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3775 short_channel_id: 3,
3778 cltv_expiry_delta: 0,
3779 htlc_minimum_msat: 0,
3780 htlc_maximum_msat: OptionalField::Absent,
3782 fee_proportional_millionths: 0,
3783 excess_data: Vec::new()
3786 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
3787 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
3788 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
3789 .push_opcode(opcodes::all::OP_PUSHNUM_2)
3790 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
3792 *chain_monitor.utxo_ret.lock().unwrap() = Ok(TxOut { value: 15, script_pubkey: good_script.clone() });
3793 gossip_sync.add_chain_access(Some(chain_monitor));
3795 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
3796 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3797 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3798 short_channel_id: 333,
3801 cltv_expiry_delta: (3 << 4) | 1,
3802 htlc_minimum_msat: 0,
3803 htlc_maximum_msat: OptionalField::Absent,
3805 fee_proportional_millionths: 0,
3806 excess_data: Vec::new()
3808 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3809 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3810 short_channel_id: 333,
3813 cltv_expiry_delta: (3 << 4) | 2,
3814 htlc_minimum_msat: 0,
3815 htlc_maximum_msat: OptionalField::Absent,
3817 fee_proportional_millionths: 0,
3818 excess_data: Vec::new()
3822 // Attempt to route more than available results in a failure.
3823 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3824 &our_id, &payment_params, &network_graph.read_only(), None, 15_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3825 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3826 } else { panic!(); }
3830 // Now, attempt to route an exact amount we have should be fine.
3831 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 15_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3832 assert_eq!(route.paths.len(), 1);
3833 let path = route.paths.last().unwrap();
3834 assert_eq!(path.len(), 2);
3835 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3836 assert_eq!(path.last().unwrap().fee_msat, 15_000);
3839 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
3840 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3841 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3842 short_channel_id: 333,
3845 cltv_expiry_delta: 0,
3846 htlc_minimum_msat: 0,
3847 htlc_maximum_msat: OptionalField::Present(10_000),
3849 fee_proportional_millionths: 0,
3850 excess_data: Vec::new()
3854 // Attempt to route more than available results in a failure.
3855 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3856 &our_id, &payment_params, &network_graph.read_only(), None, 10_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3857 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3858 } else { panic!(); }
3862 // Now, attempt to route an exact amount we have should be fine.
3863 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 10_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3864 assert_eq!(route.paths.len(), 1);
3865 let path = route.paths.last().unwrap();
3866 assert_eq!(path.len(), 2);
3867 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3868 assert_eq!(path.last().unwrap().fee_msat, 10_000);
3873 fn available_liquidity_last_hop_test() {
3874 // Check that available liquidity properly limits the path even when only
3875 // one of the latter hops is limited.
3876 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3877 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3878 let scorer = test_utils::TestScorer::with_penalty(0);
3879 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3880 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3881 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
3883 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3884 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
3885 // Total capacity: 50 sats.
3887 // Disable other potential paths.
3888 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3889 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3890 short_channel_id: 2,
3893 cltv_expiry_delta: 0,
3894 htlc_minimum_msat: 0,
3895 htlc_maximum_msat: OptionalField::Present(100_000),
3897 fee_proportional_millionths: 0,
3898 excess_data: Vec::new()
3900 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3901 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3902 short_channel_id: 7,
3905 cltv_expiry_delta: 0,
3906 htlc_minimum_msat: 0,
3907 htlc_maximum_msat: OptionalField::Present(100_000),
3909 fee_proportional_millionths: 0,
3910 excess_data: Vec::new()
3915 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3916 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3917 short_channel_id: 12,
3920 cltv_expiry_delta: 0,
3921 htlc_minimum_msat: 0,
3922 htlc_maximum_msat: OptionalField::Present(100_000),
3924 fee_proportional_millionths: 0,
3925 excess_data: Vec::new()
3927 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3928 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3929 short_channel_id: 13,
3932 cltv_expiry_delta: 0,
3933 htlc_minimum_msat: 0,
3934 htlc_maximum_msat: OptionalField::Present(100_000),
3936 fee_proportional_millionths: 0,
3937 excess_data: Vec::new()
3940 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3941 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3942 short_channel_id: 6,
3945 cltv_expiry_delta: 0,
3946 htlc_minimum_msat: 0,
3947 htlc_maximum_msat: OptionalField::Present(50_000),
3949 fee_proportional_millionths: 0,
3950 excess_data: Vec::new()
3952 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3953 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3954 short_channel_id: 11,
3957 cltv_expiry_delta: 0,
3958 htlc_minimum_msat: 0,
3959 htlc_maximum_msat: OptionalField::Present(100_000),
3961 fee_proportional_millionths: 0,
3962 excess_data: Vec::new()
3965 // Attempt to route more than available results in a failure.
3966 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3967 &our_id, &payment_params, &network_graph.read_only(), None, 60_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3968 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3969 } else { panic!(); }
3973 // Now, attempt to route 49 sats (just a bit below the capacity).
3974 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 49_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3975 assert_eq!(route.paths.len(), 1);
3976 let mut total_amount_paid_msat = 0;
3977 for path in &route.paths {
3978 assert_eq!(path.len(), 4);
3979 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3980 total_amount_paid_msat += path.last().unwrap().fee_msat;
3982 assert_eq!(total_amount_paid_msat, 49_000);
3986 // Attempt to route an exact amount is also fine
3987 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3988 assert_eq!(route.paths.len(), 1);
3989 let mut total_amount_paid_msat = 0;
3990 for path in &route.paths {
3991 assert_eq!(path.len(), 4);
3992 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3993 total_amount_paid_msat += path.last().unwrap().fee_msat;
3995 assert_eq!(total_amount_paid_msat, 50_000);
4000 fn ignore_fee_first_hop_test() {
4001 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4002 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4003 let scorer = test_utils::TestScorer::with_penalty(0);
4004 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4005 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4006 let payment_params = PaymentParameters::from_node_id(nodes[2]);
4008 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
4009 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4010 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4011 short_channel_id: 1,
4014 cltv_expiry_delta: 0,
4015 htlc_minimum_msat: 0,
4016 htlc_maximum_msat: OptionalField::Present(100_000),
4017 fee_base_msat: 1_000_000,
4018 fee_proportional_millionths: 0,
4019 excess_data: Vec::new()
4021 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4022 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4023 short_channel_id: 3,
4026 cltv_expiry_delta: 0,
4027 htlc_minimum_msat: 0,
4028 htlc_maximum_msat: OptionalField::Present(50_000),
4030 fee_proportional_millionths: 0,
4031 excess_data: Vec::new()
4035 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4036 assert_eq!(route.paths.len(), 1);
4037 let mut total_amount_paid_msat = 0;
4038 for path in &route.paths {
4039 assert_eq!(path.len(), 2);
4040 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4041 total_amount_paid_msat += path.last().unwrap().fee_msat;
4043 assert_eq!(total_amount_paid_msat, 50_000);
4048 fn simple_mpp_route_test() {
4049 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4050 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4051 let scorer = test_utils::TestScorer::with_penalty(0);
4052 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4053 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4054 let payment_params = PaymentParameters::from_node_id(nodes[2])
4055 .with_features(InvoiceFeatures::known());
4057 // We need a route consisting of 3 paths:
4058 // From our node to node2 via node0, node7, node1 (three paths one hop each).
4059 // To achieve this, the amount being transferred should be around
4060 // the total capacity of these 3 paths.
4062 // First, we set limits on these (previously unlimited) channels.
4063 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
4065 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
4066 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4067 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4068 short_channel_id: 1,
4071 cltv_expiry_delta: 0,
4072 htlc_minimum_msat: 0,
4073 htlc_maximum_msat: OptionalField::Present(100_000),
4075 fee_proportional_millionths: 0,
4076 excess_data: Vec::new()
4078 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4079 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4080 short_channel_id: 3,
4083 cltv_expiry_delta: 0,
4084 htlc_minimum_msat: 0,
4085 htlc_maximum_msat: OptionalField::Present(50_000),
4087 fee_proportional_millionths: 0,
4088 excess_data: Vec::new()
4091 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
4092 // (total limit 60).
4093 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4094 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4095 short_channel_id: 12,
4098 cltv_expiry_delta: 0,
4099 htlc_minimum_msat: 0,
4100 htlc_maximum_msat: OptionalField::Present(60_000),
4102 fee_proportional_millionths: 0,
4103 excess_data: Vec::new()
4105 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4106 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4107 short_channel_id: 13,
4110 cltv_expiry_delta: 0,
4111 htlc_minimum_msat: 0,
4112 htlc_maximum_msat: OptionalField::Present(60_000),
4114 fee_proportional_millionths: 0,
4115 excess_data: Vec::new()
4118 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
4119 // (total capacity 180 sats).
4120 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4121 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4122 short_channel_id: 2,
4125 cltv_expiry_delta: 0,
4126 htlc_minimum_msat: 0,
4127 htlc_maximum_msat: OptionalField::Present(200_000),
4129 fee_proportional_millionths: 0,
4130 excess_data: Vec::new()
4132 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4133 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4134 short_channel_id: 4,
4137 cltv_expiry_delta: 0,
4138 htlc_minimum_msat: 0,
4139 htlc_maximum_msat: OptionalField::Present(180_000),
4141 fee_proportional_millionths: 0,
4142 excess_data: Vec::new()
4146 // Attempt to route more than available results in a failure.
4147 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4148 &our_id, &payment_params, &network_graph.read_only(), None, 300_000, 42,
4149 Arc::clone(&logger), &scorer, &random_seed_bytes) {
4150 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4151 } else { panic!(); }
4155 // Attempt to route while setting max_path_count to 0 results in a failure.
4156 let zero_payment_params = payment_params.clone().with_max_path_count(0);
4157 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4158 &our_id, &zero_payment_params, &network_graph.read_only(), None, 100, 42,
4159 Arc::clone(&logger), &scorer, &random_seed_bytes) {
4160 assert_eq!(err, "Can't find a route with no paths allowed.");
4161 } else { panic!(); }
4165 // Attempt to route while setting max_path_count to 3 results in a failure.
4166 // This is the case because the minimal_value_contribution_msat would require each path
4167 // to account for 1/3 of the total value, which is violated by 2 out of 3 paths.
4168 let fail_payment_params = payment_params.clone().with_max_path_count(3);
4169 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4170 &our_id, &fail_payment_params, &network_graph.read_only(), None, 250_000, 42,
4171 Arc::clone(&logger), &scorer, &random_seed_bytes) {
4172 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4173 } else { panic!(); }
4177 // Now, attempt to route 250 sats (just a bit below the capacity).
4178 // Our algorithm should provide us with these 3 paths.
4179 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None,
4180 250_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4181 assert_eq!(route.paths.len(), 3);
4182 let mut total_amount_paid_msat = 0;
4183 for path in &route.paths {
4184 assert_eq!(path.len(), 2);
4185 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4186 total_amount_paid_msat += path.last().unwrap().fee_msat;
4188 assert_eq!(total_amount_paid_msat, 250_000);
4192 // Attempt to route an exact amount is also fine
4193 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None,
4194 290_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4195 assert_eq!(route.paths.len(), 3);
4196 let mut total_amount_paid_msat = 0;
4197 for path in &route.paths {
4198 assert_eq!(path.len(), 2);
4199 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4200 total_amount_paid_msat += path.last().unwrap().fee_msat;
4202 assert_eq!(total_amount_paid_msat, 290_000);
4207 fn long_mpp_route_test() {
4208 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4209 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4210 let scorer = test_utils::TestScorer::with_penalty(0);
4211 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4212 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4213 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
4215 // We need a route consisting of 3 paths:
4216 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
4217 // Note that these paths overlap (channels 5, 12, 13).
4218 // We will route 300 sats.
4219 // Each path will have 100 sats capacity, those channels which
4220 // are used twice will have 200 sats capacity.
4222 // Disable other potential paths.
4223 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4224 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4225 short_channel_id: 2,
4228 cltv_expiry_delta: 0,
4229 htlc_minimum_msat: 0,
4230 htlc_maximum_msat: OptionalField::Present(100_000),
4232 fee_proportional_millionths: 0,
4233 excess_data: Vec::new()
4235 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4236 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4237 short_channel_id: 7,
4240 cltv_expiry_delta: 0,
4241 htlc_minimum_msat: 0,
4242 htlc_maximum_msat: OptionalField::Present(100_000),
4244 fee_proportional_millionths: 0,
4245 excess_data: Vec::new()
4248 // Path via {node0, node2} is channels {1, 3, 5}.
4249 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4250 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4251 short_channel_id: 1,
4254 cltv_expiry_delta: 0,
4255 htlc_minimum_msat: 0,
4256 htlc_maximum_msat: OptionalField::Present(100_000),
4258 fee_proportional_millionths: 0,
4259 excess_data: Vec::new()
4261 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4262 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4263 short_channel_id: 3,
4266 cltv_expiry_delta: 0,
4267 htlc_minimum_msat: 0,
4268 htlc_maximum_msat: OptionalField::Present(100_000),
4270 fee_proportional_millionths: 0,
4271 excess_data: Vec::new()
4274 // Capacity of 200 sats because this channel will be used by 3rd path as well.
4275 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4276 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4277 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4278 short_channel_id: 5,
4281 cltv_expiry_delta: 0,
4282 htlc_minimum_msat: 0,
4283 htlc_maximum_msat: OptionalField::Present(200_000),
4285 fee_proportional_millionths: 0,
4286 excess_data: Vec::new()
4289 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4290 // Add 100 sats to the capacities of {12, 13}, because these channels
4291 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
4292 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4293 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4294 short_channel_id: 12,
4297 cltv_expiry_delta: 0,
4298 htlc_minimum_msat: 0,
4299 htlc_maximum_msat: OptionalField::Present(200_000),
4301 fee_proportional_millionths: 0,
4302 excess_data: Vec::new()
4304 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4305 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4306 short_channel_id: 13,
4309 cltv_expiry_delta: 0,
4310 htlc_minimum_msat: 0,
4311 htlc_maximum_msat: OptionalField::Present(200_000),
4313 fee_proportional_millionths: 0,
4314 excess_data: Vec::new()
4317 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4318 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4319 short_channel_id: 6,
4322 cltv_expiry_delta: 0,
4323 htlc_minimum_msat: 0,
4324 htlc_maximum_msat: OptionalField::Present(100_000),
4326 fee_proportional_millionths: 0,
4327 excess_data: Vec::new()
4329 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4330 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4331 short_channel_id: 11,
4334 cltv_expiry_delta: 0,
4335 htlc_minimum_msat: 0,
4336 htlc_maximum_msat: OptionalField::Present(100_000),
4338 fee_proportional_millionths: 0,
4339 excess_data: Vec::new()
4342 // Path via {node7, node2} is channels {12, 13, 5}.
4343 // We already limited them to 200 sats (they are used twice for 100 sats).
4344 // Nothing to do here.
4347 // Attempt to route more than available results in a failure.
4348 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4349 &our_id, &payment_params, &network_graph.read_only(), None, 350_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
4350 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4351 } else { panic!(); }
4355 // Now, attempt to route 300 sats (exact amount we can route).
4356 // Our algorithm should provide us with these 3 paths, 100 sats each.
4357 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 300_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4358 assert_eq!(route.paths.len(), 3);
4360 let mut total_amount_paid_msat = 0;
4361 for path in &route.paths {
4362 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
4363 total_amount_paid_msat += path.last().unwrap().fee_msat;
4365 assert_eq!(total_amount_paid_msat, 300_000);
4371 fn mpp_cheaper_route_test() {
4372 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4373 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4374 let scorer = test_utils::TestScorer::with_penalty(0);
4375 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4376 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4377 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
4379 // This test checks that if we have two cheaper paths and one more expensive path,
4380 // so that liquidity-wise any 2 of 3 combination is sufficient,
4381 // two cheaper paths will be taken.
4382 // These paths have equal available liquidity.
4384 // We need a combination of 3 paths:
4385 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
4386 // Note that these paths overlap (channels 5, 12, 13).
4387 // Each path will have 100 sats capacity, those channels which
4388 // are used twice will have 200 sats capacity.
4390 // Disable other potential paths.
4391 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4392 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4393 short_channel_id: 2,
4396 cltv_expiry_delta: 0,
4397 htlc_minimum_msat: 0,
4398 htlc_maximum_msat: OptionalField::Present(100_000),
4400 fee_proportional_millionths: 0,
4401 excess_data: Vec::new()
4403 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4404 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4405 short_channel_id: 7,
4408 cltv_expiry_delta: 0,
4409 htlc_minimum_msat: 0,
4410 htlc_maximum_msat: OptionalField::Present(100_000),
4412 fee_proportional_millionths: 0,
4413 excess_data: Vec::new()
4416 // Path via {node0, node2} is channels {1, 3, 5}.
4417 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4418 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4419 short_channel_id: 1,
4422 cltv_expiry_delta: 0,
4423 htlc_minimum_msat: 0,
4424 htlc_maximum_msat: OptionalField::Present(100_000),
4426 fee_proportional_millionths: 0,
4427 excess_data: Vec::new()
4429 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4430 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4431 short_channel_id: 3,
4434 cltv_expiry_delta: 0,
4435 htlc_minimum_msat: 0,
4436 htlc_maximum_msat: OptionalField::Present(100_000),
4438 fee_proportional_millionths: 0,
4439 excess_data: Vec::new()
4442 // Capacity of 200 sats because this channel will be used by 3rd path as well.
4443 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4444 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4445 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4446 short_channel_id: 5,
4449 cltv_expiry_delta: 0,
4450 htlc_minimum_msat: 0,
4451 htlc_maximum_msat: OptionalField::Present(200_000),
4453 fee_proportional_millionths: 0,
4454 excess_data: Vec::new()
4457 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4458 // Add 100 sats to the capacities of {12, 13}, because these channels
4459 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
4460 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4461 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4462 short_channel_id: 12,
4465 cltv_expiry_delta: 0,
4466 htlc_minimum_msat: 0,
4467 htlc_maximum_msat: OptionalField::Present(200_000),
4469 fee_proportional_millionths: 0,
4470 excess_data: Vec::new()
4472 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4473 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4474 short_channel_id: 13,
4477 cltv_expiry_delta: 0,
4478 htlc_minimum_msat: 0,
4479 htlc_maximum_msat: OptionalField::Present(200_000),
4481 fee_proportional_millionths: 0,
4482 excess_data: Vec::new()
4485 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4486 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4487 short_channel_id: 6,
4490 cltv_expiry_delta: 0,
4491 htlc_minimum_msat: 0,
4492 htlc_maximum_msat: OptionalField::Present(100_000),
4493 fee_base_msat: 1_000,
4494 fee_proportional_millionths: 0,
4495 excess_data: Vec::new()
4497 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4498 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4499 short_channel_id: 11,
4502 cltv_expiry_delta: 0,
4503 htlc_minimum_msat: 0,
4504 htlc_maximum_msat: OptionalField::Present(100_000),
4506 fee_proportional_millionths: 0,
4507 excess_data: Vec::new()
4510 // Path via {node7, node2} is channels {12, 13, 5}.
4511 // We already limited them to 200 sats (they are used twice for 100 sats).
4512 // Nothing to do here.
4515 // Now, attempt to route 180 sats.
4516 // Our algorithm should provide us with these 2 paths.
4517 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 180_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4518 assert_eq!(route.paths.len(), 2);
4520 let mut total_value_transferred_msat = 0;
4521 let mut total_paid_msat = 0;
4522 for path in &route.paths {
4523 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
4524 total_value_transferred_msat += path.last().unwrap().fee_msat;
4526 total_paid_msat += hop.fee_msat;
4529 // If we paid fee, this would be higher.
4530 assert_eq!(total_value_transferred_msat, 180_000);
4531 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
4532 assert_eq!(total_fees_paid, 0);
4537 fn fees_on_mpp_route_test() {
4538 // This test makes sure that MPP algorithm properly takes into account
4539 // fees charged on the channels, by making the fees impactful:
4540 // if the fee is not properly accounted for, the behavior is different.
4541 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4542 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4543 let scorer = test_utils::TestScorer::with_penalty(0);
4544 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4545 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4546 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
4548 // We need a route consisting of 2 paths:
4549 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
4550 // We will route 200 sats, Each path will have 100 sats capacity.
4552 // This test is not particularly stable: e.g.,
4553 // there's a way to route via {node0, node2, node4}.
4554 // It works while pathfinding is deterministic, but can be broken otherwise.
4555 // It's fine to ignore this concern for now.
4557 // Disable other potential paths.
4558 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4559 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4560 short_channel_id: 2,
4563 cltv_expiry_delta: 0,
4564 htlc_minimum_msat: 0,
4565 htlc_maximum_msat: OptionalField::Present(100_000),
4567 fee_proportional_millionths: 0,
4568 excess_data: Vec::new()
4571 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4572 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4573 short_channel_id: 7,
4576 cltv_expiry_delta: 0,
4577 htlc_minimum_msat: 0,
4578 htlc_maximum_msat: OptionalField::Present(100_000),
4580 fee_proportional_millionths: 0,
4581 excess_data: Vec::new()
4584 // Path via {node0, node2} is channels {1, 3, 5}.
4585 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4586 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4587 short_channel_id: 1,
4590 cltv_expiry_delta: 0,
4591 htlc_minimum_msat: 0,
4592 htlc_maximum_msat: OptionalField::Present(100_000),
4594 fee_proportional_millionths: 0,
4595 excess_data: Vec::new()
4597 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4598 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4599 short_channel_id: 3,
4602 cltv_expiry_delta: 0,
4603 htlc_minimum_msat: 0,
4604 htlc_maximum_msat: OptionalField::Present(100_000),
4606 fee_proportional_millionths: 0,
4607 excess_data: Vec::new()
4610 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4611 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4612 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4613 short_channel_id: 5,
4616 cltv_expiry_delta: 0,
4617 htlc_minimum_msat: 0,
4618 htlc_maximum_msat: OptionalField::Present(100_000),
4620 fee_proportional_millionths: 0,
4621 excess_data: Vec::new()
4624 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4625 // All channels should be 100 sats capacity. But for the fee experiment,
4626 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
4627 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
4628 // 100 sats (and pay 150 sats in fees for the use of channel 6),
4629 // so no matter how large are other channels,
4630 // the whole path will be limited by 100 sats with just these 2 conditions:
4631 // - channel 12 capacity is 250 sats
4632 // - fee for channel 6 is 150 sats
4633 // Let's test this by enforcing these 2 conditions and removing other limits.
4634 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4635 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4636 short_channel_id: 12,
4639 cltv_expiry_delta: 0,
4640 htlc_minimum_msat: 0,
4641 htlc_maximum_msat: OptionalField::Present(250_000),
4643 fee_proportional_millionths: 0,
4644 excess_data: Vec::new()
4646 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4647 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4648 short_channel_id: 13,
4651 cltv_expiry_delta: 0,
4652 htlc_minimum_msat: 0,
4653 htlc_maximum_msat: OptionalField::Absent,
4655 fee_proportional_millionths: 0,
4656 excess_data: Vec::new()
4659 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4660 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4661 short_channel_id: 6,
4664 cltv_expiry_delta: 0,
4665 htlc_minimum_msat: 0,
4666 htlc_maximum_msat: OptionalField::Absent,
4667 fee_base_msat: 150_000,
4668 fee_proportional_millionths: 0,
4669 excess_data: Vec::new()
4671 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4672 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4673 short_channel_id: 11,
4676 cltv_expiry_delta: 0,
4677 htlc_minimum_msat: 0,
4678 htlc_maximum_msat: OptionalField::Absent,
4680 fee_proportional_millionths: 0,
4681 excess_data: Vec::new()
4685 // Attempt to route more than available results in a failure.
4686 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4687 &our_id, &payment_params, &network_graph.read_only(), None, 210_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
4688 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4689 } else { panic!(); }
4693 // Now, attempt to route 200 sats (exact amount we can route).
4694 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 200_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4695 assert_eq!(route.paths.len(), 2);
4697 let mut total_amount_paid_msat = 0;
4698 for path in &route.paths {
4699 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
4700 total_amount_paid_msat += path.last().unwrap().fee_msat;
4702 assert_eq!(total_amount_paid_msat, 200_000);
4703 assert_eq!(route.get_total_fees(), 150_000);
4708 fn mpp_with_last_hops() {
4709 // Previously, if we tried to send an MPP payment to a destination which was only reachable
4710 // via a single last-hop route hint, we'd fail to route if we first collected routes
4711 // totaling close but not quite enough to fund the full payment.
4713 // This was because we considered last-hop hints to have exactly the sought payment amount
4714 // instead of the amount we were trying to collect, needlessly limiting our path searching
4715 // at the very first hop.
4717 // Specifically, this interacted with our "all paths must fund at least 5% of total target"
4718 // criterion to cause us to refuse all routes at the last hop hint which would be considered
4719 // to only have the remaining to-collect amount in available liquidity.
4721 // This bug appeared in production in some specific channel configurations.
4722 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4723 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4724 let scorer = test_utils::TestScorer::with_penalty(0);
4725 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4726 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4727 let payment_params = PaymentParameters::from_node_id(PublicKey::from_slice(&[02; 33]).unwrap()).with_features(InvoiceFeatures::known())
4728 .with_route_hints(vec![RouteHint(vec![RouteHintHop {
4729 src_node_id: nodes[2],
4730 short_channel_id: 42,
4731 fees: RoutingFees { base_msat: 0, proportional_millionths: 0 },
4732 cltv_expiry_delta: 42,
4733 htlc_minimum_msat: None,
4734 htlc_maximum_msat: None,
4737 // Keep only two paths from us to nodes[2], both with a 99sat HTLC maximum, with one with
4738 // no fee and one with a 1msat fee. Previously, trying to route 100 sats to nodes[2] here
4739 // would first use the no-fee route and then fail to find a path along the second route as
4740 // we think we can only send up to 1 additional sat over the last-hop but refuse to as its
4741 // under 5% of our payment amount.
4742 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4743 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4744 short_channel_id: 1,
4747 cltv_expiry_delta: (5 << 4) | 5,
4748 htlc_minimum_msat: 0,
4749 htlc_maximum_msat: OptionalField::Present(99_000),
4750 fee_base_msat: u32::max_value(),
4751 fee_proportional_millionths: u32::max_value(),
4752 excess_data: Vec::new()
4754 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4755 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4756 short_channel_id: 2,
4759 cltv_expiry_delta: (5 << 4) | 3,
4760 htlc_minimum_msat: 0,
4761 htlc_maximum_msat: OptionalField::Present(99_000),
4762 fee_base_msat: u32::max_value(),
4763 fee_proportional_millionths: u32::max_value(),
4764 excess_data: Vec::new()
4766 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4767 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4768 short_channel_id: 4,
4771 cltv_expiry_delta: (4 << 4) | 1,
4772 htlc_minimum_msat: 0,
4773 htlc_maximum_msat: OptionalField::Absent,
4775 fee_proportional_millionths: 0,
4776 excess_data: Vec::new()
4778 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4779 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4780 short_channel_id: 13,
4782 flags: 0|2, // Channel disabled
4783 cltv_expiry_delta: (13 << 4) | 1,
4784 htlc_minimum_msat: 0,
4785 htlc_maximum_msat: OptionalField::Absent,
4787 fee_proportional_millionths: 2000000,
4788 excess_data: Vec::new()
4791 // Get a route for 100 sats and check that we found the MPP route no problem and didn't
4793 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4794 assert_eq!(route.paths.len(), 2);
4795 // Paths are somewhat randomly ordered, but:
4796 // * the first is channel 2 (1 msat fee) -> channel 4 -> channel 42
4797 // * the second is channel 1 (0 fee, but 99 sat maximum) -> channel 3 -> channel 42
4798 assert_eq!(route.paths[0][0].short_channel_id, 2);
4799 assert_eq!(route.paths[0][0].fee_msat, 1);
4800 assert_eq!(route.paths[0][2].fee_msat, 1_000);
4801 assert_eq!(route.paths[1][0].short_channel_id, 1);
4802 assert_eq!(route.paths[1][0].fee_msat, 0);
4803 assert_eq!(route.paths[1][2].fee_msat, 99_000);
4804 assert_eq!(route.get_total_fees(), 1);
4805 assert_eq!(route.get_total_amount(), 100_000);
4809 fn drop_lowest_channel_mpp_route_test() {
4810 // This test checks that low-capacity channel is dropped when after
4811 // path finding we realize that we found more capacity than we need.
4812 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4813 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4814 let scorer = test_utils::TestScorer::with_penalty(0);
4815 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4816 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4817 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
4819 // We need a route consisting of 3 paths:
4820 // From our node to node2 via node0, node7, node1 (three paths one hop each).
4822 // The first and the second paths should be sufficient, but the third should be
4823 // cheaper, so that we select it but drop later.
4825 // First, we set limits on these (previously unlimited) channels.
4826 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
4828 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
4829 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4830 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4831 short_channel_id: 1,
4834 cltv_expiry_delta: 0,
4835 htlc_minimum_msat: 0,
4836 htlc_maximum_msat: OptionalField::Present(100_000),
4838 fee_proportional_millionths: 0,
4839 excess_data: Vec::new()
4841 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4842 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4843 short_channel_id: 3,
4846 cltv_expiry_delta: 0,
4847 htlc_minimum_msat: 0,
4848 htlc_maximum_msat: OptionalField::Present(50_000),
4850 fee_proportional_millionths: 0,
4851 excess_data: Vec::new()
4854 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
4855 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4856 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4857 short_channel_id: 12,
4860 cltv_expiry_delta: 0,
4861 htlc_minimum_msat: 0,
4862 htlc_maximum_msat: OptionalField::Present(60_000),
4864 fee_proportional_millionths: 0,
4865 excess_data: Vec::new()
4867 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4868 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4869 short_channel_id: 13,
4872 cltv_expiry_delta: 0,
4873 htlc_minimum_msat: 0,
4874 htlc_maximum_msat: OptionalField::Present(60_000),
4876 fee_proportional_millionths: 0,
4877 excess_data: Vec::new()
4880 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
4881 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4882 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4883 short_channel_id: 2,
4886 cltv_expiry_delta: 0,
4887 htlc_minimum_msat: 0,
4888 htlc_maximum_msat: OptionalField::Present(20_000),
4890 fee_proportional_millionths: 0,
4891 excess_data: Vec::new()
4893 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4894 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4895 short_channel_id: 4,
4898 cltv_expiry_delta: 0,
4899 htlc_minimum_msat: 0,
4900 htlc_maximum_msat: OptionalField::Present(20_000),
4902 fee_proportional_millionths: 0,
4903 excess_data: Vec::new()
4907 // Attempt to route more than available results in a failure.
4908 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4909 &our_id, &payment_params, &network_graph.read_only(), None, 150_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
4910 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4911 } else { panic!(); }
4915 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
4916 // Our algorithm should provide us with these 3 paths.
4917 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 125_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4918 assert_eq!(route.paths.len(), 3);
4919 let mut total_amount_paid_msat = 0;
4920 for path in &route.paths {
4921 assert_eq!(path.len(), 2);
4922 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4923 total_amount_paid_msat += path.last().unwrap().fee_msat;
4925 assert_eq!(total_amount_paid_msat, 125_000);
4929 // Attempt to route without the last small cheap channel
4930 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4931 assert_eq!(route.paths.len(), 2);
4932 let mut total_amount_paid_msat = 0;
4933 for path in &route.paths {
4934 assert_eq!(path.len(), 2);
4935 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4936 total_amount_paid_msat += path.last().unwrap().fee_msat;
4938 assert_eq!(total_amount_paid_msat, 90_000);
4943 fn min_criteria_consistency() {
4944 // Test that we don't use an inconsistent metric between updating and walking nodes during
4945 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
4946 // was updated with a different criterion from the heap sorting, resulting in loops in
4947 // calculated paths. We test for that specific case here.
4949 // We construct a network that looks like this:
4951 // node2 -1(3)2- node3
4955 // node1 -1(5)2- node4 -1(1)2- node6
4961 // We create a loop on the side of our real path - our destination is node 6, with a
4962 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
4963 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
4964 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
4965 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
4966 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
4967 // "previous hop" being set to node 3, creating a loop in the path.
4968 let secp_ctx = Secp256k1::new();
4969 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
4970 let logger = Arc::new(test_utils::TestLogger::new());
4971 let network = Arc::new(NetworkGraph::new(genesis_hash, Arc::clone(&logger)));
4972 let gossip_sync = P2PGossipSync::new(Arc::clone(&network), None, Arc::clone(&logger));
4973 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4974 let scorer = test_utils::TestScorer::with_penalty(0);
4975 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4976 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4977 let payment_params = PaymentParameters::from_node_id(nodes[6]);
4979 add_channel(&gossip_sync, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
4980 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4981 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4982 short_channel_id: 6,
4985 cltv_expiry_delta: (6 << 4) | 0,
4986 htlc_minimum_msat: 0,
4987 htlc_maximum_msat: OptionalField::Absent,
4989 fee_proportional_millionths: 0,
4990 excess_data: Vec::new()
4992 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
4994 add_channel(&gossip_sync, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4995 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4996 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4997 short_channel_id: 5,
5000 cltv_expiry_delta: (5 << 4) | 0,
5001 htlc_minimum_msat: 0,
5002 htlc_maximum_msat: OptionalField::Absent,
5004 fee_proportional_millionths: 0,
5005 excess_data: Vec::new()
5007 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
5009 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
5010 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5011 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5012 short_channel_id: 4,
5015 cltv_expiry_delta: (4 << 4) | 0,
5016 htlc_minimum_msat: 0,
5017 htlc_maximum_msat: OptionalField::Absent,
5019 fee_proportional_millionths: 0,
5020 excess_data: Vec::new()
5022 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
5024 add_channel(&gossip_sync, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
5025 update_channel(&gossip_sync, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
5026 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5027 short_channel_id: 3,
5030 cltv_expiry_delta: (3 << 4) | 0,
5031 htlc_minimum_msat: 0,
5032 htlc_maximum_msat: OptionalField::Absent,
5034 fee_proportional_millionths: 0,
5035 excess_data: Vec::new()
5037 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
5039 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
5040 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5041 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5042 short_channel_id: 2,
5045 cltv_expiry_delta: (2 << 4) | 0,
5046 htlc_minimum_msat: 0,
5047 htlc_maximum_msat: OptionalField::Absent,
5049 fee_proportional_millionths: 0,
5050 excess_data: Vec::new()
5053 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
5054 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5055 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5056 short_channel_id: 1,
5059 cltv_expiry_delta: (1 << 4) | 0,
5060 htlc_minimum_msat: 100,
5061 htlc_maximum_msat: OptionalField::Absent,
5063 fee_proportional_millionths: 0,
5064 excess_data: Vec::new()
5066 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
5069 // Now ensure the route flows simply over nodes 1 and 4 to 6.
5070 let route = get_route(&our_id, &payment_params, &network.read_only(), None, 10_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5071 assert_eq!(route.paths.len(), 1);
5072 assert_eq!(route.paths[0].len(), 3);
5074 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
5075 assert_eq!(route.paths[0][0].short_channel_id, 6);
5076 assert_eq!(route.paths[0][0].fee_msat, 100);
5077 assert_eq!(route.paths[0][0].cltv_expiry_delta, (5 << 4) | 0);
5078 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(1));
5079 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(6));
5081 assert_eq!(route.paths[0][1].pubkey, nodes[4]);
5082 assert_eq!(route.paths[0][1].short_channel_id, 5);
5083 assert_eq!(route.paths[0][1].fee_msat, 0);
5084 assert_eq!(route.paths[0][1].cltv_expiry_delta, (1 << 4) | 0);
5085 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(4));
5086 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(5));
5088 assert_eq!(route.paths[0][2].pubkey, nodes[6]);
5089 assert_eq!(route.paths[0][2].short_channel_id, 1);
5090 assert_eq!(route.paths[0][2].fee_msat, 10_000);
5091 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
5092 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
5093 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(1));
5099 fn exact_fee_liquidity_limit() {
5100 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
5101 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
5102 // we calculated fees on a higher value, resulting in us ignoring such paths.
5103 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5104 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
5105 let scorer = test_utils::TestScorer::with_penalty(0);
5106 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5107 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5108 let payment_params = PaymentParameters::from_node_id(nodes[2]);
5110 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
5112 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5113 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5114 short_channel_id: 2,
5117 cltv_expiry_delta: 0,
5118 htlc_minimum_msat: 0,
5119 htlc_maximum_msat: OptionalField::Present(85_000),
5121 fee_proportional_millionths: 0,
5122 excess_data: Vec::new()
5125 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5126 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5127 short_channel_id: 12,
5130 cltv_expiry_delta: (4 << 4) | 1,
5131 htlc_minimum_msat: 0,
5132 htlc_maximum_msat: OptionalField::Present(270_000),
5134 fee_proportional_millionths: 1000000,
5135 excess_data: Vec::new()
5139 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
5140 // 200% fee charged channel 13 in the 1-to-2 direction.
5141 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5142 assert_eq!(route.paths.len(), 1);
5143 assert_eq!(route.paths[0].len(), 2);
5145 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
5146 assert_eq!(route.paths[0][0].short_channel_id, 12);
5147 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
5148 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
5149 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
5150 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
5152 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
5153 assert_eq!(route.paths[0][1].short_channel_id, 13);
5154 assert_eq!(route.paths[0][1].fee_msat, 90_000);
5155 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
5156 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
5157 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
5162 fn htlc_max_reduction_below_min() {
5163 // Test that if, while walking the graph, we reduce the value being sent to meet an
5164 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
5165 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
5166 // resulting in us thinking there is no possible path, even if other paths exist.
5167 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5168 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5169 let scorer = test_utils::TestScorer::with_penalty(0);
5170 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5171 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5172 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
5174 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
5175 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
5176 // then try to send 90_000.
5177 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5178 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5179 short_channel_id: 2,
5182 cltv_expiry_delta: 0,
5183 htlc_minimum_msat: 0,
5184 htlc_maximum_msat: OptionalField::Present(80_000),
5186 fee_proportional_millionths: 0,
5187 excess_data: Vec::new()
5189 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5190 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5191 short_channel_id: 4,
5194 cltv_expiry_delta: (4 << 4) | 1,
5195 htlc_minimum_msat: 90_000,
5196 htlc_maximum_msat: OptionalField::Absent,
5198 fee_proportional_millionths: 0,
5199 excess_data: Vec::new()
5203 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
5204 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
5205 // expensive) channels 12-13 path.
5206 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5207 assert_eq!(route.paths.len(), 1);
5208 assert_eq!(route.paths[0].len(), 2);
5210 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
5211 assert_eq!(route.paths[0][0].short_channel_id, 12);
5212 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
5213 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
5214 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
5215 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
5217 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
5218 assert_eq!(route.paths[0][1].short_channel_id, 13);
5219 assert_eq!(route.paths[0][1].fee_msat, 90_000);
5220 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
5221 assert_eq!(route.paths[0][1].node_features.le_flags(), InvoiceFeatures::known().le_flags());
5222 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
5227 fn multiple_direct_first_hops() {
5228 // Previously we'd only ever considered one first hop path per counterparty.
5229 // However, as we don't restrict users to one channel per peer, we really need to support
5230 // looking at all first hop paths.
5231 // Here we test that we do not ignore all-but-the-last first hop paths per counterparty (as
5232 // we used to do by overwriting the `first_hop_targets` hashmap entry) and that we can MPP
5233 // route over multiple channels with the same first hop.
5234 let secp_ctx = Secp256k1::new();
5235 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5236 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
5237 let logger = Arc::new(test_utils::TestLogger::new());
5238 let network_graph = NetworkGraph::new(genesis_hash, Arc::clone(&logger));
5239 let scorer = test_utils::TestScorer::with_penalty(0);
5240 let payment_params = PaymentParameters::from_node_id(nodes[0]).with_features(InvoiceFeatures::known());
5241 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5242 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5245 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
5246 &get_channel_details(Some(3), nodes[0], InitFeatures::known(), 200_000),
5247 &get_channel_details(Some(2), nodes[0], InitFeatures::known(), 10_000),
5248 ]), 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5249 assert_eq!(route.paths.len(), 1);
5250 assert_eq!(route.paths[0].len(), 1);
5252 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
5253 assert_eq!(route.paths[0][0].short_channel_id, 3);
5254 assert_eq!(route.paths[0][0].fee_msat, 100_000);
5257 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
5258 &get_channel_details(Some(3), nodes[0], InitFeatures::known(), 50_000),
5259 &get_channel_details(Some(2), nodes[0], InitFeatures::known(), 50_000),
5260 ]), 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5261 assert_eq!(route.paths.len(), 2);
5262 assert_eq!(route.paths[0].len(), 1);
5263 assert_eq!(route.paths[1].len(), 1);
5265 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
5266 assert_eq!(route.paths[0][0].short_channel_id, 3);
5267 assert_eq!(route.paths[0][0].fee_msat, 50_000);
5269 assert_eq!(route.paths[1][0].pubkey, nodes[0]);
5270 assert_eq!(route.paths[1][0].short_channel_id, 2);
5271 assert_eq!(route.paths[1][0].fee_msat, 50_000);
5275 // If we have a bunch of outbound channels to the same node, where most are not
5276 // sufficient to pay the full payment, but one is, we should default to just using the
5277 // one single channel that has sufficient balance, avoiding MPP.
5279 // If we have several options above the 3xpayment value threshold, we should pick the
5280 // smallest of them, avoiding further fragmenting our available outbound balance to
5282 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
5283 &get_channel_details(Some(2), nodes[0], InitFeatures::known(), 50_000),
5284 &get_channel_details(Some(3), nodes[0], InitFeatures::known(), 50_000),
5285 &get_channel_details(Some(5), nodes[0], InitFeatures::known(), 50_000),
5286 &get_channel_details(Some(6), nodes[0], InitFeatures::known(), 300_000),
5287 &get_channel_details(Some(7), nodes[0], InitFeatures::known(), 50_000),
5288 &get_channel_details(Some(8), nodes[0], InitFeatures::known(), 50_000),
5289 &get_channel_details(Some(9), nodes[0], InitFeatures::known(), 50_000),
5290 &get_channel_details(Some(4), nodes[0], InitFeatures::known(), 1_000_000),
5291 ]), 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5292 assert_eq!(route.paths.len(), 1);
5293 assert_eq!(route.paths[0].len(), 1);
5295 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
5296 assert_eq!(route.paths[0][0].short_channel_id, 6);
5297 assert_eq!(route.paths[0][0].fee_msat, 100_000);
5302 fn prefers_shorter_route_with_higher_fees() {
5303 let (secp_ctx, network_graph, _, _, logger) = build_graph();
5304 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5305 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
5307 // Without penalizing each hop 100 msats, a longer path with lower fees is chosen.
5308 let scorer = test_utils::TestScorer::with_penalty(0);
5309 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5310 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5311 let route = get_route(
5312 &our_id, &payment_params, &network_graph.read_only(), None, 100, 42,
5313 Arc::clone(&logger), &scorer, &random_seed_bytes
5315 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5317 assert_eq!(route.get_total_fees(), 100);
5318 assert_eq!(route.get_total_amount(), 100);
5319 assert_eq!(path, vec![2, 4, 6, 11, 8]);
5321 // Applying a 100 msat penalty to each hop results in taking channels 7 and 10 to nodes[6]
5322 // from nodes[2] rather than channel 6, 11, and 8, even though the longer path is cheaper.
5323 let scorer = test_utils::TestScorer::with_penalty(100);
5324 let route = get_route(
5325 &our_id, &payment_params, &network_graph.read_only(), None, 100, 42,
5326 Arc::clone(&logger), &scorer, &random_seed_bytes
5328 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5330 assert_eq!(route.get_total_fees(), 300);
5331 assert_eq!(route.get_total_amount(), 100);
5332 assert_eq!(path, vec![2, 4, 7, 10]);
5335 struct BadChannelScorer {
5336 short_channel_id: u64,
5340 impl Writeable for BadChannelScorer {
5341 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), ::io::Error> { unimplemented!() }
5343 impl Score for BadChannelScorer {
5344 fn channel_penalty_msat(&self, short_channel_id: u64, _: &NodeId, _: &NodeId, _: ChannelUsage) -> u64 {
5345 if short_channel_id == self.short_channel_id { u64::max_value() } else { 0 }
5348 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
5349 fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
5350 fn probe_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
5351 fn probe_successful(&mut self, _path: &[&RouteHop]) {}
5354 struct BadNodeScorer {
5359 impl Writeable for BadNodeScorer {
5360 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), ::io::Error> { unimplemented!() }
5363 impl Score for BadNodeScorer {
5364 fn channel_penalty_msat(&self, _: u64, _: &NodeId, target: &NodeId, _: ChannelUsage) -> u64 {
5365 if *target == self.node_id { u64::max_value() } else { 0 }
5368 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
5369 fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
5370 fn probe_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
5371 fn probe_successful(&mut self, _path: &[&RouteHop]) {}
5375 fn avoids_routing_through_bad_channels_and_nodes() {
5376 let (secp_ctx, network, _, _, logger) = build_graph();
5377 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5378 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
5379 let network_graph = network.read_only();
5381 // A path to nodes[6] exists when no penalties are applied to any channel.
5382 let scorer = test_utils::TestScorer::with_penalty(0);
5383 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5384 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5385 let route = get_route(
5386 &our_id, &payment_params, &network_graph, None, 100, 42,
5387 Arc::clone(&logger), &scorer, &random_seed_bytes
5389 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5391 assert_eq!(route.get_total_fees(), 100);
5392 assert_eq!(route.get_total_amount(), 100);
5393 assert_eq!(path, vec![2, 4, 6, 11, 8]);
5395 // A different path to nodes[6] exists if channel 6 cannot be routed over.
5396 let scorer = BadChannelScorer { short_channel_id: 6 };
5397 let route = get_route(
5398 &our_id, &payment_params, &network_graph, None, 100, 42,
5399 Arc::clone(&logger), &scorer, &random_seed_bytes
5401 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5403 assert_eq!(route.get_total_fees(), 300);
5404 assert_eq!(route.get_total_amount(), 100);
5405 assert_eq!(path, vec![2, 4, 7, 10]);
5407 // A path to nodes[6] does not exist if nodes[2] cannot be routed through.
5408 let scorer = BadNodeScorer { node_id: NodeId::from_pubkey(&nodes[2]) };
5410 &our_id, &payment_params, &network_graph, None, 100, 42,
5411 Arc::clone(&logger), &scorer, &random_seed_bytes
5413 Err(LightningError { err, .. } ) => {
5414 assert_eq!(err, "Failed to find a path to the given destination");
5416 Ok(_) => panic!("Expected error"),
5421 fn total_fees_single_path() {
5425 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5426 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5427 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5430 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5431 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5432 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5435 pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
5436 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5437 short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0
5440 payment_params: None,
5443 assert_eq!(route.get_total_fees(), 250);
5444 assert_eq!(route.get_total_amount(), 225);
5448 fn total_fees_multi_path() {
5452 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5453 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5454 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5457 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5458 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5459 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5463 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5464 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5465 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5468 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5469 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5470 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5473 payment_params: None,
5476 assert_eq!(route.get_total_fees(), 200);
5477 assert_eq!(route.get_total_amount(), 300);
5481 fn total_empty_route_no_panic() {
5482 // In an earlier version of `Route::get_total_fees` and `Route::get_total_amount`, they
5483 // would both panic if the route was completely empty. We test to ensure they return 0
5484 // here, even though its somewhat nonsensical as a route.
5485 let route = Route { paths: Vec::new(), payment_params: None };
5487 assert_eq!(route.get_total_fees(), 0);
5488 assert_eq!(route.get_total_amount(), 0);
5492 fn limits_total_cltv_delta() {
5493 let (secp_ctx, network, _, _, logger) = build_graph();
5494 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5495 let network_graph = network.read_only();
5497 let scorer = test_utils::TestScorer::with_penalty(0);
5499 // Make sure that generally there is at least one route available
5500 let feasible_max_total_cltv_delta = 1008;
5501 let feasible_payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes))
5502 .with_max_total_cltv_expiry_delta(feasible_max_total_cltv_delta);
5503 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5504 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5505 let route = get_route(&our_id, &feasible_payment_params, &network_graph, None, 100, 0, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5506 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5507 assert_ne!(path.len(), 0);
5509 // But not if we exclude all paths on the basis of their accumulated CLTV delta
5510 let fail_max_total_cltv_delta = 23;
5511 let fail_payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes))
5512 .with_max_total_cltv_expiry_delta(fail_max_total_cltv_delta);
5513 match get_route(&our_id, &fail_payment_params, &network_graph, None, 100, 0, Arc::clone(&logger), &scorer, &random_seed_bytes)
5515 Err(LightningError { err, .. } ) => {
5516 assert_eq!(err, "Failed to find a path to the given destination");
5518 Ok(_) => panic!("Expected error"),
5523 fn limits_path_length() {
5524 let (secp_ctx, network, _, _, logger) = build_line_graph();
5525 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5526 let network_graph = network.read_only();
5528 let scorer = test_utils::TestScorer::with_penalty(0);
5529 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5530 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5532 // First check we can actually create a long route on this graph.
5533 let feasible_payment_params = PaymentParameters::from_node_id(nodes[18]);
5534 let route = get_route(&our_id, &feasible_payment_params, &network_graph, None, 100, 0,
5535 Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5536 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5537 assert!(path.len() == MAX_PATH_LENGTH_ESTIMATE.into());
5539 // But we can't create a path surpassing the MAX_PATH_LENGTH_ESTIMATE limit.
5540 let fail_payment_params = PaymentParameters::from_node_id(nodes[19]);
5541 match get_route(&our_id, &fail_payment_params, &network_graph, None, 100, 0,
5542 Arc::clone(&logger), &scorer, &random_seed_bytes)
5544 Err(LightningError { err, .. } ) => {
5545 assert_eq!(err, "Failed to find a path to the given destination");
5547 Ok(_) => panic!("Expected error"),
5552 fn adds_and_limits_cltv_offset() {
5553 let (secp_ctx, network_graph, _, _, logger) = build_graph();
5554 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5556 let scorer = test_utils::TestScorer::with_penalty(0);
5558 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
5559 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5560 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5561 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5562 assert_eq!(route.paths.len(), 1);
5564 let cltv_expiry_deltas_before = route.paths[0].iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5566 // Check whether the offset added to the last hop by default is in [1 .. DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA]
5567 let mut route_default = route.clone();
5568 add_random_cltv_offset(&mut route_default, &payment_params, &network_graph.read_only(), &random_seed_bytes);
5569 let cltv_expiry_deltas_default = route_default.paths[0].iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5570 assert_eq!(cltv_expiry_deltas_before.split_last().unwrap().1, cltv_expiry_deltas_default.split_last().unwrap().1);
5571 assert!(cltv_expiry_deltas_default.last() > cltv_expiry_deltas_before.last());
5572 assert!(cltv_expiry_deltas_default.last().unwrap() <= &DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA);
5574 // Check that no offset is added when we restrict the max_total_cltv_expiry_delta
5575 let mut route_limited = route.clone();
5576 let limited_max_total_cltv_expiry_delta = cltv_expiry_deltas_before.iter().sum();
5577 let limited_payment_params = payment_params.with_max_total_cltv_expiry_delta(limited_max_total_cltv_expiry_delta);
5578 add_random_cltv_offset(&mut route_limited, &limited_payment_params, &network_graph.read_only(), &random_seed_bytes);
5579 let cltv_expiry_deltas_limited = route_limited.paths[0].iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5580 assert_eq!(cltv_expiry_deltas_before, cltv_expiry_deltas_limited);
5584 fn adds_plausible_cltv_offset() {
5585 let (secp_ctx, network, _, _, logger) = build_graph();
5586 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5587 let network_graph = network.read_only();
5588 let network_nodes = network_graph.nodes();
5589 let network_channels = network_graph.channels();
5590 let scorer = test_utils::TestScorer::with_penalty(0);
5591 let payment_params = PaymentParameters::from_node_id(nodes[3]);
5592 let keys_manager = test_utils::TestKeysInterface::new(&[4u8; 32], Network::Testnet);
5593 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5595 let mut route = get_route(&our_id, &payment_params, &network_graph, None, 100, 0,
5596 Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5597 add_random_cltv_offset(&mut route, &payment_params, &network_graph, &random_seed_bytes);
5599 let mut path_plausibility = vec![];
5601 for p in route.paths {
5602 // 1. Select random observation point
5603 let mut prng = ChaCha20::new(&random_seed_bytes, &[0u8; 12]);
5604 let mut random_bytes = [0u8; ::core::mem::size_of::<usize>()];
5606 prng.process_in_place(&mut random_bytes);
5607 let random_path_index = usize::from_be_bytes(random_bytes).wrapping_rem(p.len());
5608 let observation_point = NodeId::from_pubkey(&p.get(random_path_index).unwrap().pubkey);
5610 // 2. Calculate what CLTV expiry delta we would observe there
5611 let observed_cltv_expiry_delta: u32 = p[random_path_index..].iter().map(|h| h.cltv_expiry_delta).sum();
5613 // 3. Starting from the observation point, find candidate paths
5614 let mut candidates: VecDeque<(NodeId, Vec<u32>)> = VecDeque::new();
5615 candidates.push_back((observation_point, vec![]));
5617 let mut found_plausible_candidate = false;
5619 'candidate_loop: while let Some((cur_node_id, cur_path_cltv_deltas)) = candidates.pop_front() {
5620 if let Some(remaining) = observed_cltv_expiry_delta.checked_sub(cur_path_cltv_deltas.iter().sum::<u32>()) {
5621 if remaining == 0 || remaining.wrapping_rem(40) == 0 || remaining.wrapping_rem(144) == 0 {
5622 found_plausible_candidate = true;
5623 break 'candidate_loop;
5627 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
5628 for channel_id in &cur_node.channels {
5629 if let Some(channel_info) = network_channels.get(&channel_id) {
5630 if let Some((dir_info, next_id)) = channel_info.as_directed_from(&cur_node_id) {
5631 if let Some(channel_update_info) = dir_info.direction() {
5632 let next_cltv_expiry_delta = channel_update_info.cltv_expiry_delta as u32;
5633 if cur_path_cltv_deltas.iter().sum::<u32>()
5634 .saturating_add(next_cltv_expiry_delta) <= observed_cltv_expiry_delta {
5635 let mut new_path_cltv_deltas = cur_path_cltv_deltas.clone();
5636 new_path_cltv_deltas.push(next_cltv_expiry_delta);
5637 candidates.push_back((*next_id, new_path_cltv_deltas));
5646 path_plausibility.push(found_plausible_candidate);
5648 assert!(path_plausibility.iter().all(|x| *x));
5652 fn builds_correct_path_from_hops() {
5653 let (secp_ctx, network, _, _, logger) = build_graph();
5654 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5655 let network_graph = network.read_only();
5657 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5658 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5660 let payment_params = PaymentParameters::from_node_id(nodes[3]);
5661 let hops = [nodes[1], nodes[2], nodes[4], nodes[3]];
5662 let route = build_route_from_hops_internal(&our_id, &hops, &payment_params,
5663 &network_graph, 100, 0, Arc::clone(&logger), &random_seed_bytes).unwrap();
5664 let route_hop_pubkeys = route.paths[0].iter().map(|hop| hop.pubkey).collect::<Vec<_>>();
5665 assert_eq!(hops.len(), route.paths[0].len());
5666 for (idx, hop_pubkey) in hops.iter().enumerate() {
5667 assert!(*hop_pubkey == route_hop_pubkeys[idx]);
5671 #[cfg(not(feature = "no-std"))]
5672 pub(super) fn random_init_seed() -> u64 {
5673 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
5674 use core::hash::{BuildHasher, Hasher};
5675 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
5676 println!("Using seed of {}", seed);
5679 #[cfg(not(feature = "no-std"))]
5680 use util::ser::ReadableArgs;
5683 #[cfg(not(feature = "no-std"))]
5684 fn generate_routes() {
5685 use routing::scoring::{ProbabilisticScorer, ProbabilisticScoringParameters};
5687 let mut d = match super::test_utils::get_route_file() {
5694 let logger = test_utils::TestLogger::new();
5695 let graph = NetworkGraph::read(&mut d, &logger).unwrap();
5696 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5697 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5699 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
5700 let mut seed = random_init_seed() as usize;
5701 let nodes = graph.read_only().nodes().clone();
5702 'load_endpoints: for _ in 0..10 {
5704 seed = seed.overflowing_mul(0xdeadbeef).0;
5705 let src = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5706 seed = seed.overflowing_mul(0xdeadbeef).0;
5707 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5708 let payment_params = PaymentParameters::from_node_id(dst);
5709 let amt = seed as u64 % 200_000_000;
5710 let params = ProbabilisticScoringParameters::default();
5711 let scorer = ProbabilisticScorer::new(params, &graph, &logger);
5712 if get_route(src, &payment_params, &graph.read_only(), None, amt, 42, &logger, &scorer, &random_seed_bytes).is_ok() {
5713 continue 'load_endpoints;
5720 #[cfg(not(feature = "no-std"))]
5721 fn generate_routes_mpp() {
5722 use routing::scoring::{ProbabilisticScorer, ProbabilisticScoringParameters};
5724 let mut d = match super::test_utils::get_route_file() {
5731 let logger = test_utils::TestLogger::new();
5732 let graph = NetworkGraph::read(&mut d, &logger).unwrap();
5733 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5734 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5736 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
5737 let mut seed = random_init_seed() as usize;
5738 let nodes = graph.read_only().nodes().clone();
5739 'load_endpoints: for _ in 0..10 {
5741 seed = seed.overflowing_mul(0xdeadbeef).0;
5742 let src = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5743 seed = seed.overflowing_mul(0xdeadbeef).0;
5744 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5745 let payment_params = PaymentParameters::from_node_id(dst).with_features(InvoiceFeatures::known());
5746 let amt = seed as u64 % 200_000_000;
5747 let params = ProbabilisticScoringParameters::default();
5748 let scorer = ProbabilisticScorer::new(params, &graph, &logger);
5749 if get_route(src, &payment_params, &graph.read_only(), None, amt, 42, &logger, &scorer, &random_seed_bytes).is_ok() {
5750 continue 'load_endpoints;
5757 fn avoids_banned_nodes() {
5758 let (secp_ctx, network_graph, _, _, logger) = build_line_graph();
5759 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5761 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5762 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5764 let scorer_params = ProbabilisticScoringParameters::default();
5765 let mut scorer = ProbabilisticScorer::new(scorer_params, Arc::clone(&network_graph), Arc::clone(&logger));
5767 // First check we can get a route.
5768 let payment_params = PaymentParameters::from_node_id(nodes[10]);
5769 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes);
5770 assert!(route.is_ok());
5772 // Then check that we can't get a route if we ban an intermediate node.
5773 scorer.add_banned(&NodeId::from_pubkey(&nodes[3]));
5774 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes);
5775 assert!(route.is_err());
5777 // Finally make sure we can route again, when we remove the ban.
5778 scorer.remove_banned(&NodeId::from_pubkey(&nodes[3]));
5779 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes);
5780 assert!(route.is_ok());
5784 #[cfg(all(test, not(feature = "no-std")))]
5785 pub(crate) mod test_utils {
5787 /// Tries to open a network graph file, or panics with a URL to fetch it.
5788 pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
5789 let res = File::open("net_graph-2021-05-31.bin") // By default we're run in RL/lightning
5790 .or_else(|_| File::open("lightning/net_graph-2021-05-31.bin")) // We may be run manually in RL/
5791 .or_else(|_| { // Fall back to guessing based on the binary location
5792 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
5793 let mut path = std::env::current_exe().unwrap();
5794 path.pop(); // lightning-...
5796 path.pop(); // debug
5797 path.pop(); // target
5798 path.push("lightning");
5799 path.push("net_graph-2021-05-31.bin");
5800 eprintln!("{}", path.to_str().unwrap());
5803 .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");
5804 #[cfg(require_route_graph_test)]
5805 return Ok(res.unwrap());
5806 #[cfg(not(require_route_graph_test))]
5811 #[cfg(all(test, feature = "_bench_unstable", not(feature = "no-std")))]
5814 use bitcoin::hashes::Hash;
5815 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
5816 use chain::transaction::OutPoint;
5817 use chain::keysinterface::{KeysManager,KeysInterface};
5818 use ln::channelmanager::{ChannelCounterparty, ChannelDetails};
5819 use ln::features::{InitFeatures, InvoiceFeatures};
5820 use routing::gossip::NetworkGraph;
5821 use routing::scoring::{FixedPenaltyScorer, ProbabilisticScorer, ProbabilisticScoringParameters};
5822 use util::logger::{Logger, Record};
5823 use util::ser::ReadableArgs;
5827 struct DummyLogger {}
5828 impl Logger for DummyLogger {
5829 fn log(&self, _record: &Record) {}
5832 fn read_network_graph(logger: &DummyLogger) -> NetworkGraph<&DummyLogger> {
5833 let mut d = test_utils::get_route_file().unwrap();
5834 NetworkGraph::read(&mut d, logger).unwrap()
5837 fn payer_pubkey() -> PublicKey {
5838 let secp_ctx = Secp256k1::new();
5839 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
5843 fn first_hop(node_id: PublicKey) -> ChannelDetails {
5845 channel_id: [0; 32],
5846 counterparty: ChannelCounterparty {
5847 features: InitFeatures::known(),
5849 unspendable_punishment_reserve: 0,
5850 forwarding_info: None,
5851 outbound_htlc_minimum_msat: None,
5852 outbound_htlc_maximum_msat: None,
5854 funding_txo: Some(OutPoint {
5855 txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0
5858 short_channel_id: Some(1),
5859 inbound_scid_alias: None,
5860 outbound_scid_alias: None,
5861 channel_value_satoshis: 10_000_000,
5863 balance_msat: 10_000_000,
5864 outbound_capacity_msat: 10_000_000,
5865 next_outbound_htlc_limit_msat: 10_000_000,
5866 inbound_capacity_msat: 0,
5867 unspendable_punishment_reserve: None,
5868 confirmations_required: None,
5869 force_close_spend_delay: None,
5871 is_channel_ready: true,
5874 inbound_htlc_minimum_msat: None,
5875 inbound_htlc_maximum_msat: None,
5881 fn generate_routes_with_zero_penalty_scorer(bench: &mut Bencher) {
5882 let logger = DummyLogger {};
5883 let network_graph = read_network_graph(&logger);
5884 let scorer = FixedPenaltyScorer::with_penalty(0);
5885 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::empty());
5889 fn generate_mpp_routes_with_zero_penalty_scorer(bench: &mut Bencher) {
5890 let logger = DummyLogger {};
5891 let network_graph = read_network_graph(&logger);
5892 let scorer = FixedPenaltyScorer::with_penalty(0);
5893 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::known());
5897 fn generate_routes_with_probabilistic_scorer(bench: &mut Bencher) {
5898 let logger = DummyLogger {};
5899 let network_graph = read_network_graph(&logger);
5900 let params = ProbabilisticScoringParameters::default();
5901 let scorer = ProbabilisticScorer::new(params, &network_graph, &logger);
5902 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::empty());
5906 fn generate_mpp_routes_with_probabilistic_scorer(bench: &mut Bencher) {
5907 let logger = DummyLogger {};
5908 let network_graph = read_network_graph(&logger);
5909 let params = ProbabilisticScoringParameters::default();
5910 let scorer = ProbabilisticScorer::new(params, &network_graph, &logger);
5911 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::known());
5914 fn generate_routes<S: Score>(
5915 bench: &mut Bencher, graph: &NetworkGraph<&DummyLogger>, mut scorer: S,
5916 features: InvoiceFeatures
5918 let nodes = graph.read_only().nodes().clone();
5919 let payer = payer_pubkey();
5920 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
5921 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5923 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
5924 let mut routes = Vec::new();
5925 let mut route_endpoints = Vec::new();
5926 let mut seed: usize = 0xdeadbeef;
5927 'load_endpoints: for _ in 0..150 {
5930 let src = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5932 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5933 let params = PaymentParameters::from_node_id(dst).with_features(features.clone());
5934 let first_hop = first_hop(src);
5935 let amt = seed as u64 % 1_000_000;
5936 if let Ok(route) = get_route(&payer, ¶ms, &graph.read_only(), Some(&[&first_hop]), amt, 42, &DummyLogger{}, &scorer, &random_seed_bytes) {
5938 route_endpoints.push((first_hop, params, amt));
5939 continue 'load_endpoints;
5944 // ...and seed the scorer with success and failure data...
5945 for route in routes {
5946 let amount = route.get_total_amount();
5947 if amount < 250_000 {
5948 for path in route.paths {
5949 scorer.payment_path_successful(&path.iter().collect::<Vec<_>>());
5951 } else if amount > 750_000 {
5952 for path in route.paths {
5953 let short_channel_id = path[path.len() / 2].short_channel_id;
5954 scorer.payment_path_failed(&path.iter().collect::<Vec<_>>(), short_channel_id);
5959 // Because we've changed channel scores, its possible we'll take different routes to the
5960 // selected destinations, possibly causing us to fail because, eg, the newly-selected path
5961 // requires a too-high CLTV delta.
5962 route_endpoints.retain(|(first_hop, params, amt)| {
5963 get_route(&payer, params, &graph.read_only(), Some(&[first_hop]), *amt, 42, &DummyLogger{}, &scorer, &random_seed_bytes).is_ok()
5965 route_endpoints.truncate(100);
5966 assert_eq!(route_endpoints.len(), 100);
5968 // ...then benchmark finding paths between the nodes we learned.
5971 let (first_hop, params, amt) = &route_endpoints[idx % route_endpoints.len()];
5972 assert!(get_route(&payer, params, &graph.read_only(), Some(&[first_hop]), *amt, 42, &DummyLogger{}, &scorer, &random_seed_bytes).is_ok());