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_MPP_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_MPP_PATH_COUNT`].
227 pub max_mpp_path_count: u8,
230 impl_writeable_tlv_based!(PaymentParameters, {
231 (0, payee_pubkey, required),
232 (1, max_total_cltv_expiry_delta, (default_value, DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA)),
233 (2, features, option),
234 (3, max_mpp_path_count, (default_value, DEFAULT_MAX_MPP_PATH_COUNT)),
235 (4, route_hints, vec_type),
236 (6, expiry_time, option),
239 impl PaymentParameters {
240 /// Creates a payee with the node id of the given `pubkey`.
241 pub fn from_node_id(payee_pubkey: PublicKey) -> Self {
247 max_total_cltv_expiry_delta: DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA,
248 max_mpp_path_count: DEFAULT_MAX_MPP_PATH_COUNT,
252 /// Creates a payee with the node id of the given `pubkey` to use for keysend payments.
253 pub fn for_keysend(payee_pubkey: PublicKey) -> Self {
254 Self::from_node_id(payee_pubkey).with_features(InvoiceFeatures::for_keysend())
257 /// Includes the payee's features.
259 /// (C-not exported) since bindings don't support move semantics
260 pub fn with_features(self, features: InvoiceFeatures) -> Self {
261 Self { features: Some(features), ..self }
264 /// Includes hints for routing to the payee.
266 /// (C-not exported) since bindings don't support move semantics
267 pub fn with_route_hints(self, route_hints: Vec<RouteHint>) -> Self {
268 Self { route_hints, ..self }
271 /// Includes a payment expiration in seconds relative to the UNIX epoch.
273 /// (C-not exported) since bindings don't support move semantics
274 pub fn with_expiry_time(self, expiry_time: u64) -> Self {
275 Self { expiry_time: Some(expiry_time), ..self }
278 /// Includes a limit for the total CLTV expiry delta which is considered during routing
280 /// (C-not exported) since bindings don't support move semantics
281 pub fn with_max_total_cltv_expiry_delta(self, max_total_cltv_expiry_delta: u32) -> Self {
282 Self { max_total_cltv_expiry_delta, ..self }
285 /// Includes a limit for the maximum number of payment paths that may be used by MPP.
287 /// (C-not exported) since bindings don't support move semantics
288 pub fn with_max_mpp_path_count(self, max_mpp_path_count: u8) -> Self {
289 Self { max_mpp_path_count, ..self }
293 /// A list of hops along a payment path terminating with a channel to the recipient.
294 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
295 pub struct RouteHint(pub Vec<RouteHintHop>);
297 impl Writeable for RouteHint {
298 fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
299 (self.0.len() as u64).write(writer)?;
300 for hop in self.0.iter() {
307 impl Readable for RouteHint {
308 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
309 let hop_count: u64 = Readable::read(reader)?;
310 let mut hops = Vec::with_capacity(cmp::min(hop_count, 16) as usize);
311 for _ in 0..hop_count {
312 hops.push(Readable::read(reader)?);
318 /// A channel descriptor for a hop along a payment path.
319 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
320 pub struct RouteHintHop {
321 /// The node_id of the non-target end of the route
322 pub src_node_id: PublicKey,
323 /// The short_channel_id of this channel
324 pub short_channel_id: u64,
325 /// The fees which must be paid to use this channel
326 pub fees: RoutingFees,
327 /// The difference in CLTV values between this node and the next node.
328 pub cltv_expiry_delta: u16,
329 /// The minimum value, in msat, which must be relayed to the next hop.
330 pub htlc_minimum_msat: Option<u64>,
331 /// The maximum value in msat available for routing with a single HTLC.
332 pub htlc_maximum_msat: Option<u64>,
335 impl_writeable_tlv_based!(RouteHintHop, {
336 (0, src_node_id, required),
337 (1, htlc_minimum_msat, option),
338 (2, short_channel_id, required),
339 (3, htlc_maximum_msat, option),
341 (6, cltv_expiry_delta, required),
344 #[derive(Eq, PartialEq)]
345 struct RouteGraphNode {
347 lowest_fee_to_peer_through_node: u64,
348 lowest_fee_to_node: u64,
349 total_cltv_delta: u32,
350 // The maximum value a yet-to-be-constructed payment path might flow through this node.
351 // This value is upper-bounded by us by:
352 // - how much is needed for a path being constructed
353 // - how much value can channels following this node (up to the destination) can contribute,
354 // considering their capacity and fees
355 value_contribution_msat: u64,
356 /// The effective htlc_minimum_msat at this hop. If a later hop on the path had a higher HTLC
357 /// minimum, we use it, plus the fees required at each earlier hop to meet it.
358 path_htlc_minimum_msat: u64,
359 /// All penalties incurred from this hop on the way to the destination, as calculated using
361 path_penalty_msat: u64,
362 /// The number of hops walked up to this node.
363 path_length_to_node: u8,
366 impl cmp::Ord for RouteGraphNode {
367 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
368 let other_score = cmp::max(other.lowest_fee_to_peer_through_node, other.path_htlc_minimum_msat)
369 .saturating_add(other.path_penalty_msat);
370 let self_score = cmp::max(self.lowest_fee_to_peer_through_node, self.path_htlc_minimum_msat)
371 .saturating_add(self.path_penalty_msat);
372 other_score.cmp(&self_score).then_with(|| other.node_id.cmp(&self.node_id))
376 impl cmp::PartialOrd for RouteGraphNode {
377 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
378 Some(self.cmp(other))
382 /// A wrapper around the various hop representations.
384 /// Used to construct a [`PathBuildingHop`] and to estimate [`EffectiveCapacity`].
385 #[derive(Clone, Debug)]
386 enum CandidateRouteHop<'a> {
387 /// A hop from the payer, where the outbound liquidity is known.
389 details: &'a ChannelDetails,
391 /// A hop found in the [`ReadOnlyNetworkGraph`], where the channel capacity may be unknown.
393 info: DirectedChannelInfoWithUpdate<'a>,
394 short_channel_id: u64,
396 /// A hop to the payee found in the payment invoice, though not necessarily a direct channel.
398 hint: &'a RouteHintHop,
402 impl<'a> CandidateRouteHop<'a> {
403 fn short_channel_id(&self) -> u64 {
405 CandidateRouteHop::FirstHop { details } => details.get_outbound_payment_scid().unwrap(),
406 CandidateRouteHop::PublicHop { short_channel_id, .. } => *short_channel_id,
407 CandidateRouteHop::PrivateHop { hint } => hint.short_channel_id,
411 // NOTE: This may alloc memory so avoid calling it in a hot code path.
412 fn features(&self) -> ChannelFeatures {
414 CandidateRouteHop::FirstHop { details } => details.counterparty.features.to_context(),
415 CandidateRouteHop::PublicHop { info, .. } => info.channel().features.clone(),
416 CandidateRouteHop::PrivateHop { .. } => ChannelFeatures::empty(),
420 fn cltv_expiry_delta(&self) -> u32 {
422 CandidateRouteHop::FirstHop { .. } => 0,
423 CandidateRouteHop::PublicHop { info, .. } => info.direction().cltv_expiry_delta as u32,
424 CandidateRouteHop::PrivateHop { hint } => hint.cltv_expiry_delta as u32,
428 fn htlc_minimum_msat(&self) -> u64 {
430 CandidateRouteHop::FirstHop { .. } => 0,
431 CandidateRouteHop::PublicHop { info, .. } => info.direction().htlc_minimum_msat,
432 CandidateRouteHop::PrivateHop { hint } => hint.htlc_minimum_msat.unwrap_or(0),
436 fn htlc_maximum_msat(&self) -> u64 {
438 CandidateRouteHop::FirstHop { details } => details.next_outbound_htlc_limit_msat,
439 CandidateRouteHop::PublicHop { info, .. } => info.htlc_maximum_msat(),
440 CandidateRouteHop::PrivateHop { hint } => {
441 hint.htlc_maximum_msat.unwrap_or(u64::max_value())
446 fn fees(&self) -> RoutingFees {
448 CandidateRouteHop::FirstHop { .. } => RoutingFees {
449 base_msat: 0, proportional_millionths: 0,
451 CandidateRouteHop::PublicHop { info, .. } => info.direction().fees,
452 CandidateRouteHop::PrivateHop { hint } => hint.fees,
456 fn effective_capacity(&self) -> EffectiveCapacity {
458 CandidateRouteHop::FirstHop { details } => EffectiveCapacity::ExactLiquidity {
459 liquidity_msat: details.next_outbound_htlc_limit_msat,
461 CandidateRouteHop::PublicHop { info, .. } => info.effective_capacity(),
462 CandidateRouteHop::PrivateHop { .. } => EffectiveCapacity::Infinite,
467 /// It's useful to keep track of the hops associated with the fees required to use them,
468 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
469 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
470 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
472 struct PathBuildingHop<'a> {
473 // Note that this should be dropped in favor of loading it from CandidateRouteHop, but doing so
474 // is a larger refactor and will require careful performance analysis.
476 candidate: CandidateRouteHop<'a>,
479 /// Minimal fees required to route to the source node of the current hop via any of its inbound channels.
480 src_lowest_inbound_fees: RoutingFees,
481 /// All the fees paid *after* this channel on the way to the destination
482 next_hops_fee_msat: u64,
483 /// Fee paid for the use of the current channel (see candidate.fees()).
484 /// The value will be actually deducted from the counterparty balance on the previous link.
485 hop_use_fee_msat: u64,
486 /// Used to compare channels when choosing the for routing.
487 /// Includes paying for the use of a hop and the following hops, as well as
488 /// an estimated cost of reaching this hop.
489 /// Might get stale when fees are recomputed. Primarily for internal use.
491 /// A mirror of the same field in RouteGraphNode. Note that this is only used during the graph
492 /// walk and may be invalid thereafter.
493 path_htlc_minimum_msat: u64,
494 /// All penalties incurred from this channel on the way to the destination, as calculated using
496 path_penalty_msat: u64,
497 /// If we've already processed a node as the best node, we shouldn't process it again. Normally
498 /// we'd just ignore it if we did as all channels would have a higher new fee, but because we
499 /// may decrease the amounts in use as we walk the graph, the actual calculated fee may
500 /// decrease as well. Thus, we have to explicitly track which nodes have been processed and
501 /// avoid processing them again.
503 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
504 // In tests, we apply further sanity checks on cases where we skip nodes we already processed
505 // to ensure it is specifically in cases where the fee has gone down because of a decrease in
506 // value_contribution_msat, which requires tracking it here. See comments below where it is
507 // used for more info.
508 value_contribution_msat: u64,
511 impl<'a> core::fmt::Debug for PathBuildingHop<'a> {
512 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
513 let mut debug_struct = f.debug_struct("PathBuildingHop");
515 .field("node_id", &self.node_id)
516 .field("short_channel_id", &self.candidate.short_channel_id())
517 .field("total_fee_msat", &self.total_fee_msat)
518 .field("next_hops_fee_msat", &self.next_hops_fee_msat)
519 .field("hop_use_fee_msat", &self.hop_use_fee_msat)
520 .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)))
521 .field("path_penalty_msat", &self.path_penalty_msat)
522 .field("path_htlc_minimum_msat", &self.path_htlc_minimum_msat)
523 .field("cltv_expiry_delta", &self.candidate.cltv_expiry_delta());
524 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
525 let debug_struct = debug_struct
526 .field("value_contribution_msat", &self.value_contribution_msat);
527 debug_struct.finish()
531 // Instantiated with a list of hops with correct data in them collected during path finding,
532 // an instance of this struct should be further modified only via given methods.
534 struct PaymentPath<'a> {
535 hops: Vec<(PathBuildingHop<'a>, NodeFeatures)>,
538 impl<'a> PaymentPath<'a> {
539 // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
540 fn get_value_msat(&self) -> u64 {
541 self.hops.last().unwrap().0.fee_msat
544 fn get_path_penalty_msat(&self) -> u64 {
545 self.hops.first().map(|h| h.0.path_penalty_msat).unwrap_or(u64::max_value())
548 fn get_total_fee_paid_msat(&self) -> u64 {
549 if self.hops.len() < 1 {
553 // Can't use next_hops_fee_msat because it gets outdated.
554 for (i, (hop, _)) in self.hops.iter().enumerate() {
555 if i != self.hops.len() - 1 {
556 result += hop.fee_msat;
562 fn get_cost_msat(&self) -> u64 {
563 self.get_total_fee_paid_msat().saturating_add(self.get_path_penalty_msat())
566 // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
567 // to change fees may result in an inconsistency.
569 // Sometimes we call this function right after constructing a path which is inconsistent in
570 // that it the value being transferred has decreased while we were doing path finding, leading
571 // to the fees being paid not lining up with the actual limits.
573 // Note that this function is not aware of the available_liquidity limit, and thus does not
574 // support increasing the value being transferred.
575 fn update_value_and_recompute_fees(&mut self, value_msat: u64) {
576 assert!(value_msat <= self.hops.last().unwrap().0.fee_msat);
578 let mut total_fee_paid_msat = 0 as u64;
579 for i in (0..self.hops.len()).rev() {
580 let last_hop = i == self.hops.len() - 1;
582 // For non-last-hop, this value will represent the fees paid on the current hop. It
583 // will consist of the fees for the use of the next hop, and extra fees to match
584 // htlc_minimum_msat of the current channel. Last hop is handled separately.
585 let mut cur_hop_fees_msat = 0;
587 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().0.hop_use_fee_msat;
590 let mut cur_hop = &mut self.hops.get_mut(i).unwrap().0;
591 cur_hop.next_hops_fee_msat = total_fee_paid_msat;
592 // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
593 // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
594 // set it too high just to maliciously take more fees by exploiting this
595 // match htlc_minimum_msat logic.
596 let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
597 if let Some(extra_fees_msat) = cur_hop.candidate.htlc_minimum_msat().checked_sub(cur_hop_transferred_amount_msat) {
598 // Note that there is a risk that *previous hops* (those closer to us, as we go
599 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
601 // This might make us end up with a broken route, although this should be super-rare
602 // in practice, both because of how healthy channels look like, and how we pick
603 // channels in add_entry.
604 // Also, this can't be exploited more heavily than *announce a free path and fail
606 cur_hop_transferred_amount_msat += extra_fees_msat;
607 total_fee_paid_msat += extra_fees_msat;
608 cur_hop_fees_msat += extra_fees_msat;
612 // Final hop is a special case: it usually has just value_msat (by design), but also
613 // it still could overpay for the htlc_minimum_msat.
614 cur_hop.fee_msat = cur_hop_transferred_amount_msat;
616 // Propagate updated fees for the use of the channels to one hop back, where they
617 // will be actually paid (fee_msat). The last hop is handled above separately.
618 cur_hop.fee_msat = cur_hop_fees_msat;
621 // Fee for the use of the current hop which will be deducted on the previous hop.
622 // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
623 // this channel is free for us.
625 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.candidate.fees()) {
626 cur_hop.hop_use_fee_msat = new_fee;
627 total_fee_paid_msat += new_fee;
629 // It should not be possible because this function is called only to reduce the
630 // value. In that case, compute_fee was already called with the same fees for
631 // larger amount and there was no overflow.
639 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
640 let proportional_fee_millions =
641 amount_msat.checked_mul(channel_fees.proportional_millionths as u64);
642 if let Some(new_fee) = proportional_fee_millions.and_then(|part| {
643 (channel_fees.base_msat as u64).checked_add(part / 1_000_000) }) {
647 // This function may be (indirectly) called without any verification,
648 // with channel_fees provided by a caller. We should handle it gracefully.
653 /// The default `features` we assume for a node in a route, when no `features` are known about that
656 /// Default features are:
657 /// * variable_length_onion_optional
658 fn default_node_features() -> NodeFeatures {
659 let mut features = NodeFeatures::empty();
660 features.set_variable_length_onion_optional();
664 /// Finds a route from us (payer) to the given target node (payee).
666 /// If the payee provided features in their invoice, they should be provided via `params.payee`.
667 /// Without this, MPP will only be used if the payee's features are available in the network graph.
669 /// Private routing paths between a public node and the target may be included in `params.payee`.
671 /// If some channels aren't announced, it may be useful to fill in `first_hops` with the results
672 /// from [`ChannelManager::list_usable_channels`]. If it is filled in, the view of these channels
673 /// from `network_graph` will be ignored, and only those in `first_hops` will be used.
675 /// The fees on channels from us to the next hop are ignored as they are assumed to all be equal.
676 /// However, the enabled/disabled bit on such channels as well as the `htlc_minimum_msat` /
677 /// `htlc_maximum_msat` *are* checked as they may change based on the receiving node.
681 /// May be used to re-compute a [`Route`] when handling a [`Event::PaymentPathFailed`]. Any
682 /// adjustments to the [`NetworkGraph`] and channel scores should be made prior to calling this
687 /// Panics if first_hops contains channels without short_channel_ids;
688 /// [`ChannelManager::list_usable_channels`] will never include such channels.
690 /// [`ChannelManager::list_usable_channels`]: crate::ln::channelmanager::ChannelManager::list_usable_channels
691 /// [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed
692 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
693 pub fn find_route<L: Deref, GL: Deref, S: Score>(
694 our_node_pubkey: &PublicKey, route_params: &RouteParameters,
695 network_graph: &NetworkGraph<GL>, first_hops: Option<&[&ChannelDetails]>, logger: L,
696 scorer: &S, random_seed_bytes: &[u8; 32]
697 ) -> Result<Route, LightningError>
698 where L::Target: Logger, GL::Target: Logger {
699 let graph_lock = network_graph.read_only();
700 let mut route = get_route(our_node_pubkey, &route_params.payment_params, &graph_lock, first_hops,
701 route_params.final_value_msat, route_params.final_cltv_expiry_delta, logger, scorer,
703 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
707 pub(crate) fn get_route<L: Deref, S: Score>(
708 our_node_pubkey: &PublicKey, payment_params: &PaymentParameters, network_graph: &ReadOnlyNetworkGraph,
709 first_hops: Option<&[&ChannelDetails]>, final_value_msat: u64, final_cltv_expiry_delta: u32,
710 logger: L, scorer: &S, random_seed_bytes: &[u8; 32]
711 ) -> Result<Route, LightningError>
712 where L::Target: Logger {
713 let payee_node_id = NodeId::from_pubkey(&payment_params.payee_pubkey);
714 let our_node_id = NodeId::from_pubkey(&our_node_pubkey);
716 if payee_node_id == our_node_id {
717 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
720 if final_value_msat > MAX_VALUE_MSAT {
721 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
724 if final_value_msat == 0 {
725 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
728 for route in payment_params.route_hints.iter() {
729 for hop in &route.0 {
730 if hop.src_node_id == payment_params.payee_pubkey {
731 return Err(LightningError{err: "Route hint cannot have the payee as the source.".to_owned(), action: ErrorAction::IgnoreError});
735 if payment_params.max_total_cltv_expiry_delta <= final_cltv_expiry_delta {
736 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});
739 // The general routing idea is the following:
740 // 1. Fill first/last hops communicated by the caller.
741 // 2. Attempt to construct a path from payer to payee for transferring
742 // any ~sufficient (described later) value.
743 // If succeed, remember which channels were used and how much liquidity they have available,
744 // so that future paths don't rely on the same liquidity.
745 // 3. Proceed to the next step if:
746 // - we hit the recommended target value;
747 // - OR if we could not construct a new path. Any next attempt will fail too.
748 // Otherwise, repeat step 2.
749 // 4. See if we managed to collect paths which aggregately are able to transfer target value
750 // (not recommended value).
751 // 5. If yes, proceed. If not, fail routing.
752 // 6. Randomly combine paths into routes having enough to fulfill the payment. (TODO: knapsack)
753 // 7. Of all the found paths, select only those with the lowest total fee.
754 // 8. The last path in every selected route is likely to be more than we need.
755 // Reduce its value-to-transfer and recompute fees.
756 // 9. Choose the best route by the lowest total fee.
758 // As for the actual search algorithm,
759 // we do a payee-to-payer pseudo-Dijkstra's sorting by each node's distance from the payee
760 // plus the minimum per-HTLC fee to get from it to another node (aka "shitty pseudo-A*").
762 // We are not a faithful Dijkstra's implementation because we can change values which impact
763 // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
764 // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) than
765 // the value we are currently attempting to send over a path, we simply reduce the value being
766 // sent along the path for any hops after that channel. This may imply that later fees (which
767 // we've already tabulated) are lower because a smaller value is passing through the channels
768 // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
769 // channels which were selected earlier (and which may still be used for other paths without a
770 // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
773 // One potentially problematic case for this algorithm would be if there are many
774 // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
775 // graph walking), we may never find a path which is not liquidity-limited and has lower
776 // proportional fee (and only lower absolute fee when considering the ultimate value sent).
777 // Because we only consider paths with at least 5% of the total value being sent, the damage
778 // from such a case should be limited, however this could be further reduced in the future by
779 // calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
780 // limits for the purposes of fee calculation.
782 // Alternatively, we could store more detailed path information in the heap (targets, below)
783 // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
784 // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
785 // and practically (as we would need to store dynamically-allocated path information in heap
786 // objects, increasing malloc traffic and indirect memory access significantly). Further, the
787 // results of such an algorithm would likely be biased towards lower-value paths.
789 // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
790 // outside of our current search value, running a path search more times to gather candidate
791 // paths at different values. While this may be acceptable, further path searches may increase
792 // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
793 // graph for candidate paths, calculating the maximum value which can realistically be sent at
794 // the same time, remaining generic across different payment values.
796 // TODO: There are a few tweaks we could do, including possibly pre-calculating more stuff
797 // to use as the A* heuristic beyond just the cost to get one node further than the current
800 let network_channels = network_graph.channels();
801 let network_nodes = network_graph.nodes();
803 // Allow MPP only if we have a features set from somewhere that indicates the payee supports
804 // it. If the payee supports it they're supposed to include it in the invoice, so that should
806 let allow_mpp = if let Some(features) = &payment_params.features {
807 features.supports_basic_mpp()
808 } else if let Some(node) = network_nodes.get(&payee_node_id) {
809 if let Some(node_info) = node.announcement_info.as_ref() {
810 node_info.features.supports_basic_mpp()
814 if allow_mpp && payment_params.max_mpp_path_count == 0 {
815 return Err(LightningError{err: "Can't find an MPP route with no paths allowed.".to_owned(), action: ErrorAction::IgnoreError});
818 log_trace!(logger, "Searching for a route from payer {} to payee {} {} MPP and {} first hops {}overriding the network graph", our_node_pubkey,
819 payment_params.payee_pubkey, if allow_mpp { "with" } else { "without" },
820 first_hops.map(|hops| hops.len()).unwrap_or(0), if first_hops.is_some() { "" } else { "not " });
823 // Prepare the data we'll use for payee-to-payer search by
824 // inserting first hops suggested by the caller as targets.
825 // Our search will then attempt to reach them while traversing from the payee node.
826 let mut first_hop_targets: HashMap<_, Vec<&ChannelDetails>> =
827 HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
828 if let Some(hops) = first_hops {
830 if chan.get_outbound_payment_scid().is_none() {
831 panic!("first_hops should be filled in with usable channels, not pending ones");
833 if chan.counterparty.node_id == *our_node_pubkey {
834 return Err(LightningError{err: "First hop cannot have our_node_pubkey as a destination.".to_owned(), action: ErrorAction::IgnoreError});
837 .entry(NodeId::from_pubkey(&chan.counterparty.node_id))
838 .or_insert(Vec::new())
841 if first_hop_targets.is_empty() {
842 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
846 // The main heap containing all candidate next-hops sorted by their score (max(A* fee,
847 // htlc_minimum)). Ideally this would be a heap which allowed cheap score reduction instead of
848 // adding duplicate entries when we find a better path to a given node.
849 let mut targets: BinaryHeap<RouteGraphNode> = BinaryHeap::new();
851 // Map from node_id to information about the best current path to that node, including feerate
853 let mut dist: HashMap<NodeId, PathBuildingHop> = HashMap::with_capacity(network_nodes.len());
855 // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
856 // indicating that we may wish to try again with a higher value, potentially paying to meet an
857 // htlc_minimum with extra fees while still finding a cheaper path.
858 let mut hit_minimum_limit;
860 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
861 // We start with a path_value of the exact amount we want, and if that generates a route we may
862 // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
863 // amount we want in total across paths, selecting the best subset at the end.
864 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
865 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
866 let mut path_value_msat = final_value_msat;
868 // Routing Fragmentation Mitigation heuristic:
870 // Routing fragmentation across many payment paths increases the overall routing
871 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
872 // Taking too many smaller paths also increases the chance of payment failure.
873 // Thus to avoid this effect, we require from our collected links to provide
874 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
875 // This requirement is currently set to be 1/max_mpp_path_count of the payment
876 // value to ensure we only ever return routes that do not violate this limit.
877 let minimal_value_contribution_msat: u64 = if allow_mpp {
878 (final_value_msat + (payment_params.max_mpp_path_count as u64 - 1)) / payment_params.max_mpp_path_count as u64
883 // Keep track of how much liquidity has been used in selected channels. Used to determine
884 // if the channel can be used by additional MPP paths or to inform path finding decisions. It is
885 // aware of direction *only* to ensure that the correct htlc_maximum_msat value is used. Hence,
886 // liquidity used in one direction will not offset any used in the opposite direction.
887 let mut used_channel_liquidities: HashMap<(u64, bool), u64> =
888 HashMap::with_capacity(network_nodes.len());
890 // Keeping track of how much value we already collected across other paths. Helps to decide
891 // when we want to stop looking for new paths.
892 let mut already_collected_value_msat = 0;
894 for (_, channels) in first_hop_targets.iter_mut() {
895 // Sort the first_hops channels to the same node(s) in priority order of which channel we'd
898 // First, if channels are below `recommended_value_msat`, sort them in descending order,
899 // preferring larger channels to avoid splitting the payment into more MPP parts than is
902 // Second, because simply always sorting in descending order would always use our largest
903 // available outbound capacity, needlessly fragmenting our available channel capacities,
904 // sort channels above `recommended_value_msat` in ascending order, preferring channels
905 // which have enough, but not too much, capacity for the payment.
906 channels.sort_unstable_by(|chan_a, chan_b| {
907 if chan_b.next_outbound_htlc_limit_msat < recommended_value_msat || chan_a.next_outbound_htlc_limit_msat < recommended_value_msat {
908 // Sort in descending order
909 chan_b.next_outbound_htlc_limit_msat.cmp(&chan_a.next_outbound_htlc_limit_msat)
911 // Sort in ascending order
912 chan_a.next_outbound_htlc_limit_msat.cmp(&chan_b.next_outbound_htlc_limit_msat)
917 log_trace!(logger, "Building path from {} (payee) to {} (us/payer) for value {} msat.", payment_params.payee_pubkey, our_node_pubkey, final_value_msat);
919 macro_rules! add_entry {
920 // Adds entry which goes from $src_node_id to $dest_node_id over the $candidate hop.
921 // $next_hops_fee_msat represents the fees paid for using all the channels *after* this one,
922 // since that value has to be transferred over this channel.
923 // Returns whether this channel caused an update to `targets`.
924 ( $candidate: expr, $src_node_id: expr, $dest_node_id: expr, $next_hops_fee_msat: expr,
925 $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr,
926 $next_hops_path_penalty_msat: expr, $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => { {
927 // We "return" whether we updated the path at the end, via this:
928 let mut did_add_update_path_to_src_node = false;
929 // Channels to self should not be used. This is more of belt-and-suspenders, because in
930 // practice these cases should be caught earlier:
931 // - for regular channels at channel announcement (TODO)
932 // - for first and last hops early in get_route
933 if $src_node_id != $dest_node_id {
934 let short_channel_id = $candidate.short_channel_id();
935 let htlc_maximum_msat = $candidate.htlc_maximum_msat();
937 // It is tricky to subtract $next_hops_fee_msat from available liquidity here.
938 // It may be misleading because we might later choose to reduce the value transferred
939 // over these channels, and the channel which was insufficient might become sufficient.
940 // Worst case: we drop a good channel here because it can't cover the high following
941 // fees caused by one expensive channel, but then this channel could have been used
942 // if the amount being transferred over this path is lower.
943 // We do this for now, but this is a subject for removal.
944 if let Some(mut available_value_contribution_msat) = htlc_maximum_msat.checked_sub($next_hops_fee_msat) {
945 let used_liquidity_msat = used_channel_liquidities
946 .get(&(short_channel_id, $src_node_id < $dest_node_id))
947 .map_or(0, |used_liquidity_msat| {
948 available_value_contribution_msat = available_value_contribution_msat
949 .saturating_sub(*used_liquidity_msat);
953 // Verify the liquidity offered by this channel complies to the minimal contribution.
954 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
955 // Do not consider candidate hops that would exceed the maximum path length.
956 let path_length_to_node = $next_hops_path_length + 1;
957 let doesnt_exceed_max_path_length = path_length_to_node <= MAX_PATH_LENGTH_ESTIMATE;
959 // Do not consider candidates that exceed the maximum total cltv expiry limit.
960 // In order to already account for some of the privacy enhancing random CLTV
961 // expiry delta offset we add on top later, we subtract a rough estimate
962 // (2*MEDIAN_HOP_CLTV_EXPIRY_DELTA) here.
963 let max_total_cltv_expiry_delta = (payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta)
964 .checked_sub(2*MEDIAN_HOP_CLTV_EXPIRY_DELTA)
965 .unwrap_or(payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta);
966 let hop_total_cltv_delta = ($next_hops_cltv_delta as u32)
967 .saturating_add($candidate.cltv_expiry_delta());
968 let doesnt_exceed_cltv_delta_limit = hop_total_cltv_delta <= max_total_cltv_expiry_delta;
970 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
971 // Includes paying fees for the use of the following channels.
972 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
973 Some(result) => result,
974 // Can't overflow due to how the values were computed right above.
975 None => unreachable!(),
977 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
978 let over_path_minimum_msat = amount_to_transfer_over_msat >= $candidate.htlc_minimum_msat() &&
979 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
981 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
982 let may_overpay_to_meet_path_minimum_msat =
983 ((amount_to_transfer_over_msat < $candidate.htlc_minimum_msat() &&
984 recommended_value_msat > $candidate.htlc_minimum_msat()) ||
985 (amount_to_transfer_over_msat < $next_hops_path_htlc_minimum_msat &&
986 recommended_value_msat > $next_hops_path_htlc_minimum_msat));
988 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
989 // bother considering this channel. If retrying with recommended_value_msat may
990 // allow us to hit the HTLC minimum limit, set htlc_minimum_limit so that we go
991 // around again with a higher amount.
992 if contributes_sufficient_value && doesnt_exceed_max_path_length &&
993 doesnt_exceed_cltv_delta_limit && may_overpay_to_meet_path_minimum_msat {
994 hit_minimum_limit = true;
995 } else if contributes_sufficient_value && doesnt_exceed_max_path_length &&
996 doesnt_exceed_cltv_delta_limit && over_path_minimum_msat {
997 // Note that low contribution here (limited by available_liquidity_msat)
998 // might violate htlc_minimum_msat on the hops which are next along the
999 // payment path (upstream to the payee). To avoid that, we recompute
1000 // path fees knowing the final path contribution after constructing it.
1001 let path_htlc_minimum_msat = compute_fees($next_hops_path_htlc_minimum_msat, $candidate.fees())
1002 .and_then(|fee_msat| fee_msat.checked_add($next_hops_path_htlc_minimum_msat))
1003 .map(|fee_msat| cmp::max(fee_msat, $candidate.htlc_minimum_msat()))
1004 .unwrap_or_else(|| u64::max_value());
1005 let hm_entry = dist.entry($src_node_id);
1006 let old_entry = hm_entry.or_insert_with(|| {
1007 // If there was previously no known way to access the source node
1008 // (recall it goes payee-to-payer) of short_channel_id, first add a
1009 // semi-dummy record just to compute the fees to reach the source node.
1010 // This will affect our decision on selecting short_channel_id
1011 // as a way to reach the $dest_node_id.
1012 let mut fee_base_msat = 0;
1013 let mut fee_proportional_millionths = 0;
1014 if let Some(Some(fees)) = network_nodes.get(&$src_node_id).map(|node| node.lowest_inbound_channel_fees) {
1015 fee_base_msat = fees.base_msat;
1016 fee_proportional_millionths = fees.proportional_millionths;
1019 node_id: $dest_node_id.clone(),
1020 candidate: $candidate.clone(),
1022 src_lowest_inbound_fees: RoutingFees {
1023 base_msat: fee_base_msat,
1024 proportional_millionths: fee_proportional_millionths,
1026 next_hops_fee_msat: u64::max_value(),
1027 hop_use_fee_msat: u64::max_value(),
1028 total_fee_msat: u64::max_value(),
1029 path_htlc_minimum_msat,
1030 path_penalty_msat: u64::max_value(),
1031 was_processed: false,
1032 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
1033 value_contribution_msat,
1037 #[allow(unused_mut)] // We only use the mut in cfg(test)
1038 let mut should_process = !old_entry.was_processed;
1039 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
1041 // In test/fuzzing builds, we do extra checks to make sure the skipping
1042 // of already-seen nodes only happens in cases we expect (see below).
1043 if !should_process { should_process = true; }
1047 let mut hop_use_fee_msat = 0;
1048 let mut total_fee_msat = $next_hops_fee_msat;
1050 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
1051 // will have the same effective-fee
1052 if $src_node_id != our_node_id {
1053 match compute_fees(amount_to_transfer_over_msat, $candidate.fees()) {
1054 // max_value means we'll always fail
1055 // the old_entry.total_fee_msat > total_fee_msat check
1056 None => total_fee_msat = u64::max_value(),
1058 hop_use_fee_msat = fee_msat;
1059 total_fee_msat += hop_use_fee_msat;
1060 // When calculating the lowest inbound fees to a node, we
1061 // calculate fees here not based on the actual value we think
1062 // will flow over this channel, but on the minimum value that
1063 // we'll accept flowing over it. The minimum accepted value
1064 // is a constant through each path collection run, ensuring
1065 // consistent basis. Otherwise we may later find a
1066 // different path to the source node that is more expensive,
1067 // but which we consider to be cheaper because we are capacity
1068 // constrained and the relative fee becomes lower.
1069 match compute_fees(minimal_value_contribution_msat, old_entry.src_lowest_inbound_fees)
1070 .map(|a| a.checked_add(total_fee_msat)) {
1075 total_fee_msat = u64::max_value();
1082 let channel_usage = ChannelUsage {
1083 amount_msat: amount_to_transfer_over_msat,
1084 inflight_htlc_msat: used_liquidity_msat,
1085 effective_capacity: $candidate.effective_capacity(),
1087 let channel_penalty_msat = scorer.channel_penalty_msat(
1088 short_channel_id, &$src_node_id, &$dest_node_id, channel_usage
1090 let path_penalty_msat = $next_hops_path_penalty_msat
1091 .saturating_add(channel_penalty_msat);
1092 let new_graph_node = RouteGraphNode {
1093 node_id: $src_node_id,
1094 lowest_fee_to_peer_through_node: total_fee_msat,
1095 lowest_fee_to_node: $next_hops_fee_msat as u64 + hop_use_fee_msat,
1096 total_cltv_delta: hop_total_cltv_delta,
1097 value_contribution_msat: value_contribution_msat,
1098 path_htlc_minimum_msat,
1100 path_length_to_node,
1103 // Update the way of reaching $src_node_id with the given short_channel_id (from $dest_node_id),
1104 // if this way is cheaper than the already known
1105 // (considering the cost to "reach" this channel from the route destination,
1106 // the cost of using this channel,
1107 // and the cost of routing to the source node of this channel).
1108 // Also, consider that htlc_minimum_msat_difference, because we might end up
1109 // paying it. Consider the following exploit:
1110 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
1111 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
1112 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
1113 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
1115 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
1116 // but it may require additional tracking - we don't want to double-count
1117 // the fees included in $next_hops_path_htlc_minimum_msat, but also
1118 // can't use something that may decrease on future hops.
1119 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat)
1120 .saturating_add(old_entry.path_penalty_msat);
1121 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat)
1122 .saturating_add(path_penalty_msat);
1124 if !old_entry.was_processed && new_cost < old_cost {
1125 targets.push(new_graph_node);
1126 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
1127 old_entry.hop_use_fee_msat = hop_use_fee_msat;
1128 old_entry.total_fee_msat = total_fee_msat;
1129 old_entry.node_id = $dest_node_id.clone();
1130 old_entry.candidate = $candidate.clone();
1131 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
1132 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
1133 old_entry.path_penalty_msat = path_penalty_msat;
1134 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
1136 old_entry.value_contribution_msat = value_contribution_msat;
1138 did_add_update_path_to_src_node = true;
1139 } else if old_entry.was_processed && new_cost < old_cost {
1140 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
1142 // If we're skipping processing a node which was previously
1143 // processed even though we found another path to it with a
1144 // cheaper fee, check that it was because the second path we
1145 // found (which we are processing now) has a lower value
1146 // contribution due to an HTLC minimum limit.
1148 // e.g. take a graph with two paths from node 1 to node 2, one
1149 // through channel A, and one through channel B. Channel A and
1150 // B are both in the to-process heap, with their scores set by
1151 // a higher htlc_minimum than fee.
1152 // Channel A is processed first, and the channels onwards from
1153 // node 1 are added to the to-process heap. Thereafter, we pop
1154 // Channel B off of the heap, note that it has a much more
1155 // restrictive htlc_maximum_msat, and recalculate the fees for
1156 // all of node 1's channels using the new, reduced, amount.
1158 // This would be bogus - we'd be selecting a higher-fee path
1159 // with a lower htlc_maximum_msat instead of the one we'd
1160 // already decided to use.
1161 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
1163 value_contribution_msat + path_penalty_msat <
1164 old_entry.value_contribution_msat + old_entry.path_penalty_msat
1172 did_add_update_path_to_src_node
1176 let default_node_features = default_node_features();
1178 // Find ways (channels with destination) to reach a given node and store them
1179 // in the corresponding data structures (routing graph etc).
1180 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
1181 // meaning how much will be paid in fees after this node (to the best of our knowledge).
1182 // This data can later be helpful to optimize routing (pay lower fees).
1183 macro_rules! add_entries_to_cheapest_to_target_node {
1184 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr, $next_hops_value_contribution: expr,
1185 $next_hops_path_htlc_minimum_msat: expr, $next_hops_path_penalty_msat: expr,
1186 $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => {
1187 let skip_node = if let Some(elem) = dist.get_mut(&$node_id) {
1188 let was_processed = elem.was_processed;
1189 elem.was_processed = true;
1192 // Entries are added to dist in add_entry!() when there is a channel from a node.
1193 // Because there are no channels from payee, it will not have a dist entry at this point.
1194 // If we're processing any other node, it is always be the result of a channel from it.
1195 assert_eq!($node_id, payee_node_id);
1200 if let Some(first_channels) = first_hop_targets.get(&$node_id) {
1201 for details in first_channels {
1202 let candidate = CandidateRouteHop::FirstHop { details };
1203 add_entry!(candidate, our_node_id, $node_id, $fee_to_target_msat,
1204 $next_hops_value_contribution,
1205 $next_hops_path_htlc_minimum_msat, $next_hops_path_penalty_msat,
1206 $next_hops_cltv_delta, $next_hops_path_length);
1210 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
1213 &default_node_features
1216 if !features.requires_unknown_bits() {
1217 for chan_id in $node.channels.iter() {
1218 let chan = network_channels.get(chan_id).unwrap();
1219 if !chan.features.requires_unknown_bits() {
1220 let (directed_channel, source) =
1221 chan.as_directed_to(&$node_id).expect("inconsistent NetworkGraph");
1222 if first_hops.is_none() || *source != our_node_id {
1223 if let Some(direction) = directed_channel.direction() {
1224 if direction.enabled {
1225 let candidate = CandidateRouteHop::PublicHop {
1226 info: directed_channel.with_update().unwrap(),
1227 short_channel_id: *chan_id,
1229 add_entry!(candidate, *source, $node_id,
1230 $fee_to_target_msat,
1231 $next_hops_value_contribution,
1232 $next_hops_path_htlc_minimum_msat,
1233 $next_hops_path_penalty_msat,
1234 $next_hops_cltv_delta, $next_hops_path_length);
1245 let mut payment_paths = Vec::<PaymentPath>::new();
1247 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
1248 'paths_collection: loop {
1249 // For every new path, start from scratch, except for used_channel_liquidities, which
1250 // helps to avoid reusing previously selected paths in future iterations.
1253 hit_minimum_limit = false;
1255 // If first hop is a private channel and the only way to reach the payee, this is the only
1256 // place where it could be added.
1257 if let Some(first_channels) = first_hop_targets.get(&payee_node_id) {
1258 for details in first_channels {
1259 let candidate = CandidateRouteHop::FirstHop { details };
1260 let added = add_entry!(candidate, our_node_id, payee_node_id, 0, path_value_msat,
1262 log_trace!(logger, "{} direct route to payee via SCID {}",
1263 if added { "Added" } else { "Skipped" }, candidate.short_channel_id());
1267 // Add the payee as a target, so that the payee-to-payer
1268 // search algorithm knows what to start with.
1269 match network_nodes.get(&payee_node_id) {
1270 // The payee is not in our network graph, so nothing to add here.
1271 // There is still a chance of reaching them via last_hops though,
1272 // so don't yet fail the payment here.
1273 // If not, targets.pop() will not even let us enter the loop in step 2.
1276 add_entries_to_cheapest_to_target_node!(node, payee_node_id, 0, path_value_msat, 0, 0u64, 0, 0);
1281 // If a caller provided us with last hops, add them to routing targets. Since this happens
1282 // earlier than general path finding, they will be somewhat prioritized, although currently
1283 // it matters only if the fees are exactly the same.
1284 for route in payment_params.route_hints.iter().filter(|route| !route.0.is_empty()) {
1285 let first_hop_in_route = &(route.0)[0];
1286 let have_hop_src_in_graph =
1287 // Only add the hops in this route to our candidate set if either
1288 // we have a direct channel to the first hop or the first hop is
1289 // in the regular network graph.
1290 first_hop_targets.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some() ||
1291 network_nodes.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some();
1292 if have_hop_src_in_graph {
1293 // We start building the path from reverse, i.e., from payee
1294 // to the first RouteHintHop in the path.
1295 let hop_iter = route.0.iter().rev();
1296 let prev_hop_iter = core::iter::once(&payment_params.payee_pubkey).chain(
1297 route.0.iter().skip(1).rev().map(|hop| &hop.src_node_id));
1298 let mut hop_used = true;
1299 let mut aggregate_next_hops_fee_msat: u64 = 0;
1300 let mut aggregate_next_hops_path_htlc_minimum_msat: u64 = 0;
1301 let mut aggregate_next_hops_path_penalty_msat: u64 = 0;
1302 let mut aggregate_next_hops_cltv_delta: u32 = 0;
1303 let mut aggregate_next_hops_path_length: u8 = 0;
1305 for (idx, (hop, prev_hop_id)) in hop_iter.zip(prev_hop_iter).enumerate() {
1306 let source = NodeId::from_pubkey(&hop.src_node_id);
1307 let target = NodeId::from_pubkey(&prev_hop_id);
1308 let candidate = network_channels
1309 .get(&hop.short_channel_id)
1310 .and_then(|channel| channel.as_directed_to(&target))
1311 .and_then(|(channel, _)| channel.with_update())
1312 .map(|info| CandidateRouteHop::PublicHop {
1314 short_channel_id: hop.short_channel_id,
1316 .unwrap_or_else(|| CandidateRouteHop::PrivateHop { hint: hop });
1318 if !add_entry!(candidate, source, target, aggregate_next_hops_fee_msat,
1319 path_value_msat, aggregate_next_hops_path_htlc_minimum_msat,
1320 aggregate_next_hops_path_penalty_msat,
1321 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length) {
1322 // If this hop was not used then there is no use checking the preceding
1323 // hops in the RouteHint. We can break by just searching for a direct
1324 // channel between last checked hop and first_hop_targets.
1328 let used_liquidity_msat = used_channel_liquidities
1329 .get(&(hop.short_channel_id, source < target)).copied().unwrap_or(0);
1330 let channel_usage = ChannelUsage {
1331 amount_msat: final_value_msat + aggregate_next_hops_fee_msat,
1332 inflight_htlc_msat: used_liquidity_msat,
1333 effective_capacity: candidate.effective_capacity(),
1335 let channel_penalty_msat = scorer.channel_penalty_msat(
1336 hop.short_channel_id, &source, &target, channel_usage
1338 aggregate_next_hops_path_penalty_msat = aggregate_next_hops_path_penalty_msat
1339 .saturating_add(channel_penalty_msat);
1341 aggregate_next_hops_cltv_delta = aggregate_next_hops_cltv_delta
1342 .saturating_add(hop.cltv_expiry_delta as u32);
1344 aggregate_next_hops_path_length = aggregate_next_hops_path_length
1347 // Searching for a direct channel between last checked hop and first_hop_targets
1348 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&prev_hop_id)) {
1349 for details in first_channels {
1350 let candidate = CandidateRouteHop::FirstHop { details };
1351 add_entry!(candidate, our_node_id, NodeId::from_pubkey(&prev_hop_id),
1352 aggregate_next_hops_fee_msat, path_value_msat,
1353 aggregate_next_hops_path_htlc_minimum_msat,
1354 aggregate_next_hops_path_penalty_msat, aggregate_next_hops_cltv_delta,
1355 aggregate_next_hops_path_length);
1363 // In the next values of the iterator, the aggregate fees already reflects
1364 // the sum of value sent from payer (final_value_msat) and routing fees
1365 // for the last node in the RouteHint. We need to just add the fees to
1366 // route through the current node so that the preceding node (next iteration)
1368 let hops_fee = compute_fees(aggregate_next_hops_fee_msat + final_value_msat, hop.fees)
1369 .map_or(None, |inc| inc.checked_add(aggregate_next_hops_fee_msat));
1370 aggregate_next_hops_fee_msat = if let Some(val) = hops_fee { val } else { break; };
1372 let hop_htlc_minimum_msat = candidate.htlc_minimum_msat();
1373 let hop_htlc_minimum_msat_inc = if let Some(val) = compute_fees(aggregate_next_hops_path_htlc_minimum_msat, hop.fees) { val } else { break; };
1374 let hops_path_htlc_minimum = aggregate_next_hops_path_htlc_minimum_msat
1375 .checked_add(hop_htlc_minimum_msat_inc);
1376 aggregate_next_hops_path_htlc_minimum_msat = if let Some(val) = hops_path_htlc_minimum { cmp::max(hop_htlc_minimum_msat, val) } else { break; };
1378 if idx == route.0.len() - 1 {
1379 // The last hop in this iterator is the first hop in
1380 // overall RouteHint.
1381 // If this hop connects to a node with which we have a direct channel,
1382 // ignore the network graph and, if the last hop was added, add our
1383 // direct channel to the candidate set.
1385 // Note that we *must* check if the last hop was added as `add_entry`
1386 // always assumes that the third argument is a node to which we have a
1388 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&hop.src_node_id)) {
1389 for details in first_channels {
1390 let candidate = CandidateRouteHop::FirstHop { details };
1391 add_entry!(candidate, our_node_id,
1392 NodeId::from_pubkey(&hop.src_node_id),
1393 aggregate_next_hops_fee_msat, path_value_msat,
1394 aggregate_next_hops_path_htlc_minimum_msat,
1395 aggregate_next_hops_path_penalty_msat,
1396 aggregate_next_hops_cltv_delta,
1397 aggregate_next_hops_path_length);
1405 log_trace!(logger, "Starting main path collection loop with {} nodes pre-filled from first/last hops.", targets.len());
1407 // At this point, targets are filled with the data from first and
1408 // last hops communicated by the caller, and the payment receiver.
1409 let mut found_new_path = false;
1412 // If this loop terminates due the exhaustion of targets, two situations are possible:
1413 // - not enough outgoing liquidity:
1414 // 0 < already_collected_value_msat < final_value_msat
1415 // - enough outgoing liquidity:
1416 // final_value_msat <= already_collected_value_msat < recommended_value_msat
1417 // Both these cases (and other cases except reaching recommended_value_msat) mean that
1418 // paths_collection will be stopped because found_new_path==false.
1419 // This is not necessarily a routing failure.
1420 '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() {
1422 // Since we're going payee-to-payer, hitting our node as a target means we should stop
1423 // traversing the graph and arrange the path out of what we found.
1424 if node_id == our_node_id {
1425 let mut new_entry = dist.remove(&our_node_id).unwrap();
1426 let mut ordered_hops: Vec<(PathBuildingHop, NodeFeatures)> = vec!((new_entry.clone(), default_node_features.clone()));
1429 let mut features_set = false;
1430 if let Some(first_channels) = first_hop_targets.get(&ordered_hops.last().unwrap().0.node_id) {
1431 for details in first_channels {
1432 if details.get_outbound_payment_scid().unwrap() == ordered_hops.last().unwrap().0.candidate.short_channel_id() {
1433 ordered_hops.last_mut().unwrap().1 = details.counterparty.features.to_context();
1434 features_set = true;
1440 if let Some(node) = network_nodes.get(&ordered_hops.last().unwrap().0.node_id) {
1441 if let Some(node_info) = node.announcement_info.as_ref() {
1442 ordered_hops.last_mut().unwrap().1 = node_info.features.clone();
1444 ordered_hops.last_mut().unwrap().1 = default_node_features.clone();
1447 // We can fill in features for everything except hops which were
1448 // provided via the invoice we're paying. We could guess based on the
1449 // recipient's features but for now we simply avoid guessing at all.
1453 // Means we succesfully traversed from the payer to the payee, now
1454 // save this path for the payment route. Also, update the liquidity
1455 // remaining on the used hops, so that we take them into account
1456 // while looking for more paths.
1457 if ordered_hops.last().unwrap().0.node_id == payee_node_id {
1461 new_entry = match dist.remove(&ordered_hops.last().unwrap().0.node_id) {
1462 Some(payment_hop) => payment_hop,
1463 // We can't arrive at None because, if we ever add an entry to targets,
1464 // we also fill in the entry in dist (see add_entry!).
1465 None => unreachable!(),
1467 // We "propagate" the fees one hop backward (topologically) here,
1468 // so that fees paid for a HTLC forwarding on the current channel are
1469 // associated with the previous channel (where they will be subtracted).
1470 ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
1471 ordered_hops.push((new_entry.clone(), default_node_features.clone()));
1473 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
1474 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
1476 log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: \n {:#?}",
1477 ordered_hops.len(), value_contribution_msat, ordered_hops.iter().map(|h| &(h.0)).collect::<Vec<&PathBuildingHop>>());
1479 let mut payment_path = PaymentPath {hops: ordered_hops};
1481 // We could have possibly constructed a slightly inconsistent path: since we reduce
1482 // value being transferred along the way, we could have violated htlc_minimum_msat
1483 // on some channels we already passed (assuming dest->source direction). Here, we
1484 // recompute the fees again, so that if that's the case, we match the currently
1485 // underpaid htlc_minimum_msat with fees.
1486 payment_path.update_value_and_recompute_fees(cmp::min(value_contribution_msat, final_value_msat));
1488 // Since a path allows to transfer as much value as
1489 // the smallest channel it has ("bottleneck"), we should recompute
1490 // the fees so sender HTLC don't overpay fees when traversing
1491 // larger channels than the bottleneck. This may happen because
1492 // when we were selecting those channels we were not aware how much value
1493 // this path will transfer, and the relative fee for them
1494 // might have been computed considering a larger value.
1495 // Remember that we used these channels so that we don't rely
1496 // on the same liquidity in future paths.
1497 let mut prevented_redundant_path_selection = false;
1498 let prev_hop_iter = core::iter::once(&our_node_id)
1499 .chain(payment_path.hops.iter().map(|(hop, _)| &hop.node_id));
1500 for (prev_hop, (hop, _)) in prev_hop_iter.zip(payment_path.hops.iter()) {
1501 let spent_on_hop_msat = value_contribution_msat + hop.next_hops_fee_msat;
1502 let used_liquidity_msat = used_channel_liquidities
1503 .entry((hop.candidate.short_channel_id(), *prev_hop < hop.node_id))
1504 .and_modify(|used_liquidity_msat| *used_liquidity_msat += spent_on_hop_msat)
1505 .or_insert(spent_on_hop_msat);
1506 if *used_liquidity_msat == hop.candidate.htlc_maximum_msat() {
1507 // If this path used all of this channel's available liquidity, we know
1508 // this path will not be selected again in the next loop iteration.
1509 prevented_redundant_path_selection = true;
1511 debug_assert!(*used_liquidity_msat <= hop.candidate.htlc_maximum_msat());
1513 if !prevented_redundant_path_selection {
1514 // If we weren't capped by hitting a liquidity limit on a channel in the path,
1515 // we'll probably end up picking the same path again on the next iteration.
1516 // Decrease the available liquidity of a hop in the middle of the path.
1517 let victim_scid = payment_path.hops[(payment_path.hops.len()) / 2].0.candidate.short_channel_id();
1518 let exhausted = u64::max_value();
1519 log_trace!(logger, "Disabling channel {} for future path building iterations to avoid duplicates.", victim_scid);
1520 *used_channel_liquidities.entry((victim_scid, false)).or_default() = exhausted;
1521 *used_channel_liquidities.entry((victim_scid, true)).or_default() = exhausted;
1524 // Track the total amount all our collected paths allow to send so that we know
1525 // when to stop looking for more paths
1526 already_collected_value_msat += value_contribution_msat;
1528 payment_paths.push(payment_path);
1529 found_new_path = true;
1530 break 'path_construction;
1533 // If we found a path back to the payee, we shouldn't try to process it again. This is
1534 // the equivalent of the `elem.was_processed` check in
1535 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
1536 if node_id == payee_node_id { continue 'path_construction; }
1538 // Otherwise, since the current target node is not us,
1539 // keep "unrolling" the payment graph from payee to payer by
1540 // finding a way to reach the current target from the payer side.
1541 match network_nodes.get(&node_id) {
1544 add_entries_to_cheapest_to_target_node!(node, node_id, lowest_fee_to_node,
1545 value_contribution_msat, path_htlc_minimum_msat, path_penalty_msat,
1546 total_cltv_delta, path_length_to_node);
1552 // If we don't support MPP, no use trying to gather more value ever.
1553 break 'paths_collection;
1557 // Stop either when the recommended value is reached or if no new path was found in this
1559 // In the latter case, making another path finding attempt won't help,
1560 // because we deterministically terminated the search due to low liquidity.
1561 if already_collected_value_msat >= recommended_value_msat || !found_new_path {
1562 log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
1563 already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
1564 break 'paths_collection;
1565 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
1566 // Further, if this was our first walk of the graph, and we weren't limited by an
1567 // htlc_minimum_msat, return immediately because this path should suffice. If we were
1568 // limited by an htlc_minimum_msat value, find another path with a higher value,
1569 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
1570 // still keeping a lower total fee than this path.
1571 if !hit_minimum_limit {
1572 log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
1573 break 'paths_collection;
1575 log_trace!(logger, "Collected our payment amount on the first pass, but running again to collect extra paths with a potentially higher limit.");
1576 path_value_msat = recommended_value_msat;
1581 if payment_paths.len() == 0 {
1582 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1585 if already_collected_value_msat < final_value_msat {
1586 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1589 // Sort by total fees and take the best paths.
1590 payment_paths.sort_unstable_by_key(|path| path.get_total_fee_paid_msat());
1591 if payment_paths.len() > 50 {
1592 payment_paths.truncate(50);
1595 // Draw multiple sufficient routes by randomly combining the selected paths.
1596 let mut drawn_routes = Vec::new();
1597 let mut prng = ChaCha20::new(random_seed_bytes, &[0u8; 12]);
1598 let mut random_index_bytes = [0u8; ::core::mem::size_of::<usize>()];
1600 let num_permutations = payment_paths.len();
1601 for _ in 0..num_permutations {
1602 let mut cur_route = Vec::<PaymentPath>::new();
1603 let mut aggregate_route_value_msat = 0;
1606 // Do a Fisher-Yates shuffle to create a random permutation of the payment paths
1607 for cur_index in (1..payment_paths.len()).rev() {
1608 prng.process_in_place(&mut random_index_bytes);
1609 let random_index = usize::from_be_bytes(random_index_bytes).wrapping_rem(cur_index+1);
1610 payment_paths.swap(cur_index, random_index);
1614 for payment_path in &payment_paths {
1615 cur_route.push(payment_path.clone());
1616 aggregate_route_value_msat += payment_path.get_value_msat();
1617 if aggregate_route_value_msat > final_value_msat {
1618 // Last path likely overpaid. Substract it from the most expensive
1619 // (in terms of proportional fee) path in this route and recompute fees.
1620 // This might be not the most economically efficient way, but fewer paths
1621 // also makes routing more reliable.
1622 let mut overpaid_value_msat = aggregate_route_value_msat - final_value_msat;
1624 // First, we drop some expensive low-value paths entirely if possible, since fewer
1625 // paths is better: the payment is less likely to fail. In order to do so, we sort
1626 // by value and fall back to total fees paid, i.e., in case of equal values we
1627 // prefer lower cost paths.
1628 cur_route.sort_unstable_by(|a, b| {
1629 a.get_value_msat().cmp(&b.get_value_msat())
1630 // Reverse ordering for cost, so we drop higher-cost paths first
1631 .then_with(|| b.get_cost_msat().cmp(&a.get_cost_msat()))
1634 // We should make sure that at least 1 path left.
1635 let mut paths_left = cur_route.len();
1636 cur_route.retain(|path| {
1637 if paths_left == 1 {
1640 let mut keep = true;
1641 let path_value_msat = path.get_value_msat();
1642 if path_value_msat <= overpaid_value_msat {
1644 overpaid_value_msat -= path_value_msat;
1650 if overpaid_value_msat == 0 {
1654 assert!(cur_route.len() > 0);
1657 // Now, subtract the overpaid value from the most-expensive path.
1658 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1659 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1660 cur_route.sort_unstable_by_key(|path| { path.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>() });
1661 let expensive_payment_path = cur_route.first_mut().unwrap();
1663 // We already dropped all the small value paths above, meaning all the
1664 // remaining paths are larger than remaining overpaid_value_msat.
1665 // Thus, this can't be negative.
1666 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
1667 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
1671 drawn_routes.push(cur_route);
1675 // Select the best route by lowest total cost.
1676 drawn_routes.sort_unstable_by_key(|paths| paths.iter().map(|path| path.get_cost_msat()).sum::<u64>());
1677 let mut selected_paths = Vec::<Vec<Result<RouteHop, LightningError>>>::new();
1678 for payment_path in drawn_routes.first().unwrap() {
1679 let mut path = payment_path.hops.iter().map(|(payment_hop, node_features)| {
1681 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)})?,
1682 node_features: node_features.clone(),
1683 short_channel_id: payment_hop.candidate.short_channel_id(),
1684 channel_features: payment_hop.candidate.features(),
1685 fee_msat: payment_hop.fee_msat,
1686 cltv_expiry_delta: payment_hop.candidate.cltv_expiry_delta(),
1688 }).collect::<Vec<_>>();
1689 // Propagate the cltv_expiry_delta one hop backwards since the delta from the current hop is
1690 // applicable for the previous hop.
1691 path.iter_mut().rev().fold(final_cltv_expiry_delta, |prev_cltv_expiry_delta, hop| {
1692 core::mem::replace(&mut hop.as_mut().unwrap().cltv_expiry_delta, prev_cltv_expiry_delta)
1694 selected_paths.push(path);
1696 // Make sure we would never create a route with more paths than we allow.
1697 debug_assert!(selected_paths.len() <= payment_params.max_mpp_path_count.into());
1699 if let Some(features) = &payment_params.features {
1700 for path in selected_paths.iter_mut() {
1701 if let Ok(route_hop) = path.last_mut().unwrap() {
1702 route_hop.node_features = features.to_context();
1708 paths: selected_paths.into_iter().map(|path| path.into_iter().collect()).collect::<Result<Vec<_>, _>>()?,
1709 payment_params: Some(payment_params.clone()),
1711 log_info!(logger, "Got route to {}: {}", payment_params.payee_pubkey, log_route!(route));
1715 // When an adversarial intermediary node observes a payment, it may be able to infer its
1716 // destination, if the remaining CLTV expiry delta exactly matches a feasible path in the network
1717 // graph. In order to improve privacy, this method obfuscates the CLTV expiry deltas along the
1718 // payment path by adding a randomized 'shadow route' offset to the final hop.
1719 fn add_random_cltv_offset(route: &mut Route, payment_params: &PaymentParameters,
1720 network_graph: &ReadOnlyNetworkGraph, random_seed_bytes: &[u8; 32]
1722 let network_channels = network_graph.channels();
1723 let network_nodes = network_graph.nodes();
1725 for path in route.paths.iter_mut() {
1726 let mut shadow_ctlv_expiry_delta_offset: u32 = 0;
1728 // Remember the last three nodes of the random walk and avoid looping back on them.
1729 // Init with the last three nodes from the actual path, if possible.
1730 let mut nodes_to_avoid: [NodeId; 3] = [NodeId::from_pubkey(&path.last().unwrap().pubkey),
1731 NodeId::from_pubkey(&path.get(path.len().saturating_sub(2)).unwrap().pubkey),
1732 NodeId::from_pubkey(&path.get(path.len().saturating_sub(3)).unwrap().pubkey)];
1734 // Choose the last publicly known node as the starting point for the random walk.
1735 let mut cur_hop: Option<NodeId> = None;
1736 let mut path_nonce = [0u8; 12];
1737 if let Some(starting_hop) = path.iter().rev()
1738 .find(|h| network_nodes.contains_key(&NodeId::from_pubkey(&h.pubkey))) {
1739 cur_hop = Some(NodeId::from_pubkey(&starting_hop.pubkey));
1740 path_nonce.copy_from_slice(&cur_hop.unwrap().as_slice()[..12]);
1743 // Init PRNG with the path-dependant nonce, which is static for private paths.
1744 let mut prng = ChaCha20::new(random_seed_bytes, &path_nonce);
1745 let mut random_path_bytes = [0u8; ::core::mem::size_of::<usize>()];
1747 // Pick a random path length in [1 .. 3]
1748 prng.process_in_place(&mut random_path_bytes);
1749 let random_walk_length = usize::from_be_bytes(random_path_bytes).wrapping_rem(3).wrapping_add(1);
1751 for random_hop in 0..random_walk_length {
1752 // If we don't find a suitable offset in the public network graph, we default to
1753 // MEDIAN_HOP_CLTV_EXPIRY_DELTA.
1754 let mut random_hop_offset = MEDIAN_HOP_CLTV_EXPIRY_DELTA;
1756 if let Some(cur_node_id) = cur_hop {
1757 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
1758 // Randomly choose the next unvisited hop.
1759 prng.process_in_place(&mut random_path_bytes);
1760 if let Some(random_channel) = usize::from_be_bytes(random_path_bytes)
1761 .checked_rem(cur_node.channels.len())
1762 .and_then(|index| cur_node.channels.get(index))
1763 .and_then(|id| network_channels.get(id)) {
1764 random_channel.as_directed_from(&cur_node_id).map(|(dir_info, next_id)| {
1765 if !nodes_to_avoid.iter().any(|x| x == next_id) {
1766 nodes_to_avoid[random_hop] = *next_id;
1767 dir_info.direction().map(|channel_update_info| {
1768 random_hop_offset = channel_update_info.cltv_expiry_delta.into();
1769 cur_hop = Some(*next_id);
1777 shadow_ctlv_expiry_delta_offset = shadow_ctlv_expiry_delta_offset
1778 .checked_add(random_hop_offset)
1779 .unwrap_or(shadow_ctlv_expiry_delta_offset);
1782 // Limit the total offset to reduce the worst-case locked liquidity timevalue
1783 const MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET: u32 = 3*144;
1784 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET);
1786 // Limit the offset so we never exceed the max_total_cltv_expiry_delta. To improve plausibility,
1787 // we choose the limit to be the largest possible multiple of MEDIAN_HOP_CLTV_EXPIRY_DELTA.
1788 let path_total_cltv_expiry_delta: u32 = path.iter().map(|h| h.cltv_expiry_delta).sum();
1789 let mut max_path_offset = payment_params.max_total_cltv_expiry_delta - path_total_cltv_expiry_delta;
1790 max_path_offset = cmp::max(
1791 max_path_offset - (max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA),
1792 max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA);
1793 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, max_path_offset);
1795 // Add 'shadow' CLTV offset to the final hop
1796 if let Some(last_hop) = path.last_mut() {
1797 last_hop.cltv_expiry_delta = last_hop.cltv_expiry_delta
1798 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(last_hop.cltv_expiry_delta);
1803 /// Construct a route from us (payer) to the target node (payee) via the given hops (which should
1804 /// exclude the payer, but include the payee). This may be useful, e.g., for probing the chosen path.
1806 /// Re-uses logic from `find_route`, so the restrictions described there also apply here.
1807 pub fn build_route_from_hops<L: Deref, GL: Deref>(
1808 our_node_pubkey: &PublicKey, hops: &[PublicKey], route_params: &RouteParameters,
1809 network_graph: &NetworkGraph<GL>, logger: L, random_seed_bytes: &[u8; 32]
1810 ) -> Result<Route, LightningError>
1811 where L::Target: Logger, GL::Target: Logger {
1812 let graph_lock = network_graph.read_only();
1813 let mut route = build_route_from_hops_internal(
1814 our_node_pubkey, hops, &route_params.payment_params, &graph_lock,
1815 route_params.final_value_msat, route_params.final_cltv_expiry_delta, logger, random_seed_bytes)?;
1816 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
1820 fn build_route_from_hops_internal<L: Deref>(
1821 our_node_pubkey: &PublicKey, hops: &[PublicKey], payment_params: &PaymentParameters,
1822 network_graph: &ReadOnlyNetworkGraph, final_value_msat: u64, final_cltv_expiry_delta: u32,
1823 logger: L, random_seed_bytes: &[u8; 32]
1824 ) -> Result<Route, LightningError> where L::Target: Logger {
1827 our_node_id: NodeId,
1828 hop_ids: [Option<NodeId>; MAX_PATH_LENGTH_ESTIMATE as usize],
1831 impl Score for HopScorer {
1832 fn channel_penalty_msat(&self, _short_channel_id: u64, source: &NodeId, target: &NodeId,
1833 _usage: ChannelUsage) -> u64
1835 let mut cur_id = self.our_node_id;
1836 for i in 0..self.hop_ids.len() {
1837 if let Some(next_id) = self.hop_ids[i] {
1838 if cur_id == *source && next_id == *target {
1849 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
1851 fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
1854 impl<'a> Writeable for HopScorer {
1856 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), io::Error> {
1861 if hops.len() > MAX_PATH_LENGTH_ESTIMATE.into() {
1862 return Err(LightningError{err: "Cannot build a route exceeding the maximum path length.".to_owned(), action: ErrorAction::IgnoreError});
1865 let our_node_id = NodeId::from_pubkey(our_node_pubkey);
1866 let mut hop_ids = [None; MAX_PATH_LENGTH_ESTIMATE as usize];
1867 for i in 0..hops.len() {
1868 hop_ids[i] = Some(NodeId::from_pubkey(&hops[i]));
1871 let scorer = HopScorer { our_node_id, hop_ids };
1873 get_route(our_node_pubkey, payment_params, network_graph, None, final_value_msat,
1874 final_cltv_expiry_delta, logger, &scorer, random_seed_bytes)
1879 use routing::gossip::{NetworkGraph, P2PGossipSync, NodeId};
1880 use routing::router::{get_route, build_route_from_hops_internal, add_random_cltv_offset, default_node_features,
1881 PaymentParameters, Route, RouteHint, RouteHintHop, RouteHop, RoutingFees,
1882 DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA, MAX_PATH_LENGTH_ESTIMATE};
1883 use routing::scoring::{ChannelUsage, Score, ProbabilisticScorer, ProbabilisticScoringParameters};
1884 use chain::transaction::OutPoint;
1885 use chain::keysinterface::KeysInterface;
1886 use ln::features::{ChannelFeatures, InitFeatures, InvoiceFeatures, NodeFeatures};
1887 use ln::msgs::{ErrorAction, LightningError, OptionalField, UnsignedChannelAnnouncement, ChannelAnnouncement, RoutingMessageHandler,
1888 NodeAnnouncement, UnsignedNodeAnnouncement, ChannelUpdate, UnsignedChannelUpdate};
1889 use ln::channelmanager;
1890 use util::test_utils;
1891 use util::chacha20::ChaCha20;
1892 use util::ser::Writeable;
1894 use util::ser::Writer;
1896 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
1897 use bitcoin::hashes::Hash;
1898 use bitcoin::network::constants::Network;
1899 use bitcoin::blockdata::constants::genesis_block;
1900 use bitcoin::blockdata::script::Builder;
1901 use bitcoin::blockdata::opcodes;
1902 use bitcoin::blockdata::transaction::TxOut;
1906 use bitcoin::secp256k1::{PublicKey,SecretKey};
1907 use bitcoin::secp256k1::{Secp256k1, All};
1910 use sync::{self, Arc};
1912 fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
1913 features: InitFeatures, outbound_capacity_msat: u64) -> channelmanager::ChannelDetails {
1914 channelmanager::ChannelDetails {
1915 channel_id: [0; 32],
1916 counterparty: channelmanager::ChannelCounterparty {
1919 unspendable_punishment_reserve: 0,
1920 forwarding_info: None,
1921 outbound_htlc_minimum_msat: None,
1922 outbound_htlc_maximum_msat: None,
1924 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
1927 outbound_scid_alias: None,
1928 inbound_scid_alias: None,
1929 channel_value_satoshis: 0,
1932 outbound_capacity_msat,
1933 next_outbound_htlc_limit_msat: outbound_capacity_msat,
1934 inbound_capacity_msat: 42,
1935 unspendable_punishment_reserve: None,
1936 confirmations_required: None,
1937 force_close_spend_delay: None,
1938 is_outbound: true, is_channel_ready: true,
1939 is_usable: true, is_public: true,
1940 inbound_htlc_minimum_msat: None,
1941 inbound_htlc_maximum_msat: None,
1946 // Using the same keys for LN and BTC ids
1948 gossip_sync: &P2PGossipSync<Arc<NetworkGraph<Arc<test_utils::TestLogger>>>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1949 secp_ctx: &Secp256k1<All>, node_1_privkey: &SecretKey, node_2_privkey: &SecretKey, features: ChannelFeatures, short_channel_id: u64
1951 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1952 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1954 let unsigned_announcement = UnsignedChannelAnnouncement {
1956 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1960 bitcoin_key_1: node_id_1,
1961 bitcoin_key_2: node_id_2,
1962 excess_data: Vec::new(),
1965 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1966 let valid_announcement = ChannelAnnouncement {
1967 node_signature_1: secp_ctx.sign_ecdsa(&msghash, node_1_privkey),
1968 node_signature_2: secp_ctx.sign_ecdsa(&msghash, node_2_privkey),
1969 bitcoin_signature_1: secp_ctx.sign_ecdsa(&msghash, node_1_privkey),
1970 bitcoin_signature_2: secp_ctx.sign_ecdsa(&msghash, node_2_privkey),
1971 contents: unsigned_announcement.clone(),
1973 match gossip_sync.handle_channel_announcement(&valid_announcement) {
1974 Ok(res) => assert!(res),
1980 gossip_sync: &P2PGossipSync<Arc<NetworkGraph<Arc<test_utils::TestLogger>>>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1981 secp_ctx: &Secp256k1<All>, node_privkey: &SecretKey, update: UnsignedChannelUpdate
1983 let msghash = hash_to_message!(&Sha256dHash::hash(&update.encode()[..])[..]);
1984 let valid_channel_update = ChannelUpdate {
1985 signature: secp_ctx.sign_ecdsa(&msghash, node_privkey),
1986 contents: update.clone()
1989 match gossip_sync.handle_channel_update(&valid_channel_update) {
1990 Ok(res) => assert!(res),
1995 fn add_or_update_node(
1996 gossip_sync: &P2PGossipSync<Arc<NetworkGraph<Arc<test_utils::TestLogger>>>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1997 secp_ctx: &Secp256k1<All>, node_privkey: &SecretKey, features: NodeFeatures, timestamp: u32
1999 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
2000 let unsigned_announcement = UnsignedNodeAnnouncement {
2006 addresses: Vec::new(),
2007 excess_address_data: Vec::new(),
2008 excess_data: Vec::new(),
2010 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
2011 let valid_announcement = NodeAnnouncement {
2012 signature: secp_ctx.sign_ecdsa(&msghash, node_privkey),
2013 contents: unsigned_announcement.clone()
2016 match gossip_sync.handle_node_announcement(&valid_announcement) {
2022 fn get_nodes(secp_ctx: &Secp256k1<All>) -> (SecretKey, PublicKey, Vec<SecretKey>, Vec<PublicKey>) {
2023 let privkeys: Vec<SecretKey> = (2..22).map(|i| {
2024 SecretKey::from_slice(&hex::decode(format!("{:02x}", i).repeat(32)).unwrap()[..]).unwrap()
2027 let pubkeys = privkeys.iter().map(|secret| PublicKey::from_secret_key(&secp_ctx, secret)).collect();
2029 let our_privkey = SecretKey::from_slice(&hex::decode("01".repeat(32)).unwrap()[..]).unwrap();
2030 let our_id = PublicKey::from_secret_key(&secp_ctx, &our_privkey);
2032 (our_privkey, our_id, privkeys, pubkeys)
2035 fn id_to_feature_flags(id: u8) -> Vec<u8> {
2036 // Set the feature flags to the id'th odd (ie non-required) feature bit so that we can
2037 // test for it later.
2038 let idx = (id - 1) * 2 + 1;
2040 vec![1 << (idx - 8*3), 0, 0, 0]
2041 } else if idx > 8*2 {
2042 vec![1 << (idx - 8*2), 0, 0]
2043 } else if idx > 8*1 {
2044 vec![1 << (idx - 8*1), 0]
2050 fn build_line_graph() -> (
2051 Secp256k1<All>, sync::Arc<NetworkGraph<Arc<test_utils::TestLogger>>>,
2052 P2PGossipSync<sync::Arc<NetworkGraph<Arc<test_utils::TestLogger>>>, sync::Arc<test_utils::TestChainSource>, sync::Arc<test_utils::TestLogger>>,
2053 sync::Arc<test_utils::TestChainSource>, sync::Arc<test_utils::TestLogger>,
2055 let secp_ctx = Secp256k1::new();
2056 let logger = Arc::new(test_utils::TestLogger::new());
2057 let chain_monitor = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
2058 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
2059 let network_graph = Arc::new(NetworkGraph::new(genesis_hash, Arc::clone(&logger)));
2060 let gossip_sync = P2PGossipSync::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
2062 // Build network from our_id to node 19:
2063 // our_id -1(1)2- node0 -1(2)2- node1 - ... - node19
2064 let (our_privkey, _, privkeys, _) = get_nodes(&secp_ctx);
2066 for (idx, (cur_privkey, next_privkey)) in core::iter::once(&our_privkey)
2067 .chain(privkeys.iter()).zip(privkeys.iter()).enumerate() {
2068 let cur_short_channel_id = (idx as u64) + 1;
2069 add_channel(&gossip_sync, &secp_ctx, &cur_privkey, &next_privkey,
2070 ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), cur_short_channel_id);
2071 update_channel(&gossip_sync, &secp_ctx, &cur_privkey, UnsignedChannelUpdate {
2072 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2073 short_channel_id: cur_short_channel_id,
2074 timestamp: idx as u32,
2076 cltv_expiry_delta: 0,
2077 htlc_minimum_msat: 0,
2078 htlc_maximum_msat: OptionalField::Absent,
2080 fee_proportional_millionths: 0,
2081 excess_data: Vec::new()
2083 update_channel(&gossip_sync, &secp_ctx, &next_privkey, UnsignedChannelUpdate {
2084 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2085 short_channel_id: cur_short_channel_id,
2086 timestamp: (idx as u32)+1,
2088 cltv_expiry_delta: 0,
2089 htlc_minimum_msat: 0,
2090 htlc_maximum_msat: OptionalField::Absent,
2092 fee_proportional_millionths: 0,
2093 excess_data: Vec::new()
2095 add_or_update_node(&gossip_sync, &secp_ctx, next_privkey,
2096 NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
2099 (secp_ctx, network_graph, gossip_sync, chain_monitor, logger)
2102 fn build_graph() -> (
2104 sync::Arc<NetworkGraph<Arc<test_utils::TestLogger>>>,
2105 P2PGossipSync<sync::Arc<NetworkGraph<Arc<test_utils::TestLogger>>>, sync::Arc<test_utils::TestChainSource>, sync::Arc<test_utils::TestLogger>>,
2106 sync::Arc<test_utils::TestChainSource>,
2107 sync::Arc<test_utils::TestLogger>,
2109 let secp_ctx = Secp256k1::new();
2110 let logger = Arc::new(test_utils::TestLogger::new());
2111 let chain_monitor = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
2112 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
2113 let network_graph = Arc::new(NetworkGraph::new(genesis_hash, Arc::clone(&logger)));
2114 let gossip_sync = P2PGossipSync::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
2115 // Build network from our_id to node6:
2117 // -1(1)2- node0 -1(3)2-
2119 // our_id -1(12)2- node7 -1(13)2--- node2
2121 // -1(2)2- node1 -1(4)2-
2124 // chan1 1-to-2: disabled
2125 // chan1 2-to-1: enabled, 0 fee
2127 // chan2 1-to-2: enabled, ignored fee
2128 // chan2 2-to-1: enabled, 0 fee
2130 // chan3 1-to-2: enabled, 0 fee
2131 // chan3 2-to-1: enabled, 100 msat fee
2133 // chan4 1-to-2: enabled, 100% fee
2134 // chan4 2-to-1: enabled, 0 fee
2136 // chan12 1-to-2: enabled, ignored fee
2137 // chan12 2-to-1: enabled, 0 fee
2139 // chan13 1-to-2: enabled, 200% fee
2140 // chan13 2-to-1: enabled, 0 fee
2143 // -1(5)2- node3 -1(8)2--
2147 // node2--1(6)2- node4 -1(9)2--- node6 (not in global route map)
2149 // -1(7)2- node5 -1(10)2-
2151 // Channels 5, 8, 9 and 10 are private channels.
2153 // chan5 1-to-2: enabled, 100 msat fee
2154 // chan5 2-to-1: enabled, 0 fee
2156 // chan6 1-to-2: enabled, 0 fee
2157 // chan6 2-to-1: enabled, 0 fee
2159 // chan7 1-to-2: enabled, 100% fee
2160 // chan7 2-to-1: enabled, 0 fee
2162 // chan8 1-to-2: enabled, variable fee (0 then 1000 msat)
2163 // chan8 2-to-1: enabled, 0 fee
2165 // chan9 1-to-2: enabled, 1001 msat fee
2166 // chan9 2-to-1: enabled, 0 fee
2168 // chan10 1-to-2: enabled, 0 fee
2169 // chan10 2-to-1: enabled, 0 fee
2171 // chan11 1-to-2: enabled, 0 fee
2172 // chan11 2-to-1: enabled, 0 fee
2174 let (our_privkey, _, privkeys, _) = get_nodes(&secp_ctx);
2176 add_channel(&gossip_sync, &secp_ctx, &our_privkey, &privkeys[0], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
2177 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2178 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2179 short_channel_id: 1,
2182 cltv_expiry_delta: 0,
2183 htlc_minimum_msat: 0,
2184 htlc_maximum_msat: OptionalField::Absent,
2186 fee_proportional_millionths: 0,
2187 excess_data: Vec::new()
2190 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[0], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
2192 add_channel(&gossip_sync, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
2193 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2194 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2195 short_channel_id: 2,
2198 cltv_expiry_delta: (5 << 4) | 3,
2199 htlc_minimum_msat: 0,
2200 htlc_maximum_msat: OptionalField::Absent,
2201 fee_base_msat: u32::max_value(),
2202 fee_proportional_millionths: u32::max_value(),
2203 excess_data: Vec::new()
2205 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2206 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2207 short_channel_id: 2,
2210 cltv_expiry_delta: 0,
2211 htlc_minimum_msat: 0,
2212 htlc_maximum_msat: OptionalField::Absent,
2214 fee_proportional_millionths: 0,
2215 excess_data: Vec::new()
2218 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
2220 add_channel(&gossip_sync, &secp_ctx, &our_privkey, &privkeys[7], ChannelFeatures::from_le_bytes(id_to_feature_flags(12)), 12);
2221 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2222 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2223 short_channel_id: 12,
2226 cltv_expiry_delta: (5 << 4) | 3,
2227 htlc_minimum_msat: 0,
2228 htlc_maximum_msat: OptionalField::Absent,
2229 fee_base_msat: u32::max_value(),
2230 fee_proportional_millionths: u32::max_value(),
2231 excess_data: Vec::new()
2233 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2234 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2235 short_channel_id: 12,
2238 cltv_expiry_delta: 0,
2239 htlc_minimum_msat: 0,
2240 htlc_maximum_msat: OptionalField::Absent,
2242 fee_proportional_millionths: 0,
2243 excess_data: Vec::new()
2246 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[7], NodeFeatures::from_le_bytes(id_to_feature_flags(8)), 0);
2248 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
2249 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2250 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2251 short_channel_id: 3,
2254 cltv_expiry_delta: (3 << 4) | 1,
2255 htlc_minimum_msat: 0,
2256 htlc_maximum_msat: OptionalField::Absent,
2258 fee_proportional_millionths: 0,
2259 excess_data: Vec::new()
2261 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2262 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2263 short_channel_id: 3,
2266 cltv_expiry_delta: (3 << 4) | 2,
2267 htlc_minimum_msat: 0,
2268 htlc_maximum_msat: OptionalField::Absent,
2270 fee_proportional_millionths: 0,
2271 excess_data: Vec::new()
2274 add_channel(&gossip_sync, &secp_ctx, &privkeys[1], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
2275 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2276 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2277 short_channel_id: 4,
2280 cltv_expiry_delta: (4 << 4) | 1,
2281 htlc_minimum_msat: 0,
2282 htlc_maximum_msat: OptionalField::Absent,
2284 fee_proportional_millionths: 1000000,
2285 excess_data: Vec::new()
2287 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2288 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2289 short_channel_id: 4,
2292 cltv_expiry_delta: (4 << 4) | 2,
2293 htlc_minimum_msat: 0,
2294 htlc_maximum_msat: OptionalField::Absent,
2296 fee_proportional_millionths: 0,
2297 excess_data: Vec::new()
2300 add_channel(&gossip_sync, &secp_ctx, &privkeys[7], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(13)), 13);
2301 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2302 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2303 short_channel_id: 13,
2306 cltv_expiry_delta: (13 << 4) | 1,
2307 htlc_minimum_msat: 0,
2308 htlc_maximum_msat: OptionalField::Absent,
2310 fee_proportional_millionths: 2000000,
2311 excess_data: Vec::new()
2313 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2314 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2315 short_channel_id: 13,
2318 cltv_expiry_delta: (13 << 4) | 2,
2319 htlc_minimum_msat: 0,
2320 htlc_maximum_msat: OptionalField::Absent,
2322 fee_proportional_millionths: 0,
2323 excess_data: Vec::new()
2326 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
2328 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
2329 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2330 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2331 short_channel_id: 6,
2334 cltv_expiry_delta: (6 << 4) | 1,
2335 htlc_minimum_msat: 0,
2336 htlc_maximum_msat: OptionalField::Absent,
2338 fee_proportional_millionths: 0,
2339 excess_data: Vec::new()
2341 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
2342 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2343 short_channel_id: 6,
2346 cltv_expiry_delta: (6 << 4) | 2,
2347 htlc_minimum_msat: 0,
2348 htlc_maximum_msat: OptionalField::Absent,
2350 fee_proportional_millionths: 0,
2351 excess_data: Vec::new(),
2354 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(11)), 11);
2355 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
2356 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2357 short_channel_id: 11,
2360 cltv_expiry_delta: (11 << 4) | 1,
2361 htlc_minimum_msat: 0,
2362 htlc_maximum_msat: OptionalField::Absent,
2364 fee_proportional_millionths: 0,
2365 excess_data: Vec::new()
2367 update_channel(&gossip_sync, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
2368 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2369 short_channel_id: 11,
2372 cltv_expiry_delta: (11 << 4) | 2,
2373 htlc_minimum_msat: 0,
2374 htlc_maximum_msat: OptionalField::Absent,
2376 fee_proportional_millionths: 0,
2377 excess_data: Vec::new()
2380 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(5)), 0);
2382 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
2384 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[5], ChannelFeatures::from_le_bytes(id_to_feature_flags(7)), 7);
2385 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2386 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2387 short_channel_id: 7,
2390 cltv_expiry_delta: (7 << 4) | 1,
2391 htlc_minimum_msat: 0,
2392 htlc_maximum_msat: OptionalField::Absent,
2394 fee_proportional_millionths: 1000000,
2395 excess_data: Vec::new()
2397 update_channel(&gossip_sync, &secp_ctx, &privkeys[5], UnsignedChannelUpdate {
2398 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2399 short_channel_id: 7,
2402 cltv_expiry_delta: (7 << 4) | 2,
2403 htlc_minimum_msat: 0,
2404 htlc_maximum_msat: OptionalField::Absent,
2406 fee_proportional_millionths: 0,
2407 excess_data: Vec::new()
2410 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[5], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
2412 (secp_ctx, network_graph, gossip_sync, chain_monitor, logger)
2416 fn simple_route_test() {
2417 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2418 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2419 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2420 let scorer = test_utils::TestScorer::with_penalty(0);
2421 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2422 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2424 // Simple route to 2 via 1
2426 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) {
2427 assert_eq!(err, "Cannot send a payment of 0 msat");
2428 } else { panic!(); }
2430 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2431 assert_eq!(route.paths[0].len(), 2);
2433 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2434 assert_eq!(route.paths[0][0].short_channel_id, 2);
2435 assert_eq!(route.paths[0][0].fee_msat, 100);
2436 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2437 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2438 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2440 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2441 assert_eq!(route.paths[0][1].short_channel_id, 4);
2442 assert_eq!(route.paths[0][1].fee_msat, 100);
2443 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2444 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2445 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2449 fn invalid_first_hop_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 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
2461 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) =
2462 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) {
2463 assert_eq!(err, "First hop cannot have our_node_pubkey as a destination.");
2464 } else { panic!(); }
2466 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2467 assert_eq!(route.paths[0].len(), 2);
2471 fn htlc_minimum_test() {
2472 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2473 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2474 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2475 let scorer = test_utils::TestScorer::with_penalty(0);
2476 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2477 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2479 // Simple route to 2 via 1
2481 // Disable other paths
2482 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2483 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2484 short_channel_id: 12,
2486 flags: 2, // to disable
2487 cltv_expiry_delta: 0,
2488 htlc_minimum_msat: 0,
2489 htlc_maximum_msat: OptionalField::Absent,
2491 fee_proportional_millionths: 0,
2492 excess_data: Vec::new()
2494 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2495 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2496 short_channel_id: 3,
2498 flags: 2, // to disable
2499 cltv_expiry_delta: 0,
2500 htlc_minimum_msat: 0,
2501 htlc_maximum_msat: OptionalField::Absent,
2503 fee_proportional_millionths: 0,
2504 excess_data: Vec::new()
2506 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2507 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2508 short_channel_id: 13,
2510 flags: 2, // to disable
2511 cltv_expiry_delta: 0,
2512 htlc_minimum_msat: 0,
2513 htlc_maximum_msat: OptionalField::Absent,
2515 fee_proportional_millionths: 0,
2516 excess_data: Vec::new()
2518 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2519 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2520 short_channel_id: 6,
2522 flags: 2, // to disable
2523 cltv_expiry_delta: 0,
2524 htlc_minimum_msat: 0,
2525 htlc_maximum_msat: OptionalField::Absent,
2527 fee_proportional_millionths: 0,
2528 excess_data: Vec::new()
2530 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2531 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2532 short_channel_id: 7,
2534 flags: 2, // to disable
2535 cltv_expiry_delta: 0,
2536 htlc_minimum_msat: 0,
2537 htlc_maximum_msat: OptionalField::Absent,
2539 fee_proportional_millionths: 0,
2540 excess_data: Vec::new()
2543 // Check against amount_to_transfer_over_msat.
2544 // Set minimal HTLC of 200_000_000 msat.
2545 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2546 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2547 short_channel_id: 2,
2550 cltv_expiry_delta: 0,
2551 htlc_minimum_msat: 200_000_000,
2552 htlc_maximum_msat: OptionalField::Absent,
2554 fee_proportional_millionths: 0,
2555 excess_data: Vec::new()
2558 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
2560 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2561 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2562 short_channel_id: 4,
2565 cltv_expiry_delta: 0,
2566 htlc_minimum_msat: 0,
2567 htlc_maximum_msat: OptionalField::Present(199_999_999),
2569 fee_proportional_millionths: 0,
2570 excess_data: Vec::new()
2573 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
2574 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) {
2575 assert_eq!(err, "Failed to find a path to the given destination");
2576 } else { panic!(); }
2578 // Lift the restriction on the first hop.
2579 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2580 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2581 short_channel_id: 2,
2584 cltv_expiry_delta: 0,
2585 htlc_minimum_msat: 0,
2586 htlc_maximum_msat: OptionalField::Absent,
2588 fee_proportional_millionths: 0,
2589 excess_data: Vec::new()
2592 // A payment above the minimum should pass
2593 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();
2594 assert_eq!(route.paths[0].len(), 2);
2598 fn htlc_minimum_overpay_test() {
2599 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2600 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2601 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
2602 let scorer = test_utils::TestScorer::with_penalty(0);
2603 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2604 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2606 // A route to node#2 via two paths.
2607 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
2608 // Thus, they can't send 60 without overpaying.
2609 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2610 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2611 short_channel_id: 2,
2614 cltv_expiry_delta: 0,
2615 htlc_minimum_msat: 35_000,
2616 htlc_maximum_msat: OptionalField::Present(40_000),
2618 fee_proportional_millionths: 0,
2619 excess_data: Vec::new()
2621 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2622 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2623 short_channel_id: 12,
2626 cltv_expiry_delta: 0,
2627 htlc_minimum_msat: 35_000,
2628 htlc_maximum_msat: OptionalField::Present(40_000),
2630 fee_proportional_millionths: 0,
2631 excess_data: Vec::new()
2635 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2636 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2637 short_channel_id: 13,
2640 cltv_expiry_delta: 0,
2641 htlc_minimum_msat: 0,
2642 htlc_maximum_msat: OptionalField::Absent,
2644 fee_proportional_millionths: 0,
2645 excess_data: Vec::new()
2647 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2648 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2649 short_channel_id: 4,
2652 cltv_expiry_delta: 0,
2653 htlc_minimum_msat: 0,
2654 htlc_maximum_msat: OptionalField::Absent,
2656 fee_proportional_millionths: 0,
2657 excess_data: Vec::new()
2660 // Disable other paths
2661 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2662 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2663 short_channel_id: 1,
2665 flags: 2, // to disable
2666 cltv_expiry_delta: 0,
2667 htlc_minimum_msat: 0,
2668 htlc_maximum_msat: OptionalField::Absent,
2670 fee_proportional_millionths: 0,
2671 excess_data: Vec::new()
2674 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 60_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2675 // Overpay fees to hit htlc_minimum_msat.
2676 let overpaid_fees = route.paths[0][0].fee_msat + route.paths[1][0].fee_msat;
2677 // TODO: this could be better balanced to overpay 10k and not 15k.
2678 assert_eq!(overpaid_fees, 15_000);
2680 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
2681 // while taking even more fee to match htlc_minimum_msat.
2682 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2683 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2684 short_channel_id: 12,
2687 cltv_expiry_delta: 0,
2688 htlc_minimum_msat: 65_000,
2689 htlc_maximum_msat: OptionalField::Present(80_000),
2691 fee_proportional_millionths: 0,
2692 excess_data: Vec::new()
2694 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2695 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2696 short_channel_id: 2,
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()
2706 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2707 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2708 short_channel_id: 4,
2711 cltv_expiry_delta: 0,
2712 htlc_minimum_msat: 0,
2713 htlc_maximum_msat: OptionalField::Absent,
2715 fee_proportional_millionths: 100_000,
2716 excess_data: Vec::new()
2719 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 60_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2720 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
2721 assert_eq!(route.paths.len(), 1);
2722 assert_eq!(route.paths[0][0].short_channel_id, 12);
2723 let fees = route.paths[0][0].fee_msat;
2724 assert_eq!(fees, 5_000);
2726 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2727 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
2728 // the other channel.
2729 assert_eq!(route.paths.len(), 1);
2730 assert_eq!(route.paths[0][0].short_channel_id, 2);
2731 let fees = route.paths[0][0].fee_msat;
2732 assert_eq!(fees, 5_000);
2736 fn disable_channels_test() {
2737 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2738 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2739 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2740 let scorer = test_utils::TestScorer::with_penalty(0);
2741 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2742 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2744 // // Disable channels 4 and 12 by flags=2
2745 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2746 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2747 short_channel_id: 4,
2749 flags: 2, // to disable
2750 cltv_expiry_delta: 0,
2751 htlc_minimum_msat: 0,
2752 htlc_maximum_msat: OptionalField::Absent,
2754 fee_proportional_millionths: 0,
2755 excess_data: Vec::new()
2757 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2758 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2759 short_channel_id: 12,
2761 flags: 2, // to disable
2762 cltv_expiry_delta: 0,
2763 htlc_minimum_msat: 0,
2764 htlc_maximum_msat: OptionalField::Absent,
2766 fee_proportional_millionths: 0,
2767 excess_data: Vec::new()
2770 // If all the channels require some features we don't understand, route should fail
2771 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) {
2772 assert_eq!(err, "Failed to find a path to the given destination");
2773 } else { panic!(); }
2775 // If we specify a channel to node7, that overrides our local channel view and that gets used
2776 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2777 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();
2778 assert_eq!(route.paths[0].len(), 2);
2780 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2781 assert_eq!(route.paths[0][0].short_channel_id, 42);
2782 assert_eq!(route.paths[0][0].fee_msat, 200);
2783 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2784 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2785 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2787 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2788 assert_eq!(route.paths[0][1].short_channel_id, 13);
2789 assert_eq!(route.paths[0][1].fee_msat, 100);
2790 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2791 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2792 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2796 fn disable_node_test() {
2797 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2798 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2799 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2800 let scorer = test_utils::TestScorer::with_penalty(0);
2801 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2802 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2804 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
2805 let mut unknown_features = NodeFeatures::known();
2806 unknown_features.set_unknown_feature_required();
2807 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
2808 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
2809 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
2811 // If all nodes require some features we don't understand, route should fail
2812 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) {
2813 assert_eq!(err, "Failed to find a path to the given destination");
2814 } else { panic!(); }
2816 // If we specify a channel to node7, that overrides our local channel view and that gets used
2817 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2818 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();
2819 assert_eq!(route.paths[0].len(), 2);
2821 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2822 assert_eq!(route.paths[0][0].short_channel_id, 42);
2823 assert_eq!(route.paths[0][0].fee_msat, 200);
2824 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2825 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2826 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2828 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2829 assert_eq!(route.paths[0][1].short_channel_id, 13);
2830 assert_eq!(route.paths[0][1].fee_msat, 100);
2831 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2832 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2833 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2835 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
2836 // naively) assume that the user checked the feature bits on the invoice, which override
2837 // the node_announcement.
2841 fn our_chans_test() {
2842 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2843 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2844 let scorer = test_utils::TestScorer::with_penalty(0);
2845 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2846 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2848 // Route to 1 via 2 and 3 because our channel to 1 is disabled
2849 let payment_params = PaymentParameters::from_node_id(nodes[0]);
2850 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2851 assert_eq!(route.paths[0].len(), 3);
2853 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2854 assert_eq!(route.paths[0][0].short_channel_id, 2);
2855 assert_eq!(route.paths[0][0].fee_msat, 200);
2856 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2857 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2858 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2860 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2861 assert_eq!(route.paths[0][1].short_channel_id, 4);
2862 assert_eq!(route.paths[0][1].fee_msat, 100);
2863 assert_eq!(route.paths[0][1].cltv_expiry_delta, (3 << 4) | 2);
2864 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2865 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2867 assert_eq!(route.paths[0][2].pubkey, nodes[0]);
2868 assert_eq!(route.paths[0][2].short_channel_id, 3);
2869 assert_eq!(route.paths[0][2].fee_msat, 100);
2870 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
2871 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(1));
2872 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(3));
2874 // If we specify a channel to node7, that overrides our local channel view and that gets used
2875 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2876 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2877 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();
2878 assert_eq!(route.paths[0].len(), 2);
2880 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2881 assert_eq!(route.paths[0][0].short_channel_id, 42);
2882 assert_eq!(route.paths[0][0].fee_msat, 200);
2883 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2884 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2885 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2887 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2888 assert_eq!(route.paths[0][1].short_channel_id, 13);
2889 assert_eq!(route.paths[0][1].fee_msat, 100);
2890 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2891 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2892 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2895 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2896 let zero_fees = RoutingFees {
2898 proportional_millionths: 0,
2900 vec![RouteHint(vec![RouteHintHop {
2901 src_node_id: nodes[3],
2902 short_channel_id: 8,
2904 cltv_expiry_delta: (8 << 4) | 1,
2905 htlc_minimum_msat: None,
2906 htlc_maximum_msat: None,
2908 ]), RouteHint(vec![RouteHintHop {
2909 src_node_id: nodes[4],
2910 short_channel_id: 9,
2913 proportional_millionths: 0,
2915 cltv_expiry_delta: (9 << 4) | 1,
2916 htlc_minimum_msat: None,
2917 htlc_maximum_msat: None,
2918 }]), RouteHint(vec![RouteHintHop {
2919 src_node_id: nodes[5],
2920 short_channel_id: 10,
2922 cltv_expiry_delta: (10 << 4) | 1,
2923 htlc_minimum_msat: None,
2924 htlc_maximum_msat: None,
2928 fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2929 let zero_fees = RoutingFees {
2931 proportional_millionths: 0,
2933 vec![RouteHint(vec![RouteHintHop {
2934 src_node_id: nodes[2],
2935 short_channel_id: 5,
2938 proportional_millionths: 0,
2940 cltv_expiry_delta: (5 << 4) | 1,
2941 htlc_minimum_msat: None,
2942 htlc_maximum_msat: None,
2944 src_node_id: nodes[3],
2945 short_channel_id: 8,
2947 cltv_expiry_delta: (8 << 4) | 1,
2948 htlc_minimum_msat: None,
2949 htlc_maximum_msat: None,
2951 ]), RouteHint(vec![RouteHintHop {
2952 src_node_id: nodes[4],
2953 short_channel_id: 9,
2956 proportional_millionths: 0,
2958 cltv_expiry_delta: (9 << 4) | 1,
2959 htlc_minimum_msat: None,
2960 htlc_maximum_msat: None,
2961 }]), RouteHint(vec![RouteHintHop {
2962 src_node_id: nodes[5],
2963 short_channel_id: 10,
2965 cltv_expiry_delta: (10 << 4) | 1,
2966 htlc_minimum_msat: None,
2967 htlc_maximum_msat: None,
2972 fn partial_route_hint_test() {
2973 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2974 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2975 let scorer = test_utils::TestScorer::with_penalty(0);
2976 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2977 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2979 // Simple test across 2, 3, 5, and 4 via a last_hop channel
2980 // Tests the behaviour when the RouteHint contains a suboptimal hop.
2981 // RouteHint may be partially used by the algo to build the best path.
2983 // First check that last hop can't have its source as the payee.
2984 let invalid_last_hop = RouteHint(vec![RouteHintHop {
2985 src_node_id: nodes[6],
2986 short_channel_id: 8,
2989 proportional_millionths: 0,
2991 cltv_expiry_delta: (8 << 4) | 1,
2992 htlc_minimum_msat: None,
2993 htlc_maximum_msat: None,
2996 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
2997 invalid_last_hops.push(invalid_last_hop);
2999 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(invalid_last_hops);
3000 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) {
3001 assert_eq!(err, "Route hint cannot have the payee as the source.");
3002 } else { panic!(); }
3005 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops_multi_private_channels(&nodes));
3006 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3007 assert_eq!(route.paths[0].len(), 5);
3009 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3010 assert_eq!(route.paths[0][0].short_channel_id, 2);
3011 assert_eq!(route.paths[0][0].fee_msat, 100);
3012 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
3013 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3014 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3016 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3017 assert_eq!(route.paths[0][1].short_channel_id, 4);
3018 assert_eq!(route.paths[0][1].fee_msat, 0);
3019 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
3020 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3021 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3023 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
3024 assert_eq!(route.paths[0][2].short_channel_id, 6);
3025 assert_eq!(route.paths[0][2].fee_msat, 0);
3026 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
3027 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
3028 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
3030 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
3031 assert_eq!(route.paths[0][3].short_channel_id, 11);
3032 assert_eq!(route.paths[0][3].fee_msat, 0);
3033 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
3034 // If we have a peer in the node map, we'll use their features here since we don't have
3035 // a way of figuring out their features from the invoice:
3036 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
3037 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
3039 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
3040 assert_eq!(route.paths[0][4].short_channel_id, 8);
3041 assert_eq!(route.paths[0][4].fee_msat, 100);
3042 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
3043 assert_eq!(route.paths[0][4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3044 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3047 fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3048 let zero_fees = RoutingFees {
3050 proportional_millionths: 0,
3052 vec![RouteHint(vec![RouteHintHop {
3053 src_node_id: nodes[3],
3054 short_channel_id: 8,
3056 cltv_expiry_delta: (8 << 4) | 1,
3057 htlc_minimum_msat: None,
3058 htlc_maximum_msat: None,
3059 }]), RouteHint(vec![
3061 ]), RouteHint(vec![RouteHintHop {
3062 src_node_id: nodes[5],
3063 short_channel_id: 10,
3065 cltv_expiry_delta: (10 << 4) | 1,
3066 htlc_minimum_msat: None,
3067 htlc_maximum_msat: None,
3072 fn ignores_empty_last_hops_test() {
3073 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3074 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3075 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(empty_last_hop(&nodes));
3076 let scorer = test_utils::TestScorer::with_penalty(0);
3077 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3078 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3080 // Test handling of an empty RouteHint passed in Invoice.
3082 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3083 assert_eq!(route.paths[0].len(), 5);
3085 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3086 assert_eq!(route.paths[0][0].short_channel_id, 2);
3087 assert_eq!(route.paths[0][0].fee_msat, 100);
3088 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
3089 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3090 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3092 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3093 assert_eq!(route.paths[0][1].short_channel_id, 4);
3094 assert_eq!(route.paths[0][1].fee_msat, 0);
3095 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
3096 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3097 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3099 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
3100 assert_eq!(route.paths[0][2].short_channel_id, 6);
3101 assert_eq!(route.paths[0][2].fee_msat, 0);
3102 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
3103 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
3104 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
3106 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
3107 assert_eq!(route.paths[0][3].short_channel_id, 11);
3108 assert_eq!(route.paths[0][3].fee_msat, 0);
3109 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
3110 // If we have a peer in the node map, we'll use their features here since we don't have
3111 // a way of figuring out their features from the invoice:
3112 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
3113 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
3115 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
3116 assert_eq!(route.paths[0][4].short_channel_id, 8);
3117 assert_eq!(route.paths[0][4].fee_msat, 100);
3118 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
3119 assert_eq!(route.paths[0][4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3120 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3123 /// Builds a trivial last-hop hint that passes through the two nodes given, with channel 0xff00
3125 fn multi_hop_last_hops_hint(hint_hops: [PublicKey; 2]) -> Vec<RouteHint> {
3126 let zero_fees = RoutingFees {
3128 proportional_millionths: 0,
3130 vec![RouteHint(vec![RouteHintHop {
3131 src_node_id: hint_hops[0],
3132 short_channel_id: 0xff00,
3135 proportional_millionths: 0,
3137 cltv_expiry_delta: (5 << 4) | 1,
3138 htlc_minimum_msat: None,
3139 htlc_maximum_msat: None,
3141 src_node_id: hint_hops[1],
3142 short_channel_id: 0xff01,
3144 cltv_expiry_delta: (8 << 4) | 1,
3145 htlc_minimum_msat: None,
3146 htlc_maximum_msat: None,
3151 fn multi_hint_last_hops_test() {
3152 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3153 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3154 let last_hops = multi_hop_last_hops_hint([nodes[2], nodes[3]]);
3155 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops.clone());
3156 let scorer = test_utils::TestScorer::with_penalty(0);
3157 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3158 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3159 // Test through channels 2, 3, 0xff00, 0xff01.
3160 // Test shows that multiple hop hints are considered.
3162 // Disabling channels 6 & 7 by flags=2
3163 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3164 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3165 short_channel_id: 6,
3167 flags: 2, // to disable
3168 cltv_expiry_delta: 0,
3169 htlc_minimum_msat: 0,
3170 htlc_maximum_msat: OptionalField::Absent,
3172 fee_proportional_millionths: 0,
3173 excess_data: Vec::new()
3175 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3176 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3177 short_channel_id: 7,
3179 flags: 2, // to disable
3180 cltv_expiry_delta: 0,
3181 htlc_minimum_msat: 0,
3182 htlc_maximum_msat: OptionalField::Absent,
3184 fee_proportional_millionths: 0,
3185 excess_data: Vec::new()
3188 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3189 assert_eq!(route.paths[0].len(), 4);
3191 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3192 assert_eq!(route.paths[0][0].short_channel_id, 2);
3193 assert_eq!(route.paths[0][0].fee_msat, 200);
3194 assert_eq!(route.paths[0][0].cltv_expiry_delta, 65);
3195 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3196 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3198 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3199 assert_eq!(route.paths[0][1].short_channel_id, 4);
3200 assert_eq!(route.paths[0][1].fee_msat, 100);
3201 assert_eq!(route.paths[0][1].cltv_expiry_delta, 81);
3202 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3203 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3205 assert_eq!(route.paths[0][2].pubkey, nodes[3]);
3206 assert_eq!(route.paths[0][2].short_channel_id, last_hops[0].0[0].short_channel_id);
3207 assert_eq!(route.paths[0][2].fee_msat, 0);
3208 assert_eq!(route.paths[0][2].cltv_expiry_delta, 129);
3209 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(4));
3210 assert_eq!(route.paths[0][2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3212 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
3213 assert_eq!(route.paths[0][3].short_channel_id, last_hops[0].0[1].short_channel_id);
3214 assert_eq!(route.paths[0][3].fee_msat, 100);
3215 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
3216 assert_eq!(route.paths[0][3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3217 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3221 fn private_multi_hint_last_hops_test() {
3222 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3223 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3225 let non_announced_privkey = SecretKey::from_slice(&hex::decode(format!("{:02x}", 0xf0).repeat(32)).unwrap()[..]).unwrap();
3226 let non_announced_pubkey = PublicKey::from_secret_key(&secp_ctx, &non_announced_privkey);
3228 let last_hops = multi_hop_last_hops_hint([nodes[2], non_announced_pubkey]);
3229 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops.clone());
3230 let scorer = test_utils::TestScorer::with_penalty(0);
3231 // Test through channels 2, 3, 0xff00, 0xff01.
3232 // Test shows that multiple hop hints are considered.
3234 // Disabling channels 6 & 7 by flags=2
3235 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3236 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3237 short_channel_id: 6,
3239 flags: 2, // to disable
3240 cltv_expiry_delta: 0,
3241 htlc_minimum_msat: 0,
3242 htlc_maximum_msat: OptionalField::Absent,
3244 fee_proportional_millionths: 0,
3245 excess_data: Vec::new()
3247 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3248 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3249 short_channel_id: 7,
3251 flags: 2, // to disable
3252 cltv_expiry_delta: 0,
3253 htlc_minimum_msat: 0,
3254 htlc_maximum_msat: OptionalField::Absent,
3256 fee_proportional_millionths: 0,
3257 excess_data: Vec::new()
3260 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &[42u8; 32]).unwrap();
3261 assert_eq!(route.paths[0].len(), 4);
3263 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3264 assert_eq!(route.paths[0][0].short_channel_id, 2);
3265 assert_eq!(route.paths[0][0].fee_msat, 200);
3266 assert_eq!(route.paths[0][0].cltv_expiry_delta, 65);
3267 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3268 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3270 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3271 assert_eq!(route.paths[0][1].short_channel_id, 4);
3272 assert_eq!(route.paths[0][1].fee_msat, 100);
3273 assert_eq!(route.paths[0][1].cltv_expiry_delta, 81);
3274 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3275 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3277 assert_eq!(route.paths[0][2].pubkey, non_announced_pubkey);
3278 assert_eq!(route.paths[0][2].short_channel_id, last_hops[0].0[0].short_channel_id);
3279 assert_eq!(route.paths[0][2].fee_msat, 0);
3280 assert_eq!(route.paths[0][2].cltv_expiry_delta, 129);
3281 assert_eq!(route.paths[0][2].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3282 assert_eq!(route.paths[0][2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3284 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
3285 assert_eq!(route.paths[0][3].short_channel_id, last_hops[0].0[1].short_channel_id);
3286 assert_eq!(route.paths[0][3].fee_msat, 100);
3287 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
3288 assert_eq!(route.paths[0][3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3289 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3292 fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3293 let zero_fees = RoutingFees {
3295 proportional_millionths: 0,
3297 vec![RouteHint(vec![RouteHintHop {
3298 src_node_id: nodes[4],
3299 short_channel_id: 11,
3301 cltv_expiry_delta: (11 << 4) | 1,
3302 htlc_minimum_msat: None,
3303 htlc_maximum_msat: None,
3305 src_node_id: nodes[3],
3306 short_channel_id: 8,
3308 cltv_expiry_delta: (8 << 4) | 1,
3309 htlc_minimum_msat: None,
3310 htlc_maximum_msat: None,
3311 }]), RouteHint(vec![RouteHintHop {
3312 src_node_id: nodes[4],
3313 short_channel_id: 9,
3316 proportional_millionths: 0,
3318 cltv_expiry_delta: (9 << 4) | 1,
3319 htlc_minimum_msat: None,
3320 htlc_maximum_msat: None,
3321 }]), RouteHint(vec![RouteHintHop {
3322 src_node_id: nodes[5],
3323 short_channel_id: 10,
3325 cltv_expiry_delta: (10 << 4) | 1,
3326 htlc_minimum_msat: None,
3327 htlc_maximum_msat: None,
3332 fn last_hops_with_public_channel_test() {
3333 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3334 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3335 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops_with_public_channel(&nodes));
3336 let scorer = test_utils::TestScorer::with_penalty(0);
3337 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3338 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3339 // This test shows that public routes can be present in the invoice
3340 // which would be handled in the same manner.
3342 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3343 assert_eq!(route.paths[0].len(), 5);
3345 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3346 assert_eq!(route.paths[0][0].short_channel_id, 2);
3347 assert_eq!(route.paths[0][0].fee_msat, 100);
3348 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
3349 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3350 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3352 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3353 assert_eq!(route.paths[0][1].short_channel_id, 4);
3354 assert_eq!(route.paths[0][1].fee_msat, 0);
3355 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
3356 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3357 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3359 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
3360 assert_eq!(route.paths[0][2].short_channel_id, 6);
3361 assert_eq!(route.paths[0][2].fee_msat, 0);
3362 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
3363 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
3364 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
3366 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
3367 assert_eq!(route.paths[0][3].short_channel_id, 11);
3368 assert_eq!(route.paths[0][3].fee_msat, 0);
3369 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
3370 // If we have a peer in the node map, we'll use their features here since we don't have
3371 // a way of figuring out their features from the invoice:
3372 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
3373 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
3375 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
3376 assert_eq!(route.paths[0][4].short_channel_id, 8);
3377 assert_eq!(route.paths[0][4].fee_msat, 100);
3378 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
3379 assert_eq!(route.paths[0][4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3380 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3384 fn our_chans_last_hop_connect_test() {
3385 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3386 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3387 let scorer = test_utils::TestScorer::with_penalty(0);
3388 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3389 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3391 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
3392 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3393 let mut last_hops = last_hops(&nodes);
3394 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops.clone());
3395 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();
3396 assert_eq!(route.paths[0].len(), 2);
3398 assert_eq!(route.paths[0][0].pubkey, nodes[3]);
3399 assert_eq!(route.paths[0][0].short_channel_id, 42);
3400 assert_eq!(route.paths[0][0].fee_msat, 0);
3401 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 4) | 1);
3402 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
3403 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3405 assert_eq!(route.paths[0][1].pubkey, nodes[6]);
3406 assert_eq!(route.paths[0][1].short_channel_id, 8);
3407 assert_eq!(route.paths[0][1].fee_msat, 100);
3408 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
3409 assert_eq!(route.paths[0][1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3410 assert_eq!(route.paths[0][1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3412 last_hops[0].0[0].fees.base_msat = 1000;
3414 // Revert to via 6 as the fee on 8 goes up
3415 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops);
3416 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3417 assert_eq!(route.paths[0].len(), 4);
3419 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3420 assert_eq!(route.paths[0][0].short_channel_id, 2);
3421 assert_eq!(route.paths[0][0].fee_msat, 200); // fee increased as its % of value transferred across node
3422 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
3423 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3424 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3426 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3427 assert_eq!(route.paths[0][1].short_channel_id, 4);
3428 assert_eq!(route.paths[0][1].fee_msat, 100);
3429 assert_eq!(route.paths[0][1].cltv_expiry_delta, (7 << 4) | 1);
3430 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3431 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3433 assert_eq!(route.paths[0][2].pubkey, nodes[5]);
3434 assert_eq!(route.paths[0][2].short_channel_id, 7);
3435 assert_eq!(route.paths[0][2].fee_msat, 0);
3436 assert_eq!(route.paths[0][2].cltv_expiry_delta, (10 << 4) | 1);
3437 // If we have a peer in the node map, we'll use their features here since we don't have
3438 // a way of figuring out their features from the invoice:
3439 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
3440 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(7));
3442 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
3443 assert_eq!(route.paths[0][3].short_channel_id, 10);
3444 assert_eq!(route.paths[0][3].fee_msat, 100);
3445 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
3446 assert_eq!(route.paths[0][3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3447 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3449 // ...but still use 8 for larger payments as 6 has a variable feerate
3450 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 2000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3451 assert_eq!(route.paths[0].len(), 5);
3453 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3454 assert_eq!(route.paths[0][0].short_channel_id, 2);
3455 assert_eq!(route.paths[0][0].fee_msat, 3000);
3456 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
3457 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3458 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3460 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3461 assert_eq!(route.paths[0][1].short_channel_id, 4);
3462 assert_eq!(route.paths[0][1].fee_msat, 0);
3463 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
3464 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3465 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3467 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
3468 assert_eq!(route.paths[0][2].short_channel_id, 6);
3469 assert_eq!(route.paths[0][2].fee_msat, 0);
3470 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
3471 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
3472 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
3474 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
3475 assert_eq!(route.paths[0][3].short_channel_id, 11);
3476 assert_eq!(route.paths[0][3].fee_msat, 1000);
3477 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
3478 // If we have a peer in the node map, we'll use their features here since we don't have
3479 // a way of figuring out their features from the invoice:
3480 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
3481 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
3483 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
3484 assert_eq!(route.paths[0][4].short_channel_id, 8);
3485 assert_eq!(route.paths[0][4].fee_msat, 2000);
3486 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
3487 assert_eq!(route.paths[0][4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3488 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3491 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> {
3492 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
3493 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3494 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3496 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
3497 let last_hops = RouteHint(vec![RouteHintHop {
3498 src_node_id: middle_node_id,
3499 short_channel_id: 8,
3502 proportional_millionths: last_hop_fee_prop,
3504 cltv_expiry_delta: (8 << 4) | 1,
3505 htlc_minimum_msat: None,
3506 htlc_maximum_msat: last_hop_htlc_max,
3508 let payment_params = PaymentParameters::from_node_id(target_node_id).with_route_hints(vec![last_hops]);
3509 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
3510 let scorer = test_utils::TestScorer::with_penalty(0);
3511 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3512 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3513 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
3514 let logger = test_utils::TestLogger::new();
3515 let network_graph = NetworkGraph::new(genesis_hash, &logger);
3516 let route = get_route(&source_node_id, &payment_params, &network_graph.read_only(),
3517 Some(&our_chans.iter().collect::<Vec<_>>()), route_val, 42, &logger, &scorer, &random_seed_bytes);
3522 fn unannounced_path_test() {
3523 // We should be able to send a payment to a destination without any help of a routing graph
3524 // if we have a channel with a common counterparty that appears in the first and last hop
3526 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
3528 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3529 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3530 assert_eq!(route.paths[0].len(), 2);
3532 assert_eq!(route.paths[0][0].pubkey, middle_node_id);
3533 assert_eq!(route.paths[0][0].short_channel_id, 42);
3534 assert_eq!(route.paths[0][0].fee_msat, 1001);
3535 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 4) | 1);
3536 assert_eq!(route.paths[0][0].node_features.le_flags(), &[0b11]);
3537 assert_eq!(route.paths[0][0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3539 assert_eq!(route.paths[0][1].pubkey, target_node_id);
3540 assert_eq!(route.paths[0][1].short_channel_id, 8);
3541 assert_eq!(route.paths[0][1].fee_msat, 1000000);
3542 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
3543 assert_eq!(route.paths[0][1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3544 assert_eq!(route.paths[0][1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3548 fn overflow_unannounced_path_test_liquidity_underflow() {
3549 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
3550 // the last-hop had a fee which overflowed a u64, we'd panic.
3551 // This was due to us adding the first-hop from us unconditionally, causing us to think
3552 // we'd built a path (as our node is in the "best candidate" set), when we had not.
3553 // In this test, we previously hit a subtraction underflow due to having less available
3554 // liquidity at the last hop than 0.
3555 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());
3559 fn overflow_unannounced_path_test_feerate_overflow() {
3560 // This tests for the same case as above, except instead of hitting a subtraction
3561 // underflow, we hit a case where the fee charged at a hop overflowed.
3562 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());
3566 fn available_amount_while_routing_test() {
3567 // Tests whether we choose the correct available channel amount while routing.
3569 let (secp_ctx, network_graph, mut gossip_sync, chain_monitor, logger) = build_graph();
3570 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3571 let scorer = test_utils::TestScorer::with_penalty(0);
3572 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3573 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3574 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
3576 // We will use a simple single-path route from
3577 // our node to node2 via node0: channels {1, 3}.
3579 // First disable all other paths.
3580 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3581 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3582 short_channel_id: 2,
3585 cltv_expiry_delta: 0,
3586 htlc_minimum_msat: 0,
3587 htlc_maximum_msat: OptionalField::Present(100_000),
3589 fee_proportional_millionths: 0,
3590 excess_data: Vec::new()
3592 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3593 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3594 short_channel_id: 12,
3597 cltv_expiry_delta: 0,
3598 htlc_minimum_msat: 0,
3599 htlc_maximum_msat: OptionalField::Present(100_000),
3601 fee_proportional_millionths: 0,
3602 excess_data: Vec::new()
3605 // Make the first channel (#1) very permissive,
3606 // and we will be testing all limits on the second channel.
3607 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3608 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3609 short_channel_id: 1,
3612 cltv_expiry_delta: 0,
3613 htlc_minimum_msat: 0,
3614 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3616 fee_proportional_millionths: 0,
3617 excess_data: Vec::new()
3620 // First, let's see if routing works if we have absolutely no idea about the available amount.
3621 // In this case, it should be set to 250_000 sats.
3622 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3623 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3624 short_channel_id: 3,
3627 cltv_expiry_delta: 0,
3628 htlc_minimum_msat: 0,
3629 htlc_maximum_msat: OptionalField::Absent,
3631 fee_proportional_millionths: 0,
3632 excess_data: Vec::new()
3636 // Attempt to route more than available results in a failure.
3637 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3638 &our_id, &payment_params, &network_graph.read_only(), None, 250_000_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3639 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3640 } else { panic!(); }
3644 // Now, attempt to route an exact amount we have should be fine.
3645 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();
3646 assert_eq!(route.paths.len(), 1);
3647 let path = route.paths.last().unwrap();
3648 assert_eq!(path.len(), 2);
3649 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3650 assert_eq!(path.last().unwrap().fee_msat, 250_000_000);
3653 // Check that setting next_outbound_htlc_limit_msat in first_hops limits the channels.
3654 // Disable channel #1 and use another first hop.
3655 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3656 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3657 short_channel_id: 1,
3660 cltv_expiry_delta: 0,
3661 htlc_minimum_msat: 0,
3662 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3664 fee_proportional_millionths: 0,
3665 excess_data: Vec::new()
3668 // Now, limit the first_hop by the next_outbound_htlc_limit_msat of 200_000 sats.
3669 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
3672 // Attempt to route more than available results in a failure.
3673 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3674 &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) {
3675 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3676 } else { panic!(); }
3680 // Now, attempt to route an exact amount we have should be fine.
3681 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();
3682 assert_eq!(route.paths.len(), 1);
3683 let path = route.paths.last().unwrap();
3684 assert_eq!(path.len(), 2);
3685 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3686 assert_eq!(path.last().unwrap().fee_msat, 200_000_000);
3689 // Enable channel #1 back.
3690 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3691 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3692 short_channel_id: 1,
3695 cltv_expiry_delta: 0,
3696 htlc_minimum_msat: 0,
3697 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3699 fee_proportional_millionths: 0,
3700 excess_data: Vec::new()
3704 // Now let's see if routing works if we know only htlc_maximum_msat.
3705 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3706 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3707 short_channel_id: 3,
3710 cltv_expiry_delta: 0,
3711 htlc_minimum_msat: 0,
3712 htlc_maximum_msat: OptionalField::Present(15_000),
3714 fee_proportional_millionths: 0,
3715 excess_data: Vec::new()
3719 // Attempt to route more than available results in a failure.
3720 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3721 &our_id, &payment_params, &network_graph.read_only(), None, 15_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3722 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3723 } else { panic!(); }
3727 // Now, attempt to route an exact amount we have should be fine.
3728 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 15_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3729 assert_eq!(route.paths.len(), 1);
3730 let path = route.paths.last().unwrap();
3731 assert_eq!(path.len(), 2);
3732 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3733 assert_eq!(path.last().unwrap().fee_msat, 15_000);
3736 // Now let's see if routing works if we know only capacity from the UTXO.
3738 // We can't change UTXO capacity on the fly, so we'll disable
3739 // the existing channel and add another one with the capacity we need.
3740 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3741 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3742 short_channel_id: 3,
3745 cltv_expiry_delta: 0,
3746 htlc_minimum_msat: 0,
3747 htlc_maximum_msat: OptionalField::Absent,
3749 fee_proportional_millionths: 0,
3750 excess_data: Vec::new()
3753 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
3754 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
3755 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
3756 .push_opcode(opcodes::all::OP_PUSHNUM_2)
3757 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
3759 *chain_monitor.utxo_ret.lock().unwrap() = Ok(TxOut { value: 15, script_pubkey: good_script.clone() });
3760 gossip_sync.add_chain_access(Some(chain_monitor));
3762 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
3763 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3764 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3765 short_channel_id: 333,
3768 cltv_expiry_delta: (3 << 4) | 1,
3769 htlc_minimum_msat: 0,
3770 htlc_maximum_msat: OptionalField::Absent,
3772 fee_proportional_millionths: 0,
3773 excess_data: Vec::new()
3775 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3776 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3777 short_channel_id: 333,
3780 cltv_expiry_delta: (3 << 4) | 2,
3781 htlc_minimum_msat: 0,
3782 htlc_maximum_msat: OptionalField::Absent,
3784 fee_proportional_millionths: 0,
3785 excess_data: Vec::new()
3789 // Attempt to route more than available results in a failure.
3790 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3791 &our_id, &payment_params, &network_graph.read_only(), None, 15_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3792 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3793 } else { panic!(); }
3797 // Now, attempt to route an exact amount we have should be fine.
3798 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 15_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3799 assert_eq!(route.paths.len(), 1);
3800 let path = route.paths.last().unwrap();
3801 assert_eq!(path.len(), 2);
3802 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3803 assert_eq!(path.last().unwrap().fee_msat, 15_000);
3806 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
3807 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3808 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3809 short_channel_id: 333,
3812 cltv_expiry_delta: 0,
3813 htlc_minimum_msat: 0,
3814 htlc_maximum_msat: OptionalField::Present(10_000),
3816 fee_proportional_millionths: 0,
3817 excess_data: Vec::new()
3821 // Attempt to route more than available results in a failure.
3822 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3823 &our_id, &payment_params, &network_graph.read_only(), None, 10_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3824 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3825 } else { panic!(); }
3829 // Now, attempt to route an exact amount we have should be fine.
3830 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 10_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3831 assert_eq!(route.paths.len(), 1);
3832 let path = route.paths.last().unwrap();
3833 assert_eq!(path.len(), 2);
3834 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3835 assert_eq!(path.last().unwrap().fee_msat, 10_000);
3840 fn available_liquidity_last_hop_test() {
3841 // Check that available liquidity properly limits the path even when only
3842 // one of the latter hops is limited.
3843 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3844 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3845 let scorer = test_utils::TestScorer::with_penalty(0);
3846 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3847 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3848 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
3850 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3851 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
3852 // Total capacity: 50 sats.
3854 // Disable other potential paths.
3855 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3856 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3857 short_channel_id: 2,
3860 cltv_expiry_delta: 0,
3861 htlc_minimum_msat: 0,
3862 htlc_maximum_msat: OptionalField::Present(100_000),
3864 fee_proportional_millionths: 0,
3865 excess_data: Vec::new()
3867 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3868 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3869 short_channel_id: 7,
3872 cltv_expiry_delta: 0,
3873 htlc_minimum_msat: 0,
3874 htlc_maximum_msat: OptionalField::Present(100_000),
3876 fee_proportional_millionths: 0,
3877 excess_data: Vec::new()
3882 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3883 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3884 short_channel_id: 12,
3887 cltv_expiry_delta: 0,
3888 htlc_minimum_msat: 0,
3889 htlc_maximum_msat: OptionalField::Present(100_000),
3891 fee_proportional_millionths: 0,
3892 excess_data: Vec::new()
3894 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3895 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3896 short_channel_id: 13,
3899 cltv_expiry_delta: 0,
3900 htlc_minimum_msat: 0,
3901 htlc_maximum_msat: OptionalField::Present(100_000),
3903 fee_proportional_millionths: 0,
3904 excess_data: Vec::new()
3907 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3908 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3909 short_channel_id: 6,
3912 cltv_expiry_delta: 0,
3913 htlc_minimum_msat: 0,
3914 htlc_maximum_msat: OptionalField::Present(50_000),
3916 fee_proportional_millionths: 0,
3917 excess_data: Vec::new()
3919 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3920 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3921 short_channel_id: 11,
3924 cltv_expiry_delta: 0,
3925 htlc_minimum_msat: 0,
3926 htlc_maximum_msat: OptionalField::Present(100_000),
3928 fee_proportional_millionths: 0,
3929 excess_data: Vec::new()
3932 // Attempt to route more than available results in a failure.
3933 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3934 &our_id, &payment_params, &network_graph.read_only(), None, 60_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3935 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3936 } else { panic!(); }
3940 // Now, attempt to route 49 sats (just a bit below the capacity).
3941 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 49_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3942 assert_eq!(route.paths.len(), 1);
3943 let mut total_amount_paid_msat = 0;
3944 for path in &route.paths {
3945 assert_eq!(path.len(), 4);
3946 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3947 total_amount_paid_msat += path.last().unwrap().fee_msat;
3949 assert_eq!(total_amount_paid_msat, 49_000);
3953 // Attempt to route an exact amount is also fine
3954 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3955 assert_eq!(route.paths.len(), 1);
3956 let mut total_amount_paid_msat = 0;
3957 for path in &route.paths {
3958 assert_eq!(path.len(), 4);
3959 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3960 total_amount_paid_msat += path.last().unwrap().fee_msat;
3962 assert_eq!(total_amount_paid_msat, 50_000);
3967 fn ignore_fee_first_hop_test() {
3968 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3969 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3970 let scorer = test_utils::TestScorer::with_penalty(0);
3971 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3972 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3973 let payment_params = PaymentParameters::from_node_id(nodes[2]);
3975 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3976 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3977 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3978 short_channel_id: 1,
3981 cltv_expiry_delta: 0,
3982 htlc_minimum_msat: 0,
3983 htlc_maximum_msat: OptionalField::Present(100_000),
3984 fee_base_msat: 1_000_000,
3985 fee_proportional_millionths: 0,
3986 excess_data: Vec::new()
3988 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3989 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3990 short_channel_id: 3,
3993 cltv_expiry_delta: 0,
3994 htlc_minimum_msat: 0,
3995 htlc_maximum_msat: OptionalField::Present(50_000),
3997 fee_proportional_millionths: 0,
3998 excess_data: Vec::new()
4002 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4003 assert_eq!(route.paths.len(), 1);
4004 let mut total_amount_paid_msat = 0;
4005 for path in &route.paths {
4006 assert_eq!(path.len(), 2);
4007 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4008 total_amount_paid_msat += path.last().unwrap().fee_msat;
4010 assert_eq!(total_amount_paid_msat, 50_000);
4015 fn simple_mpp_route_test() {
4016 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4017 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4018 let scorer = test_utils::TestScorer::with_penalty(0);
4019 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4020 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4021 let payment_params = PaymentParameters::from_node_id(nodes[2])
4022 .with_features(InvoiceFeatures::known());
4024 // We need a route consisting of 3 paths:
4025 // From our node to node2 via node0, node7, node1 (three paths one hop each).
4026 // To achieve this, the amount being transferred should be around
4027 // the total capacity of these 3 paths.
4029 // First, we set limits on these (previously unlimited) channels.
4030 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
4032 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
4033 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4034 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4035 short_channel_id: 1,
4038 cltv_expiry_delta: 0,
4039 htlc_minimum_msat: 0,
4040 htlc_maximum_msat: OptionalField::Present(100_000),
4042 fee_proportional_millionths: 0,
4043 excess_data: Vec::new()
4045 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4046 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4047 short_channel_id: 3,
4050 cltv_expiry_delta: 0,
4051 htlc_minimum_msat: 0,
4052 htlc_maximum_msat: OptionalField::Present(50_000),
4054 fee_proportional_millionths: 0,
4055 excess_data: Vec::new()
4058 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
4059 // (total limit 60).
4060 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4061 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4062 short_channel_id: 12,
4065 cltv_expiry_delta: 0,
4066 htlc_minimum_msat: 0,
4067 htlc_maximum_msat: OptionalField::Present(60_000),
4069 fee_proportional_millionths: 0,
4070 excess_data: Vec::new()
4072 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4073 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4074 short_channel_id: 13,
4077 cltv_expiry_delta: 0,
4078 htlc_minimum_msat: 0,
4079 htlc_maximum_msat: OptionalField::Present(60_000),
4081 fee_proportional_millionths: 0,
4082 excess_data: Vec::new()
4085 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
4086 // (total capacity 180 sats).
4087 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4088 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4089 short_channel_id: 2,
4092 cltv_expiry_delta: 0,
4093 htlc_minimum_msat: 0,
4094 htlc_maximum_msat: OptionalField::Present(200_000),
4096 fee_proportional_millionths: 0,
4097 excess_data: Vec::new()
4099 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4100 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4101 short_channel_id: 4,
4104 cltv_expiry_delta: 0,
4105 htlc_minimum_msat: 0,
4106 htlc_maximum_msat: OptionalField::Present(180_000),
4108 fee_proportional_millionths: 0,
4109 excess_data: Vec::new()
4113 // Attempt to route more than available results in a failure.
4114 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4115 &our_id, &payment_params, &network_graph.read_only(), None, 300_000, 42,
4116 Arc::clone(&logger), &scorer, &random_seed_bytes) {
4117 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4118 } else { panic!(); }
4122 // Attempt to route while setting max_mpp_path_count to 0 results in a failure.
4123 let zero_payment_params = payment_params.clone().with_max_mpp_path_count(0);
4124 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4125 &our_id, &zero_payment_params, &network_graph.read_only(), None, 100, 42,
4126 Arc::clone(&logger), &scorer, &random_seed_bytes) {
4127 assert_eq!(err, "Can't find an MPP route with no paths allowed.");
4128 } else { panic!(); }
4132 // Attempt to route while setting max_mpp_path_count to 3 results in a failure.
4133 // This is the case because the minimal_value_contribution_msat would require each path
4134 // to account for 1/3 of the total value, which is violated by 2 out of 3 paths.
4135 let fail_payment_params = payment_params.clone().with_max_mpp_path_count(3);
4136 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4137 &our_id, &fail_payment_params, &network_graph.read_only(), None, 250_000, 42,
4138 Arc::clone(&logger), &scorer, &random_seed_bytes) {
4139 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4140 } else { panic!(); }
4144 // Now, attempt to route 250 sats (just a bit below the capacity).
4145 // Our algorithm should provide us with these 3 paths.
4146 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None,
4147 250_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4148 assert_eq!(route.paths.len(), 3);
4149 let mut total_amount_paid_msat = 0;
4150 for path in &route.paths {
4151 assert_eq!(path.len(), 2);
4152 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4153 total_amount_paid_msat += path.last().unwrap().fee_msat;
4155 assert_eq!(total_amount_paid_msat, 250_000);
4159 // Attempt to route an exact amount is also fine
4160 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None,
4161 290_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4162 assert_eq!(route.paths.len(), 3);
4163 let mut total_amount_paid_msat = 0;
4164 for path in &route.paths {
4165 assert_eq!(path.len(), 2);
4166 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4167 total_amount_paid_msat += path.last().unwrap().fee_msat;
4169 assert_eq!(total_amount_paid_msat, 290_000);
4174 fn long_mpp_route_test() {
4175 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4176 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4177 let scorer = test_utils::TestScorer::with_penalty(0);
4178 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4179 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4180 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
4182 // We need a route consisting of 3 paths:
4183 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
4184 // Note that these paths overlap (channels 5, 12, 13).
4185 // We will route 300 sats.
4186 // Each path will have 100 sats capacity, those channels which
4187 // are used twice will have 200 sats capacity.
4189 // Disable other potential paths.
4190 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4191 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4192 short_channel_id: 2,
4195 cltv_expiry_delta: 0,
4196 htlc_minimum_msat: 0,
4197 htlc_maximum_msat: OptionalField::Present(100_000),
4199 fee_proportional_millionths: 0,
4200 excess_data: Vec::new()
4202 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4203 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4204 short_channel_id: 7,
4207 cltv_expiry_delta: 0,
4208 htlc_minimum_msat: 0,
4209 htlc_maximum_msat: OptionalField::Present(100_000),
4211 fee_proportional_millionths: 0,
4212 excess_data: Vec::new()
4215 // Path via {node0, node2} is channels {1, 3, 5}.
4216 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4217 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4218 short_channel_id: 1,
4221 cltv_expiry_delta: 0,
4222 htlc_minimum_msat: 0,
4223 htlc_maximum_msat: OptionalField::Present(100_000),
4225 fee_proportional_millionths: 0,
4226 excess_data: Vec::new()
4228 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4229 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4230 short_channel_id: 3,
4233 cltv_expiry_delta: 0,
4234 htlc_minimum_msat: 0,
4235 htlc_maximum_msat: OptionalField::Present(100_000),
4237 fee_proportional_millionths: 0,
4238 excess_data: Vec::new()
4241 // Capacity of 200 sats because this channel will be used by 3rd path as well.
4242 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4243 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4244 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4245 short_channel_id: 5,
4248 cltv_expiry_delta: 0,
4249 htlc_minimum_msat: 0,
4250 htlc_maximum_msat: OptionalField::Present(200_000),
4252 fee_proportional_millionths: 0,
4253 excess_data: Vec::new()
4256 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4257 // Add 100 sats to the capacities of {12, 13}, because these channels
4258 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
4259 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4260 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4261 short_channel_id: 12,
4264 cltv_expiry_delta: 0,
4265 htlc_minimum_msat: 0,
4266 htlc_maximum_msat: OptionalField::Present(200_000),
4268 fee_proportional_millionths: 0,
4269 excess_data: Vec::new()
4271 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4272 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4273 short_channel_id: 13,
4276 cltv_expiry_delta: 0,
4277 htlc_minimum_msat: 0,
4278 htlc_maximum_msat: OptionalField::Present(200_000),
4280 fee_proportional_millionths: 0,
4281 excess_data: Vec::new()
4284 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4285 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4286 short_channel_id: 6,
4289 cltv_expiry_delta: 0,
4290 htlc_minimum_msat: 0,
4291 htlc_maximum_msat: OptionalField::Present(100_000),
4293 fee_proportional_millionths: 0,
4294 excess_data: Vec::new()
4296 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4297 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4298 short_channel_id: 11,
4301 cltv_expiry_delta: 0,
4302 htlc_minimum_msat: 0,
4303 htlc_maximum_msat: OptionalField::Present(100_000),
4305 fee_proportional_millionths: 0,
4306 excess_data: Vec::new()
4309 // Path via {node7, node2} is channels {12, 13, 5}.
4310 // We already limited them to 200 sats (they are used twice for 100 sats).
4311 // Nothing to do here.
4314 // Attempt to route more than available results in a failure.
4315 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4316 &our_id, &payment_params, &network_graph.read_only(), None, 350_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
4317 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4318 } else { panic!(); }
4322 // Now, attempt to route 300 sats (exact amount we can route).
4323 // Our algorithm should provide us with these 3 paths, 100 sats each.
4324 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 300_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4325 assert_eq!(route.paths.len(), 3);
4327 let mut total_amount_paid_msat = 0;
4328 for path in &route.paths {
4329 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
4330 total_amount_paid_msat += path.last().unwrap().fee_msat;
4332 assert_eq!(total_amount_paid_msat, 300_000);
4338 fn mpp_cheaper_route_test() {
4339 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4340 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4341 let scorer = test_utils::TestScorer::with_penalty(0);
4342 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4343 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4344 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
4346 // This test checks that if we have two cheaper paths and one more expensive path,
4347 // so that liquidity-wise any 2 of 3 combination is sufficient,
4348 // two cheaper paths will be taken.
4349 // These paths have equal available liquidity.
4351 // We need a combination of 3 paths:
4352 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
4353 // Note that these paths overlap (channels 5, 12, 13).
4354 // Each path will have 100 sats capacity, those channels which
4355 // are used twice will have 200 sats capacity.
4357 // Disable other potential paths.
4358 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4359 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4360 short_channel_id: 2,
4363 cltv_expiry_delta: 0,
4364 htlc_minimum_msat: 0,
4365 htlc_maximum_msat: OptionalField::Present(100_000),
4367 fee_proportional_millionths: 0,
4368 excess_data: Vec::new()
4370 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4371 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4372 short_channel_id: 7,
4375 cltv_expiry_delta: 0,
4376 htlc_minimum_msat: 0,
4377 htlc_maximum_msat: OptionalField::Present(100_000),
4379 fee_proportional_millionths: 0,
4380 excess_data: Vec::new()
4383 // Path via {node0, node2} is channels {1, 3, 5}.
4384 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4385 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4386 short_channel_id: 1,
4389 cltv_expiry_delta: 0,
4390 htlc_minimum_msat: 0,
4391 htlc_maximum_msat: OptionalField::Present(100_000),
4393 fee_proportional_millionths: 0,
4394 excess_data: Vec::new()
4396 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4397 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4398 short_channel_id: 3,
4401 cltv_expiry_delta: 0,
4402 htlc_minimum_msat: 0,
4403 htlc_maximum_msat: OptionalField::Present(100_000),
4405 fee_proportional_millionths: 0,
4406 excess_data: Vec::new()
4409 // Capacity of 200 sats because this channel will be used by 3rd path as well.
4410 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4411 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4412 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4413 short_channel_id: 5,
4416 cltv_expiry_delta: 0,
4417 htlc_minimum_msat: 0,
4418 htlc_maximum_msat: OptionalField::Present(200_000),
4420 fee_proportional_millionths: 0,
4421 excess_data: Vec::new()
4424 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4425 // Add 100 sats to the capacities of {12, 13}, because these channels
4426 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
4427 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4428 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4429 short_channel_id: 12,
4432 cltv_expiry_delta: 0,
4433 htlc_minimum_msat: 0,
4434 htlc_maximum_msat: OptionalField::Present(200_000),
4436 fee_proportional_millionths: 0,
4437 excess_data: Vec::new()
4439 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4440 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4441 short_channel_id: 13,
4444 cltv_expiry_delta: 0,
4445 htlc_minimum_msat: 0,
4446 htlc_maximum_msat: OptionalField::Present(200_000),
4448 fee_proportional_millionths: 0,
4449 excess_data: Vec::new()
4452 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4453 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4454 short_channel_id: 6,
4457 cltv_expiry_delta: 0,
4458 htlc_minimum_msat: 0,
4459 htlc_maximum_msat: OptionalField::Present(100_000),
4460 fee_base_msat: 1_000,
4461 fee_proportional_millionths: 0,
4462 excess_data: Vec::new()
4464 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4465 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4466 short_channel_id: 11,
4469 cltv_expiry_delta: 0,
4470 htlc_minimum_msat: 0,
4471 htlc_maximum_msat: OptionalField::Present(100_000),
4473 fee_proportional_millionths: 0,
4474 excess_data: Vec::new()
4477 // Path via {node7, node2} is channels {12, 13, 5}.
4478 // We already limited them to 200 sats (they are used twice for 100 sats).
4479 // Nothing to do here.
4482 // Now, attempt to route 180 sats.
4483 // Our algorithm should provide us with these 2 paths.
4484 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 180_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4485 assert_eq!(route.paths.len(), 2);
4487 let mut total_value_transferred_msat = 0;
4488 let mut total_paid_msat = 0;
4489 for path in &route.paths {
4490 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
4491 total_value_transferred_msat += path.last().unwrap().fee_msat;
4493 total_paid_msat += hop.fee_msat;
4496 // If we paid fee, this would be higher.
4497 assert_eq!(total_value_transferred_msat, 180_000);
4498 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
4499 assert_eq!(total_fees_paid, 0);
4504 fn fees_on_mpp_route_test() {
4505 // This test makes sure that MPP algorithm properly takes into account
4506 // fees charged on the channels, by making the fees impactful:
4507 // if the fee is not properly accounted for, the behavior is different.
4508 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4509 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4510 let scorer = test_utils::TestScorer::with_penalty(0);
4511 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4512 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4513 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
4515 // We need a route consisting of 2 paths:
4516 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
4517 // We will route 200 sats, Each path will have 100 sats capacity.
4519 // This test is not particularly stable: e.g.,
4520 // there's a way to route via {node0, node2, node4}.
4521 // It works while pathfinding is deterministic, but can be broken otherwise.
4522 // It's fine to ignore this concern for now.
4524 // Disable other potential paths.
4525 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4526 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4527 short_channel_id: 2,
4530 cltv_expiry_delta: 0,
4531 htlc_minimum_msat: 0,
4532 htlc_maximum_msat: OptionalField::Present(100_000),
4534 fee_proportional_millionths: 0,
4535 excess_data: Vec::new()
4538 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4539 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4540 short_channel_id: 7,
4543 cltv_expiry_delta: 0,
4544 htlc_minimum_msat: 0,
4545 htlc_maximum_msat: OptionalField::Present(100_000),
4547 fee_proportional_millionths: 0,
4548 excess_data: Vec::new()
4551 // Path via {node0, node2} is channels {1, 3, 5}.
4552 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4553 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4554 short_channel_id: 1,
4557 cltv_expiry_delta: 0,
4558 htlc_minimum_msat: 0,
4559 htlc_maximum_msat: OptionalField::Present(100_000),
4561 fee_proportional_millionths: 0,
4562 excess_data: Vec::new()
4564 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4565 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4566 short_channel_id: 3,
4569 cltv_expiry_delta: 0,
4570 htlc_minimum_msat: 0,
4571 htlc_maximum_msat: OptionalField::Present(100_000),
4573 fee_proportional_millionths: 0,
4574 excess_data: Vec::new()
4577 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4578 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4579 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4580 short_channel_id: 5,
4583 cltv_expiry_delta: 0,
4584 htlc_minimum_msat: 0,
4585 htlc_maximum_msat: OptionalField::Present(100_000),
4587 fee_proportional_millionths: 0,
4588 excess_data: Vec::new()
4591 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4592 // All channels should be 100 sats capacity. But for the fee experiment,
4593 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
4594 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
4595 // 100 sats (and pay 150 sats in fees for the use of channel 6),
4596 // so no matter how large are other channels,
4597 // the whole path will be limited by 100 sats with just these 2 conditions:
4598 // - channel 12 capacity is 250 sats
4599 // - fee for channel 6 is 150 sats
4600 // Let's test this by enforcing these 2 conditions and removing other limits.
4601 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4602 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4603 short_channel_id: 12,
4606 cltv_expiry_delta: 0,
4607 htlc_minimum_msat: 0,
4608 htlc_maximum_msat: OptionalField::Present(250_000),
4610 fee_proportional_millionths: 0,
4611 excess_data: Vec::new()
4613 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4614 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4615 short_channel_id: 13,
4618 cltv_expiry_delta: 0,
4619 htlc_minimum_msat: 0,
4620 htlc_maximum_msat: OptionalField::Absent,
4622 fee_proportional_millionths: 0,
4623 excess_data: Vec::new()
4626 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4627 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4628 short_channel_id: 6,
4631 cltv_expiry_delta: 0,
4632 htlc_minimum_msat: 0,
4633 htlc_maximum_msat: OptionalField::Absent,
4634 fee_base_msat: 150_000,
4635 fee_proportional_millionths: 0,
4636 excess_data: Vec::new()
4638 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4639 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4640 short_channel_id: 11,
4643 cltv_expiry_delta: 0,
4644 htlc_minimum_msat: 0,
4645 htlc_maximum_msat: OptionalField::Absent,
4647 fee_proportional_millionths: 0,
4648 excess_data: Vec::new()
4652 // Attempt to route more than available results in a failure.
4653 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4654 &our_id, &payment_params, &network_graph.read_only(), None, 210_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
4655 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4656 } else { panic!(); }
4660 // Now, attempt to route 200 sats (exact amount we can route).
4661 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 200_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4662 assert_eq!(route.paths.len(), 2);
4664 let mut total_amount_paid_msat = 0;
4665 for path in &route.paths {
4666 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
4667 total_amount_paid_msat += path.last().unwrap().fee_msat;
4669 assert_eq!(total_amount_paid_msat, 200_000);
4670 assert_eq!(route.get_total_fees(), 150_000);
4675 fn mpp_with_last_hops() {
4676 // Previously, if we tried to send an MPP payment to a destination which was only reachable
4677 // via a single last-hop route hint, we'd fail to route if we first collected routes
4678 // totaling close but not quite enough to fund the full payment.
4680 // This was because we considered last-hop hints to have exactly the sought payment amount
4681 // instead of the amount we were trying to collect, needlessly limiting our path searching
4682 // at the very first hop.
4684 // Specifically, this interacted with our "all paths must fund at least 5% of total target"
4685 // criterion to cause us to refuse all routes at the last hop hint which would be considered
4686 // to only have the remaining to-collect amount in available liquidity.
4688 // This bug appeared in production in some specific channel configurations.
4689 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4690 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4691 let scorer = test_utils::TestScorer::with_penalty(0);
4692 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4693 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4694 let payment_params = PaymentParameters::from_node_id(PublicKey::from_slice(&[02; 33]).unwrap()).with_features(InvoiceFeatures::known())
4695 .with_route_hints(vec![RouteHint(vec![RouteHintHop {
4696 src_node_id: nodes[2],
4697 short_channel_id: 42,
4698 fees: RoutingFees { base_msat: 0, proportional_millionths: 0 },
4699 cltv_expiry_delta: 42,
4700 htlc_minimum_msat: None,
4701 htlc_maximum_msat: None,
4704 // Keep only two paths from us to nodes[2], both with a 99sat HTLC maximum, with one with
4705 // no fee and one with a 1msat fee. Previously, trying to route 100 sats to nodes[2] here
4706 // would first use the no-fee route and then fail to find a path along the second route as
4707 // we think we can only send up to 1 additional sat over the last-hop but refuse to as its
4708 // under 5% of our payment amount.
4709 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4710 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4711 short_channel_id: 1,
4714 cltv_expiry_delta: (5 << 4) | 5,
4715 htlc_minimum_msat: 0,
4716 htlc_maximum_msat: OptionalField::Present(99_000),
4717 fee_base_msat: u32::max_value(),
4718 fee_proportional_millionths: u32::max_value(),
4719 excess_data: Vec::new()
4721 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4722 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4723 short_channel_id: 2,
4726 cltv_expiry_delta: (5 << 4) | 3,
4727 htlc_minimum_msat: 0,
4728 htlc_maximum_msat: OptionalField::Present(99_000),
4729 fee_base_msat: u32::max_value(),
4730 fee_proportional_millionths: u32::max_value(),
4731 excess_data: Vec::new()
4733 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4734 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4735 short_channel_id: 4,
4738 cltv_expiry_delta: (4 << 4) | 1,
4739 htlc_minimum_msat: 0,
4740 htlc_maximum_msat: OptionalField::Absent,
4742 fee_proportional_millionths: 0,
4743 excess_data: Vec::new()
4745 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4746 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4747 short_channel_id: 13,
4749 flags: 0|2, // Channel disabled
4750 cltv_expiry_delta: (13 << 4) | 1,
4751 htlc_minimum_msat: 0,
4752 htlc_maximum_msat: OptionalField::Absent,
4754 fee_proportional_millionths: 2000000,
4755 excess_data: Vec::new()
4758 // Get a route for 100 sats and check that we found the MPP route no problem and didn't
4760 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4761 assert_eq!(route.paths.len(), 2);
4762 // Paths are somewhat randomly ordered, but:
4763 // * the first is channel 2 (1 msat fee) -> channel 4 -> channel 42
4764 // * the second is channel 1 (0 fee, but 99 sat maximum) -> channel 3 -> channel 42
4765 assert_eq!(route.paths[0][0].short_channel_id, 2);
4766 assert_eq!(route.paths[0][0].fee_msat, 1);
4767 assert_eq!(route.paths[0][2].fee_msat, 1_000);
4768 assert_eq!(route.paths[1][0].short_channel_id, 1);
4769 assert_eq!(route.paths[1][0].fee_msat, 0);
4770 assert_eq!(route.paths[1][2].fee_msat, 99_000);
4771 assert_eq!(route.get_total_fees(), 1);
4772 assert_eq!(route.get_total_amount(), 100_000);
4776 fn drop_lowest_channel_mpp_route_test() {
4777 // This test checks that low-capacity channel is dropped when after
4778 // path finding we realize that we found more capacity than we need.
4779 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4780 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4781 let scorer = test_utils::TestScorer::with_penalty(0);
4782 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4783 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4784 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
4786 // We need a route consisting of 3 paths:
4787 // From our node to node2 via node0, node7, node1 (three paths one hop each).
4789 // The first and the second paths should be sufficient, but the third should be
4790 // cheaper, so that we select it but drop later.
4792 // First, we set limits on these (previously unlimited) channels.
4793 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
4795 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
4796 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4797 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4798 short_channel_id: 1,
4801 cltv_expiry_delta: 0,
4802 htlc_minimum_msat: 0,
4803 htlc_maximum_msat: OptionalField::Present(100_000),
4805 fee_proportional_millionths: 0,
4806 excess_data: Vec::new()
4808 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4809 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4810 short_channel_id: 3,
4813 cltv_expiry_delta: 0,
4814 htlc_minimum_msat: 0,
4815 htlc_maximum_msat: OptionalField::Present(50_000),
4817 fee_proportional_millionths: 0,
4818 excess_data: Vec::new()
4821 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
4822 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4823 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4824 short_channel_id: 12,
4827 cltv_expiry_delta: 0,
4828 htlc_minimum_msat: 0,
4829 htlc_maximum_msat: OptionalField::Present(60_000),
4831 fee_proportional_millionths: 0,
4832 excess_data: Vec::new()
4834 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4835 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4836 short_channel_id: 13,
4839 cltv_expiry_delta: 0,
4840 htlc_minimum_msat: 0,
4841 htlc_maximum_msat: OptionalField::Present(60_000),
4843 fee_proportional_millionths: 0,
4844 excess_data: Vec::new()
4847 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
4848 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4849 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4850 short_channel_id: 2,
4853 cltv_expiry_delta: 0,
4854 htlc_minimum_msat: 0,
4855 htlc_maximum_msat: OptionalField::Present(20_000),
4857 fee_proportional_millionths: 0,
4858 excess_data: Vec::new()
4860 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4861 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4862 short_channel_id: 4,
4865 cltv_expiry_delta: 0,
4866 htlc_minimum_msat: 0,
4867 htlc_maximum_msat: OptionalField::Present(20_000),
4869 fee_proportional_millionths: 0,
4870 excess_data: Vec::new()
4874 // Attempt to route more than available results in a failure.
4875 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4876 &our_id, &payment_params, &network_graph.read_only(), None, 150_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
4877 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4878 } else { panic!(); }
4882 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
4883 // Our algorithm should provide us with these 3 paths.
4884 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 125_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4885 assert_eq!(route.paths.len(), 3);
4886 let mut total_amount_paid_msat = 0;
4887 for path in &route.paths {
4888 assert_eq!(path.len(), 2);
4889 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4890 total_amount_paid_msat += path.last().unwrap().fee_msat;
4892 assert_eq!(total_amount_paid_msat, 125_000);
4896 // Attempt to route without the last small cheap channel
4897 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4898 assert_eq!(route.paths.len(), 2);
4899 let mut total_amount_paid_msat = 0;
4900 for path in &route.paths {
4901 assert_eq!(path.len(), 2);
4902 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4903 total_amount_paid_msat += path.last().unwrap().fee_msat;
4905 assert_eq!(total_amount_paid_msat, 90_000);
4910 fn min_criteria_consistency() {
4911 // Test that we don't use an inconsistent metric between updating and walking nodes during
4912 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
4913 // was updated with a different criterion from the heap sorting, resulting in loops in
4914 // calculated paths. We test for that specific case here.
4916 // We construct a network that looks like this:
4918 // node2 -1(3)2- node3
4922 // node1 -1(5)2- node4 -1(1)2- node6
4928 // We create a loop on the side of our real path - our destination is node 6, with a
4929 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
4930 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
4931 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
4932 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
4933 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
4934 // "previous hop" being set to node 3, creating a loop in the path.
4935 let secp_ctx = Secp256k1::new();
4936 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
4937 let logger = Arc::new(test_utils::TestLogger::new());
4938 let network = Arc::new(NetworkGraph::new(genesis_hash, Arc::clone(&logger)));
4939 let gossip_sync = P2PGossipSync::new(Arc::clone(&network), None, Arc::clone(&logger));
4940 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4941 let scorer = test_utils::TestScorer::with_penalty(0);
4942 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4943 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4944 let payment_params = PaymentParameters::from_node_id(nodes[6]);
4946 add_channel(&gossip_sync, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
4947 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4948 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4949 short_channel_id: 6,
4952 cltv_expiry_delta: (6 << 4) | 0,
4953 htlc_minimum_msat: 0,
4954 htlc_maximum_msat: OptionalField::Absent,
4956 fee_proportional_millionths: 0,
4957 excess_data: Vec::new()
4959 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
4961 add_channel(&gossip_sync, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4962 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4963 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4964 short_channel_id: 5,
4967 cltv_expiry_delta: (5 << 4) | 0,
4968 htlc_minimum_msat: 0,
4969 htlc_maximum_msat: OptionalField::Absent,
4971 fee_proportional_millionths: 0,
4972 excess_data: Vec::new()
4974 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
4976 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
4977 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4978 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4979 short_channel_id: 4,
4982 cltv_expiry_delta: (4 << 4) | 0,
4983 htlc_minimum_msat: 0,
4984 htlc_maximum_msat: OptionalField::Absent,
4986 fee_proportional_millionths: 0,
4987 excess_data: Vec::new()
4989 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
4991 add_channel(&gossip_sync, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
4992 update_channel(&gossip_sync, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
4993 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4994 short_channel_id: 3,
4997 cltv_expiry_delta: (3 << 4) | 0,
4998 htlc_minimum_msat: 0,
4999 htlc_maximum_msat: OptionalField::Absent,
5001 fee_proportional_millionths: 0,
5002 excess_data: Vec::new()
5004 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
5006 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
5007 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5008 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5009 short_channel_id: 2,
5012 cltv_expiry_delta: (2 << 4) | 0,
5013 htlc_minimum_msat: 0,
5014 htlc_maximum_msat: OptionalField::Absent,
5016 fee_proportional_millionths: 0,
5017 excess_data: Vec::new()
5020 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
5021 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5022 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5023 short_channel_id: 1,
5026 cltv_expiry_delta: (1 << 4) | 0,
5027 htlc_minimum_msat: 100,
5028 htlc_maximum_msat: OptionalField::Absent,
5030 fee_proportional_millionths: 0,
5031 excess_data: Vec::new()
5033 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
5036 // Now ensure the route flows simply over nodes 1 and 4 to 6.
5037 let route = get_route(&our_id, &payment_params, &network.read_only(), None, 10_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5038 assert_eq!(route.paths.len(), 1);
5039 assert_eq!(route.paths[0].len(), 3);
5041 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
5042 assert_eq!(route.paths[0][0].short_channel_id, 6);
5043 assert_eq!(route.paths[0][0].fee_msat, 100);
5044 assert_eq!(route.paths[0][0].cltv_expiry_delta, (5 << 4) | 0);
5045 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(1));
5046 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(6));
5048 assert_eq!(route.paths[0][1].pubkey, nodes[4]);
5049 assert_eq!(route.paths[0][1].short_channel_id, 5);
5050 assert_eq!(route.paths[0][1].fee_msat, 0);
5051 assert_eq!(route.paths[0][1].cltv_expiry_delta, (1 << 4) | 0);
5052 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(4));
5053 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(5));
5055 assert_eq!(route.paths[0][2].pubkey, nodes[6]);
5056 assert_eq!(route.paths[0][2].short_channel_id, 1);
5057 assert_eq!(route.paths[0][2].fee_msat, 10_000);
5058 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
5059 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
5060 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(1));
5066 fn exact_fee_liquidity_limit() {
5067 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
5068 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
5069 // we calculated fees on a higher value, resulting in us ignoring such paths.
5070 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5071 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
5072 let scorer = test_utils::TestScorer::with_penalty(0);
5073 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5074 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5075 let payment_params = PaymentParameters::from_node_id(nodes[2]);
5077 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
5079 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5080 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5081 short_channel_id: 2,
5084 cltv_expiry_delta: 0,
5085 htlc_minimum_msat: 0,
5086 htlc_maximum_msat: OptionalField::Present(85_000),
5088 fee_proportional_millionths: 0,
5089 excess_data: Vec::new()
5092 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5093 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5094 short_channel_id: 12,
5097 cltv_expiry_delta: (4 << 4) | 1,
5098 htlc_minimum_msat: 0,
5099 htlc_maximum_msat: OptionalField::Present(270_000),
5101 fee_proportional_millionths: 1000000,
5102 excess_data: Vec::new()
5106 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
5107 // 200% fee charged channel 13 in the 1-to-2 direction.
5108 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5109 assert_eq!(route.paths.len(), 1);
5110 assert_eq!(route.paths[0].len(), 2);
5112 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
5113 assert_eq!(route.paths[0][0].short_channel_id, 12);
5114 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
5115 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
5116 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
5117 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
5119 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
5120 assert_eq!(route.paths[0][1].short_channel_id, 13);
5121 assert_eq!(route.paths[0][1].fee_msat, 90_000);
5122 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
5123 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
5124 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
5129 fn htlc_max_reduction_below_min() {
5130 // Test that if, while walking the graph, we reduce the value being sent to meet an
5131 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
5132 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
5133 // resulting in us thinking there is no possible path, even if other paths exist.
5134 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5135 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5136 let scorer = test_utils::TestScorer::with_penalty(0);
5137 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5138 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5139 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
5141 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
5142 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
5143 // then try to send 90_000.
5144 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5145 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5146 short_channel_id: 2,
5149 cltv_expiry_delta: 0,
5150 htlc_minimum_msat: 0,
5151 htlc_maximum_msat: OptionalField::Present(80_000),
5153 fee_proportional_millionths: 0,
5154 excess_data: Vec::new()
5156 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5157 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5158 short_channel_id: 4,
5161 cltv_expiry_delta: (4 << 4) | 1,
5162 htlc_minimum_msat: 90_000,
5163 htlc_maximum_msat: OptionalField::Absent,
5165 fee_proportional_millionths: 0,
5166 excess_data: Vec::new()
5170 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
5171 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
5172 // expensive) channels 12-13 path.
5173 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5174 assert_eq!(route.paths.len(), 1);
5175 assert_eq!(route.paths[0].len(), 2);
5177 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
5178 assert_eq!(route.paths[0][0].short_channel_id, 12);
5179 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
5180 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
5181 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
5182 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
5184 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
5185 assert_eq!(route.paths[0][1].short_channel_id, 13);
5186 assert_eq!(route.paths[0][1].fee_msat, 90_000);
5187 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
5188 assert_eq!(route.paths[0][1].node_features.le_flags(), InvoiceFeatures::known().le_flags());
5189 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
5194 fn multiple_direct_first_hops() {
5195 // Previously we'd only ever considered one first hop path per counterparty.
5196 // However, as we don't restrict users to one channel per peer, we really need to support
5197 // looking at all first hop paths.
5198 // Here we test that we do not ignore all-but-the-last first hop paths per counterparty (as
5199 // we used to do by overwriting the `first_hop_targets` hashmap entry) and that we can MPP
5200 // route over multiple channels with the same first hop.
5201 let secp_ctx = Secp256k1::new();
5202 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5203 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
5204 let logger = Arc::new(test_utils::TestLogger::new());
5205 let network_graph = NetworkGraph::new(genesis_hash, Arc::clone(&logger));
5206 let scorer = test_utils::TestScorer::with_penalty(0);
5207 let payment_params = PaymentParameters::from_node_id(nodes[0]).with_features(InvoiceFeatures::known());
5208 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5209 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5212 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
5213 &get_channel_details(Some(3), nodes[0], InitFeatures::known(), 200_000),
5214 &get_channel_details(Some(2), nodes[0], InitFeatures::known(), 10_000),
5215 ]), 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5216 assert_eq!(route.paths.len(), 1);
5217 assert_eq!(route.paths[0].len(), 1);
5219 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
5220 assert_eq!(route.paths[0][0].short_channel_id, 3);
5221 assert_eq!(route.paths[0][0].fee_msat, 100_000);
5224 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
5225 &get_channel_details(Some(3), nodes[0], InitFeatures::known(), 50_000),
5226 &get_channel_details(Some(2), nodes[0], InitFeatures::known(), 50_000),
5227 ]), 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5228 assert_eq!(route.paths.len(), 2);
5229 assert_eq!(route.paths[0].len(), 1);
5230 assert_eq!(route.paths[1].len(), 1);
5232 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
5233 assert_eq!(route.paths[0][0].short_channel_id, 3);
5234 assert_eq!(route.paths[0][0].fee_msat, 50_000);
5236 assert_eq!(route.paths[1][0].pubkey, nodes[0]);
5237 assert_eq!(route.paths[1][0].short_channel_id, 2);
5238 assert_eq!(route.paths[1][0].fee_msat, 50_000);
5242 // If we have a bunch of outbound channels to the same node, where most are not
5243 // sufficient to pay the full payment, but one is, we should default to just using the
5244 // one single channel that has sufficient balance, avoiding MPP.
5246 // If we have several options above the 3xpayment value threshold, we should pick the
5247 // smallest of them, avoiding further fragmenting our available outbound balance to
5249 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
5250 &get_channel_details(Some(2), nodes[0], InitFeatures::known(), 50_000),
5251 &get_channel_details(Some(3), nodes[0], InitFeatures::known(), 50_000),
5252 &get_channel_details(Some(5), nodes[0], InitFeatures::known(), 50_000),
5253 &get_channel_details(Some(6), nodes[0], InitFeatures::known(), 300_000),
5254 &get_channel_details(Some(7), nodes[0], InitFeatures::known(), 50_000),
5255 &get_channel_details(Some(8), nodes[0], InitFeatures::known(), 50_000),
5256 &get_channel_details(Some(9), nodes[0], InitFeatures::known(), 50_000),
5257 &get_channel_details(Some(4), nodes[0], InitFeatures::known(), 1_000_000),
5258 ]), 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5259 assert_eq!(route.paths.len(), 1);
5260 assert_eq!(route.paths[0].len(), 1);
5262 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
5263 assert_eq!(route.paths[0][0].short_channel_id, 6);
5264 assert_eq!(route.paths[0][0].fee_msat, 100_000);
5269 fn prefers_shorter_route_with_higher_fees() {
5270 let (secp_ctx, network_graph, _, _, logger) = build_graph();
5271 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5272 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
5274 // Without penalizing each hop 100 msats, a longer path with lower fees is chosen.
5275 let scorer = test_utils::TestScorer::with_penalty(0);
5276 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5277 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5278 let route = get_route(
5279 &our_id, &payment_params, &network_graph.read_only(), None, 100, 42,
5280 Arc::clone(&logger), &scorer, &random_seed_bytes
5282 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5284 assert_eq!(route.get_total_fees(), 100);
5285 assert_eq!(route.get_total_amount(), 100);
5286 assert_eq!(path, vec![2, 4, 6, 11, 8]);
5288 // Applying a 100 msat penalty to each hop results in taking channels 7 and 10 to nodes[6]
5289 // from nodes[2] rather than channel 6, 11, and 8, even though the longer path is cheaper.
5290 let scorer = test_utils::TestScorer::with_penalty(100);
5291 let route = get_route(
5292 &our_id, &payment_params, &network_graph.read_only(), None, 100, 42,
5293 Arc::clone(&logger), &scorer, &random_seed_bytes
5295 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5297 assert_eq!(route.get_total_fees(), 300);
5298 assert_eq!(route.get_total_amount(), 100);
5299 assert_eq!(path, vec![2, 4, 7, 10]);
5302 struct BadChannelScorer {
5303 short_channel_id: u64,
5307 impl Writeable for BadChannelScorer {
5308 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), ::io::Error> { unimplemented!() }
5310 impl Score for BadChannelScorer {
5311 fn channel_penalty_msat(&self, short_channel_id: u64, _: &NodeId, _: &NodeId, _: ChannelUsage) -> u64 {
5312 if short_channel_id == self.short_channel_id { u64::max_value() } else { 0 }
5315 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
5316 fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
5319 struct BadNodeScorer {
5324 impl Writeable for BadNodeScorer {
5325 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), ::io::Error> { unimplemented!() }
5328 impl Score for BadNodeScorer {
5329 fn channel_penalty_msat(&self, _: u64, _: &NodeId, target: &NodeId, _: ChannelUsage) -> u64 {
5330 if *target == self.node_id { u64::max_value() } else { 0 }
5333 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
5334 fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
5338 fn avoids_routing_through_bad_channels_and_nodes() {
5339 let (secp_ctx, network, _, _, logger) = build_graph();
5340 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5341 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
5342 let network_graph = network.read_only();
5344 // A path to nodes[6] exists when no penalties are applied to any channel.
5345 let scorer = test_utils::TestScorer::with_penalty(0);
5346 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5347 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5348 let route = get_route(
5349 &our_id, &payment_params, &network_graph, None, 100, 42,
5350 Arc::clone(&logger), &scorer, &random_seed_bytes
5352 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5354 assert_eq!(route.get_total_fees(), 100);
5355 assert_eq!(route.get_total_amount(), 100);
5356 assert_eq!(path, vec![2, 4, 6, 11, 8]);
5358 // A different path to nodes[6] exists if channel 6 cannot be routed over.
5359 let scorer = BadChannelScorer { short_channel_id: 6 };
5360 let route = get_route(
5361 &our_id, &payment_params, &network_graph, None, 100, 42,
5362 Arc::clone(&logger), &scorer, &random_seed_bytes
5364 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5366 assert_eq!(route.get_total_fees(), 300);
5367 assert_eq!(route.get_total_amount(), 100);
5368 assert_eq!(path, vec![2, 4, 7, 10]);
5370 // A path to nodes[6] does not exist if nodes[2] cannot be routed through.
5371 let scorer = BadNodeScorer { node_id: NodeId::from_pubkey(&nodes[2]) };
5373 &our_id, &payment_params, &network_graph, None, 100, 42,
5374 Arc::clone(&logger), &scorer, &random_seed_bytes
5376 Err(LightningError { err, .. } ) => {
5377 assert_eq!(err, "Failed to find a path to the given destination");
5379 Ok(_) => panic!("Expected error"),
5384 fn total_fees_single_path() {
5388 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5389 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5390 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5393 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5394 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5395 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5398 pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
5399 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5400 short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0
5403 payment_params: None,
5406 assert_eq!(route.get_total_fees(), 250);
5407 assert_eq!(route.get_total_amount(), 225);
5411 fn total_fees_multi_path() {
5415 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5416 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5417 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5420 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5421 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5422 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5426 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5427 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5428 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5431 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5432 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5433 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5436 payment_params: None,
5439 assert_eq!(route.get_total_fees(), 200);
5440 assert_eq!(route.get_total_amount(), 300);
5444 fn total_empty_route_no_panic() {
5445 // In an earlier version of `Route::get_total_fees` and `Route::get_total_amount`, they
5446 // would both panic if the route was completely empty. We test to ensure they return 0
5447 // here, even though its somewhat nonsensical as a route.
5448 let route = Route { paths: Vec::new(), payment_params: None };
5450 assert_eq!(route.get_total_fees(), 0);
5451 assert_eq!(route.get_total_amount(), 0);
5455 fn limits_total_cltv_delta() {
5456 let (secp_ctx, network, _, _, logger) = build_graph();
5457 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5458 let network_graph = network.read_only();
5460 let scorer = test_utils::TestScorer::with_penalty(0);
5462 // Make sure that generally there is at least one route available
5463 let feasible_max_total_cltv_delta = 1008;
5464 let feasible_payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes))
5465 .with_max_total_cltv_expiry_delta(feasible_max_total_cltv_delta);
5466 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5467 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5468 let route = get_route(&our_id, &feasible_payment_params, &network_graph, None, 100, 0, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5469 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5470 assert_ne!(path.len(), 0);
5472 // But not if we exclude all paths on the basis of their accumulated CLTV delta
5473 let fail_max_total_cltv_delta = 23;
5474 let fail_payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes))
5475 .with_max_total_cltv_expiry_delta(fail_max_total_cltv_delta);
5476 match get_route(&our_id, &fail_payment_params, &network_graph, None, 100, 0, Arc::clone(&logger), &scorer, &random_seed_bytes)
5478 Err(LightningError { err, .. } ) => {
5479 assert_eq!(err, "Failed to find a path to the given destination");
5481 Ok(_) => panic!("Expected error"),
5486 fn limits_path_length() {
5487 let (secp_ctx, network, _, _, logger) = build_line_graph();
5488 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5489 let network_graph = network.read_only();
5491 let scorer = test_utils::TestScorer::with_penalty(0);
5492 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5493 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5495 // First check we can actually create a long route on this graph.
5496 let feasible_payment_params = PaymentParameters::from_node_id(nodes[18]);
5497 let route = get_route(&our_id, &feasible_payment_params, &network_graph, None, 100, 0,
5498 Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5499 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5500 assert!(path.len() == MAX_PATH_LENGTH_ESTIMATE.into());
5502 // But we can't create a path surpassing the MAX_PATH_LENGTH_ESTIMATE limit.
5503 let fail_payment_params = PaymentParameters::from_node_id(nodes[19]);
5504 match get_route(&our_id, &fail_payment_params, &network_graph, None, 100, 0,
5505 Arc::clone(&logger), &scorer, &random_seed_bytes)
5507 Err(LightningError { err, .. } ) => {
5508 assert_eq!(err, "Failed to find a path to the given destination");
5510 Ok(_) => panic!("Expected error"),
5515 fn adds_and_limits_cltv_offset() {
5516 let (secp_ctx, network_graph, _, _, logger) = build_graph();
5517 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5519 let scorer = test_utils::TestScorer::with_penalty(0);
5521 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
5522 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5523 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5524 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5525 assert_eq!(route.paths.len(), 1);
5527 let cltv_expiry_deltas_before = route.paths[0].iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5529 // Check whether the offset added to the last hop by default is in [1 .. DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA]
5530 let mut route_default = route.clone();
5531 add_random_cltv_offset(&mut route_default, &payment_params, &network_graph.read_only(), &random_seed_bytes);
5532 let cltv_expiry_deltas_default = route_default.paths[0].iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5533 assert_eq!(cltv_expiry_deltas_before.split_last().unwrap().1, cltv_expiry_deltas_default.split_last().unwrap().1);
5534 assert!(cltv_expiry_deltas_default.last() > cltv_expiry_deltas_before.last());
5535 assert!(cltv_expiry_deltas_default.last().unwrap() <= &DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA);
5537 // Check that no offset is added when we restrict the max_total_cltv_expiry_delta
5538 let mut route_limited = route.clone();
5539 let limited_max_total_cltv_expiry_delta = cltv_expiry_deltas_before.iter().sum();
5540 let limited_payment_params = payment_params.with_max_total_cltv_expiry_delta(limited_max_total_cltv_expiry_delta);
5541 add_random_cltv_offset(&mut route_limited, &limited_payment_params, &network_graph.read_only(), &random_seed_bytes);
5542 let cltv_expiry_deltas_limited = route_limited.paths[0].iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5543 assert_eq!(cltv_expiry_deltas_before, cltv_expiry_deltas_limited);
5547 fn adds_plausible_cltv_offset() {
5548 let (secp_ctx, network, _, _, logger) = build_graph();
5549 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5550 let network_graph = network.read_only();
5551 let network_nodes = network_graph.nodes();
5552 let network_channels = network_graph.channels();
5553 let scorer = test_utils::TestScorer::with_penalty(0);
5554 let payment_params = PaymentParameters::from_node_id(nodes[3]);
5555 let keys_manager = test_utils::TestKeysInterface::new(&[4u8; 32], Network::Testnet);
5556 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5558 let mut route = get_route(&our_id, &payment_params, &network_graph, None, 100, 0,
5559 Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5560 add_random_cltv_offset(&mut route, &payment_params, &network_graph, &random_seed_bytes);
5562 let mut path_plausibility = vec![];
5564 for p in route.paths {
5565 // 1. Select random observation point
5566 let mut prng = ChaCha20::new(&random_seed_bytes, &[0u8; 12]);
5567 let mut random_bytes = [0u8; ::core::mem::size_of::<usize>()];
5569 prng.process_in_place(&mut random_bytes);
5570 let random_path_index = usize::from_be_bytes(random_bytes).wrapping_rem(p.len());
5571 let observation_point = NodeId::from_pubkey(&p.get(random_path_index).unwrap().pubkey);
5573 // 2. Calculate what CLTV expiry delta we would observe there
5574 let observed_cltv_expiry_delta: u32 = p[random_path_index..].iter().map(|h| h.cltv_expiry_delta).sum();
5576 // 3. Starting from the observation point, find candidate paths
5577 let mut candidates: VecDeque<(NodeId, Vec<u32>)> = VecDeque::new();
5578 candidates.push_back((observation_point, vec![]));
5580 let mut found_plausible_candidate = false;
5582 'candidate_loop: while let Some((cur_node_id, cur_path_cltv_deltas)) = candidates.pop_front() {
5583 if let Some(remaining) = observed_cltv_expiry_delta.checked_sub(cur_path_cltv_deltas.iter().sum::<u32>()) {
5584 if remaining == 0 || remaining.wrapping_rem(40) == 0 || remaining.wrapping_rem(144) == 0 {
5585 found_plausible_candidate = true;
5586 break 'candidate_loop;
5590 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
5591 for channel_id in &cur_node.channels {
5592 if let Some(channel_info) = network_channels.get(&channel_id) {
5593 if let Some((dir_info, next_id)) = channel_info.as_directed_from(&cur_node_id) {
5594 if let Some(channel_update_info) = dir_info.direction() {
5595 let next_cltv_expiry_delta = channel_update_info.cltv_expiry_delta as u32;
5596 if cur_path_cltv_deltas.iter().sum::<u32>()
5597 .saturating_add(next_cltv_expiry_delta) <= observed_cltv_expiry_delta {
5598 let mut new_path_cltv_deltas = cur_path_cltv_deltas.clone();
5599 new_path_cltv_deltas.push(next_cltv_expiry_delta);
5600 candidates.push_back((*next_id, new_path_cltv_deltas));
5609 path_plausibility.push(found_plausible_candidate);
5611 assert!(path_plausibility.iter().all(|x| *x));
5615 fn builds_correct_path_from_hops() {
5616 let (secp_ctx, network, _, _, logger) = build_graph();
5617 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5618 let network_graph = network.read_only();
5620 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5621 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5623 let payment_params = PaymentParameters::from_node_id(nodes[3]);
5624 let hops = [nodes[1], nodes[2], nodes[4], nodes[3]];
5625 let route = build_route_from_hops_internal(&our_id, &hops, &payment_params,
5626 &network_graph, 100, 0, Arc::clone(&logger), &random_seed_bytes).unwrap();
5627 let route_hop_pubkeys = route.paths[0].iter().map(|hop| hop.pubkey).collect::<Vec<_>>();
5628 assert_eq!(hops.len(), route.paths[0].len());
5629 for (idx, hop_pubkey) in hops.iter().enumerate() {
5630 assert!(*hop_pubkey == route_hop_pubkeys[idx]);
5634 #[cfg(not(feature = "no-std"))]
5635 pub(super) fn random_init_seed() -> u64 {
5636 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
5637 use core::hash::{BuildHasher, Hasher};
5638 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
5639 println!("Using seed of {}", seed);
5642 #[cfg(not(feature = "no-std"))]
5643 use util::ser::ReadableArgs;
5646 #[cfg(not(feature = "no-std"))]
5647 fn generate_routes() {
5648 use routing::scoring::{ProbabilisticScorer, ProbabilisticScoringParameters};
5650 let mut d = match super::test_utils::get_route_file() {
5657 let logger = test_utils::TestLogger::new();
5658 let graph = NetworkGraph::read(&mut d, &logger).unwrap();
5659 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5660 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5662 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
5663 let mut seed = random_init_seed() as usize;
5664 let nodes = graph.read_only().nodes().clone();
5665 'load_endpoints: for _ in 0..10 {
5667 seed = seed.overflowing_mul(0xdeadbeef).0;
5668 let src = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5669 seed = seed.overflowing_mul(0xdeadbeef).0;
5670 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5671 let payment_params = PaymentParameters::from_node_id(dst);
5672 let amt = seed as u64 % 200_000_000;
5673 let params = ProbabilisticScoringParameters::default();
5674 let scorer = ProbabilisticScorer::new(params, &graph, &logger);
5675 if get_route(src, &payment_params, &graph.read_only(), None, amt, 42, &logger, &scorer, &random_seed_bytes).is_ok() {
5676 continue 'load_endpoints;
5683 #[cfg(not(feature = "no-std"))]
5684 fn generate_routes_mpp() {
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).with_features(InvoiceFeatures::known());
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 fn avoids_banned_nodes() {
5721 let (secp_ctx, network_graph, _, _, logger) = build_line_graph();
5722 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5724 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5725 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5727 let scorer_params = ProbabilisticScoringParameters::default();
5728 let mut scorer = ProbabilisticScorer::new(scorer_params, Arc::clone(&network_graph), Arc::clone(&logger));
5730 // First check we can get a route.
5731 let payment_params = PaymentParameters::from_node_id(nodes[10]);
5732 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes);
5733 assert!(route.is_ok());
5735 // Then check that we can't get a route if we ban an intermediate node.
5736 scorer.add_banned(&NodeId::from_pubkey(&nodes[3]));
5737 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes);
5738 assert!(route.is_err());
5740 // Finally make sure we can route again, when we remove the ban.
5741 scorer.remove_banned(&NodeId::from_pubkey(&nodes[3]));
5742 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes);
5743 assert!(route.is_ok());
5747 #[cfg(all(test, not(feature = "no-std")))]
5748 pub(crate) mod test_utils {
5750 /// Tries to open a network graph file, or panics with a URL to fetch it.
5751 pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
5752 let res = File::open("net_graph-2021-05-31.bin") // By default we're run in RL/lightning
5753 .or_else(|_| File::open("lightning/net_graph-2021-05-31.bin")) // We may be run manually in RL/
5754 .or_else(|_| { // Fall back to guessing based on the binary location
5755 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
5756 let mut path = std::env::current_exe().unwrap();
5757 path.pop(); // lightning-...
5759 path.pop(); // debug
5760 path.pop(); // target
5761 path.push("lightning");
5762 path.push("net_graph-2021-05-31.bin");
5763 eprintln!("{}", path.to_str().unwrap());
5766 .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");
5767 #[cfg(require_route_graph_test)]
5768 return Ok(res.unwrap());
5769 #[cfg(not(require_route_graph_test))]
5774 #[cfg(all(test, feature = "_bench_unstable", not(feature = "no-std")))]
5777 use bitcoin::hashes::Hash;
5778 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
5779 use chain::transaction::OutPoint;
5780 use chain::keysinterface::{KeysManager,KeysInterface};
5781 use ln::channelmanager::{ChannelCounterparty, ChannelDetails};
5782 use ln::features::{InitFeatures, InvoiceFeatures};
5783 use routing::gossip::NetworkGraph;
5784 use routing::scoring::{FixedPenaltyScorer, ProbabilisticScorer, ProbabilisticScoringParameters};
5785 use util::logger::{Logger, Record};
5786 use util::ser::ReadableArgs;
5790 struct DummyLogger {}
5791 impl Logger for DummyLogger {
5792 fn log(&self, _record: &Record) {}
5795 fn read_network_graph(logger: &DummyLogger) -> NetworkGraph<&DummyLogger> {
5796 let mut d = test_utils::get_route_file().unwrap();
5797 NetworkGraph::read(&mut d, logger).unwrap()
5800 fn payer_pubkey() -> PublicKey {
5801 let secp_ctx = Secp256k1::new();
5802 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
5806 fn first_hop(node_id: PublicKey) -> ChannelDetails {
5808 channel_id: [0; 32],
5809 counterparty: ChannelCounterparty {
5810 features: InitFeatures::known(),
5812 unspendable_punishment_reserve: 0,
5813 forwarding_info: None,
5814 outbound_htlc_minimum_msat: None,
5815 outbound_htlc_maximum_msat: None,
5817 funding_txo: Some(OutPoint {
5818 txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0
5821 short_channel_id: Some(1),
5822 inbound_scid_alias: None,
5823 outbound_scid_alias: None,
5824 channel_value_satoshis: 10_000_000,
5826 balance_msat: 10_000_000,
5827 outbound_capacity_msat: 10_000_000,
5828 next_outbound_htlc_limit_msat: 10_000_000,
5829 inbound_capacity_msat: 0,
5830 unspendable_punishment_reserve: None,
5831 confirmations_required: None,
5832 force_close_spend_delay: None,
5834 is_channel_ready: true,
5837 inbound_htlc_minimum_msat: None,
5838 inbound_htlc_maximum_msat: None,
5844 fn generate_routes_with_zero_penalty_scorer(bench: &mut Bencher) {
5845 let logger = DummyLogger {};
5846 let network_graph = read_network_graph(&logger);
5847 let scorer = FixedPenaltyScorer::with_penalty(0);
5848 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::empty());
5852 fn generate_mpp_routes_with_zero_penalty_scorer(bench: &mut Bencher) {
5853 let logger = DummyLogger {};
5854 let network_graph = read_network_graph(&logger);
5855 let scorer = FixedPenaltyScorer::with_penalty(0);
5856 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::known());
5860 fn generate_routes_with_probabilistic_scorer(bench: &mut Bencher) {
5861 let logger = DummyLogger {};
5862 let network_graph = read_network_graph(&logger);
5863 let params = ProbabilisticScoringParameters::default();
5864 let scorer = ProbabilisticScorer::new(params, &network_graph, &logger);
5865 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::empty());
5869 fn generate_mpp_routes_with_probabilistic_scorer(bench: &mut Bencher) {
5870 let logger = DummyLogger {};
5871 let network_graph = read_network_graph(&logger);
5872 let params = ProbabilisticScoringParameters::default();
5873 let scorer = ProbabilisticScorer::new(params, &network_graph, &logger);
5874 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::known());
5877 fn generate_routes<S: Score>(
5878 bench: &mut Bencher, graph: &NetworkGraph<&DummyLogger>, mut scorer: S,
5879 features: InvoiceFeatures
5881 let nodes = graph.read_only().nodes().clone();
5882 let payer = payer_pubkey();
5883 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
5884 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5886 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
5887 let mut routes = Vec::new();
5888 let mut route_endpoints = Vec::new();
5889 let mut seed: usize = 0xdeadbeef;
5890 'load_endpoints: for _ in 0..150 {
5893 let src = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5895 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5896 let params = PaymentParameters::from_node_id(dst).with_features(features.clone());
5897 let first_hop = first_hop(src);
5898 let amt = seed as u64 % 1_000_000;
5899 if let Ok(route) = get_route(&payer, ¶ms, &graph.read_only(), Some(&[&first_hop]), amt, 42, &DummyLogger{}, &scorer, &random_seed_bytes) {
5901 route_endpoints.push((first_hop, params, amt));
5902 continue 'load_endpoints;
5907 // ...and seed the scorer with success and failure data...
5908 for route in routes {
5909 let amount = route.get_total_amount();
5910 if amount < 250_000 {
5911 for path in route.paths {
5912 scorer.payment_path_successful(&path.iter().collect::<Vec<_>>());
5914 } else if amount > 750_000 {
5915 for path in route.paths {
5916 let short_channel_id = path[path.len() / 2].short_channel_id;
5917 scorer.payment_path_failed(&path.iter().collect::<Vec<_>>(), short_channel_id);
5922 // Because we've changed channel scores, its possible we'll take different routes to the
5923 // selected destinations, possibly causing us to fail because, eg, the newly-selected path
5924 // requires a too-high CLTV delta.
5925 route_endpoints.retain(|(first_hop, params, amt)| {
5926 get_route(&payer, params, &graph.read_only(), Some(&[first_hop]), *amt, 42, &DummyLogger{}, &scorer, &random_seed_bytes).is_ok()
5928 route_endpoints.truncate(100);
5929 assert_eq!(route_endpoints.len(), 100);
5931 // ...then benchmark finding paths between the nodes we learned.
5934 let (first_hop, params, amt) = &route_endpoints[idx % route_endpoints.len()];
5935 assert!(get_route(&payer, params, &graph.read_only(), Some(&[first_hop]), *amt, 42, &DummyLogger{}, &scorer, &random_seed_bytes).is_ok());