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;
16 use bitcoin::hashes::Hash;
17 use bitcoin::hashes::sha256::Hash as Sha256;
19 use crate::ln::PaymentHash;
20 use crate::ln::channelmanager::{ChannelDetails, PaymentId};
21 use crate::ln::features::{ChannelFeatures, InvoiceFeatures, NodeFeatures};
22 use crate::ln::msgs::{DecodeError, ErrorAction, LightningError, MAX_VALUE_MSAT};
23 use crate::routing::gossip::{DirectedChannelInfo, EffectiveCapacity, ReadOnlyNetworkGraph, NetworkGraph, NodeId, RoutingFees};
24 use crate::routing::scoring::{ChannelUsage, LockableScore, Score};
25 use crate::util::ser::{Writeable, Readable, Writer};
26 use crate::util::logger::{Level, Logger};
27 use crate::util::chacha20::ChaCha20;
30 use crate::prelude::*;
31 use crate::sync::Mutex;
32 use alloc::collections::BinaryHeap;
36 /// A [`Router`] implemented using [`find_route`].
37 pub struct DefaultRouter<G: Deref<Target = NetworkGraph<L>>, L: Deref, S: Deref> where
39 S::Target: for <'a> LockableScore<'a>,
43 random_seed_bytes: Mutex<[u8; 32]>,
47 impl<G: Deref<Target = NetworkGraph<L>>, L: Deref, S: Deref> DefaultRouter<G, L, S> where
49 S::Target: for <'a> LockableScore<'a>,
51 /// Creates a new router.
52 pub fn new(network_graph: G, logger: L, random_seed_bytes: [u8; 32], scorer: S) -> Self {
53 let random_seed_bytes = Mutex::new(random_seed_bytes);
54 Self { network_graph, logger, random_seed_bytes, scorer }
58 impl<G: Deref<Target = NetworkGraph<L>>, L: Deref, S: Deref> Router for DefaultRouter<G, L, S> where
60 S::Target: for <'a> LockableScore<'a>,
63 &self, payer: &PublicKey, params: &RouteParameters, first_hops: Option<&[&ChannelDetails]>,
64 inflight_htlcs: &InFlightHtlcs
65 ) -> Result<Route, LightningError> {
66 let random_seed_bytes = {
67 let mut locked_random_seed_bytes = self.random_seed_bytes.lock().unwrap();
68 *locked_random_seed_bytes = Sha256::hash(&*locked_random_seed_bytes).into_inner();
69 *locked_random_seed_bytes
73 payer, params, &self.network_graph, first_hops, &*self.logger,
74 &ScorerAccountingForInFlightHtlcs::new(self.scorer.lock(), inflight_htlcs),
79 fn notify_payment_path_failed(&self, path: &[&RouteHop], short_channel_id: u64) {
80 self.scorer.lock().payment_path_failed(path, short_channel_id);
83 fn notify_payment_path_successful(&self, path: &[&RouteHop]) {
84 self.scorer.lock().payment_path_successful(path);
87 fn notify_payment_probe_successful(&self, path: &[&RouteHop]) {
88 self.scorer.lock().probe_successful(path);
91 fn notify_payment_probe_failed(&self, path: &[&RouteHop], short_channel_id: u64) {
92 self.scorer.lock().probe_failed(path, short_channel_id);
96 /// A trait defining behavior for routing a payment.
98 /// Finds a [`Route`] between `payer` and `payee` for a payment with the given values.
100 &self, payer: &PublicKey, route_params: &RouteParameters,
101 first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: &InFlightHtlcs
102 ) -> Result<Route, LightningError>;
103 /// Finds a [`Route`] between `payer` and `payee` for a payment with the given values. Includes
104 /// `PaymentHash` and `PaymentId` to be able to correlate the request with a specific payment.
105 fn find_route_with_id(
106 &self, payer: &PublicKey, route_params: &RouteParameters,
107 first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: &InFlightHtlcs,
108 _payment_hash: PaymentHash, _payment_id: PaymentId
109 ) -> Result<Route, LightningError> {
110 self.find_route(payer, route_params, first_hops, inflight_htlcs)
112 /// Lets the router know that payment through a specific path has failed.
113 fn notify_payment_path_failed(&self, path: &[&RouteHop], short_channel_id: u64);
114 /// Lets the router know that payment through a specific path was successful.
115 fn notify_payment_path_successful(&self, path: &[&RouteHop]);
116 /// Lets the router know that a payment probe was successful.
117 fn notify_payment_probe_successful(&self, path: &[&RouteHop]);
118 /// Lets the router know that a payment probe failed.
119 fn notify_payment_probe_failed(&self, path: &[&RouteHop], short_channel_id: u64);
122 /// [`Score`] implementation that factors in in-flight HTLC liquidity.
124 /// Useful for custom [`Router`] implementations to wrap their [`Score`] on-the-fly when calling
127 /// [`Score`]: crate::routing::scoring::Score
128 pub struct ScorerAccountingForInFlightHtlcs<'a, S: Score> {
130 // Maps a channel's short channel id and its direction to the liquidity used up.
131 inflight_htlcs: &'a InFlightHtlcs,
134 impl<'a, S: Score> ScorerAccountingForInFlightHtlcs<'a, S> {
135 /// Initialize a new `ScorerAccountingForInFlightHtlcs`.
136 pub fn new(scorer: S, inflight_htlcs: &'a InFlightHtlcs) -> Self {
137 ScorerAccountingForInFlightHtlcs {
145 impl<'a, S: Score> Writeable for ScorerAccountingForInFlightHtlcs<'a, S> {
146 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> { self.scorer.write(writer) }
149 impl<'a, S: Score> Score for ScorerAccountingForInFlightHtlcs<'a, S> {
150 fn channel_penalty_msat(&self, short_channel_id: u64, source: &NodeId, target: &NodeId, usage: ChannelUsage) -> u64 {
151 if let Some(used_liquidity) = self.inflight_htlcs.used_liquidity_msat(
152 source, target, short_channel_id
154 let usage = ChannelUsage {
155 inflight_htlc_msat: usage.inflight_htlc_msat + used_liquidity,
159 self.scorer.channel_penalty_msat(short_channel_id, source, target, usage)
161 self.scorer.channel_penalty_msat(short_channel_id, source, target, usage)
165 fn payment_path_failed(&mut self, path: &[&RouteHop], short_channel_id: u64) {
166 self.scorer.payment_path_failed(path, short_channel_id)
169 fn payment_path_successful(&mut self, path: &[&RouteHop]) {
170 self.scorer.payment_path_successful(path)
173 fn probe_failed(&mut self, path: &[&RouteHop], short_channel_id: u64) {
174 self.scorer.probe_failed(path, short_channel_id)
177 fn probe_successful(&mut self, path: &[&RouteHop]) {
178 self.scorer.probe_successful(path)
182 /// A data structure for tracking in-flight HTLCs. May be used during pathfinding to account for
183 /// in-use channel liquidity.
185 pub struct InFlightHtlcs(
186 // A map with liquidity value (in msat) keyed by a short channel id and the direction the HTLC
187 // is traveling in. The direction boolean is determined by checking if the HTLC source's public
188 // key is less than its destination. See `InFlightHtlcs::used_liquidity_msat` for more
190 HashMap<(u64, bool), u64>
194 /// Constructs an empty `InFlightHtlcs`.
195 pub fn new() -> Self { InFlightHtlcs(HashMap::new()) }
197 /// Takes in a path with payer's node id and adds the path's details to `InFlightHtlcs`.
198 pub fn process_path(&mut self, path: &[RouteHop], payer_node_id: PublicKey) {
199 if path.is_empty() { return };
200 // total_inflight_map needs to be direction-sensitive when keeping track of the HTLC value
201 // that is held up. However, the `hops` array, which is a path returned by `find_route` in
202 // the router excludes the payer node. In the following lines, the payer's information is
203 // hardcoded with an inflight value of 0 so that we can correctly represent the first hop
204 // in our sliding window of two.
205 let reversed_hops_with_payer = path.iter().rev().skip(1)
206 .map(|hop| hop.pubkey)
207 .chain(core::iter::once(payer_node_id));
208 let mut cumulative_msat = 0;
210 // Taking the reversed vector from above, we zip it with just the reversed hops list to
211 // work "backwards" of the given path, since the last hop's `fee_msat` actually represents
212 // the total amount sent.
213 for (next_hop, prev_hop) in path.iter().rev().zip(reversed_hops_with_payer) {
214 cumulative_msat += next_hop.fee_msat;
216 .entry((next_hop.short_channel_id, NodeId::from_pubkey(&prev_hop) < NodeId::from_pubkey(&next_hop.pubkey)))
217 .and_modify(|used_liquidity_msat| *used_liquidity_msat += cumulative_msat)
218 .or_insert(cumulative_msat);
222 /// Returns liquidity in msat given the public key of the HTLC source, target, and short channel
224 pub fn used_liquidity_msat(&self, source: &NodeId, target: &NodeId, channel_scid: u64) -> Option<u64> {
225 self.0.get(&(channel_scid, source < target)).map(|v| *v)
229 impl Writeable for InFlightHtlcs {
230 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> { self.0.write(writer) }
233 impl Readable for InFlightHtlcs {
234 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
235 let infight_map: HashMap<(u64, bool), u64> = Readable::read(reader)?;
236 Ok(Self(infight_map))
241 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
242 pub struct RouteHop {
243 /// The node_id of the node at this hop.
244 pub pubkey: PublicKey,
245 /// The node_announcement features of the node at this hop. For the last hop, these may be
246 /// amended to match the features present in the invoice this node generated.
247 pub node_features: NodeFeatures,
248 /// The channel that should be used from the previous hop to reach this node.
249 pub short_channel_id: u64,
250 /// The channel_announcement features of the channel that should be used from the previous hop
251 /// to reach this node.
252 pub channel_features: ChannelFeatures,
253 /// The fee taken on this hop (for paying for the use of the *next* channel in the path).
254 /// For the last hop, this should be the full value of the payment (might be more than
255 /// requested if we had to match htlc_minimum_msat).
257 /// The CLTV delta added for this hop. For the last hop, this should be the full CLTV value
258 /// expected at the destination, in excess of the current block height.
259 pub cltv_expiry_delta: u32,
262 impl_writeable_tlv_based!(RouteHop, {
263 (0, pubkey, required),
264 (2, node_features, required),
265 (4, short_channel_id, required),
266 (6, channel_features, required),
267 (8, fee_msat, required),
268 (10, cltv_expiry_delta, required),
271 /// A route directs a payment from the sender (us) to the recipient. If the recipient supports MPP,
272 /// it can take multiple paths. Each path is composed of one or more hops through the network.
273 #[derive(Clone, Hash, PartialEq, Eq)]
275 /// The list of routes taken for a single (potentially-)multi-part payment. The pubkey of the
276 /// last RouteHop in each path must be the same. Each entry represents a list of hops, NOT
277 /// INCLUDING our own, where the last hop is the destination. Thus, this must always be at
278 /// least length one. While the maximum length of any given path is variable, keeping the length
279 /// of any path less or equal to 19 should currently ensure it is viable.
280 pub paths: Vec<Vec<RouteHop>>,
281 /// The `payment_params` parameter passed to [`find_route`].
282 /// This is used by `ChannelManager` to track information which may be required for retries,
283 /// provided back to you via [`Event::PaymentPathFailed`].
285 /// [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed
286 pub payment_params: Option<PaymentParameters>,
289 pub(crate) trait RoutePath {
290 /// Gets the fees for a given path, excluding any excess paid to the recipient.
291 fn get_path_fees(&self) -> u64;
293 impl RoutePath for Vec<RouteHop> {
294 fn get_path_fees(&self) -> u64 {
295 // Do not count last hop of each path since that's the full value of the payment
296 self.split_last().map(|(_, path_prefix)| path_prefix).unwrap_or(&[])
297 .iter().map(|hop| &hop.fee_msat)
303 /// Returns the total amount of fees paid on this [`Route`].
305 /// This doesn't include any extra payment made to the recipient, which can happen in excess of
306 /// the amount passed to [`find_route`]'s `params.final_value_msat`.
307 pub fn get_total_fees(&self) -> u64 {
308 self.paths.iter().map(|path| path.get_path_fees()).sum()
311 /// Returns the total amount paid on this [`Route`], excluding the fees.
312 pub fn get_total_amount(&self) -> u64 {
313 return self.paths.iter()
314 .map(|path| path.split_last().map(|(hop, _)| hop.fee_msat).unwrap_or(0))
319 const SERIALIZATION_VERSION: u8 = 1;
320 const MIN_SERIALIZATION_VERSION: u8 = 1;
322 impl Writeable for Route {
323 fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
324 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
325 (self.paths.len() as u64).write(writer)?;
326 for hops in self.paths.iter() {
327 (hops.len() as u8).write(writer)?;
328 for hop in hops.iter() {
332 write_tlv_fields!(writer, {
333 (1, self.payment_params, option),
339 impl Readable for Route {
340 fn read<R: io::Read>(reader: &mut R) -> Result<Route, DecodeError> {
341 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
342 let path_count: u64 = Readable::read(reader)?;
343 let mut paths = Vec::with_capacity(cmp::min(path_count, 128) as usize);
344 for _ in 0..path_count {
345 let hop_count: u8 = Readable::read(reader)?;
346 let mut hops = Vec::with_capacity(hop_count as usize);
347 for _ in 0..hop_count {
348 hops.push(Readable::read(reader)?);
352 let mut payment_params = None;
353 read_tlv_fields!(reader, {
354 (1, payment_params, option),
356 Ok(Route { paths, payment_params })
360 /// Parameters needed to find a [`Route`].
362 /// Passed to [`find_route`] and [`build_route_from_hops`], but also provided in
363 /// [`Event::PaymentPathFailed`] for retrying a failed payment path.
365 /// [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed
366 #[derive(Clone, Debug)]
367 pub struct RouteParameters {
368 /// The parameters of the failed payment path.
369 pub payment_params: PaymentParameters,
371 /// The amount in msats sent on the failed payment path.
372 pub final_value_msat: u64,
374 /// The CLTV on the final hop of the failed payment path.
375 pub final_cltv_expiry_delta: u32,
378 impl_writeable_tlv_based!(RouteParameters, {
379 (0, payment_params, required),
380 (2, final_value_msat, required),
381 (4, final_cltv_expiry_delta, required),
384 /// Maximum total CTLV difference we allow for a full payment path.
385 pub const DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA: u32 = 1008;
387 /// Maximum number of paths we allow an (MPP) payment to have.
388 // The default limit is currently set rather arbitrary - there aren't any real fundamental path-count
389 // limits, but for now more than 10 paths likely carries too much one-path failure.
390 pub const DEFAULT_MAX_PATH_COUNT: u8 = 10;
392 // The median hop CLTV expiry delta currently seen in the network.
393 const MEDIAN_HOP_CLTV_EXPIRY_DELTA: u32 = 40;
395 // During routing, we only consider paths shorter than our maximum length estimate.
396 // In the TLV onion format, there is no fixed maximum length, but the `hop_payloads`
397 // field is always 1300 bytes. As the `tlv_payload` for each hop may vary in length, we have to
398 // estimate how many hops the route may have so that it actually fits the `hop_payloads` field.
400 // We estimate 3+32 (payload length and HMAC) + 2+8 (amt_to_forward) + 2+4 (outgoing_cltv_value) +
401 // 2+8 (short_channel_id) = 61 bytes for each intermediate hop and 3+32
402 // (payload length and HMAC) + 2+8 (amt_to_forward) + 2+4 (outgoing_cltv_value) + 2+32+8
403 // (payment_secret and total_msat) = 93 bytes for the final hop.
404 // Since the length of the potentially included `payment_metadata` is unknown to us, we round
405 // down from (1300-93) / 61 = 19.78... to arrive at a conservative estimate of 19.
406 const MAX_PATH_LENGTH_ESTIMATE: u8 = 19;
408 /// The recipient of a payment.
409 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
410 pub struct PaymentParameters {
411 /// The node id of the payee.
412 pub payee_pubkey: PublicKey,
414 /// Features supported by the payee.
416 /// May be set from the payee's invoice or via [`for_keysend`]. May be `None` if the invoice
417 /// does not contain any features.
419 /// [`for_keysend`]: Self::for_keysend
420 pub features: Option<InvoiceFeatures>,
422 /// Hints for routing to the payee, containing channels connecting the payee to public nodes.
423 pub route_hints: Vec<RouteHint>,
425 /// Expiration of a payment to the payee, in seconds relative to the UNIX epoch.
426 pub expiry_time: Option<u64>,
428 /// The maximum total CLTV delta we accept for the route.
429 /// Defaults to [`DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA`].
430 pub max_total_cltv_expiry_delta: u32,
432 /// The maximum number of paths that may be used by (MPP) payments.
433 /// Defaults to [`DEFAULT_MAX_PATH_COUNT`].
434 pub max_path_count: u8,
436 /// Selects the maximum share of a channel's total capacity which will be sent over a channel,
437 /// as a power of 1/2. A higher value prefers to send the payment using more MPP parts whereas
438 /// a lower value prefers to send larger MPP parts, potentially saturating channels and
439 /// increasing failure probability for those paths.
441 /// Note that this restriction will be relaxed during pathfinding after paths which meet this
442 /// restriction have been found. While paths which meet this criteria will be searched for, it
443 /// is ultimately up to the scorer to select them over other paths.
445 /// A value of 0 will allow payments up to and including a channel's total announced usable
446 /// capacity, a value of one will only use up to half its capacity, two 1/4, etc.
449 pub max_channel_saturation_power_of_half: u8,
451 /// A list of SCIDs which this payment was previously attempted over and which caused the
452 /// payment to fail. Future attempts for the same payment shouldn't be relayed through any of
454 pub previously_failed_channels: Vec<u64>,
457 impl_writeable_tlv_based!(PaymentParameters, {
458 (0, payee_pubkey, required),
459 (1, max_total_cltv_expiry_delta, (default_value, DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA)),
460 (2, features, option),
461 (3, max_path_count, (default_value, DEFAULT_MAX_PATH_COUNT)),
462 (4, route_hints, vec_type),
463 (5, max_channel_saturation_power_of_half, (default_value, 2)),
464 (6, expiry_time, option),
465 (7, previously_failed_channels, vec_type),
468 impl PaymentParameters {
469 /// Creates a payee with the node id of the given `pubkey`.
470 pub fn from_node_id(payee_pubkey: PublicKey) -> Self {
476 max_total_cltv_expiry_delta: DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA,
477 max_path_count: DEFAULT_MAX_PATH_COUNT,
478 max_channel_saturation_power_of_half: 2,
479 previously_failed_channels: Vec::new(),
483 /// Creates a payee with the node id of the given `pubkey` to use for keysend payments.
484 pub fn for_keysend(payee_pubkey: PublicKey) -> Self {
485 Self::from_node_id(payee_pubkey).with_features(InvoiceFeatures::for_keysend())
488 /// Includes the payee's features.
490 /// (C-not exported) since bindings don't support move semantics
491 pub fn with_features(self, features: InvoiceFeatures) -> Self {
492 Self { features: Some(features), ..self }
495 /// Includes hints for routing to the payee.
497 /// (C-not exported) since bindings don't support move semantics
498 pub fn with_route_hints(self, route_hints: Vec<RouteHint>) -> Self {
499 Self { route_hints, ..self }
502 /// Includes a payment expiration in seconds relative to the UNIX epoch.
504 /// (C-not exported) since bindings don't support move semantics
505 pub fn with_expiry_time(self, expiry_time: u64) -> Self {
506 Self { expiry_time: Some(expiry_time), ..self }
509 /// Includes a limit for the total CLTV expiry delta which is considered during routing
511 /// (C-not exported) since bindings don't support move semantics
512 pub fn with_max_total_cltv_expiry_delta(self, max_total_cltv_expiry_delta: u32) -> Self {
513 Self { max_total_cltv_expiry_delta, ..self }
516 /// Includes a limit for the maximum number of payment paths that may be used.
518 /// (C-not exported) since bindings don't support move semantics
519 pub fn with_max_path_count(self, max_path_count: u8) -> Self {
520 Self { max_path_count, ..self }
523 /// Includes a limit for the maximum number of payment paths that may be used.
525 /// (C-not exported) since bindings don't support move semantics
526 pub fn with_max_channel_saturation_power_of_half(self, max_channel_saturation_power_of_half: u8) -> Self {
527 Self { max_channel_saturation_power_of_half, ..self }
531 /// A list of hops along a payment path terminating with a channel to the recipient.
532 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
533 pub struct RouteHint(pub Vec<RouteHintHop>);
535 impl Writeable for RouteHint {
536 fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
537 (self.0.len() as u64).write(writer)?;
538 for hop in self.0.iter() {
545 impl Readable for RouteHint {
546 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
547 let hop_count: u64 = Readable::read(reader)?;
548 let mut hops = Vec::with_capacity(cmp::min(hop_count, 16) as usize);
549 for _ in 0..hop_count {
550 hops.push(Readable::read(reader)?);
556 /// A channel descriptor for a hop along a payment path.
557 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
558 pub struct RouteHintHop {
559 /// The node_id of the non-target end of the route
560 pub src_node_id: PublicKey,
561 /// The short_channel_id of this channel
562 pub short_channel_id: u64,
563 /// The fees which must be paid to use this channel
564 pub fees: RoutingFees,
565 /// The difference in CLTV values between this node and the next node.
566 pub cltv_expiry_delta: u16,
567 /// The minimum value, in msat, which must be relayed to the next hop.
568 pub htlc_minimum_msat: Option<u64>,
569 /// The maximum value in msat available for routing with a single HTLC.
570 pub htlc_maximum_msat: Option<u64>,
573 impl_writeable_tlv_based!(RouteHintHop, {
574 (0, src_node_id, required),
575 (1, htlc_minimum_msat, option),
576 (2, short_channel_id, required),
577 (3, htlc_maximum_msat, option),
579 (6, cltv_expiry_delta, required),
582 #[derive(Eq, PartialEq)]
583 struct RouteGraphNode {
585 lowest_fee_to_peer_through_node: u64,
586 lowest_fee_to_node: u64,
587 total_cltv_delta: u32,
588 // The maximum value a yet-to-be-constructed payment path might flow through this node.
589 // This value is upper-bounded by us by:
590 // - how much is needed for a path being constructed
591 // - how much value can channels following this node (up to the destination) can contribute,
592 // considering their capacity and fees
593 value_contribution_msat: u64,
594 /// The effective htlc_minimum_msat at this hop. If a later hop on the path had a higher HTLC
595 /// minimum, we use it, plus the fees required at each earlier hop to meet it.
596 path_htlc_minimum_msat: u64,
597 /// All penalties incurred from this hop on the way to the destination, as calculated using
599 path_penalty_msat: u64,
600 /// The number of hops walked up to this node.
601 path_length_to_node: u8,
604 impl cmp::Ord for RouteGraphNode {
605 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
606 let other_score = cmp::max(other.lowest_fee_to_peer_through_node, other.path_htlc_minimum_msat)
607 .saturating_add(other.path_penalty_msat);
608 let self_score = cmp::max(self.lowest_fee_to_peer_through_node, self.path_htlc_minimum_msat)
609 .saturating_add(self.path_penalty_msat);
610 other_score.cmp(&self_score).then_with(|| other.node_id.cmp(&self.node_id))
614 impl cmp::PartialOrd for RouteGraphNode {
615 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
616 Some(self.cmp(other))
620 /// A wrapper around the various hop representations.
622 /// Used to construct a [`PathBuildingHop`] and to estimate [`EffectiveCapacity`].
623 #[derive(Clone, Debug)]
624 enum CandidateRouteHop<'a> {
625 /// A hop from the payer, where the outbound liquidity is known.
627 details: &'a ChannelDetails,
629 /// A hop found in the [`ReadOnlyNetworkGraph`], where the channel capacity may be unknown.
631 info: DirectedChannelInfo<'a>,
632 short_channel_id: u64,
634 /// A hop to the payee found in the payment invoice, though not necessarily a direct channel.
636 hint: &'a RouteHintHop,
640 impl<'a> CandidateRouteHop<'a> {
641 fn short_channel_id(&self) -> u64 {
643 CandidateRouteHop::FirstHop { details } => details.get_outbound_payment_scid().unwrap(),
644 CandidateRouteHop::PublicHop { short_channel_id, .. } => *short_channel_id,
645 CandidateRouteHop::PrivateHop { hint } => hint.short_channel_id,
649 // NOTE: This may alloc memory so avoid calling it in a hot code path.
650 fn features(&self) -> ChannelFeatures {
652 CandidateRouteHop::FirstHop { details } => details.counterparty.features.to_context(),
653 CandidateRouteHop::PublicHop { info, .. } => info.channel().features.clone(),
654 CandidateRouteHop::PrivateHop { .. } => ChannelFeatures::empty(),
658 fn cltv_expiry_delta(&self) -> u32 {
660 CandidateRouteHop::FirstHop { .. } => 0,
661 CandidateRouteHop::PublicHop { info, .. } => info.direction().cltv_expiry_delta as u32,
662 CandidateRouteHop::PrivateHop { hint } => hint.cltv_expiry_delta as u32,
666 fn htlc_minimum_msat(&self) -> u64 {
668 CandidateRouteHop::FirstHop { .. } => 0,
669 CandidateRouteHop::PublicHop { info, .. } => info.direction().htlc_minimum_msat,
670 CandidateRouteHop::PrivateHop { hint } => hint.htlc_minimum_msat.unwrap_or(0),
674 fn fees(&self) -> RoutingFees {
676 CandidateRouteHop::FirstHop { .. } => RoutingFees {
677 base_msat: 0, proportional_millionths: 0,
679 CandidateRouteHop::PublicHop { info, .. } => info.direction().fees,
680 CandidateRouteHop::PrivateHop { hint } => hint.fees,
684 fn effective_capacity(&self) -> EffectiveCapacity {
686 CandidateRouteHop::FirstHop { details } => EffectiveCapacity::ExactLiquidity {
687 liquidity_msat: details.next_outbound_htlc_limit_msat,
689 CandidateRouteHop::PublicHop { info, .. } => info.effective_capacity(),
690 CandidateRouteHop::PrivateHop { .. } => EffectiveCapacity::Infinite,
696 fn max_htlc_from_capacity(capacity: EffectiveCapacity, max_channel_saturation_power_of_half: u8) -> u64 {
697 let saturation_shift: u32 = max_channel_saturation_power_of_half as u32;
699 EffectiveCapacity::ExactLiquidity { liquidity_msat } => liquidity_msat,
700 EffectiveCapacity::Infinite => u64::max_value(),
701 EffectiveCapacity::Unknown => EffectiveCapacity::Unknown.as_msat(),
702 EffectiveCapacity::MaximumHTLC { amount_msat } =>
703 amount_msat.checked_shr(saturation_shift).unwrap_or(0),
704 EffectiveCapacity::Total { capacity_msat, htlc_maximum_msat } =>
705 cmp::min(capacity_msat.checked_shr(saturation_shift).unwrap_or(0), htlc_maximum_msat),
709 fn iter_equal<I1: Iterator, I2: Iterator>(mut iter_a: I1, mut iter_b: I2)
710 -> bool where I1::Item: PartialEq<I2::Item> {
712 let a = iter_a.next();
713 let b = iter_b.next();
714 if a.is_none() && b.is_none() { return true; }
715 if a.is_none() || b.is_none() { return false; }
716 if a.unwrap().ne(&b.unwrap()) { return false; }
720 /// It's useful to keep track of the hops associated with the fees required to use them,
721 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
722 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
723 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
725 struct PathBuildingHop<'a> {
726 // Note that this should be dropped in favor of loading it from CandidateRouteHop, but doing so
727 // is a larger refactor and will require careful performance analysis.
729 candidate: CandidateRouteHop<'a>,
732 /// Minimal fees required to route to the source node of the current hop via any of its inbound channels.
733 src_lowest_inbound_fees: RoutingFees,
734 /// All the fees paid *after* this channel on the way to the destination
735 next_hops_fee_msat: u64,
736 /// Fee paid for the use of the current channel (see candidate.fees()).
737 /// The value will be actually deducted from the counterparty balance on the previous link.
738 hop_use_fee_msat: u64,
739 /// Used to compare channels when choosing the for routing.
740 /// Includes paying for the use of a hop and the following hops, as well as
741 /// an estimated cost of reaching this hop.
742 /// Might get stale when fees are recomputed. Primarily for internal use.
744 /// A mirror of the same field in RouteGraphNode. Note that this is only used during the graph
745 /// walk and may be invalid thereafter.
746 path_htlc_minimum_msat: u64,
747 /// All penalties incurred from this channel on the way to the destination, as calculated using
749 path_penalty_msat: u64,
750 /// If we've already processed a node as the best node, we shouldn't process it again. Normally
751 /// we'd just ignore it if we did as all channels would have a higher new fee, but because we
752 /// may decrease the amounts in use as we walk the graph, the actual calculated fee may
753 /// decrease as well. Thus, we have to explicitly track which nodes have been processed and
754 /// avoid processing them again.
756 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
757 // In tests, we apply further sanity checks on cases where we skip nodes we already processed
758 // to ensure it is specifically in cases where the fee has gone down because of a decrease in
759 // value_contribution_msat, which requires tracking it here. See comments below where it is
760 // used for more info.
761 value_contribution_msat: u64,
764 impl<'a> core::fmt::Debug for PathBuildingHop<'a> {
765 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
766 let mut debug_struct = f.debug_struct("PathBuildingHop");
768 .field("node_id", &self.node_id)
769 .field("short_channel_id", &self.candidate.short_channel_id())
770 .field("total_fee_msat", &self.total_fee_msat)
771 .field("next_hops_fee_msat", &self.next_hops_fee_msat)
772 .field("hop_use_fee_msat", &self.hop_use_fee_msat)
773 .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)))
774 .field("path_penalty_msat", &self.path_penalty_msat)
775 .field("path_htlc_minimum_msat", &self.path_htlc_minimum_msat)
776 .field("cltv_expiry_delta", &self.candidate.cltv_expiry_delta());
777 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
778 let debug_struct = debug_struct
779 .field("value_contribution_msat", &self.value_contribution_msat);
780 debug_struct.finish()
784 // Instantiated with a list of hops with correct data in them collected during path finding,
785 // an instance of this struct should be further modified only via given methods.
787 struct PaymentPath<'a> {
788 hops: Vec<(PathBuildingHop<'a>, NodeFeatures)>,
791 impl<'a> PaymentPath<'a> {
792 // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
793 fn get_value_msat(&self) -> u64 {
794 self.hops.last().unwrap().0.fee_msat
797 fn get_path_penalty_msat(&self) -> u64 {
798 self.hops.first().map(|h| h.0.path_penalty_msat).unwrap_or(u64::max_value())
801 fn get_total_fee_paid_msat(&self) -> u64 {
802 if self.hops.len() < 1 {
806 // Can't use next_hops_fee_msat because it gets outdated.
807 for (i, (hop, _)) in self.hops.iter().enumerate() {
808 if i != self.hops.len() - 1 {
809 result += hop.fee_msat;
815 fn get_cost_msat(&self) -> u64 {
816 self.get_total_fee_paid_msat().saturating_add(self.get_path_penalty_msat())
819 // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
820 // to change fees may result in an inconsistency.
822 // Sometimes we call this function right after constructing a path which is inconsistent in
823 // that it the value being transferred has decreased while we were doing path finding, leading
824 // to the fees being paid not lining up with the actual limits.
826 // Note that this function is not aware of the available_liquidity limit, and thus does not
827 // support increasing the value being transferred beyond what was selected during the initial
829 fn update_value_and_recompute_fees(&mut self, value_msat: u64) {
830 let mut total_fee_paid_msat = 0 as u64;
831 for i in (0..self.hops.len()).rev() {
832 let last_hop = i == self.hops.len() - 1;
834 // For non-last-hop, this value will represent the fees paid on the current hop. It
835 // will consist of the fees for the use of the next hop, and extra fees to match
836 // htlc_minimum_msat of the current channel. Last hop is handled separately.
837 let mut cur_hop_fees_msat = 0;
839 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().0.hop_use_fee_msat;
842 let mut cur_hop = &mut self.hops.get_mut(i).unwrap().0;
843 cur_hop.next_hops_fee_msat = total_fee_paid_msat;
844 // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
845 // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
846 // set it too high just to maliciously take more fees by exploiting this
847 // match htlc_minimum_msat logic.
848 let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
849 if let Some(extra_fees_msat) = cur_hop.candidate.htlc_minimum_msat().checked_sub(cur_hop_transferred_amount_msat) {
850 // Note that there is a risk that *previous hops* (those closer to us, as we go
851 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
853 // This might make us end up with a broken route, although this should be super-rare
854 // in practice, both because of how healthy channels look like, and how we pick
855 // channels in add_entry.
856 // Also, this can't be exploited more heavily than *announce a free path and fail
858 cur_hop_transferred_amount_msat += extra_fees_msat;
859 total_fee_paid_msat += extra_fees_msat;
860 cur_hop_fees_msat += extra_fees_msat;
864 // Final hop is a special case: it usually has just value_msat (by design), but also
865 // it still could overpay for the htlc_minimum_msat.
866 cur_hop.fee_msat = cur_hop_transferred_amount_msat;
868 // Propagate updated fees for the use of the channels to one hop back, where they
869 // will be actually paid (fee_msat). The last hop is handled above separately.
870 cur_hop.fee_msat = cur_hop_fees_msat;
873 // Fee for the use of the current hop which will be deducted on the previous hop.
874 // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
875 // this channel is free for us.
877 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.candidate.fees()) {
878 cur_hop.hop_use_fee_msat = new_fee;
879 total_fee_paid_msat += new_fee;
881 // It should not be possible because this function is called only to reduce the
882 // value. In that case, compute_fee was already called with the same fees for
883 // larger amount and there was no overflow.
891 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
892 let proportional_fee_millions =
893 amount_msat.checked_mul(channel_fees.proportional_millionths as u64);
894 if let Some(new_fee) = proportional_fee_millions.and_then(|part| {
895 (channel_fees.base_msat as u64).checked_add(part / 1_000_000) }) {
899 // This function may be (indirectly) called without any verification,
900 // with channel_fees provided by a caller. We should handle it gracefully.
905 /// The default `features` we assume for a node in a route, when no `features` are known about that
908 /// Default features are:
909 /// * variable_length_onion_optional
910 fn default_node_features() -> NodeFeatures {
911 let mut features = NodeFeatures::empty();
912 features.set_variable_length_onion_optional();
916 /// Finds a route from us (payer) to the given target node (payee).
918 /// If the payee provided features in their invoice, they should be provided via `params.payee`.
919 /// Without this, MPP will only be used if the payee's features are available in the network graph.
921 /// Private routing paths between a public node and the target may be included in `params.payee`.
923 /// If some channels aren't announced, it may be useful to fill in `first_hops` with the results
924 /// from [`ChannelManager::list_usable_channels`]. If it is filled in, the view of these channels
925 /// from `network_graph` will be ignored, and only those in `first_hops` will be used.
927 /// The fees on channels from us to the next hop are ignored as they are assumed to all be equal.
928 /// However, the enabled/disabled bit on such channels as well as the `htlc_minimum_msat` /
929 /// `htlc_maximum_msat` *are* checked as they may change based on the receiving node.
933 /// May be used to re-compute a [`Route`] when handling a [`Event::PaymentPathFailed`]. Any
934 /// adjustments to the [`NetworkGraph`] and channel scores should be made prior to calling this
939 /// Panics if first_hops contains channels without short_channel_ids;
940 /// [`ChannelManager::list_usable_channels`] will never include such channels.
942 /// [`ChannelManager::list_usable_channels`]: crate::ln::channelmanager::ChannelManager::list_usable_channels
943 /// [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed
944 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
945 pub fn find_route<L: Deref, GL: Deref, S: Score>(
946 our_node_pubkey: &PublicKey, route_params: &RouteParameters,
947 network_graph: &NetworkGraph<GL>, first_hops: Option<&[&ChannelDetails]>, logger: L,
948 scorer: &S, random_seed_bytes: &[u8; 32]
949 ) -> Result<Route, LightningError>
950 where L::Target: Logger, GL::Target: Logger {
951 let graph_lock = network_graph.read_only();
952 let mut route = get_route(our_node_pubkey, &route_params.payment_params, &graph_lock, first_hops,
953 route_params.final_value_msat, route_params.final_cltv_expiry_delta, logger, scorer,
955 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
959 pub(crate) fn get_route<L: Deref, S: Score>(
960 our_node_pubkey: &PublicKey, payment_params: &PaymentParameters, network_graph: &ReadOnlyNetworkGraph,
961 first_hops: Option<&[&ChannelDetails]>, final_value_msat: u64, final_cltv_expiry_delta: u32,
962 logger: L, scorer: &S, _random_seed_bytes: &[u8; 32]
963 ) -> Result<Route, LightningError>
964 where L::Target: Logger {
965 let payee_node_id = NodeId::from_pubkey(&payment_params.payee_pubkey);
966 let our_node_id = NodeId::from_pubkey(&our_node_pubkey);
968 if payee_node_id == our_node_id {
969 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
972 if final_value_msat > MAX_VALUE_MSAT {
973 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
976 if final_value_msat == 0 {
977 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
980 for route in payment_params.route_hints.iter() {
981 for hop in &route.0 {
982 if hop.src_node_id == payment_params.payee_pubkey {
983 return Err(LightningError{err: "Route hint cannot have the payee as the source.".to_owned(), action: ErrorAction::IgnoreError});
987 if payment_params.max_total_cltv_expiry_delta <= final_cltv_expiry_delta {
988 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});
991 // The general routing idea is the following:
992 // 1. Fill first/last hops communicated by the caller.
993 // 2. Attempt to construct a path from payer to payee for transferring
994 // any ~sufficient (described later) value.
995 // If succeed, remember which channels were used and how much liquidity they have available,
996 // so that future paths don't rely on the same liquidity.
997 // 3. Proceed to the next step if:
998 // - we hit the recommended target value;
999 // - OR if we could not construct a new path. Any next attempt will fail too.
1000 // Otherwise, repeat step 2.
1001 // 4. See if we managed to collect paths which aggregately are able to transfer target value
1002 // (not recommended value).
1003 // 5. If yes, proceed. If not, fail routing.
1004 // 6. Select the paths which have the lowest cost (fee plus scorer penalty) per amount
1005 // transferred up to the transfer target value.
1006 // 7. Reduce the value of the last path until we are sending only the target value.
1007 // 8. If our maximum channel saturation limit caused us to pick two identical paths, combine
1008 // them so that we're not sending two HTLCs along the same path.
1010 // As for the actual search algorithm,
1011 // we do a payee-to-payer pseudo-Dijkstra's sorting by each node's distance from the payee
1012 // plus the minimum per-HTLC fee to get from it to another node (aka "shitty pseudo-A*").
1014 // We are not a faithful Dijkstra's implementation because we can change values which impact
1015 // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
1016 // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) than
1017 // the value we are currently attempting to send over a path, we simply reduce the value being
1018 // sent along the path for any hops after that channel. This may imply that later fees (which
1019 // we've already tabulated) are lower because a smaller value is passing through the channels
1020 // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
1021 // channels which were selected earlier (and which may still be used for other paths without a
1022 // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
1025 // One potentially problematic case for this algorithm would be if there are many
1026 // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
1027 // graph walking), we may never find a path which is not liquidity-limited and has lower
1028 // proportional fee (and only lower absolute fee when considering the ultimate value sent).
1029 // Because we only consider paths with at least 5% of the total value being sent, the damage
1030 // from such a case should be limited, however this could be further reduced in the future by
1031 // calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
1032 // limits for the purposes of fee calculation.
1034 // Alternatively, we could store more detailed path information in the heap (targets, below)
1035 // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
1036 // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
1037 // and practically (as we would need to store dynamically-allocated path information in heap
1038 // objects, increasing malloc traffic and indirect memory access significantly). Further, the
1039 // results of such an algorithm would likely be biased towards lower-value paths.
1041 // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
1042 // outside of our current search value, running a path search more times to gather candidate
1043 // paths at different values. While this may be acceptable, further path searches may increase
1044 // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
1045 // graph for candidate paths, calculating the maximum value which can realistically be sent at
1046 // the same time, remaining generic across different payment values.
1048 // TODO: There are a few tweaks we could do, including possibly pre-calculating more stuff
1049 // to use as the A* heuristic beyond just the cost to get one node further than the current
1052 let network_channels = network_graph.channels();
1053 let network_nodes = network_graph.nodes();
1055 if payment_params.max_path_count == 0 {
1056 return Err(LightningError{err: "Can't find a route with no paths allowed.".to_owned(), action: ErrorAction::IgnoreError});
1059 // Allow MPP only if we have a features set from somewhere that indicates the payee supports
1060 // it. If the payee supports it they're supposed to include it in the invoice, so that should
1062 let allow_mpp = if payment_params.max_path_count == 1 {
1064 } else if let Some(features) = &payment_params.features {
1065 features.supports_basic_mpp()
1066 } else if let Some(node) = network_nodes.get(&payee_node_id) {
1067 if let Some(node_info) = node.announcement_info.as_ref() {
1068 node_info.features.supports_basic_mpp()
1072 log_trace!(logger, "Searching for a route from payer {} to payee {} {} MPP and {} first hops {}overriding the network graph", our_node_pubkey,
1073 payment_params.payee_pubkey, if allow_mpp { "with" } else { "without" },
1074 first_hops.map(|hops| hops.len()).unwrap_or(0), if first_hops.is_some() { "" } else { "not " });
1077 // Prepare the data we'll use for payee-to-payer search by
1078 // inserting first hops suggested by the caller as targets.
1079 // Our search will then attempt to reach them while traversing from the payee node.
1080 let mut first_hop_targets: HashMap<_, Vec<&ChannelDetails>> =
1081 HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
1082 if let Some(hops) = first_hops {
1084 if chan.get_outbound_payment_scid().is_none() {
1085 panic!("first_hops should be filled in with usable channels, not pending ones");
1087 if chan.counterparty.node_id == *our_node_pubkey {
1088 return Err(LightningError{err: "First hop cannot have our_node_pubkey as a destination.".to_owned(), action: ErrorAction::IgnoreError});
1091 .entry(NodeId::from_pubkey(&chan.counterparty.node_id))
1092 .or_insert(Vec::new())
1095 if first_hop_targets.is_empty() {
1096 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
1100 // The main heap containing all candidate next-hops sorted by their score (max(A* fee,
1101 // htlc_minimum)). Ideally this would be a heap which allowed cheap score reduction instead of
1102 // adding duplicate entries when we find a better path to a given node.
1103 let mut targets: BinaryHeap<RouteGraphNode> = BinaryHeap::new();
1105 // Map from node_id to information about the best current path to that node, including feerate
1107 let mut dist: HashMap<NodeId, PathBuildingHop> = HashMap::with_capacity(network_nodes.len());
1109 // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
1110 // indicating that we may wish to try again with a higher value, potentially paying to meet an
1111 // htlc_minimum with extra fees while still finding a cheaper path.
1112 let mut hit_minimum_limit;
1114 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
1115 // We start with a path_value of the exact amount we want, and if that generates a route we may
1116 // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
1117 // amount we want in total across paths, selecting the best subset at the end.
1118 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
1119 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
1120 let mut path_value_msat = final_value_msat;
1122 // Routing Fragmentation Mitigation heuristic:
1124 // Routing fragmentation across many payment paths increases the overall routing
1125 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
1126 // Taking too many smaller paths also increases the chance of payment failure.
1127 // Thus to avoid this effect, we require from our collected links to provide
1128 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
1129 // This requirement is currently set to be 1/max_path_count of the payment
1130 // value to ensure we only ever return routes that do not violate this limit.
1131 let minimal_value_contribution_msat: u64 = if allow_mpp {
1132 (final_value_msat + (payment_params.max_path_count as u64 - 1)) / payment_params.max_path_count as u64
1137 // When we start collecting routes we enforce the max_channel_saturation_power_of_half
1138 // requirement strictly. After we've collected enough (or if we fail to find new routes) we
1139 // drop the requirement by setting this to 0.
1140 let mut channel_saturation_pow_half = payment_params.max_channel_saturation_power_of_half;
1142 // Keep track of how much liquidity has been used in selected channels. Used to determine
1143 // if the channel can be used by additional MPP paths or to inform path finding decisions. It is
1144 // aware of direction *only* to ensure that the correct htlc_maximum_msat value is used. Hence,
1145 // liquidity used in one direction will not offset any used in the opposite direction.
1146 let mut used_channel_liquidities: HashMap<(u64, bool), u64> =
1147 HashMap::with_capacity(network_nodes.len());
1149 // Keeping track of how much value we already collected across other paths. Helps to decide
1150 // when we want to stop looking for new paths.
1151 let mut already_collected_value_msat = 0;
1153 for (_, channels) in first_hop_targets.iter_mut() {
1154 // Sort the first_hops channels to the same node(s) in priority order of which channel we'd
1155 // most like to use.
1157 // First, if channels are below `recommended_value_msat`, sort them in descending order,
1158 // preferring larger channels to avoid splitting the payment into more MPP parts than is
1161 // Second, because simply always sorting in descending order would always use our largest
1162 // available outbound capacity, needlessly fragmenting our available channel capacities,
1163 // sort channels above `recommended_value_msat` in ascending order, preferring channels
1164 // which have enough, but not too much, capacity for the payment.
1165 channels.sort_unstable_by(|chan_a, chan_b| {
1166 if chan_b.next_outbound_htlc_limit_msat < recommended_value_msat || chan_a.next_outbound_htlc_limit_msat < recommended_value_msat {
1167 // Sort in descending order
1168 chan_b.next_outbound_htlc_limit_msat.cmp(&chan_a.next_outbound_htlc_limit_msat)
1170 // Sort in ascending order
1171 chan_a.next_outbound_htlc_limit_msat.cmp(&chan_b.next_outbound_htlc_limit_msat)
1176 log_trace!(logger, "Building path from {} (payee) to {} (us/payer) for value {} msat.", payment_params.payee_pubkey, our_node_pubkey, final_value_msat);
1178 macro_rules! add_entry {
1179 // Adds entry which goes from $src_node_id to $dest_node_id over the $candidate hop.
1180 // $next_hops_fee_msat represents the fees paid for using all the channels *after* this one,
1181 // since that value has to be transferred over this channel.
1182 // Returns whether this channel caused an update to `targets`.
1183 ( $candidate: expr, $src_node_id: expr, $dest_node_id: expr, $next_hops_fee_msat: expr,
1184 $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr,
1185 $next_hops_path_penalty_msat: expr, $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => { {
1186 // We "return" whether we updated the path at the end, via this:
1187 let mut did_add_update_path_to_src_node = false;
1188 // Channels to self should not be used. This is more of belt-and-suspenders, because in
1189 // practice these cases should be caught earlier:
1190 // - for regular channels at channel announcement (TODO)
1191 // - for first and last hops early in get_route
1192 if $src_node_id != $dest_node_id {
1193 let short_channel_id = $candidate.short_channel_id();
1194 let effective_capacity = $candidate.effective_capacity();
1195 let htlc_maximum_msat = max_htlc_from_capacity(effective_capacity, channel_saturation_pow_half);
1197 // It is tricky to subtract $next_hops_fee_msat from available liquidity here.
1198 // It may be misleading because we might later choose to reduce the value transferred
1199 // over these channels, and the channel which was insufficient might become sufficient.
1200 // Worst case: we drop a good channel here because it can't cover the high following
1201 // fees caused by one expensive channel, but then this channel could have been used
1202 // if the amount being transferred over this path is lower.
1203 // We do this for now, but this is a subject for removal.
1204 if let Some(mut available_value_contribution_msat) = htlc_maximum_msat.checked_sub($next_hops_fee_msat) {
1205 let used_liquidity_msat = used_channel_liquidities
1206 .get(&(short_channel_id, $src_node_id < $dest_node_id))
1207 .map_or(0, |used_liquidity_msat| {
1208 available_value_contribution_msat = available_value_contribution_msat
1209 .saturating_sub(*used_liquidity_msat);
1210 *used_liquidity_msat
1213 // Verify the liquidity offered by this channel complies to the minimal contribution.
1214 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
1215 // Do not consider candidate hops that would exceed the maximum path length.
1216 let path_length_to_node = $next_hops_path_length + 1;
1217 let exceeds_max_path_length = path_length_to_node > MAX_PATH_LENGTH_ESTIMATE;
1219 // Do not consider candidates that exceed the maximum total cltv expiry limit.
1220 // In order to already account for some of the privacy enhancing random CLTV
1221 // expiry delta offset we add on top later, we subtract a rough estimate
1222 // (2*MEDIAN_HOP_CLTV_EXPIRY_DELTA) here.
1223 let max_total_cltv_expiry_delta = (payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta)
1224 .checked_sub(2*MEDIAN_HOP_CLTV_EXPIRY_DELTA)
1225 .unwrap_or(payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta);
1226 let hop_total_cltv_delta = ($next_hops_cltv_delta as u32)
1227 .saturating_add($candidate.cltv_expiry_delta());
1228 let exceeds_cltv_delta_limit = hop_total_cltv_delta > max_total_cltv_expiry_delta;
1230 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
1231 // Includes paying fees for the use of the following channels.
1232 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
1233 Some(result) => result,
1234 // Can't overflow due to how the values were computed right above.
1235 None => unreachable!(),
1237 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
1238 let over_path_minimum_msat = amount_to_transfer_over_msat >= $candidate.htlc_minimum_msat() &&
1239 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
1241 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
1242 let may_overpay_to_meet_path_minimum_msat =
1243 ((amount_to_transfer_over_msat < $candidate.htlc_minimum_msat() &&
1244 recommended_value_msat > $candidate.htlc_minimum_msat()) ||
1245 (amount_to_transfer_over_msat < $next_hops_path_htlc_minimum_msat &&
1246 recommended_value_msat > $next_hops_path_htlc_minimum_msat));
1248 let payment_failed_on_this_channel =
1249 payment_params.previously_failed_channels.contains(&short_channel_id);
1251 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
1252 // bother considering this channel. If retrying with recommended_value_msat may
1253 // allow us to hit the HTLC minimum limit, set htlc_minimum_limit so that we go
1254 // around again with a higher amount.
1255 if !contributes_sufficient_value || exceeds_max_path_length ||
1256 exceeds_cltv_delta_limit || payment_failed_on_this_channel {
1257 // Path isn't useful, ignore it and move on.
1258 } else if may_overpay_to_meet_path_minimum_msat {
1259 hit_minimum_limit = true;
1260 } else if over_path_minimum_msat {
1261 // Note that low contribution here (limited by available_liquidity_msat)
1262 // might violate htlc_minimum_msat on the hops which are next along the
1263 // payment path (upstream to the payee). To avoid that, we recompute
1264 // path fees knowing the final path contribution after constructing it.
1265 let path_htlc_minimum_msat = compute_fees($next_hops_path_htlc_minimum_msat, $candidate.fees())
1266 .and_then(|fee_msat| fee_msat.checked_add($next_hops_path_htlc_minimum_msat))
1267 .map(|fee_msat| cmp::max(fee_msat, $candidate.htlc_minimum_msat()))
1268 .unwrap_or_else(|| u64::max_value());
1269 let hm_entry = dist.entry($src_node_id);
1270 let old_entry = hm_entry.or_insert_with(|| {
1271 // If there was previously no known way to access the source node
1272 // (recall it goes payee-to-payer) of short_channel_id, first add a
1273 // semi-dummy record just to compute the fees to reach the source node.
1274 // This will affect our decision on selecting short_channel_id
1275 // as a way to reach the $dest_node_id.
1276 let mut fee_base_msat = 0;
1277 let mut fee_proportional_millionths = 0;
1278 if let Some(Some(fees)) = network_nodes.get(&$src_node_id).map(|node| node.lowest_inbound_channel_fees) {
1279 fee_base_msat = fees.base_msat;
1280 fee_proportional_millionths = fees.proportional_millionths;
1283 node_id: $dest_node_id.clone(),
1284 candidate: $candidate.clone(),
1286 src_lowest_inbound_fees: RoutingFees {
1287 base_msat: fee_base_msat,
1288 proportional_millionths: fee_proportional_millionths,
1290 next_hops_fee_msat: u64::max_value(),
1291 hop_use_fee_msat: u64::max_value(),
1292 total_fee_msat: u64::max_value(),
1293 path_htlc_minimum_msat,
1294 path_penalty_msat: u64::max_value(),
1295 was_processed: false,
1296 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
1297 value_contribution_msat,
1301 #[allow(unused_mut)] // We only use the mut in cfg(test)
1302 let mut should_process = !old_entry.was_processed;
1303 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
1305 // In test/fuzzing builds, we do extra checks to make sure the skipping
1306 // of already-seen nodes only happens in cases we expect (see below).
1307 if !should_process { should_process = true; }
1311 let mut hop_use_fee_msat = 0;
1312 let mut total_fee_msat = $next_hops_fee_msat;
1314 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
1315 // will have the same effective-fee
1316 if $src_node_id != our_node_id {
1317 match compute_fees(amount_to_transfer_over_msat, $candidate.fees()) {
1318 // max_value means we'll always fail
1319 // the old_entry.total_fee_msat > total_fee_msat check
1320 None => total_fee_msat = u64::max_value(),
1322 hop_use_fee_msat = fee_msat;
1323 total_fee_msat += hop_use_fee_msat;
1324 // When calculating the lowest inbound fees to a node, we
1325 // calculate fees here not based on the actual value we think
1326 // will flow over this channel, but on the minimum value that
1327 // we'll accept flowing over it. The minimum accepted value
1328 // is a constant through each path collection run, ensuring
1329 // consistent basis. Otherwise we may later find a
1330 // different path to the source node that is more expensive,
1331 // but which we consider to be cheaper because we are capacity
1332 // constrained and the relative fee becomes lower.
1333 match compute_fees(minimal_value_contribution_msat, old_entry.src_lowest_inbound_fees)
1334 .map(|a| a.checked_add(total_fee_msat)) {
1339 total_fee_msat = u64::max_value();
1346 let channel_usage = ChannelUsage {
1347 amount_msat: amount_to_transfer_over_msat,
1348 inflight_htlc_msat: used_liquidity_msat,
1351 let channel_penalty_msat = scorer.channel_penalty_msat(
1352 short_channel_id, &$src_node_id, &$dest_node_id, channel_usage
1354 let path_penalty_msat = $next_hops_path_penalty_msat
1355 .saturating_add(channel_penalty_msat);
1356 let new_graph_node = RouteGraphNode {
1357 node_id: $src_node_id,
1358 lowest_fee_to_peer_through_node: total_fee_msat,
1359 lowest_fee_to_node: $next_hops_fee_msat as u64 + hop_use_fee_msat,
1360 total_cltv_delta: hop_total_cltv_delta,
1361 value_contribution_msat,
1362 path_htlc_minimum_msat,
1364 path_length_to_node,
1367 // Update the way of reaching $src_node_id with the given short_channel_id (from $dest_node_id),
1368 // if this way is cheaper than the already known
1369 // (considering the cost to "reach" this channel from the route destination,
1370 // the cost of using this channel,
1371 // and the cost of routing to the source node of this channel).
1372 // Also, consider that htlc_minimum_msat_difference, because we might end up
1373 // paying it. Consider the following exploit:
1374 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
1375 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
1376 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
1377 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
1379 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
1380 // but it may require additional tracking - we don't want to double-count
1381 // the fees included in $next_hops_path_htlc_minimum_msat, but also
1382 // can't use something that may decrease on future hops.
1383 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat)
1384 .saturating_add(old_entry.path_penalty_msat);
1385 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat)
1386 .saturating_add(path_penalty_msat);
1388 if !old_entry.was_processed && new_cost < old_cost {
1389 targets.push(new_graph_node);
1390 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
1391 old_entry.hop_use_fee_msat = hop_use_fee_msat;
1392 old_entry.total_fee_msat = total_fee_msat;
1393 old_entry.node_id = $dest_node_id.clone();
1394 old_entry.candidate = $candidate.clone();
1395 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
1396 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
1397 old_entry.path_penalty_msat = path_penalty_msat;
1398 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
1400 old_entry.value_contribution_msat = value_contribution_msat;
1402 did_add_update_path_to_src_node = true;
1403 } else if old_entry.was_processed && new_cost < old_cost {
1404 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
1406 // If we're skipping processing a node which was previously
1407 // processed even though we found another path to it with a
1408 // cheaper fee, check that it was because the second path we
1409 // found (which we are processing now) has a lower value
1410 // contribution due to an HTLC minimum limit.
1412 // e.g. take a graph with two paths from node 1 to node 2, one
1413 // through channel A, and one through channel B. Channel A and
1414 // B are both in the to-process heap, with their scores set by
1415 // a higher htlc_minimum than fee.
1416 // Channel A is processed first, and the channels onwards from
1417 // node 1 are added to the to-process heap. Thereafter, we pop
1418 // Channel B off of the heap, note that it has a much more
1419 // restrictive htlc_maximum_msat, and recalculate the fees for
1420 // all of node 1's channels using the new, reduced, amount.
1422 // This would be bogus - we'd be selecting a higher-fee path
1423 // with a lower htlc_maximum_msat instead of the one we'd
1424 // already decided to use.
1425 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
1427 value_contribution_msat + path_penalty_msat <
1428 old_entry.value_contribution_msat + old_entry.path_penalty_msat
1436 did_add_update_path_to_src_node
1440 let default_node_features = default_node_features();
1442 // Find ways (channels with destination) to reach a given node and store them
1443 // in the corresponding data structures (routing graph etc).
1444 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
1445 // meaning how much will be paid in fees after this node (to the best of our knowledge).
1446 // This data can later be helpful to optimize routing (pay lower fees).
1447 macro_rules! add_entries_to_cheapest_to_target_node {
1448 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr, $next_hops_value_contribution: expr,
1449 $next_hops_path_htlc_minimum_msat: expr, $next_hops_path_penalty_msat: expr,
1450 $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => {
1451 let skip_node = if let Some(elem) = dist.get_mut(&$node_id) {
1452 let was_processed = elem.was_processed;
1453 elem.was_processed = true;
1456 // Entries are added to dist in add_entry!() when there is a channel from a node.
1457 // Because there are no channels from payee, it will not have a dist entry at this point.
1458 // If we're processing any other node, it is always be the result of a channel from it.
1459 assert_eq!($node_id, payee_node_id);
1464 if let Some(first_channels) = first_hop_targets.get(&$node_id) {
1465 for details in first_channels {
1466 let candidate = CandidateRouteHop::FirstHop { details };
1467 add_entry!(candidate, our_node_id, $node_id, $fee_to_target_msat,
1468 $next_hops_value_contribution,
1469 $next_hops_path_htlc_minimum_msat, $next_hops_path_penalty_msat,
1470 $next_hops_cltv_delta, $next_hops_path_length);
1474 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
1477 &default_node_features
1480 if !features.requires_unknown_bits() {
1481 for chan_id in $node.channels.iter() {
1482 let chan = network_channels.get(chan_id).unwrap();
1483 if !chan.features.requires_unknown_bits() {
1484 if let Some((directed_channel, source)) = chan.as_directed_to(&$node_id) {
1485 if first_hops.is_none() || *source != our_node_id {
1486 if directed_channel.direction().enabled {
1487 let candidate = CandidateRouteHop::PublicHop {
1488 info: directed_channel,
1489 short_channel_id: *chan_id,
1491 add_entry!(candidate, *source, $node_id,
1492 $fee_to_target_msat,
1493 $next_hops_value_contribution,
1494 $next_hops_path_htlc_minimum_msat,
1495 $next_hops_path_penalty_msat,
1496 $next_hops_cltv_delta, $next_hops_path_length);
1507 let mut payment_paths = Vec::<PaymentPath>::new();
1509 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
1510 'paths_collection: loop {
1511 // For every new path, start from scratch, except for used_channel_liquidities, which
1512 // helps to avoid reusing previously selected paths in future iterations.
1515 hit_minimum_limit = false;
1517 // If first hop is a private channel and the only way to reach the payee, this is the only
1518 // place where it could be added.
1519 if let Some(first_channels) = first_hop_targets.get(&payee_node_id) {
1520 for details in first_channels {
1521 let candidate = CandidateRouteHop::FirstHop { details };
1522 let added = add_entry!(candidate, our_node_id, payee_node_id, 0, path_value_msat,
1524 log_trace!(logger, "{} direct route to payee via SCID {}",
1525 if added { "Added" } else { "Skipped" }, candidate.short_channel_id());
1529 // Add the payee as a target, so that the payee-to-payer
1530 // search algorithm knows what to start with.
1531 match network_nodes.get(&payee_node_id) {
1532 // The payee is not in our network graph, so nothing to add here.
1533 // There is still a chance of reaching them via last_hops though,
1534 // so don't yet fail the payment here.
1535 // If not, targets.pop() will not even let us enter the loop in step 2.
1538 add_entries_to_cheapest_to_target_node!(node, payee_node_id, 0, path_value_msat, 0, 0u64, 0, 0);
1543 // If a caller provided us with last hops, add them to routing targets. Since this happens
1544 // earlier than general path finding, they will be somewhat prioritized, although currently
1545 // it matters only if the fees are exactly the same.
1546 for route in payment_params.route_hints.iter().filter(|route| !route.0.is_empty()) {
1547 let first_hop_in_route = &(route.0)[0];
1548 let have_hop_src_in_graph =
1549 // Only add the hops in this route to our candidate set if either
1550 // we have a direct channel to the first hop or the first hop is
1551 // in the regular network graph.
1552 first_hop_targets.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some() ||
1553 network_nodes.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some();
1554 if have_hop_src_in_graph {
1555 // We start building the path from reverse, i.e., from payee
1556 // to the first RouteHintHop in the path.
1557 let hop_iter = route.0.iter().rev();
1558 let prev_hop_iter = core::iter::once(&payment_params.payee_pubkey).chain(
1559 route.0.iter().skip(1).rev().map(|hop| &hop.src_node_id));
1560 let mut hop_used = true;
1561 let mut aggregate_next_hops_fee_msat: u64 = 0;
1562 let mut aggregate_next_hops_path_htlc_minimum_msat: u64 = 0;
1563 let mut aggregate_next_hops_path_penalty_msat: u64 = 0;
1564 let mut aggregate_next_hops_cltv_delta: u32 = 0;
1565 let mut aggregate_next_hops_path_length: u8 = 0;
1567 for (idx, (hop, prev_hop_id)) in hop_iter.zip(prev_hop_iter).enumerate() {
1568 let source = NodeId::from_pubkey(&hop.src_node_id);
1569 let target = NodeId::from_pubkey(&prev_hop_id);
1570 let candidate = network_channels
1571 .get(&hop.short_channel_id)
1572 .and_then(|channel| channel.as_directed_to(&target))
1573 .map(|(info, _)| CandidateRouteHop::PublicHop {
1575 short_channel_id: hop.short_channel_id,
1577 .unwrap_or_else(|| CandidateRouteHop::PrivateHop { hint: hop });
1579 if !add_entry!(candidate, source, target, aggregate_next_hops_fee_msat,
1580 path_value_msat, aggregate_next_hops_path_htlc_minimum_msat,
1581 aggregate_next_hops_path_penalty_msat,
1582 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length) {
1583 // If this hop was not used then there is no use checking the preceding
1584 // hops in the RouteHint. We can break by just searching for a direct
1585 // channel between last checked hop and first_hop_targets.
1589 let used_liquidity_msat = used_channel_liquidities
1590 .get(&(hop.short_channel_id, source < target)).copied().unwrap_or(0);
1591 let channel_usage = ChannelUsage {
1592 amount_msat: final_value_msat + aggregate_next_hops_fee_msat,
1593 inflight_htlc_msat: used_liquidity_msat,
1594 effective_capacity: candidate.effective_capacity(),
1596 let channel_penalty_msat = scorer.channel_penalty_msat(
1597 hop.short_channel_id, &source, &target, channel_usage
1599 aggregate_next_hops_path_penalty_msat = aggregate_next_hops_path_penalty_msat
1600 .saturating_add(channel_penalty_msat);
1602 aggregate_next_hops_cltv_delta = aggregate_next_hops_cltv_delta
1603 .saturating_add(hop.cltv_expiry_delta as u32);
1605 aggregate_next_hops_path_length = aggregate_next_hops_path_length
1608 // Searching for a direct channel between last checked hop and first_hop_targets
1609 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&prev_hop_id)) {
1610 for details in first_channels {
1611 let candidate = CandidateRouteHop::FirstHop { details };
1612 add_entry!(candidate, our_node_id, NodeId::from_pubkey(&prev_hop_id),
1613 aggregate_next_hops_fee_msat, path_value_msat,
1614 aggregate_next_hops_path_htlc_minimum_msat,
1615 aggregate_next_hops_path_penalty_msat, aggregate_next_hops_cltv_delta,
1616 aggregate_next_hops_path_length);
1624 // In the next values of the iterator, the aggregate fees already reflects
1625 // the sum of value sent from payer (final_value_msat) and routing fees
1626 // for the last node in the RouteHint. We need to just add the fees to
1627 // route through the current node so that the preceding node (next iteration)
1629 let hops_fee = compute_fees(aggregate_next_hops_fee_msat + final_value_msat, hop.fees)
1630 .map_or(None, |inc| inc.checked_add(aggregate_next_hops_fee_msat));
1631 aggregate_next_hops_fee_msat = if let Some(val) = hops_fee { val } else { break; };
1633 let hop_htlc_minimum_msat = candidate.htlc_minimum_msat();
1634 let hop_htlc_minimum_msat_inc = if let Some(val) = compute_fees(aggregate_next_hops_path_htlc_minimum_msat, hop.fees) { val } else { break; };
1635 let hops_path_htlc_minimum = aggregate_next_hops_path_htlc_minimum_msat
1636 .checked_add(hop_htlc_minimum_msat_inc);
1637 aggregate_next_hops_path_htlc_minimum_msat = if let Some(val) = hops_path_htlc_minimum { cmp::max(hop_htlc_minimum_msat, val) } else { break; };
1639 if idx == route.0.len() - 1 {
1640 // The last hop in this iterator is the first hop in
1641 // overall RouteHint.
1642 // If this hop connects to a node with which we have a direct channel,
1643 // ignore the network graph and, if the last hop was added, add our
1644 // direct channel to the candidate set.
1646 // Note that we *must* check if the last hop was added as `add_entry`
1647 // always assumes that the third argument is a node to which we have a
1649 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&hop.src_node_id)) {
1650 for details in first_channels {
1651 let candidate = CandidateRouteHop::FirstHop { details };
1652 add_entry!(candidate, our_node_id,
1653 NodeId::from_pubkey(&hop.src_node_id),
1654 aggregate_next_hops_fee_msat, path_value_msat,
1655 aggregate_next_hops_path_htlc_minimum_msat,
1656 aggregate_next_hops_path_penalty_msat,
1657 aggregate_next_hops_cltv_delta,
1658 aggregate_next_hops_path_length);
1666 log_trace!(logger, "Starting main path collection loop with {} nodes pre-filled from first/last hops.", targets.len());
1668 // At this point, targets are filled with the data from first and
1669 // last hops communicated by the caller, and the payment receiver.
1670 let mut found_new_path = false;
1673 // If this loop terminates due the exhaustion of targets, two situations are possible:
1674 // - not enough outgoing liquidity:
1675 // 0 < already_collected_value_msat < final_value_msat
1676 // - enough outgoing liquidity:
1677 // final_value_msat <= already_collected_value_msat < recommended_value_msat
1678 // Both these cases (and other cases except reaching recommended_value_msat) mean that
1679 // paths_collection will be stopped because found_new_path==false.
1680 // This is not necessarily a routing failure.
1681 'path_construction: while let Some(RouteGraphNode { node_id, lowest_fee_to_node, total_cltv_delta, mut value_contribution_msat, path_htlc_minimum_msat, path_penalty_msat, path_length_to_node, .. }) = targets.pop() {
1683 // Since we're going payee-to-payer, hitting our node as a target means we should stop
1684 // traversing the graph and arrange the path out of what we found.
1685 if node_id == our_node_id {
1686 let mut new_entry = dist.remove(&our_node_id).unwrap();
1687 let mut ordered_hops: Vec<(PathBuildingHop, NodeFeatures)> = vec!((new_entry.clone(), default_node_features.clone()));
1690 let mut features_set = false;
1691 if let Some(first_channels) = first_hop_targets.get(&ordered_hops.last().unwrap().0.node_id) {
1692 for details in first_channels {
1693 if details.get_outbound_payment_scid().unwrap() == ordered_hops.last().unwrap().0.candidate.short_channel_id() {
1694 ordered_hops.last_mut().unwrap().1 = details.counterparty.features.to_context();
1695 features_set = true;
1701 if let Some(node) = network_nodes.get(&ordered_hops.last().unwrap().0.node_id) {
1702 if let Some(node_info) = node.announcement_info.as_ref() {
1703 ordered_hops.last_mut().unwrap().1 = node_info.features.clone();
1705 ordered_hops.last_mut().unwrap().1 = default_node_features.clone();
1708 // We can fill in features for everything except hops which were
1709 // provided via the invoice we're paying. We could guess based on the
1710 // recipient's features but for now we simply avoid guessing at all.
1714 // Means we succesfully traversed from the payer to the payee, now
1715 // save this path for the payment route. Also, update the liquidity
1716 // remaining on the used hops, so that we take them into account
1717 // while looking for more paths.
1718 if ordered_hops.last().unwrap().0.node_id == payee_node_id {
1722 new_entry = match dist.remove(&ordered_hops.last().unwrap().0.node_id) {
1723 Some(payment_hop) => payment_hop,
1724 // We can't arrive at None because, if we ever add an entry to targets,
1725 // we also fill in the entry in dist (see add_entry!).
1726 None => unreachable!(),
1728 // We "propagate" the fees one hop backward (topologically) here,
1729 // so that fees paid for a HTLC forwarding on the current channel are
1730 // associated with the previous channel (where they will be subtracted).
1731 ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
1732 ordered_hops.push((new_entry.clone(), default_node_features.clone()));
1734 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
1735 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
1737 log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: \n {:#?}",
1738 ordered_hops.len(), value_contribution_msat, ordered_hops.iter().map(|h| &(h.0)).collect::<Vec<&PathBuildingHop>>());
1740 let mut payment_path = PaymentPath {hops: ordered_hops};
1742 // We could have possibly constructed a slightly inconsistent path: since we reduce
1743 // value being transferred along the way, we could have violated htlc_minimum_msat
1744 // on some channels we already passed (assuming dest->source direction). Here, we
1745 // recompute the fees again, so that if that's the case, we match the currently
1746 // underpaid htlc_minimum_msat with fees.
1747 debug_assert_eq!(payment_path.get_value_msat(), value_contribution_msat);
1748 value_contribution_msat = cmp::min(value_contribution_msat, final_value_msat);
1749 payment_path.update_value_and_recompute_fees(value_contribution_msat);
1751 // Since a path allows to transfer as much value as
1752 // the smallest channel it has ("bottleneck"), we should recompute
1753 // the fees so sender HTLC don't overpay fees when traversing
1754 // larger channels than the bottleneck. This may happen because
1755 // when we were selecting those channels we were not aware how much value
1756 // this path will transfer, and the relative fee for them
1757 // might have been computed considering a larger value.
1758 // Remember that we used these channels so that we don't rely
1759 // on the same liquidity in future paths.
1760 let mut prevented_redundant_path_selection = false;
1761 let prev_hop_iter = core::iter::once(&our_node_id)
1762 .chain(payment_path.hops.iter().map(|(hop, _)| &hop.node_id));
1763 for (prev_hop, (hop, _)) in prev_hop_iter.zip(payment_path.hops.iter()) {
1764 let spent_on_hop_msat = value_contribution_msat + hop.next_hops_fee_msat;
1765 let used_liquidity_msat = used_channel_liquidities
1766 .entry((hop.candidate.short_channel_id(), *prev_hop < hop.node_id))
1767 .and_modify(|used_liquidity_msat| *used_liquidity_msat += spent_on_hop_msat)
1768 .or_insert(spent_on_hop_msat);
1769 let hop_capacity = hop.candidate.effective_capacity();
1770 let hop_max_msat = max_htlc_from_capacity(hop_capacity, channel_saturation_pow_half);
1771 if *used_liquidity_msat == hop_max_msat {
1772 // If this path used all of this channel's available liquidity, we know
1773 // this path will not be selected again in the next loop iteration.
1774 prevented_redundant_path_selection = true;
1776 debug_assert!(*used_liquidity_msat <= hop_max_msat);
1778 if !prevented_redundant_path_selection {
1779 // If we weren't capped by hitting a liquidity limit on a channel in the path,
1780 // we'll probably end up picking the same path again on the next iteration.
1781 // Decrease the available liquidity of a hop in the middle of the path.
1782 let victim_scid = payment_path.hops[(payment_path.hops.len()) / 2].0.candidate.short_channel_id();
1783 let exhausted = u64::max_value();
1784 log_trace!(logger, "Disabling channel {} for future path building iterations to avoid duplicates.", victim_scid);
1785 *used_channel_liquidities.entry((victim_scid, false)).or_default() = exhausted;
1786 *used_channel_liquidities.entry((victim_scid, true)).or_default() = exhausted;
1789 // Track the total amount all our collected paths allow to send so that we know
1790 // when to stop looking for more paths
1791 already_collected_value_msat += value_contribution_msat;
1793 payment_paths.push(payment_path);
1794 found_new_path = true;
1795 break 'path_construction;
1798 // If we found a path back to the payee, we shouldn't try to process it again. This is
1799 // the equivalent of the `elem.was_processed` check in
1800 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
1801 if node_id == payee_node_id { continue 'path_construction; }
1803 // Otherwise, since the current target node is not us,
1804 // keep "unrolling" the payment graph from payee to payer by
1805 // finding a way to reach the current target from the payer side.
1806 match network_nodes.get(&node_id) {
1809 add_entries_to_cheapest_to_target_node!(node, node_id, lowest_fee_to_node,
1810 value_contribution_msat, path_htlc_minimum_msat, path_penalty_msat,
1811 total_cltv_delta, path_length_to_node);
1817 if !found_new_path && channel_saturation_pow_half != 0 {
1818 channel_saturation_pow_half = 0;
1819 continue 'paths_collection;
1821 // If we don't support MPP, no use trying to gather more value ever.
1822 break 'paths_collection;
1826 // Stop either when the recommended value is reached or if no new path was found in this
1828 // In the latter case, making another path finding attempt won't help,
1829 // because we deterministically terminated the search due to low liquidity.
1830 if !found_new_path && channel_saturation_pow_half != 0 {
1831 channel_saturation_pow_half = 0;
1832 } else if already_collected_value_msat >= recommended_value_msat || !found_new_path {
1833 log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
1834 already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
1835 break 'paths_collection;
1836 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
1837 // Further, if this was our first walk of the graph, and we weren't limited by an
1838 // htlc_minimum_msat, return immediately because this path should suffice. If we were
1839 // limited by an htlc_minimum_msat value, find another path with a higher value,
1840 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
1841 // still keeping a lower total fee than this path.
1842 if !hit_minimum_limit {
1843 log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
1844 break 'paths_collection;
1846 log_trace!(logger, "Collected our payment amount on the first pass, but running again to collect extra paths with a potentially higher limit.");
1847 path_value_msat = recommended_value_msat;
1852 if payment_paths.len() == 0 {
1853 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1856 if already_collected_value_msat < final_value_msat {
1857 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1861 let mut selected_route = payment_paths;
1863 debug_assert_eq!(selected_route.iter().map(|p| p.get_value_msat()).sum::<u64>(), already_collected_value_msat);
1864 let mut overpaid_value_msat = already_collected_value_msat - final_value_msat;
1866 // First, sort by the cost-per-value of the path, dropping the paths that cost the most for
1867 // the value they contribute towards the payment amount.
1868 // We sort in descending order as we will remove from the front in `retain`, next.
1869 selected_route.sort_unstable_by(|a, b|
1870 (((b.get_cost_msat() as u128) << 64) / (b.get_value_msat() as u128))
1871 .cmp(&(((a.get_cost_msat() as u128) << 64) / (a.get_value_msat() as u128)))
1874 // We should make sure that at least 1 path left.
1875 let mut paths_left = selected_route.len();
1876 selected_route.retain(|path| {
1877 if paths_left == 1 {
1880 let path_value_msat = path.get_value_msat();
1881 if path_value_msat <= overpaid_value_msat {
1882 overpaid_value_msat -= path_value_msat;
1888 debug_assert!(selected_route.len() > 0);
1890 if overpaid_value_msat != 0 {
1892 // Now, subtract the remaining overpaid value from the most-expensive path.
1893 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1894 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1895 selected_route.sort_unstable_by(|a, b| {
1896 let a_f = a.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
1897 let b_f = b.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
1898 a_f.cmp(&b_f).then_with(|| b.get_cost_msat().cmp(&a.get_cost_msat()))
1900 let expensive_payment_path = selected_route.first_mut().unwrap();
1902 // We already dropped all the paths with value below `overpaid_value_msat` above, thus this
1903 // can't go negative.
1904 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
1905 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
1909 // Sort by the path itself and combine redundant paths.
1910 // Note that we sort by SCIDs alone as its simpler but when combining we have to ensure we
1911 // compare both SCIDs and NodeIds as individual nodes may use random aliases causing collisions
1913 selected_route.sort_unstable_by_key(|path| {
1914 let mut key = [0u64; MAX_PATH_LENGTH_ESTIMATE as usize];
1915 debug_assert!(path.hops.len() <= key.len());
1916 for (scid, key) in path.hops.iter().map(|h| h.0.candidate.short_channel_id()).zip(key.iter_mut()) {
1921 for idx in 0..(selected_route.len() - 1) {
1922 if idx + 1 >= selected_route.len() { break; }
1923 if iter_equal(selected_route[idx ].hops.iter().map(|h| (h.0.candidate.short_channel_id(), h.0.node_id)),
1924 selected_route[idx + 1].hops.iter().map(|h| (h.0.candidate.short_channel_id(), h.0.node_id))) {
1925 let new_value = selected_route[idx].get_value_msat() + selected_route[idx + 1].get_value_msat();
1926 selected_route[idx].update_value_and_recompute_fees(new_value);
1927 selected_route.remove(idx + 1);
1931 let mut selected_paths = Vec::<Vec<Result<RouteHop, LightningError>>>::new();
1932 for payment_path in selected_route {
1933 let mut path = payment_path.hops.iter().map(|(payment_hop, node_features)| {
1935 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)})?,
1936 node_features: node_features.clone(),
1937 short_channel_id: payment_hop.candidate.short_channel_id(),
1938 channel_features: payment_hop.candidate.features(),
1939 fee_msat: payment_hop.fee_msat,
1940 cltv_expiry_delta: payment_hop.candidate.cltv_expiry_delta(),
1942 }).collect::<Vec<_>>();
1943 // Propagate the cltv_expiry_delta one hop backwards since the delta from the current hop is
1944 // applicable for the previous hop.
1945 path.iter_mut().rev().fold(final_cltv_expiry_delta, |prev_cltv_expiry_delta, hop| {
1946 core::mem::replace(&mut hop.as_mut().unwrap().cltv_expiry_delta, prev_cltv_expiry_delta)
1948 selected_paths.push(path);
1950 // Make sure we would never create a route with more paths than we allow.
1951 debug_assert!(selected_paths.len() <= payment_params.max_path_count.into());
1953 if let Some(features) = &payment_params.features {
1954 for path in selected_paths.iter_mut() {
1955 if let Ok(route_hop) = path.last_mut().unwrap() {
1956 route_hop.node_features = features.to_context();
1962 paths: selected_paths.into_iter().map(|path| path.into_iter().collect()).collect::<Result<Vec<_>, _>>()?,
1963 payment_params: Some(payment_params.clone()),
1965 log_info!(logger, "Got route to {}: {}", payment_params.payee_pubkey, log_route!(route));
1969 // When an adversarial intermediary node observes a payment, it may be able to infer its
1970 // destination, if the remaining CLTV expiry delta exactly matches a feasible path in the network
1971 // graph. In order to improve privacy, this method obfuscates the CLTV expiry deltas along the
1972 // payment path by adding a randomized 'shadow route' offset to the final hop.
1973 fn add_random_cltv_offset(route: &mut Route, payment_params: &PaymentParameters,
1974 network_graph: &ReadOnlyNetworkGraph, random_seed_bytes: &[u8; 32]
1976 let network_channels = network_graph.channels();
1977 let network_nodes = network_graph.nodes();
1979 for path in route.paths.iter_mut() {
1980 let mut shadow_ctlv_expiry_delta_offset: u32 = 0;
1982 // Remember the last three nodes of the random walk and avoid looping back on them.
1983 // Init with the last three nodes from the actual path, if possible.
1984 let mut nodes_to_avoid: [NodeId; 3] = [NodeId::from_pubkey(&path.last().unwrap().pubkey),
1985 NodeId::from_pubkey(&path.get(path.len().saturating_sub(2)).unwrap().pubkey),
1986 NodeId::from_pubkey(&path.get(path.len().saturating_sub(3)).unwrap().pubkey)];
1988 // Choose the last publicly known node as the starting point for the random walk.
1989 let mut cur_hop: Option<NodeId> = None;
1990 let mut path_nonce = [0u8; 12];
1991 if let Some(starting_hop) = path.iter().rev()
1992 .find(|h| network_nodes.contains_key(&NodeId::from_pubkey(&h.pubkey))) {
1993 cur_hop = Some(NodeId::from_pubkey(&starting_hop.pubkey));
1994 path_nonce.copy_from_slice(&cur_hop.unwrap().as_slice()[..12]);
1997 // Init PRNG with the path-dependant nonce, which is static for private paths.
1998 let mut prng = ChaCha20::new(random_seed_bytes, &path_nonce);
1999 let mut random_path_bytes = [0u8; ::core::mem::size_of::<usize>()];
2001 // Pick a random path length in [1 .. 3]
2002 prng.process_in_place(&mut random_path_bytes);
2003 let random_walk_length = usize::from_be_bytes(random_path_bytes).wrapping_rem(3).wrapping_add(1);
2005 for random_hop in 0..random_walk_length {
2006 // If we don't find a suitable offset in the public network graph, we default to
2007 // MEDIAN_HOP_CLTV_EXPIRY_DELTA.
2008 let mut random_hop_offset = MEDIAN_HOP_CLTV_EXPIRY_DELTA;
2010 if let Some(cur_node_id) = cur_hop {
2011 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
2012 // Randomly choose the next unvisited hop.
2013 prng.process_in_place(&mut random_path_bytes);
2014 if let Some(random_channel) = usize::from_be_bytes(random_path_bytes)
2015 .checked_rem(cur_node.channels.len())
2016 .and_then(|index| cur_node.channels.get(index))
2017 .and_then(|id| network_channels.get(id)) {
2018 random_channel.as_directed_from(&cur_node_id).map(|(dir_info, next_id)| {
2019 if !nodes_to_avoid.iter().any(|x| x == next_id) {
2020 nodes_to_avoid[random_hop] = *next_id;
2021 random_hop_offset = dir_info.direction().cltv_expiry_delta.into();
2022 cur_hop = Some(*next_id);
2029 shadow_ctlv_expiry_delta_offset = shadow_ctlv_expiry_delta_offset
2030 .checked_add(random_hop_offset)
2031 .unwrap_or(shadow_ctlv_expiry_delta_offset);
2034 // Limit the total offset to reduce the worst-case locked liquidity timevalue
2035 const MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET: u32 = 3*144;
2036 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET);
2038 // Limit the offset so we never exceed the max_total_cltv_expiry_delta. To improve plausibility,
2039 // we choose the limit to be the largest possible multiple of MEDIAN_HOP_CLTV_EXPIRY_DELTA.
2040 let path_total_cltv_expiry_delta: u32 = path.iter().map(|h| h.cltv_expiry_delta).sum();
2041 let mut max_path_offset = payment_params.max_total_cltv_expiry_delta - path_total_cltv_expiry_delta;
2042 max_path_offset = cmp::max(
2043 max_path_offset - (max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA),
2044 max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA);
2045 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, max_path_offset);
2047 // Add 'shadow' CLTV offset to the final hop
2048 if let Some(last_hop) = path.last_mut() {
2049 last_hop.cltv_expiry_delta = last_hop.cltv_expiry_delta
2050 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(last_hop.cltv_expiry_delta);
2055 /// Construct a route from us (payer) to the target node (payee) via the given hops (which should
2056 /// exclude the payer, but include the payee). This may be useful, e.g., for probing the chosen path.
2058 /// Re-uses logic from `find_route`, so the restrictions described there also apply here.
2059 pub fn build_route_from_hops<L: Deref, GL: Deref>(
2060 our_node_pubkey: &PublicKey, hops: &[PublicKey], route_params: &RouteParameters,
2061 network_graph: &NetworkGraph<GL>, logger: L, random_seed_bytes: &[u8; 32]
2062 ) -> Result<Route, LightningError>
2063 where L::Target: Logger, GL::Target: Logger {
2064 let graph_lock = network_graph.read_only();
2065 let mut route = build_route_from_hops_internal(
2066 our_node_pubkey, hops, &route_params.payment_params, &graph_lock,
2067 route_params.final_value_msat, route_params.final_cltv_expiry_delta, logger, random_seed_bytes)?;
2068 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
2072 fn build_route_from_hops_internal<L: Deref>(
2073 our_node_pubkey: &PublicKey, hops: &[PublicKey], payment_params: &PaymentParameters,
2074 network_graph: &ReadOnlyNetworkGraph, final_value_msat: u64, final_cltv_expiry_delta: u32,
2075 logger: L, random_seed_bytes: &[u8; 32]
2076 ) -> Result<Route, LightningError> where L::Target: Logger {
2079 our_node_id: NodeId,
2080 hop_ids: [Option<NodeId>; MAX_PATH_LENGTH_ESTIMATE as usize],
2083 impl Score for HopScorer {
2084 fn channel_penalty_msat(&self, _short_channel_id: u64, source: &NodeId, target: &NodeId,
2085 _usage: ChannelUsage) -> u64
2087 let mut cur_id = self.our_node_id;
2088 for i in 0..self.hop_ids.len() {
2089 if let Some(next_id) = self.hop_ids[i] {
2090 if cur_id == *source && next_id == *target {
2101 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
2103 fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
2105 fn probe_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
2107 fn probe_successful(&mut self, _path: &[&RouteHop]) {}
2110 impl<'a> Writeable for HopScorer {
2112 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), io::Error> {
2117 if hops.len() > MAX_PATH_LENGTH_ESTIMATE.into() {
2118 return Err(LightningError{err: "Cannot build a route exceeding the maximum path length.".to_owned(), action: ErrorAction::IgnoreError});
2121 let our_node_id = NodeId::from_pubkey(our_node_pubkey);
2122 let mut hop_ids = [None; MAX_PATH_LENGTH_ESTIMATE as usize];
2123 for i in 0..hops.len() {
2124 hop_ids[i] = Some(NodeId::from_pubkey(&hops[i]));
2127 let scorer = HopScorer { our_node_id, hop_ids };
2129 get_route(our_node_pubkey, payment_params, network_graph, None, final_value_msat,
2130 final_cltv_expiry_delta, logger, &scorer, random_seed_bytes)
2135 use crate::routing::gossip::{NetworkGraph, P2PGossipSync, NodeId, EffectiveCapacity};
2136 use crate::routing::router::{get_route, build_route_from_hops_internal, add_random_cltv_offset, default_node_features,
2137 PaymentParameters, Route, RouteHint, RouteHintHop, RouteHop, RoutingFees,
2138 DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA, MAX_PATH_LENGTH_ESTIMATE};
2139 use crate::routing::scoring::{ChannelUsage, Score, ProbabilisticScorer, ProbabilisticScoringParameters};
2140 use crate::routing::test_utils::{add_channel, add_or_update_node, build_graph, build_line_graph, id_to_feature_flags, get_nodes, update_channel};
2141 use crate::chain::transaction::OutPoint;
2142 use crate::chain::keysinterface::EntropySource;
2143 use crate::ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
2144 use crate::ln::msgs::{ErrorAction, LightningError, UnsignedChannelUpdate, MAX_VALUE_MSAT};
2145 use crate::ln::channelmanager;
2146 use crate::util::config::UserConfig;
2147 use crate::util::test_utils as ln_test_utils;
2148 use crate::util::chacha20::ChaCha20;
2150 use crate::util::ser::{Writeable, Writer};
2152 use bitcoin::hashes::Hash;
2153 use bitcoin::network::constants::Network;
2154 use bitcoin::blockdata::constants::genesis_block;
2155 use bitcoin::blockdata::script::Builder;
2156 use bitcoin::blockdata::opcodes;
2157 use bitcoin::blockdata::transaction::TxOut;
2161 use bitcoin::secp256k1::{PublicKey,SecretKey};
2162 use bitcoin::secp256k1::Secp256k1;
2164 use crate::prelude::*;
2165 use crate::sync::Arc;
2167 use core::convert::TryInto;
2169 fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
2170 features: InitFeatures, outbound_capacity_msat: u64) -> channelmanager::ChannelDetails {
2171 channelmanager::ChannelDetails {
2172 channel_id: [0; 32],
2173 counterparty: channelmanager::ChannelCounterparty {
2176 unspendable_punishment_reserve: 0,
2177 forwarding_info: None,
2178 outbound_htlc_minimum_msat: None,
2179 outbound_htlc_maximum_msat: None,
2181 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
2184 outbound_scid_alias: None,
2185 inbound_scid_alias: None,
2186 channel_value_satoshis: 0,
2189 outbound_capacity_msat,
2190 next_outbound_htlc_limit_msat: outbound_capacity_msat,
2191 inbound_capacity_msat: 42,
2192 unspendable_punishment_reserve: None,
2193 confirmations_required: None,
2194 confirmations: None,
2195 force_close_spend_delay: None,
2196 is_outbound: true, is_channel_ready: true,
2197 is_usable: true, is_public: true,
2198 inbound_htlc_minimum_msat: None,
2199 inbound_htlc_maximum_msat: None,
2205 fn simple_route_test() {
2206 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2207 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2208 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2209 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2210 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2211 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2213 // Simple route to 2 via 1
2215 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) {
2216 assert_eq!(err, "Cannot send a payment of 0 msat");
2217 } else { panic!(); }
2219 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2220 assert_eq!(route.paths[0].len(), 2);
2222 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2223 assert_eq!(route.paths[0][0].short_channel_id, 2);
2224 assert_eq!(route.paths[0][0].fee_msat, 100);
2225 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2226 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2227 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2229 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2230 assert_eq!(route.paths[0][1].short_channel_id, 4);
2231 assert_eq!(route.paths[0][1].fee_msat, 100);
2232 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2233 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2234 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2238 fn invalid_first_hop_test() {
2239 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2240 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2241 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2242 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2243 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2244 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2246 // Simple route to 2 via 1
2248 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
2250 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) =
2251 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) {
2252 assert_eq!(err, "First hop cannot have our_node_pubkey as a destination.");
2253 } else { panic!(); }
2255 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2256 assert_eq!(route.paths[0].len(), 2);
2260 fn htlc_minimum_test() {
2261 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2262 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2263 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2264 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2265 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2266 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2268 // Simple route to 2 via 1
2270 // Disable other paths
2271 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2272 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2273 short_channel_id: 12,
2275 flags: 2, // to disable
2276 cltv_expiry_delta: 0,
2277 htlc_minimum_msat: 0,
2278 htlc_maximum_msat: MAX_VALUE_MSAT,
2280 fee_proportional_millionths: 0,
2281 excess_data: Vec::new()
2283 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2284 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2285 short_channel_id: 3,
2287 flags: 2, // to disable
2288 cltv_expiry_delta: 0,
2289 htlc_minimum_msat: 0,
2290 htlc_maximum_msat: MAX_VALUE_MSAT,
2292 fee_proportional_millionths: 0,
2293 excess_data: Vec::new()
2295 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2296 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2297 short_channel_id: 13,
2299 flags: 2, // to disable
2300 cltv_expiry_delta: 0,
2301 htlc_minimum_msat: 0,
2302 htlc_maximum_msat: MAX_VALUE_MSAT,
2304 fee_proportional_millionths: 0,
2305 excess_data: Vec::new()
2307 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2308 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2309 short_channel_id: 6,
2311 flags: 2, // to disable
2312 cltv_expiry_delta: 0,
2313 htlc_minimum_msat: 0,
2314 htlc_maximum_msat: MAX_VALUE_MSAT,
2316 fee_proportional_millionths: 0,
2317 excess_data: Vec::new()
2319 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2320 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2321 short_channel_id: 7,
2323 flags: 2, // to disable
2324 cltv_expiry_delta: 0,
2325 htlc_minimum_msat: 0,
2326 htlc_maximum_msat: MAX_VALUE_MSAT,
2328 fee_proportional_millionths: 0,
2329 excess_data: Vec::new()
2332 // Check against amount_to_transfer_over_msat.
2333 // Set minimal HTLC of 200_000_000 msat.
2334 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2335 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2336 short_channel_id: 2,
2339 cltv_expiry_delta: 0,
2340 htlc_minimum_msat: 200_000_000,
2341 htlc_maximum_msat: MAX_VALUE_MSAT,
2343 fee_proportional_millionths: 0,
2344 excess_data: Vec::new()
2347 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
2349 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2350 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2351 short_channel_id: 4,
2354 cltv_expiry_delta: 0,
2355 htlc_minimum_msat: 0,
2356 htlc_maximum_msat: 199_999_999,
2358 fee_proportional_millionths: 0,
2359 excess_data: Vec::new()
2362 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
2363 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) {
2364 assert_eq!(err, "Failed to find a path to the given destination");
2365 } else { panic!(); }
2367 // Lift the restriction on the first hop.
2368 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2369 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2370 short_channel_id: 2,
2373 cltv_expiry_delta: 0,
2374 htlc_minimum_msat: 0,
2375 htlc_maximum_msat: MAX_VALUE_MSAT,
2377 fee_proportional_millionths: 0,
2378 excess_data: Vec::new()
2381 // A payment above the minimum should pass
2382 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();
2383 assert_eq!(route.paths[0].len(), 2);
2387 fn htlc_minimum_overpay_test() {
2388 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2389 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2390 let config = UserConfig::default();
2391 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(channelmanager::provided_invoice_features(&config));
2392 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2393 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2394 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2396 // A route to node#2 via two paths.
2397 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
2398 // Thus, they can't send 60 without overpaying.
2399 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2400 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2401 short_channel_id: 2,
2404 cltv_expiry_delta: 0,
2405 htlc_minimum_msat: 35_000,
2406 htlc_maximum_msat: 40_000,
2408 fee_proportional_millionths: 0,
2409 excess_data: Vec::new()
2411 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2412 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2413 short_channel_id: 12,
2416 cltv_expiry_delta: 0,
2417 htlc_minimum_msat: 35_000,
2418 htlc_maximum_msat: 40_000,
2420 fee_proportional_millionths: 0,
2421 excess_data: Vec::new()
2425 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2426 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2427 short_channel_id: 13,
2430 cltv_expiry_delta: 0,
2431 htlc_minimum_msat: 0,
2432 htlc_maximum_msat: MAX_VALUE_MSAT,
2434 fee_proportional_millionths: 0,
2435 excess_data: Vec::new()
2437 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2438 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2439 short_channel_id: 4,
2442 cltv_expiry_delta: 0,
2443 htlc_minimum_msat: 0,
2444 htlc_maximum_msat: MAX_VALUE_MSAT,
2446 fee_proportional_millionths: 0,
2447 excess_data: Vec::new()
2450 // Disable other paths
2451 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2452 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2453 short_channel_id: 1,
2455 flags: 2, // to disable
2456 cltv_expiry_delta: 0,
2457 htlc_minimum_msat: 0,
2458 htlc_maximum_msat: MAX_VALUE_MSAT,
2460 fee_proportional_millionths: 0,
2461 excess_data: Vec::new()
2464 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 60_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2465 // Overpay fees to hit htlc_minimum_msat.
2466 let overpaid_fees = route.paths[0][0].fee_msat + route.paths[1][0].fee_msat;
2467 // TODO: this could be better balanced to overpay 10k and not 15k.
2468 assert_eq!(overpaid_fees, 15_000);
2470 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
2471 // while taking even more fee to match htlc_minimum_msat.
2472 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2473 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2474 short_channel_id: 12,
2477 cltv_expiry_delta: 0,
2478 htlc_minimum_msat: 65_000,
2479 htlc_maximum_msat: 80_000,
2481 fee_proportional_millionths: 0,
2482 excess_data: Vec::new()
2484 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2485 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2486 short_channel_id: 2,
2489 cltv_expiry_delta: 0,
2490 htlc_minimum_msat: 0,
2491 htlc_maximum_msat: MAX_VALUE_MSAT,
2493 fee_proportional_millionths: 0,
2494 excess_data: Vec::new()
2496 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2497 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2498 short_channel_id: 4,
2501 cltv_expiry_delta: 0,
2502 htlc_minimum_msat: 0,
2503 htlc_maximum_msat: MAX_VALUE_MSAT,
2505 fee_proportional_millionths: 100_000,
2506 excess_data: Vec::new()
2509 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 60_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2510 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
2511 assert_eq!(route.paths.len(), 1);
2512 assert_eq!(route.paths[0][0].short_channel_id, 12);
2513 let fees = route.paths[0][0].fee_msat;
2514 assert_eq!(fees, 5_000);
2516 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2517 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
2518 // the other channel.
2519 assert_eq!(route.paths.len(), 1);
2520 assert_eq!(route.paths[0][0].short_channel_id, 2);
2521 let fees = route.paths[0][0].fee_msat;
2522 assert_eq!(fees, 5_000);
2526 fn disable_channels_test() {
2527 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2528 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2529 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2530 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2531 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2532 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2534 // // Disable channels 4 and 12 by flags=2
2535 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2536 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2537 short_channel_id: 4,
2539 flags: 2, // to disable
2540 cltv_expiry_delta: 0,
2541 htlc_minimum_msat: 0,
2542 htlc_maximum_msat: MAX_VALUE_MSAT,
2544 fee_proportional_millionths: 0,
2545 excess_data: Vec::new()
2547 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2548 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2549 short_channel_id: 12,
2551 flags: 2, // to disable
2552 cltv_expiry_delta: 0,
2553 htlc_minimum_msat: 0,
2554 htlc_maximum_msat: MAX_VALUE_MSAT,
2556 fee_proportional_millionths: 0,
2557 excess_data: Vec::new()
2560 // If all the channels require some features we don't understand, route should fail
2561 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) {
2562 assert_eq!(err, "Failed to find a path to the given destination");
2563 } else { panic!(); }
2565 // If we specify a channel to node7, that overrides our local channel view and that gets used
2566 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2567 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();
2568 assert_eq!(route.paths[0].len(), 2);
2570 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2571 assert_eq!(route.paths[0][0].short_channel_id, 42);
2572 assert_eq!(route.paths[0][0].fee_msat, 200);
2573 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2574 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2575 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2577 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2578 assert_eq!(route.paths[0][1].short_channel_id, 13);
2579 assert_eq!(route.paths[0][1].fee_msat, 100);
2580 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2581 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2582 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2586 fn disable_node_test() {
2587 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2588 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2589 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2590 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2591 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2592 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2594 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
2595 let mut unknown_features = NodeFeatures::empty();
2596 unknown_features.set_unknown_feature_required();
2597 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
2598 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
2599 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
2601 // If all nodes require some features we don't understand, route should fail
2602 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) {
2603 assert_eq!(err, "Failed to find a path to the given destination");
2604 } else { panic!(); }
2606 // If we specify a channel to node7, that overrides our local channel view and that gets used
2607 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2608 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();
2609 assert_eq!(route.paths[0].len(), 2);
2611 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2612 assert_eq!(route.paths[0][0].short_channel_id, 42);
2613 assert_eq!(route.paths[0][0].fee_msat, 200);
2614 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2615 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2616 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2618 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2619 assert_eq!(route.paths[0][1].short_channel_id, 13);
2620 assert_eq!(route.paths[0][1].fee_msat, 100);
2621 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2622 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2623 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2625 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
2626 // naively) assume that the user checked the feature bits on the invoice, which override
2627 // the node_announcement.
2631 fn our_chans_test() {
2632 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2633 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2634 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2635 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2636 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2638 // Route to 1 via 2 and 3 because our channel to 1 is disabled
2639 let payment_params = PaymentParameters::from_node_id(nodes[0]);
2640 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2641 assert_eq!(route.paths[0].len(), 3);
2643 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2644 assert_eq!(route.paths[0][0].short_channel_id, 2);
2645 assert_eq!(route.paths[0][0].fee_msat, 200);
2646 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2647 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2648 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2650 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2651 assert_eq!(route.paths[0][1].short_channel_id, 4);
2652 assert_eq!(route.paths[0][1].fee_msat, 100);
2653 assert_eq!(route.paths[0][1].cltv_expiry_delta, (3 << 4) | 2);
2654 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2655 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2657 assert_eq!(route.paths[0][2].pubkey, nodes[0]);
2658 assert_eq!(route.paths[0][2].short_channel_id, 3);
2659 assert_eq!(route.paths[0][2].fee_msat, 100);
2660 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
2661 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(1));
2662 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(3));
2664 // If we specify a channel to node7, that overrides our local channel view and that gets used
2665 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2666 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2667 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();
2668 assert_eq!(route.paths[0].len(), 2);
2670 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2671 assert_eq!(route.paths[0][0].short_channel_id, 42);
2672 assert_eq!(route.paths[0][0].fee_msat, 200);
2673 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2674 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2675 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2677 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2678 assert_eq!(route.paths[0][1].short_channel_id, 13);
2679 assert_eq!(route.paths[0][1].fee_msat, 100);
2680 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2681 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2682 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2685 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2686 let zero_fees = RoutingFees {
2688 proportional_millionths: 0,
2690 vec![RouteHint(vec![RouteHintHop {
2691 src_node_id: nodes[3],
2692 short_channel_id: 8,
2694 cltv_expiry_delta: (8 << 4) | 1,
2695 htlc_minimum_msat: None,
2696 htlc_maximum_msat: None,
2698 ]), RouteHint(vec![RouteHintHop {
2699 src_node_id: nodes[4],
2700 short_channel_id: 9,
2703 proportional_millionths: 0,
2705 cltv_expiry_delta: (9 << 4) | 1,
2706 htlc_minimum_msat: None,
2707 htlc_maximum_msat: None,
2708 }]), RouteHint(vec![RouteHintHop {
2709 src_node_id: nodes[5],
2710 short_channel_id: 10,
2712 cltv_expiry_delta: (10 << 4) | 1,
2713 htlc_minimum_msat: None,
2714 htlc_maximum_msat: None,
2718 fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2719 let zero_fees = RoutingFees {
2721 proportional_millionths: 0,
2723 vec![RouteHint(vec![RouteHintHop {
2724 src_node_id: nodes[2],
2725 short_channel_id: 5,
2728 proportional_millionths: 0,
2730 cltv_expiry_delta: (5 << 4) | 1,
2731 htlc_minimum_msat: None,
2732 htlc_maximum_msat: None,
2734 src_node_id: nodes[3],
2735 short_channel_id: 8,
2737 cltv_expiry_delta: (8 << 4) | 1,
2738 htlc_minimum_msat: None,
2739 htlc_maximum_msat: None,
2741 ]), RouteHint(vec![RouteHintHop {
2742 src_node_id: nodes[4],
2743 short_channel_id: 9,
2746 proportional_millionths: 0,
2748 cltv_expiry_delta: (9 << 4) | 1,
2749 htlc_minimum_msat: None,
2750 htlc_maximum_msat: None,
2751 }]), RouteHint(vec![RouteHintHop {
2752 src_node_id: nodes[5],
2753 short_channel_id: 10,
2755 cltv_expiry_delta: (10 << 4) | 1,
2756 htlc_minimum_msat: None,
2757 htlc_maximum_msat: None,
2762 fn partial_route_hint_test() {
2763 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2764 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2765 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2766 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2767 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2769 // Simple test across 2, 3, 5, and 4 via a last_hop channel
2770 // Tests the behaviour when the RouteHint contains a suboptimal hop.
2771 // RouteHint may be partially used by the algo to build the best path.
2773 // First check that last hop can't have its source as the payee.
2774 let invalid_last_hop = RouteHint(vec![RouteHintHop {
2775 src_node_id: nodes[6],
2776 short_channel_id: 8,
2779 proportional_millionths: 0,
2781 cltv_expiry_delta: (8 << 4) | 1,
2782 htlc_minimum_msat: None,
2783 htlc_maximum_msat: None,
2786 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
2787 invalid_last_hops.push(invalid_last_hop);
2789 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(invalid_last_hops);
2790 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
2791 assert_eq!(err, "Route hint cannot have the payee as the source.");
2792 } else { panic!(); }
2795 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops_multi_private_channels(&nodes));
2796 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2797 assert_eq!(route.paths[0].len(), 5);
2799 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2800 assert_eq!(route.paths[0][0].short_channel_id, 2);
2801 assert_eq!(route.paths[0][0].fee_msat, 100);
2802 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2803 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2804 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2806 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2807 assert_eq!(route.paths[0][1].short_channel_id, 4);
2808 assert_eq!(route.paths[0][1].fee_msat, 0);
2809 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
2810 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2811 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2813 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2814 assert_eq!(route.paths[0][2].short_channel_id, 6);
2815 assert_eq!(route.paths[0][2].fee_msat, 0);
2816 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
2817 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2818 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2820 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2821 assert_eq!(route.paths[0][3].short_channel_id, 11);
2822 assert_eq!(route.paths[0][3].fee_msat, 0);
2823 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
2824 // If we have a peer in the node map, we'll use their features here since we don't have
2825 // a way of figuring out their features from the invoice:
2826 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2827 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2829 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2830 assert_eq!(route.paths[0][4].short_channel_id, 8);
2831 assert_eq!(route.paths[0][4].fee_msat, 100);
2832 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2833 assert_eq!(route.paths[0][4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
2834 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2837 fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2838 let zero_fees = RoutingFees {
2840 proportional_millionths: 0,
2842 vec![RouteHint(vec![RouteHintHop {
2843 src_node_id: nodes[3],
2844 short_channel_id: 8,
2846 cltv_expiry_delta: (8 << 4) | 1,
2847 htlc_minimum_msat: None,
2848 htlc_maximum_msat: None,
2849 }]), RouteHint(vec![
2851 ]), RouteHint(vec![RouteHintHop {
2852 src_node_id: nodes[5],
2853 short_channel_id: 10,
2855 cltv_expiry_delta: (10 << 4) | 1,
2856 htlc_minimum_msat: None,
2857 htlc_maximum_msat: None,
2862 fn ignores_empty_last_hops_test() {
2863 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2864 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2865 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(empty_last_hop(&nodes));
2866 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2867 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2868 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2870 // Test handling of an empty RouteHint passed in Invoice.
2872 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2873 assert_eq!(route.paths[0].len(), 5);
2875 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2876 assert_eq!(route.paths[0][0].short_channel_id, 2);
2877 assert_eq!(route.paths[0][0].fee_msat, 100);
2878 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2879 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2880 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2882 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2883 assert_eq!(route.paths[0][1].short_channel_id, 4);
2884 assert_eq!(route.paths[0][1].fee_msat, 0);
2885 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
2886 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2887 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2889 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2890 assert_eq!(route.paths[0][2].short_channel_id, 6);
2891 assert_eq!(route.paths[0][2].fee_msat, 0);
2892 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
2893 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2894 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2896 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2897 assert_eq!(route.paths[0][3].short_channel_id, 11);
2898 assert_eq!(route.paths[0][3].fee_msat, 0);
2899 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
2900 // If we have a peer in the node map, we'll use their features here since we don't have
2901 // a way of figuring out their features from the invoice:
2902 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2903 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2905 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2906 assert_eq!(route.paths[0][4].short_channel_id, 8);
2907 assert_eq!(route.paths[0][4].fee_msat, 100);
2908 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2909 assert_eq!(route.paths[0][4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
2910 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2913 /// Builds a trivial last-hop hint that passes through the two nodes given, with channel 0xff00
2915 fn multi_hop_last_hops_hint(hint_hops: [PublicKey; 2]) -> Vec<RouteHint> {
2916 let zero_fees = RoutingFees {
2918 proportional_millionths: 0,
2920 vec![RouteHint(vec![RouteHintHop {
2921 src_node_id: hint_hops[0],
2922 short_channel_id: 0xff00,
2925 proportional_millionths: 0,
2927 cltv_expiry_delta: (5 << 4) | 1,
2928 htlc_minimum_msat: None,
2929 htlc_maximum_msat: None,
2931 src_node_id: hint_hops[1],
2932 short_channel_id: 0xff01,
2934 cltv_expiry_delta: (8 << 4) | 1,
2935 htlc_minimum_msat: None,
2936 htlc_maximum_msat: None,
2941 fn multi_hint_last_hops_test() {
2942 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2943 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2944 let last_hops = multi_hop_last_hops_hint([nodes[2], nodes[3]]);
2945 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops.clone());
2946 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2947 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2948 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2949 // Test through channels 2, 3, 0xff00, 0xff01.
2950 // Test shows that multiple hop hints are considered.
2952 // Disabling channels 6 & 7 by flags=2
2953 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2954 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2955 short_channel_id: 6,
2957 flags: 2, // to disable
2958 cltv_expiry_delta: 0,
2959 htlc_minimum_msat: 0,
2960 htlc_maximum_msat: MAX_VALUE_MSAT,
2962 fee_proportional_millionths: 0,
2963 excess_data: Vec::new()
2965 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2966 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2967 short_channel_id: 7,
2969 flags: 2, // to disable
2970 cltv_expiry_delta: 0,
2971 htlc_minimum_msat: 0,
2972 htlc_maximum_msat: MAX_VALUE_MSAT,
2974 fee_proportional_millionths: 0,
2975 excess_data: Vec::new()
2978 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2979 assert_eq!(route.paths[0].len(), 4);
2981 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2982 assert_eq!(route.paths[0][0].short_channel_id, 2);
2983 assert_eq!(route.paths[0][0].fee_msat, 200);
2984 assert_eq!(route.paths[0][0].cltv_expiry_delta, 65);
2985 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2986 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2988 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2989 assert_eq!(route.paths[0][1].short_channel_id, 4);
2990 assert_eq!(route.paths[0][1].fee_msat, 100);
2991 assert_eq!(route.paths[0][1].cltv_expiry_delta, 81);
2992 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2993 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2995 assert_eq!(route.paths[0][2].pubkey, nodes[3]);
2996 assert_eq!(route.paths[0][2].short_channel_id, last_hops[0].0[0].short_channel_id);
2997 assert_eq!(route.paths[0][2].fee_msat, 0);
2998 assert_eq!(route.paths[0][2].cltv_expiry_delta, 129);
2999 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(4));
3000 assert_eq!(route.paths[0][2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3002 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
3003 assert_eq!(route.paths[0][3].short_channel_id, last_hops[0].0[1].short_channel_id);
3004 assert_eq!(route.paths[0][3].fee_msat, 100);
3005 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
3006 assert_eq!(route.paths[0][3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3007 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3011 fn private_multi_hint_last_hops_test() {
3012 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3013 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3015 let non_announced_privkey = SecretKey::from_slice(&hex::decode(format!("{:02x}", 0xf0).repeat(32)).unwrap()[..]).unwrap();
3016 let non_announced_pubkey = PublicKey::from_secret_key(&secp_ctx, &non_announced_privkey);
3018 let last_hops = multi_hop_last_hops_hint([nodes[2], non_announced_pubkey]);
3019 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops.clone());
3020 let scorer = ln_test_utils::TestScorer::with_penalty(0);
3021 // Test through channels 2, 3, 0xff00, 0xff01.
3022 // Test shows that multiple hop hints are considered.
3024 // Disabling channels 6 & 7 by flags=2
3025 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3026 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3027 short_channel_id: 6,
3029 flags: 2, // to disable
3030 cltv_expiry_delta: 0,
3031 htlc_minimum_msat: 0,
3032 htlc_maximum_msat: MAX_VALUE_MSAT,
3034 fee_proportional_millionths: 0,
3035 excess_data: Vec::new()
3037 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3038 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3039 short_channel_id: 7,
3041 flags: 2, // to disable
3042 cltv_expiry_delta: 0,
3043 htlc_minimum_msat: 0,
3044 htlc_maximum_msat: MAX_VALUE_MSAT,
3046 fee_proportional_millionths: 0,
3047 excess_data: Vec::new()
3050 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &[42u8; 32]).unwrap();
3051 assert_eq!(route.paths[0].len(), 4);
3053 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3054 assert_eq!(route.paths[0][0].short_channel_id, 2);
3055 assert_eq!(route.paths[0][0].fee_msat, 200);
3056 assert_eq!(route.paths[0][0].cltv_expiry_delta, 65);
3057 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3058 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3060 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3061 assert_eq!(route.paths[0][1].short_channel_id, 4);
3062 assert_eq!(route.paths[0][1].fee_msat, 100);
3063 assert_eq!(route.paths[0][1].cltv_expiry_delta, 81);
3064 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3065 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3067 assert_eq!(route.paths[0][2].pubkey, non_announced_pubkey);
3068 assert_eq!(route.paths[0][2].short_channel_id, last_hops[0].0[0].short_channel_id);
3069 assert_eq!(route.paths[0][2].fee_msat, 0);
3070 assert_eq!(route.paths[0][2].cltv_expiry_delta, 129);
3071 assert_eq!(route.paths[0][2].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3072 assert_eq!(route.paths[0][2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3074 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
3075 assert_eq!(route.paths[0][3].short_channel_id, last_hops[0].0[1].short_channel_id);
3076 assert_eq!(route.paths[0][3].fee_msat, 100);
3077 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
3078 assert_eq!(route.paths[0][3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3079 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3082 fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3083 let zero_fees = RoutingFees {
3085 proportional_millionths: 0,
3087 vec![RouteHint(vec![RouteHintHop {
3088 src_node_id: nodes[4],
3089 short_channel_id: 11,
3091 cltv_expiry_delta: (11 << 4) | 1,
3092 htlc_minimum_msat: None,
3093 htlc_maximum_msat: None,
3095 src_node_id: nodes[3],
3096 short_channel_id: 8,
3098 cltv_expiry_delta: (8 << 4) | 1,
3099 htlc_minimum_msat: None,
3100 htlc_maximum_msat: None,
3101 }]), RouteHint(vec![RouteHintHop {
3102 src_node_id: nodes[4],
3103 short_channel_id: 9,
3106 proportional_millionths: 0,
3108 cltv_expiry_delta: (9 << 4) | 1,
3109 htlc_minimum_msat: None,
3110 htlc_maximum_msat: None,
3111 }]), RouteHint(vec![RouteHintHop {
3112 src_node_id: nodes[5],
3113 short_channel_id: 10,
3115 cltv_expiry_delta: (10 << 4) | 1,
3116 htlc_minimum_msat: None,
3117 htlc_maximum_msat: None,
3122 fn last_hops_with_public_channel_test() {
3123 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3124 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3125 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops_with_public_channel(&nodes));
3126 let scorer = ln_test_utils::TestScorer::with_penalty(0);
3127 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3128 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3129 // This test shows that public routes can be present in the invoice
3130 // which would be handled in the same manner.
3132 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3133 assert_eq!(route.paths[0].len(), 5);
3135 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3136 assert_eq!(route.paths[0][0].short_channel_id, 2);
3137 assert_eq!(route.paths[0][0].fee_msat, 100);
3138 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
3139 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3140 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3142 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3143 assert_eq!(route.paths[0][1].short_channel_id, 4);
3144 assert_eq!(route.paths[0][1].fee_msat, 0);
3145 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
3146 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3147 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3149 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
3150 assert_eq!(route.paths[0][2].short_channel_id, 6);
3151 assert_eq!(route.paths[0][2].fee_msat, 0);
3152 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
3153 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
3154 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
3156 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
3157 assert_eq!(route.paths[0][3].short_channel_id, 11);
3158 assert_eq!(route.paths[0][3].fee_msat, 0);
3159 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
3160 // If we have a peer in the node map, we'll use their features here since we don't have
3161 // a way of figuring out their features from the invoice:
3162 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
3163 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
3165 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
3166 assert_eq!(route.paths[0][4].short_channel_id, 8);
3167 assert_eq!(route.paths[0][4].fee_msat, 100);
3168 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
3169 assert_eq!(route.paths[0][4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3170 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3174 fn our_chans_last_hop_connect_test() {
3175 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3176 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3177 let scorer = ln_test_utils::TestScorer::with_penalty(0);
3178 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3179 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3181 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
3182 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3183 let mut last_hops = last_hops(&nodes);
3184 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops.clone());
3185 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();
3186 assert_eq!(route.paths[0].len(), 2);
3188 assert_eq!(route.paths[0][0].pubkey, nodes[3]);
3189 assert_eq!(route.paths[0][0].short_channel_id, 42);
3190 assert_eq!(route.paths[0][0].fee_msat, 0);
3191 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 4) | 1);
3192 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
3193 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3195 assert_eq!(route.paths[0][1].pubkey, nodes[6]);
3196 assert_eq!(route.paths[0][1].short_channel_id, 8);
3197 assert_eq!(route.paths[0][1].fee_msat, 100);
3198 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
3199 assert_eq!(route.paths[0][1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3200 assert_eq!(route.paths[0][1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3202 last_hops[0].0[0].fees.base_msat = 1000;
3204 // Revert to via 6 as the fee on 8 goes up
3205 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops);
3206 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3207 assert_eq!(route.paths[0].len(), 4);
3209 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3210 assert_eq!(route.paths[0][0].short_channel_id, 2);
3211 assert_eq!(route.paths[0][0].fee_msat, 200); // fee increased as its % of value transferred across node
3212 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
3213 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3214 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3216 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3217 assert_eq!(route.paths[0][1].short_channel_id, 4);
3218 assert_eq!(route.paths[0][1].fee_msat, 100);
3219 assert_eq!(route.paths[0][1].cltv_expiry_delta, (7 << 4) | 1);
3220 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3221 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3223 assert_eq!(route.paths[0][2].pubkey, nodes[5]);
3224 assert_eq!(route.paths[0][2].short_channel_id, 7);
3225 assert_eq!(route.paths[0][2].fee_msat, 0);
3226 assert_eq!(route.paths[0][2].cltv_expiry_delta, (10 << 4) | 1);
3227 // If we have a peer in the node map, we'll use their features here since we don't have
3228 // a way of figuring out their features from the invoice:
3229 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
3230 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(7));
3232 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
3233 assert_eq!(route.paths[0][3].short_channel_id, 10);
3234 assert_eq!(route.paths[0][3].fee_msat, 100);
3235 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
3236 assert_eq!(route.paths[0][3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3237 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3239 // ...but still use 8 for larger payments as 6 has a variable feerate
3240 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 2000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3241 assert_eq!(route.paths[0].len(), 5);
3243 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3244 assert_eq!(route.paths[0][0].short_channel_id, 2);
3245 assert_eq!(route.paths[0][0].fee_msat, 3000);
3246 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
3247 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3248 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3250 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3251 assert_eq!(route.paths[0][1].short_channel_id, 4);
3252 assert_eq!(route.paths[0][1].fee_msat, 0);
3253 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
3254 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3255 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3257 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
3258 assert_eq!(route.paths[0][2].short_channel_id, 6);
3259 assert_eq!(route.paths[0][2].fee_msat, 0);
3260 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
3261 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
3262 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
3264 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
3265 assert_eq!(route.paths[0][3].short_channel_id, 11);
3266 assert_eq!(route.paths[0][3].fee_msat, 1000);
3267 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
3268 // If we have a peer in the node map, we'll use their features here since we don't have
3269 // a way of figuring out their features from the invoice:
3270 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
3271 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
3273 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
3274 assert_eq!(route.paths[0][4].short_channel_id, 8);
3275 assert_eq!(route.paths[0][4].fee_msat, 2000);
3276 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
3277 assert_eq!(route.paths[0][4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3278 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3281 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> {
3282 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
3283 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3284 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3286 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
3287 let last_hops = RouteHint(vec![RouteHintHop {
3288 src_node_id: middle_node_id,
3289 short_channel_id: 8,
3292 proportional_millionths: last_hop_fee_prop,
3294 cltv_expiry_delta: (8 << 4) | 1,
3295 htlc_minimum_msat: None,
3296 htlc_maximum_msat: last_hop_htlc_max,
3298 let payment_params = PaymentParameters::from_node_id(target_node_id).with_route_hints(vec![last_hops]);
3299 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
3300 let scorer = ln_test_utils::TestScorer::with_penalty(0);
3301 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3302 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3303 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
3304 let logger = ln_test_utils::TestLogger::new();
3305 let network_graph = NetworkGraph::new(genesis_hash, &logger);
3306 let route = get_route(&source_node_id, &payment_params, &network_graph.read_only(),
3307 Some(&our_chans.iter().collect::<Vec<_>>()), route_val, 42, &logger, &scorer, &random_seed_bytes);
3312 fn unannounced_path_test() {
3313 // We should be able to send a payment to a destination without any help of a routing graph
3314 // if we have a channel with a common counterparty that appears in the first and last hop
3316 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
3318 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3319 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3320 assert_eq!(route.paths[0].len(), 2);
3322 assert_eq!(route.paths[0][0].pubkey, middle_node_id);
3323 assert_eq!(route.paths[0][0].short_channel_id, 42);
3324 assert_eq!(route.paths[0][0].fee_msat, 1001);
3325 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 4) | 1);
3326 assert_eq!(route.paths[0][0].node_features.le_flags(), &[0b11]);
3327 assert_eq!(route.paths[0][0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3329 assert_eq!(route.paths[0][1].pubkey, target_node_id);
3330 assert_eq!(route.paths[0][1].short_channel_id, 8);
3331 assert_eq!(route.paths[0][1].fee_msat, 1000000);
3332 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
3333 assert_eq!(route.paths[0][1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3334 assert_eq!(route.paths[0][1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3338 fn overflow_unannounced_path_test_liquidity_underflow() {
3339 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
3340 // the last-hop had a fee which overflowed a u64, we'd panic.
3341 // This was due to us adding the first-hop from us unconditionally, causing us to think
3342 // we'd built a path (as our node is in the "best candidate" set), when we had not.
3343 // In this test, we previously hit a subtraction underflow due to having less available
3344 // liquidity at the last hop than 0.
3345 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());
3349 fn overflow_unannounced_path_test_feerate_overflow() {
3350 // This tests for the same case as above, except instead of hitting a subtraction
3351 // underflow, we hit a case where the fee charged at a hop overflowed.
3352 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());
3356 fn available_amount_while_routing_test() {
3357 // Tests whether we choose the correct available channel amount while routing.
3359 let (secp_ctx, network_graph, mut gossip_sync, chain_monitor, logger) = build_graph();
3360 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3361 let scorer = ln_test_utils::TestScorer::with_penalty(0);
3362 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3363 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3364 let config = UserConfig::default();
3365 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(channelmanager::provided_invoice_features(&config));
3367 // We will use a simple single-path route from
3368 // our node to node2 via node0: channels {1, 3}.
3370 // First disable all other paths.
3371 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3372 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3373 short_channel_id: 2,
3376 cltv_expiry_delta: 0,
3377 htlc_minimum_msat: 0,
3378 htlc_maximum_msat: 100_000,
3380 fee_proportional_millionths: 0,
3381 excess_data: Vec::new()
3383 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3384 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3385 short_channel_id: 12,
3388 cltv_expiry_delta: 0,
3389 htlc_minimum_msat: 0,
3390 htlc_maximum_msat: 100_000,
3392 fee_proportional_millionths: 0,
3393 excess_data: Vec::new()
3396 // Make the first channel (#1) very permissive,
3397 // and we will be testing all limits on the second channel.
3398 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3399 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3400 short_channel_id: 1,
3403 cltv_expiry_delta: 0,
3404 htlc_minimum_msat: 0,
3405 htlc_maximum_msat: 1_000_000_000,
3407 fee_proportional_millionths: 0,
3408 excess_data: Vec::new()
3411 // First, let's see if routing works if we have absolutely no idea about the available amount.
3412 // In this case, it should be set to 250_000 sats.
3413 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3414 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3415 short_channel_id: 3,
3418 cltv_expiry_delta: 0,
3419 htlc_minimum_msat: 0,
3420 htlc_maximum_msat: 250_000_000,
3422 fee_proportional_millionths: 0,
3423 excess_data: Vec::new()
3427 // Attempt to route more than available results in a failure.
3428 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3429 &our_id, &payment_params, &network_graph.read_only(), None, 250_000_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3430 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3431 } else { panic!(); }
3435 // Now, attempt to route an exact amount we have should be fine.
3436 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();
3437 assert_eq!(route.paths.len(), 1);
3438 let path = route.paths.last().unwrap();
3439 assert_eq!(path.len(), 2);
3440 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3441 assert_eq!(path.last().unwrap().fee_msat, 250_000_000);
3444 // Check that setting next_outbound_htlc_limit_msat in first_hops limits the channels.
3445 // Disable channel #1 and use another first hop.
3446 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3447 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3448 short_channel_id: 1,
3451 cltv_expiry_delta: 0,
3452 htlc_minimum_msat: 0,
3453 htlc_maximum_msat: 1_000_000_000,
3455 fee_proportional_millionths: 0,
3456 excess_data: Vec::new()
3459 // Now, limit the first_hop by the next_outbound_htlc_limit_msat of 200_000 sats.
3460 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
3463 // Attempt to route more than available results in a failure.
3464 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3465 &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) {
3466 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3467 } else { panic!(); }
3471 // Now, attempt to route an exact amount we have should be fine.
3472 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();
3473 assert_eq!(route.paths.len(), 1);
3474 let path = route.paths.last().unwrap();
3475 assert_eq!(path.len(), 2);
3476 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3477 assert_eq!(path.last().unwrap().fee_msat, 200_000_000);
3480 // Enable channel #1 back.
3481 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3482 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3483 short_channel_id: 1,
3486 cltv_expiry_delta: 0,
3487 htlc_minimum_msat: 0,
3488 htlc_maximum_msat: 1_000_000_000,
3490 fee_proportional_millionths: 0,
3491 excess_data: Vec::new()
3495 // Now let's see if routing works if we know only htlc_maximum_msat.
3496 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3497 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3498 short_channel_id: 3,
3501 cltv_expiry_delta: 0,
3502 htlc_minimum_msat: 0,
3503 htlc_maximum_msat: 15_000,
3505 fee_proportional_millionths: 0,
3506 excess_data: Vec::new()
3510 // Attempt to route more than available results in a failure.
3511 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3512 &our_id, &payment_params, &network_graph.read_only(), None, 15_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3513 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3514 } else { panic!(); }
3518 // Now, attempt to route an exact amount we have should be fine.
3519 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 15_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3520 assert_eq!(route.paths.len(), 1);
3521 let path = route.paths.last().unwrap();
3522 assert_eq!(path.len(), 2);
3523 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3524 assert_eq!(path.last().unwrap().fee_msat, 15_000);
3527 // Now let's see if routing works if we know only capacity from the UTXO.
3529 // We can't change UTXO capacity on the fly, so we'll disable
3530 // the existing channel and add another one with the capacity we need.
3531 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3532 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3533 short_channel_id: 3,
3536 cltv_expiry_delta: 0,
3537 htlc_minimum_msat: 0,
3538 htlc_maximum_msat: MAX_VALUE_MSAT,
3540 fee_proportional_millionths: 0,
3541 excess_data: Vec::new()
3544 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
3545 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
3546 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
3547 .push_opcode(opcodes::all::OP_PUSHNUM_2)
3548 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
3550 *chain_monitor.utxo_ret.lock().unwrap() = Ok(TxOut { value: 15, script_pubkey: good_script.clone() });
3551 gossip_sync.add_chain_access(Some(chain_monitor));
3553 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
3554 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3555 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3556 short_channel_id: 333,
3559 cltv_expiry_delta: (3 << 4) | 1,
3560 htlc_minimum_msat: 0,
3561 htlc_maximum_msat: 15_000,
3563 fee_proportional_millionths: 0,
3564 excess_data: Vec::new()
3566 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3567 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3568 short_channel_id: 333,
3571 cltv_expiry_delta: (3 << 4) | 2,
3572 htlc_minimum_msat: 0,
3573 htlc_maximum_msat: 15_000,
3575 fee_proportional_millionths: 0,
3576 excess_data: Vec::new()
3580 // Attempt to route more than available results in a failure.
3581 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3582 &our_id, &payment_params, &network_graph.read_only(), None, 15_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3583 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3584 } else { panic!(); }
3588 // Now, attempt to route an exact amount we have should be fine.
3589 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 15_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3590 assert_eq!(route.paths.len(), 1);
3591 let path = route.paths.last().unwrap();
3592 assert_eq!(path.len(), 2);
3593 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3594 assert_eq!(path.last().unwrap().fee_msat, 15_000);
3597 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
3598 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3599 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3600 short_channel_id: 333,
3603 cltv_expiry_delta: 0,
3604 htlc_minimum_msat: 0,
3605 htlc_maximum_msat: 10_000,
3607 fee_proportional_millionths: 0,
3608 excess_data: Vec::new()
3612 // Attempt to route more than available results in a failure.
3613 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3614 &our_id, &payment_params, &network_graph.read_only(), None, 10_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3615 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3616 } else { panic!(); }
3620 // Now, attempt to route an exact amount we have should be fine.
3621 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 10_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3622 assert_eq!(route.paths.len(), 1);
3623 let path = route.paths.last().unwrap();
3624 assert_eq!(path.len(), 2);
3625 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3626 assert_eq!(path.last().unwrap().fee_msat, 10_000);
3631 fn available_liquidity_last_hop_test() {
3632 // Check that available liquidity properly limits the path even when only
3633 // one of the latter hops is limited.
3634 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3635 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3636 let scorer = ln_test_utils::TestScorer::with_penalty(0);
3637 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3638 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3639 let config = UserConfig::default();
3640 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(channelmanager::provided_invoice_features(&config));
3642 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3643 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
3644 // Total capacity: 50 sats.
3646 // Disable other potential paths.
3647 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3648 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3649 short_channel_id: 2,
3652 cltv_expiry_delta: 0,
3653 htlc_minimum_msat: 0,
3654 htlc_maximum_msat: 100_000,
3656 fee_proportional_millionths: 0,
3657 excess_data: Vec::new()
3659 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3660 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3661 short_channel_id: 7,
3664 cltv_expiry_delta: 0,
3665 htlc_minimum_msat: 0,
3666 htlc_maximum_msat: 100_000,
3668 fee_proportional_millionths: 0,
3669 excess_data: Vec::new()
3674 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3675 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3676 short_channel_id: 12,
3679 cltv_expiry_delta: 0,
3680 htlc_minimum_msat: 0,
3681 htlc_maximum_msat: 100_000,
3683 fee_proportional_millionths: 0,
3684 excess_data: Vec::new()
3686 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3687 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3688 short_channel_id: 13,
3691 cltv_expiry_delta: 0,
3692 htlc_minimum_msat: 0,
3693 htlc_maximum_msat: 100_000,
3695 fee_proportional_millionths: 0,
3696 excess_data: Vec::new()
3699 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3700 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3701 short_channel_id: 6,
3704 cltv_expiry_delta: 0,
3705 htlc_minimum_msat: 0,
3706 htlc_maximum_msat: 50_000,
3708 fee_proportional_millionths: 0,
3709 excess_data: Vec::new()
3711 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3712 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3713 short_channel_id: 11,
3716 cltv_expiry_delta: 0,
3717 htlc_minimum_msat: 0,
3718 htlc_maximum_msat: 100_000,
3720 fee_proportional_millionths: 0,
3721 excess_data: Vec::new()
3724 // Attempt to route more than available results in a failure.
3725 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3726 &our_id, &payment_params, &network_graph.read_only(), None, 60_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3727 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3728 } else { panic!(); }
3732 // Now, attempt to route 49 sats (just a bit below the capacity).
3733 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 49_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3734 assert_eq!(route.paths.len(), 1);
3735 let mut total_amount_paid_msat = 0;
3736 for path in &route.paths {
3737 assert_eq!(path.len(), 4);
3738 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3739 total_amount_paid_msat += path.last().unwrap().fee_msat;
3741 assert_eq!(total_amount_paid_msat, 49_000);
3745 // Attempt to route an exact amount is also fine
3746 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3747 assert_eq!(route.paths.len(), 1);
3748 let mut total_amount_paid_msat = 0;
3749 for path in &route.paths {
3750 assert_eq!(path.len(), 4);
3751 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3752 total_amount_paid_msat += path.last().unwrap().fee_msat;
3754 assert_eq!(total_amount_paid_msat, 50_000);
3759 fn ignore_fee_first_hop_test() {
3760 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3761 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3762 let scorer = ln_test_utils::TestScorer::with_penalty(0);
3763 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3764 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3765 let payment_params = PaymentParameters::from_node_id(nodes[2]);
3767 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3768 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3769 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3770 short_channel_id: 1,
3773 cltv_expiry_delta: 0,
3774 htlc_minimum_msat: 0,
3775 htlc_maximum_msat: 100_000,
3776 fee_base_msat: 1_000_000,
3777 fee_proportional_millionths: 0,
3778 excess_data: Vec::new()
3780 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3781 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3782 short_channel_id: 3,
3785 cltv_expiry_delta: 0,
3786 htlc_minimum_msat: 0,
3787 htlc_maximum_msat: 50_000,
3789 fee_proportional_millionths: 0,
3790 excess_data: Vec::new()
3794 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3795 assert_eq!(route.paths.len(), 1);
3796 let mut total_amount_paid_msat = 0;
3797 for path in &route.paths {
3798 assert_eq!(path.len(), 2);
3799 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3800 total_amount_paid_msat += path.last().unwrap().fee_msat;
3802 assert_eq!(total_amount_paid_msat, 50_000);
3807 fn simple_mpp_route_test() {
3808 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3809 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3810 let scorer = ln_test_utils::TestScorer::with_penalty(0);
3811 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3812 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3813 let config = UserConfig::default();
3814 let payment_params = PaymentParameters::from_node_id(nodes[2])
3815 .with_features(channelmanager::provided_invoice_features(&config));
3817 // We need a route consisting of 3 paths:
3818 // From our node to node2 via node0, node7, node1 (three paths one hop each).
3819 // To achieve this, the amount being transferred should be around
3820 // the total capacity of these 3 paths.
3822 // First, we set limits on these (previously unlimited) channels.
3823 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
3825 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3826 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3827 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3828 short_channel_id: 1,
3831 cltv_expiry_delta: 0,
3832 htlc_minimum_msat: 0,
3833 htlc_maximum_msat: 100_000,
3835 fee_proportional_millionths: 0,
3836 excess_data: Vec::new()
3838 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3839 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3840 short_channel_id: 3,
3843 cltv_expiry_delta: 0,
3844 htlc_minimum_msat: 0,
3845 htlc_maximum_msat: 50_000,
3847 fee_proportional_millionths: 0,
3848 excess_data: Vec::new()
3851 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
3852 // (total limit 60).
3853 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3854 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3855 short_channel_id: 12,
3858 cltv_expiry_delta: 0,
3859 htlc_minimum_msat: 0,
3860 htlc_maximum_msat: 60_000,
3862 fee_proportional_millionths: 0,
3863 excess_data: Vec::new()
3865 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3866 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3867 short_channel_id: 13,
3870 cltv_expiry_delta: 0,
3871 htlc_minimum_msat: 0,
3872 htlc_maximum_msat: 60_000,
3874 fee_proportional_millionths: 0,
3875 excess_data: Vec::new()
3878 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
3879 // (total capacity 180 sats).
3880 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3881 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3882 short_channel_id: 2,
3885 cltv_expiry_delta: 0,
3886 htlc_minimum_msat: 0,
3887 htlc_maximum_msat: 200_000,
3889 fee_proportional_millionths: 0,
3890 excess_data: Vec::new()
3892 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3893 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3894 short_channel_id: 4,
3897 cltv_expiry_delta: 0,
3898 htlc_minimum_msat: 0,
3899 htlc_maximum_msat: 180_000,
3901 fee_proportional_millionths: 0,
3902 excess_data: Vec::new()
3906 // Attempt to route more than available results in a failure.
3907 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3908 &our_id, &payment_params, &network_graph.read_only(), None, 300_000, 42,
3909 Arc::clone(&logger), &scorer, &random_seed_bytes) {
3910 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3911 } else { panic!(); }
3915 // Attempt to route while setting max_path_count to 0 results in a failure.
3916 let zero_payment_params = payment_params.clone().with_max_path_count(0);
3917 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3918 &our_id, &zero_payment_params, &network_graph.read_only(), None, 100, 42,
3919 Arc::clone(&logger), &scorer, &random_seed_bytes) {
3920 assert_eq!(err, "Can't find a route with no paths allowed.");
3921 } else { panic!(); }
3925 // Attempt to route while setting max_path_count to 3 results in a failure.
3926 // This is the case because the minimal_value_contribution_msat would require each path
3927 // to account for 1/3 of the total value, which is violated by 2 out of 3 paths.
3928 let fail_payment_params = payment_params.clone().with_max_path_count(3);
3929 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3930 &our_id, &fail_payment_params, &network_graph.read_only(), None, 250_000, 42,
3931 Arc::clone(&logger), &scorer, &random_seed_bytes) {
3932 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3933 } else { panic!(); }
3937 // Now, attempt to route 250 sats (just a bit below the capacity).
3938 // Our algorithm should provide us with these 3 paths.
3939 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None,
3940 250_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3941 assert_eq!(route.paths.len(), 3);
3942 let mut total_amount_paid_msat = 0;
3943 for path in &route.paths {
3944 assert_eq!(path.len(), 2);
3945 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3946 total_amount_paid_msat += path.last().unwrap().fee_msat;
3948 assert_eq!(total_amount_paid_msat, 250_000);
3952 // Attempt to route an exact amount is also fine
3953 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None,
3954 290_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3955 assert_eq!(route.paths.len(), 3);
3956 let mut total_amount_paid_msat = 0;
3957 for path in &route.paths {
3958 assert_eq!(path.len(), 2);
3959 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3960 total_amount_paid_msat += path.last().unwrap().fee_msat;
3962 assert_eq!(total_amount_paid_msat, 290_000);
3967 fn long_mpp_route_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 = ln_test_utils::TestScorer::with_penalty(0);
3971 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3972 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3973 let config = UserConfig::default();
3974 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(channelmanager::provided_invoice_features(&config));
3976 // We need a route consisting of 3 paths:
3977 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3978 // Note that these paths overlap (channels 5, 12, 13).
3979 // We will route 300 sats.
3980 // Each path will have 100 sats capacity, those channels which
3981 // are used twice will have 200 sats capacity.
3983 // Disable other potential paths.
3984 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3985 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3986 short_channel_id: 2,
3989 cltv_expiry_delta: 0,
3990 htlc_minimum_msat: 0,
3991 htlc_maximum_msat: 100_000,
3993 fee_proportional_millionths: 0,
3994 excess_data: Vec::new()
3996 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3997 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3998 short_channel_id: 7,
4001 cltv_expiry_delta: 0,
4002 htlc_minimum_msat: 0,
4003 htlc_maximum_msat: 100_000,
4005 fee_proportional_millionths: 0,
4006 excess_data: Vec::new()
4009 // Path via {node0, node2} is channels {1, 3, 5}.
4010 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4011 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4012 short_channel_id: 1,
4015 cltv_expiry_delta: 0,
4016 htlc_minimum_msat: 0,
4017 htlc_maximum_msat: 100_000,
4019 fee_proportional_millionths: 0,
4020 excess_data: Vec::new()
4022 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4023 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4024 short_channel_id: 3,
4027 cltv_expiry_delta: 0,
4028 htlc_minimum_msat: 0,
4029 htlc_maximum_msat: 100_000,
4031 fee_proportional_millionths: 0,
4032 excess_data: Vec::new()
4035 // Capacity of 200 sats because this channel will be used by 3rd path as well.
4036 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4037 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4038 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4039 short_channel_id: 5,
4042 cltv_expiry_delta: 0,
4043 htlc_minimum_msat: 0,
4044 htlc_maximum_msat: 200_000,
4046 fee_proportional_millionths: 0,
4047 excess_data: Vec::new()
4050 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4051 // Add 100 sats to the capacities of {12, 13}, because these channels
4052 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
4053 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4054 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4055 short_channel_id: 12,
4058 cltv_expiry_delta: 0,
4059 htlc_minimum_msat: 0,
4060 htlc_maximum_msat: 200_000,
4062 fee_proportional_millionths: 0,
4063 excess_data: Vec::new()
4065 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4066 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4067 short_channel_id: 13,
4070 cltv_expiry_delta: 0,
4071 htlc_minimum_msat: 0,
4072 htlc_maximum_msat: 200_000,
4074 fee_proportional_millionths: 0,
4075 excess_data: Vec::new()
4078 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4079 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4080 short_channel_id: 6,
4083 cltv_expiry_delta: 0,
4084 htlc_minimum_msat: 0,
4085 htlc_maximum_msat: 100_000,
4087 fee_proportional_millionths: 0,
4088 excess_data: Vec::new()
4090 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4091 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4092 short_channel_id: 11,
4095 cltv_expiry_delta: 0,
4096 htlc_minimum_msat: 0,
4097 htlc_maximum_msat: 100_000,
4099 fee_proportional_millionths: 0,
4100 excess_data: Vec::new()
4103 // Path via {node7, node2} is channels {12, 13, 5}.
4104 // We already limited them to 200 sats (they are used twice for 100 sats).
4105 // Nothing to do here.
4108 // Attempt to route more than available results in a failure.
4109 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4110 &our_id, &payment_params, &network_graph.read_only(), None, 350_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
4111 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4112 } else { panic!(); }
4116 // Now, attempt to route 300 sats (exact amount we can route).
4117 // Our algorithm should provide us with these 3 paths, 100 sats each.
4118 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 300_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4119 assert_eq!(route.paths.len(), 3);
4121 let mut total_amount_paid_msat = 0;
4122 for path in &route.paths {
4123 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
4124 total_amount_paid_msat += path.last().unwrap().fee_msat;
4126 assert_eq!(total_amount_paid_msat, 300_000);
4132 fn mpp_cheaper_route_test() {
4133 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4134 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4135 let scorer = ln_test_utils::TestScorer::with_penalty(0);
4136 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4137 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4138 let config = UserConfig::default();
4139 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(channelmanager::provided_invoice_features(&config));
4141 // This test checks that if we have two cheaper paths and one more expensive path,
4142 // so that liquidity-wise any 2 of 3 combination is sufficient,
4143 // two cheaper paths will be taken.
4144 // These paths have equal available liquidity.
4146 // We need a combination of 3 paths:
4147 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
4148 // Note that these paths overlap (channels 5, 12, 13).
4149 // Each path will have 100 sats capacity, those channels which
4150 // are used twice will have 200 sats capacity.
4152 // Disable other potential paths.
4153 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4154 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4155 short_channel_id: 2,
4158 cltv_expiry_delta: 0,
4159 htlc_minimum_msat: 0,
4160 htlc_maximum_msat: 100_000,
4162 fee_proportional_millionths: 0,
4163 excess_data: Vec::new()
4165 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4166 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4167 short_channel_id: 7,
4170 cltv_expiry_delta: 0,
4171 htlc_minimum_msat: 0,
4172 htlc_maximum_msat: 100_000,
4174 fee_proportional_millionths: 0,
4175 excess_data: Vec::new()
4178 // Path via {node0, node2} is channels {1, 3, 5}.
4179 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4180 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4181 short_channel_id: 1,
4184 cltv_expiry_delta: 0,
4185 htlc_minimum_msat: 0,
4186 htlc_maximum_msat: 100_000,
4188 fee_proportional_millionths: 0,
4189 excess_data: Vec::new()
4191 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4192 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4193 short_channel_id: 3,
4196 cltv_expiry_delta: 0,
4197 htlc_minimum_msat: 0,
4198 htlc_maximum_msat: 100_000,
4200 fee_proportional_millionths: 0,
4201 excess_data: Vec::new()
4204 // Capacity of 200 sats because this channel will be used by 3rd path as well.
4205 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4206 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4207 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4208 short_channel_id: 5,
4211 cltv_expiry_delta: 0,
4212 htlc_minimum_msat: 0,
4213 htlc_maximum_msat: 200_000,
4215 fee_proportional_millionths: 0,
4216 excess_data: Vec::new()
4219 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4220 // Add 100 sats to the capacities of {12, 13}, because these channels
4221 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
4222 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4223 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4224 short_channel_id: 12,
4227 cltv_expiry_delta: 0,
4228 htlc_minimum_msat: 0,
4229 htlc_maximum_msat: 200_000,
4231 fee_proportional_millionths: 0,
4232 excess_data: Vec::new()
4234 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4235 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4236 short_channel_id: 13,
4239 cltv_expiry_delta: 0,
4240 htlc_minimum_msat: 0,
4241 htlc_maximum_msat: 200_000,
4243 fee_proportional_millionths: 0,
4244 excess_data: Vec::new()
4247 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4248 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4249 short_channel_id: 6,
4252 cltv_expiry_delta: 0,
4253 htlc_minimum_msat: 0,
4254 htlc_maximum_msat: 100_000,
4255 fee_base_msat: 1_000,
4256 fee_proportional_millionths: 0,
4257 excess_data: Vec::new()
4259 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4260 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4261 short_channel_id: 11,
4264 cltv_expiry_delta: 0,
4265 htlc_minimum_msat: 0,
4266 htlc_maximum_msat: 100_000,
4268 fee_proportional_millionths: 0,
4269 excess_data: Vec::new()
4272 // Path via {node7, node2} is channels {12, 13, 5}.
4273 // We already limited them to 200 sats (they are used twice for 100 sats).
4274 // Nothing to do here.
4277 // Now, attempt to route 180 sats.
4278 // Our algorithm should provide us with these 2 paths.
4279 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 180_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4280 assert_eq!(route.paths.len(), 2);
4282 let mut total_value_transferred_msat = 0;
4283 let mut total_paid_msat = 0;
4284 for path in &route.paths {
4285 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
4286 total_value_transferred_msat += path.last().unwrap().fee_msat;
4288 total_paid_msat += hop.fee_msat;
4291 // If we paid fee, this would be higher.
4292 assert_eq!(total_value_transferred_msat, 180_000);
4293 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
4294 assert_eq!(total_fees_paid, 0);
4299 fn fees_on_mpp_route_test() {
4300 // This test makes sure that MPP algorithm properly takes into account
4301 // fees charged on the channels, by making the fees impactful:
4302 // if the fee is not properly accounted for, the behavior is different.
4303 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4304 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4305 let scorer = ln_test_utils::TestScorer::with_penalty(0);
4306 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4307 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4308 let config = UserConfig::default();
4309 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(channelmanager::provided_invoice_features(&config));
4311 // We need a route consisting of 2 paths:
4312 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
4313 // We will route 200 sats, Each path will have 100 sats capacity.
4315 // This test is not particularly stable: e.g.,
4316 // there's a way to route via {node0, node2, node4}.
4317 // It works while pathfinding is deterministic, but can be broken otherwise.
4318 // It's fine to ignore this concern for now.
4320 // Disable other potential paths.
4321 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4322 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4323 short_channel_id: 2,
4326 cltv_expiry_delta: 0,
4327 htlc_minimum_msat: 0,
4328 htlc_maximum_msat: 100_000,
4330 fee_proportional_millionths: 0,
4331 excess_data: Vec::new()
4334 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4335 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4336 short_channel_id: 7,
4339 cltv_expiry_delta: 0,
4340 htlc_minimum_msat: 0,
4341 htlc_maximum_msat: 100_000,
4343 fee_proportional_millionths: 0,
4344 excess_data: Vec::new()
4347 // Path via {node0, node2} is channels {1, 3, 5}.
4348 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4349 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4350 short_channel_id: 1,
4353 cltv_expiry_delta: 0,
4354 htlc_minimum_msat: 0,
4355 htlc_maximum_msat: 100_000,
4357 fee_proportional_millionths: 0,
4358 excess_data: Vec::new()
4360 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4361 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4362 short_channel_id: 3,
4365 cltv_expiry_delta: 0,
4366 htlc_minimum_msat: 0,
4367 htlc_maximum_msat: 100_000,
4369 fee_proportional_millionths: 0,
4370 excess_data: Vec::new()
4373 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4374 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4375 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4376 short_channel_id: 5,
4379 cltv_expiry_delta: 0,
4380 htlc_minimum_msat: 0,
4381 htlc_maximum_msat: 100_000,
4383 fee_proportional_millionths: 0,
4384 excess_data: Vec::new()
4387 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4388 // All channels should be 100 sats capacity. But for the fee experiment,
4389 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
4390 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
4391 // 100 sats (and pay 150 sats in fees for the use of channel 6),
4392 // so no matter how large are other channels,
4393 // the whole path will be limited by 100 sats with just these 2 conditions:
4394 // - channel 12 capacity is 250 sats
4395 // - fee for channel 6 is 150 sats
4396 // Let's test this by enforcing these 2 conditions and removing other limits.
4397 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4398 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4399 short_channel_id: 12,
4402 cltv_expiry_delta: 0,
4403 htlc_minimum_msat: 0,
4404 htlc_maximum_msat: 250_000,
4406 fee_proportional_millionths: 0,
4407 excess_data: Vec::new()
4409 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4410 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4411 short_channel_id: 13,
4414 cltv_expiry_delta: 0,
4415 htlc_minimum_msat: 0,
4416 htlc_maximum_msat: MAX_VALUE_MSAT,
4418 fee_proportional_millionths: 0,
4419 excess_data: Vec::new()
4422 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4423 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4424 short_channel_id: 6,
4427 cltv_expiry_delta: 0,
4428 htlc_minimum_msat: 0,
4429 htlc_maximum_msat: MAX_VALUE_MSAT,
4430 fee_base_msat: 150_000,
4431 fee_proportional_millionths: 0,
4432 excess_data: Vec::new()
4434 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4435 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4436 short_channel_id: 11,
4439 cltv_expiry_delta: 0,
4440 htlc_minimum_msat: 0,
4441 htlc_maximum_msat: MAX_VALUE_MSAT,
4443 fee_proportional_millionths: 0,
4444 excess_data: Vec::new()
4448 // Attempt to route more than available results in a failure.
4449 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4450 &our_id, &payment_params, &network_graph.read_only(), None, 210_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
4451 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4452 } else { panic!(); }
4456 // Now, attempt to route 200 sats (exact amount we can route).
4457 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 200_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4458 assert_eq!(route.paths.len(), 2);
4460 let mut total_amount_paid_msat = 0;
4461 for path in &route.paths {
4462 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
4463 total_amount_paid_msat += path.last().unwrap().fee_msat;
4465 assert_eq!(total_amount_paid_msat, 200_000);
4466 assert_eq!(route.get_total_fees(), 150_000);
4471 fn mpp_with_last_hops() {
4472 // Previously, if we tried to send an MPP payment to a destination which was only reachable
4473 // via a single last-hop route hint, we'd fail to route if we first collected routes
4474 // totaling close but not quite enough to fund the full payment.
4476 // This was because we considered last-hop hints to have exactly the sought payment amount
4477 // instead of the amount we were trying to collect, needlessly limiting our path searching
4478 // at the very first hop.
4480 // Specifically, this interacted with our "all paths must fund at least 5% of total target"
4481 // criterion to cause us to refuse all routes at the last hop hint which would be considered
4482 // to only have the remaining to-collect amount in available liquidity.
4484 // This bug appeared in production in some specific channel configurations.
4485 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4486 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4487 let scorer = ln_test_utils::TestScorer::with_penalty(0);
4488 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4489 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4490 let config = UserConfig::default();
4491 let payment_params = PaymentParameters::from_node_id(PublicKey::from_slice(&[02; 33]).unwrap()).with_features(channelmanager::provided_invoice_features(&config))
4492 .with_route_hints(vec![RouteHint(vec![RouteHintHop {
4493 src_node_id: nodes[2],
4494 short_channel_id: 42,
4495 fees: RoutingFees { base_msat: 0, proportional_millionths: 0 },
4496 cltv_expiry_delta: 42,
4497 htlc_minimum_msat: None,
4498 htlc_maximum_msat: None,
4499 }])]).with_max_channel_saturation_power_of_half(0);
4501 // Keep only two paths from us to nodes[2], both with a 99sat HTLC maximum, with one with
4502 // no fee and one with a 1msat fee. Previously, trying to route 100 sats to nodes[2] here
4503 // would first use the no-fee route and then fail to find a path along the second route as
4504 // we think we can only send up to 1 additional sat over the last-hop but refuse to as its
4505 // under 5% of our payment amount.
4506 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4507 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4508 short_channel_id: 1,
4511 cltv_expiry_delta: (5 << 4) | 5,
4512 htlc_minimum_msat: 0,
4513 htlc_maximum_msat: 99_000,
4514 fee_base_msat: u32::max_value(),
4515 fee_proportional_millionths: u32::max_value(),
4516 excess_data: Vec::new()
4518 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4519 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4520 short_channel_id: 2,
4523 cltv_expiry_delta: (5 << 4) | 3,
4524 htlc_minimum_msat: 0,
4525 htlc_maximum_msat: 99_000,
4526 fee_base_msat: u32::max_value(),
4527 fee_proportional_millionths: u32::max_value(),
4528 excess_data: Vec::new()
4530 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4531 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4532 short_channel_id: 4,
4535 cltv_expiry_delta: (4 << 4) | 1,
4536 htlc_minimum_msat: 0,
4537 htlc_maximum_msat: MAX_VALUE_MSAT,
4539 fee_proportional_millionths: 0,
4540 excess_data: Vec::new()
4542 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4543 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4544 short_channel_id: 13,
4546 flags: 0|2, // Channel disabled
4547 cltv_expiry_delta: (13 << 4) | 1,
4548 htlc_minimum_msat: 0,
4549 htlc_maximum_msat: MAX_VALUE_MSAT,
4551 fee_proportional_millionths: 2000000,
4552 excess_data: Vec::new()
4555 // Get a route for 100 sats and check that we found the MPP route no problem and didn't
4557 let mut route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4558 assert_eq!(route.paths.len(), 2);
4559 route.paths.sort_by_key(|path| path[0].short_channel_id);
4560 // Paths are manually ordered ordered by SCID, so:
4561 // * the first is channel 1 (0 fee, but 99 sat maximum) -> channel 3 -> channel 42
4562 // * the second is channel 2 (1 msat fee) -> channel 4 -> channel 42
4563 assert_eq!(route.paths[0][0].short_channel_id, 1);
4564 assert_eq!(route.paths[0][0].fee_msat, 0);
4565 assert_eq!(route.paths[0][2].fee_msat, 99_000);
4566 assert_eq!(route.paths[1][0].short_channel_id, 2);
4567 assert_eq!(route.paths[1][0].fee_msat, 1);
4568 assert_eq!(route.paths[1][2].fee_msat, 1_000);
4569 assert_eq!(route.get_total_fees(), 1);
4570 assert_eq!(route.get_total_amount(), 100_000);
4574 fn drop_lowest_channel_mpp_route_test() {
4575 // This test checks that low-capacity channel is dropped when after
4576 // path finding we realize that we found more capacity than we need.
4577 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4578 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4579 let scorer = ln_test_utils::TestScorer::with_penalty(0);
4580 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4581 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4582 let config = UserConfig::default();
4583 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(channelmanager::provided_invoice_features(&config))
4584 .with_max_channel_saturation_power_of_half(0);
4586 // We need a route consisting of 3 paths:
4587 // From our node to node2 via node0, node7, node1 (three paths one hop each).
4589 // The first and the second paths should be sufficient, but the third should be
4590 // cheaper, so that we select it but drop later.
4592 // First, we set limits on these (previously unlimited) channels.
4593 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
4595 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
4596 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4597 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4598 short_channel_id: 1,
4601 cltv_expiry_delta: 0,
4602 htlc_minimum_msat: 0,
4603 htlc_maximum_msat: 100_000,
4605 fee_proportional_millionths: 0,
4606 excess_data: Vec::new()
4608 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4609 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4610 short_channel_id: 3,
4613 cltv_expiry_delta: 0,
4614 htlc_minimum_msat: 0,
4615 htlc_maximum_msat: 50_000,
4617 fee_proportional_millionths: 0,
4618 excess_data: Vec::new()
4621 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
4622 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4623 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4624 short_channel_id: 12,
4627 cltv_expiry_delta: 0,
4628 htlc_minimum_msat: 0,
4629 htlc_maximum_msat: 60_000,
4631 fee_proportional_millionths: 0,
4632 excess_data: Vec::new()
4634 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4635 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4636 short_channel_id: 13,
4639 cltv_expiry_delta: 0,
4640 htlc_minimum_msat: 0,
4641 htlc_maximum_msat: 60_000,
4643 fee_proportional_millionths: 0,
4644 excess_data: Vec::new()
4647 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
4648 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4649 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4650 short_channel_id: 2,
4653 cltv_expiry_delta: 0,
4654 htlc_minimum_msat: 0,
4655 htlc_maximum_msat: 20_000,
4657 fee_proportional_millionths: 0,
4658 excess_data: Vec::new()
4660 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4661 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4662 short_channel_id: 4,
4665 cltv_expiry_delta: 0,
4666 htlc_minimum_msat: 0,
4667 htlc_maximum_msat: 20_000,
4669 fee_proportional_millionths: 0,
4670 excess_data: Vec::new()
4674 // Attempt to route more than available results in a failure.
4675 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4676 &our_id, &payment_params, &network_graph.read_only(), None, 150_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
4677 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4678 } else { panic!(); }
4682 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
4683 // Our algorithm should provide us with these 3 paths.
4684 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 125_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4685 assert_eq!(route.paths.len(), 3);
4686 let mut total_amount_paid_msat = 0;
4687 for path in &route.paths {
4688 assert_eq!(path.len(), 2);
4689 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4690 total_amount_paid_msat += path.last().unwrap().fee_msat;
4692 assert_eq!(total_amount_paid_msat, 125_000);
4696 // Attempt to route without the last small cheap channel
4697 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4698 assert_eq!(route.paths.len(), 2);
4699 let mut total_amount_paid_msat = 0;
4700 for path in &route.paths {
4701 assert_eq!(path.len(), 2);
4702 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4703 total_amount_paid_msat += path.last().unwrap().fee_msat;
4705 assert_eq!(total_amount_paid_msat, 90_000);
4710 fn min_criteria_consistency() {
4711 // Test that we don't use an inconsistent metric between updating and walking nodes during
4712 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
4713 // was updated with a different criterion from the heap sorting, resulting in loops in
4714 // calculated paths. We test for that specific case here.
4716 // We construct a network that looks like this:
4718 // node2 -1(3)2- node3
4722 // node1 -1(5)2- node4 -1(1)2- node6
4728 // We create a loop on the side of our real path - our destination is node 6, with a
4729 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
4730 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
4731 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
4732 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
4733 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
4734 // "previous hop" being set to node 3, creating a loop in the path.
4735 let secp_ctx = Secp256k1::new();
4736 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
4737 let logger = Arc::new(ln_test_utils::TestLogger::new());
4738 let network = Arc::new(NetworkGraph::new(genesis_hash, Arc::clone(&logger)));
4739 let gossip_sync = P2PGossipSync::new(Arc::clone(&network), None, Arc::clone(&logger));
4740 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4741 let scorer = ln_test_utils::TestScorer::with_penalty(0);
4742 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4743 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4744 let payment_params = PaymentParameters::from_node_id(nodes[6]);
4746 add_channel(&gossip_sync, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
4747 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4748 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4749 short_channel_id: 6,
4752 cltv_expiry_delta: (6 << 4) | 0,
4753 htlc_minimum_msat: 0,
4754 htlc_maximum_msat: MAX_VALUE_MSAT,
4756 fee_proportional_millionths: 0,
4757 excess_data: Vec::new()
4759 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
4761 add_channel(&gossip_sync, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4762 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4763 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4764 short_channel_id: 5,
4767 cltv_expiry_delta: (5 << 4) | 0,
4768 htlc_minimum_msat: 0,
4769 htlc_maximum_msat: MAX_VALUE_MSAT,
4771 fee_proportional_millionths: 0,
4772 excess_data: Vec::new()
4774 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
4776 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
4777 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4778 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4779 short_channel_id: 4,
4782 cltv_expiry_delta: (4 << 4) | 0,
4783 htlc_minimum_msat: 0,
4784 htlc_maximum_msat: MAX_VALUE_MSAT,
4786 fee_proportional_millionths: 0,
4787 excess_data: Vec::new()
4789 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
4791 add_channel(&gossip_sync, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
4792 update_channel(&gossip_sync, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
4793 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4794 short_channel_id: 3,
4797 cltv_expiry_delta: (3 << 4) | 0,
4798 htlc_minimum_msat: 0,
4799 htlc_maximum_msat: MAX_VALUE_MSAT,
4801 fee_proportional_millionths: 0,
4802 excess_data: Vec::new()
4804 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
4806 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
4807 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4808 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4809 short_channel_id: 2,
4812 cltv_expiry_delta: (2 << 4) | 0,
4813 htlc_minimum_msat: 0,
4814 htlc_maximum_msat: MAX_VALUE_MSAT,
4816 fee_proportional_millionths: 0,
4817 excess_data: Vec::new()
4820 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
4821 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4822 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4823 short_channel_id: 1,
4826 cltv_expiry_delta: (1 << 4) | 0,
4827 htlc_minimum_msat: 100,
4828 htlc_maximum_msat: MAX_VALUE_MSAT,
4830 fee_proportional_millionths: 0,
4831 excess_data: Vec::new()
4833 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
4836 // Now ensure the route flows simply over nodes 1 and 4 to 6.
4837 let route = get_route(&our_id, &payment_params, &network.read_only(), None, 10_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4838 assert_eq!(route.paths.len(), 1);
4839 assert_eq!(route.paths[0].len(), 3);
4841 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
4842 assert_eq!(route.paths[0][0].short_channel_id, 6);
4843 assert_eq!(route.paths[0][0].fee_msat, 100);
4844 assert_eq!(route.paths[0][0].cltv_expiry_delta, (5 << 4) | 0);
4845 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(1));
4846 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(6));
4848 assert_eq!(route.paths[0][1].pubkey, nodes[4]);
4849 assert_eq!(route.paths[0][1].short_channel_id, 5);
4850 assert_eq!(route.paths[0][1].fee_msat, 0);
4851 assert_eq!(route.paths[0][1].cltv_expiry_delta, (1 << 4) | 0);
4852 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(4));
4853 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(5));
4855 assert_eq!(route.paths[0][2].pubkey, nodes[6]);
4856 assert_eq!(route.paths[0][2].short_channel_id, 1);
4857 assert_eq!(route.paths[0][2].fee_msat, 10_000);
4858 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
4859 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
4860 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(1));
4866 fn exact_fee_liquidity_limit() {
4867 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
4868 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
4869 // we calculated fees on a higher value, resulting in us ignoring such paths.
4870 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4871 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
4872 let scorer = ln_test_utils::TestScorer::with_penalty(0);
4873 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4874 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4875 let payment_params = PaymentParameters::from_node_id(nodes[2]);
4877 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
4879 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4880 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4881 short_channel_id: 2,
4884 cltv_expiry_delta: 0,
4885 htlc_minimum_msat: 0,
4886 htlc_maximum_msat: 85_000,
4888 fee_proportional_millionths: 0,
4889 excess_data: Vec::new()
4892 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4893 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4894 short_channel_id: 12,
4897 cltv_expiry_delta: (4 << 4) | 1,
4898 htlc_minimum_msat: 0,
4899 htlc_maximum_msat: 270_000,
4901 fee_proportional_millionths: 1000000,
4902 excess_data: Vec::new()
4906 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
4907 // 200% fee charged channel 13 in the 1-to-2 direction.
4908 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4909 assert_eq!(route.paths.len(), 1);
4910 assert_eq!(route.paths[0].len(), 2);
4912 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
4913 assert_eq!(route.paths[0][0].short_channel_id, 12);
4914 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
4915 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
4916 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
4917 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
4919 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
4920 assert_eq!(route.paths[0][1].short_channel_id, 13);
4921 assert_eq!(route.paths[0][1].fee_msat, 90_000);
4922 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
4923 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
4924 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
4929 fn htlc_max_reduction_below_min() {
4930 // Test that if, while walking the graph, we reduce the value being sent to meet an
4931 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
4932 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
4933 // resulting in us thinking there is no possible path, even if other paths exist.
4934 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4935 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4936 let scorer = ln_test_utils::TestScorer::with_penalty(0);
4937 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4938 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4939 let config = UserConfig::default();
4940 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(channelmanager::provided_invoice_features(&config));
4942 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
4943 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
4944 // then try to send 90_000.
4945 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4946 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4947 short_channel_id: 2,
4950 cltv_expiry_delta: 0,
4951 htlc_minimum_msat: 0,
4952 htlc_maximum_msat: 80_000,
4954 fee_proportional_millionths: 0,
4955 excess_data: Vec::new()
4957 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4958 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4959 short_channel_id: 4,
4962 cltv_expiry_delta: (4 << 4) | 1,
4963 htlc_minimum_msat: 90_000,
4964 htlc_maximum_msat: MAX_VALUE_MSAT,
4966 fee_proportional_millionths: 0,
4967 excess_data: Vec::new()
4971 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
4972 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
4973 // expensive) channels 12-13 path.
4974 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4975 assert_eq!(route.paths.len(), 1);
4976 assert_eq!(route.paths[0].len(), 2);
4978 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
4979 assert_eq!(route.paths[0][0].short_channel_id, 12);
4980 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
4981 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
4982 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
4983 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
4985 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
4986 assert_eq!(route.paths[0][1].short_channel_id, 13);
4987 assert_eq!(route.paths[0][1].fee_msat, 90_000);
4988 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
4989 assert_eq!(route.paths[0][1].node_features.le_flags(), channelmanager::provided_invoice_features(&config).le_flags());
4990 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
4995 fn multiple_direct_first_hops() {
4996 // Previously we'd only ever considered one first hop path per counterparty.
4997 // However, as we don't restrict users to one channel per peer, we really need to support
4998 // looking at all first hop paths.
4999 // Here we test that we do not ignore all-but-the-last first hop paths per counterparty (as
5000 // we used to do by overwriting the `first_hop_targets` hashmap entry) and that we can MPP
5001 // route over multiple channels with the same first hop.
5002 let secp_ctx = Secp256k1::new();
5003 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5004 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
5005 let logger = Arc::new(ln_test_utils::TestLogger::new());
5006 let network_graph = NetworkGraph::new(genesis_hash, Arc::clone(&logger));
5007 let scorer = ln_test_utils::TestScorer::with_penalty(0);
5008 let config = UserConfig::default();
5009 let payment_params = PaymentParameters::from_node_id(nodes[0]).with_features(channelmanager::provided_invoice_features(&config));
5010 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5011 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5014 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
5015 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 200_000),
5016 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 10_000),
5017 ]), 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5018 assert_eq!(route.paths.len(), 1);
5019 assert_eq!(route.paths[0].len(), 1);
5021 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
5022 assert_eq!(route.paths[0][0].short_channel_id, 3);
5023 assert_eq!(route.paths[0][0].fee_msat, 100_000);
5026 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
5027 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5028 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5029 ]), 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5030 assert_eq!(route.paths.len(), 2);
5031 assert_eq!(route.paths[0].len(), 1);
5032 assert_eq!(route.paths[1].len(), 1);
5034 assert!((route.paths[0][0].short_channel_id == 3 && route.paths[1][0].short_channel_id == 2) ||
5035 (route.paths[0][0].short_channel_id == 2 && route.paths[1][0].short_channel_id == 3));
5037 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
5038 assert_eq!(route.paths[0][0].fee_msat, 50_000);
5040 assert_eq!(route.paths[1][0].pubkey, nodes[0]);
5041 assert_eq!(route.paths[1][0].fee_msat, 50_000);
5045 // If we have a bunch of outbound channels to the same node, where most are not
5046 // sufficient to pay the full payment, but one is, we should default to just using the
5047 // one single channel that has sufficient balance, avoiding MPP.
5049 // If we have several options above the 3xpayment value threshold, we should pick the
5050 // smallest of them, avoiding further fragmenting our available outbound balance to
5052 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
5053 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5054 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5055 &get_channel_details(Some(5), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5056 &get_channel_details(Some(6), nodes[0], channelmanager::provided_init_features(&config), 300_000),
5057 &get_channel_details(Some(7), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5058 &get_channel_details(Some(8), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5059 &get_channel_details(Some(9), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5060 &get_channel_details(Some(4), nodes[0], channelmanager::provided_init_features(&config), 1_000_000),
5061 ]), 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5062 assert_eq!(route.paths.len(), 1);
5063 assert_eq!(route.paths[0].len(), 1);
5065 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
5066 assert_eq!(route.paths[0][0].short_channel_id, 6);
5067 assert_eq!(route.paths[0][0].fee_msat, 100_000);
5072 fn prefers_shorter_route_with_higher_fees() {
5073 let (secp_ctx, network_graph, _, _, logger) = build_graph();
5074 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5075 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
5077 // Without penalizing each hop 100 msats, a longer path with lower fees is chosen.
5078 let scorer = ln_test_utils::TestScorer::with_penalty(0);
5079 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5080 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5081 let route = get_route(
5082 &our_id, &payment_params, &network_graph.read_only(), None, 100, 42,
5083 Arc::clone(&logger), &scorer, &random_seed_bytes
5085 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5087 assert_eq!(route.get_total_fees(), 100);
5088 assert_eq!(route.get_total_amount(), 100);
5089 assert_eq!(path, vec![2, 4, 6, 11, 8]);
5091 // Applying a 100 msat penalty to each hop results in taking channels 7 and 10 to nodes[6]
5092 // from nodes[2] rather than channel 6, 11, and 8, even though the longer path is cheaper.
5093 let scorer = ln_test_utils::TestScorer::with_penalty(100);
5094 let route = get_route(
5095 &our_id, &payment_params, &network_graph.read_only(), None, 100, 42,
5096 Arc::clone(&logger), &scorer, &random_seed_bytes
5098 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5100 assert_eq!(route.get_total_fees(), 300);
5101 assert_eq!(route.get_total_amount(), 100);
5102 assert_eq!(path, vec![2, 4, 7, 10]);
5105 struct BadChannelScorer {
5106 short_channel_id: u64,
5110 impl Writeable for BadChannelScorer {
5111 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
5113 impl Score for BadChannelScorer {
5114 fn channel_penalty_msat(&self, short_channel_id: u64, _: &NodeId, _: &NodeId, _: ChannelUsage) -> u64 {
5115 if short_channel_id == self.short_channel_id { u64::max_value() } else { 0 }
5118 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
5119 fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
5120 fn probe_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
5121 fn probe_successful(&mut self, _path: &[&RouteHop]) {}
5124 struct BadNodeScorer {
5129 impl Writeable for BadNodeScorer {
5130 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
5133 impl Score for BadNodeScorer {
5134 fn channel_penalty_msat(&self, _: u64, _: &NodeId, target: &NodeId, _: ChannelUsage) -> u64 {
5135 if *target == self.node_id { u64::max_value() } else { 0 }
5138 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
5139 fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
5140 fn probe_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
5141 fn probe_successful(&mut self, _path: &[&RouteHop]) {}
5145 fn avoids_routing_through_bad_channels_and_nodes() {
5146 let (secp_ctx, network, _, _, logger) = build_graph();
5147 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5148 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
5149 let network_graph = network.read_only();
5151 // A path to nodes[6] exists when no penalties are applied to any channel.
5152 let scorer = ln_test_utils::TestScorer::with_penalty(0);
5153 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5154 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5155 let route = get_route(
5156 &our_id, &payment_params, &network_graph, None, 100, 42,
5157 Arc::clone(&logger), &scorer, &random_seed_bytes
5159 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5161 assert_eq!(route.get_total_fees(), 100);
5162 assert_eq!(route.get_total_amount(), 100);
5163 assert_eq!(path, vec![2, 4, 6, 11, 8]);
5165 // A different path to nodes[6] exists if channel 6 cannot be routed over.
5166 let scorer = BadChannelScorer { short_channel_id: 6 };
5167 let route = get_route(
5168 &our_id, &payment_params, &network_graph, None, 100, 42,
5169 Arc::clone(&logger), &scorer, &random_seed_bytes
5171 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5173 assert_eq!(route.get_total_fees(), 300);
5174 assert_eq!(route.get_total_amount(), 100);
5175 assert_eq!(path, vec![2, 4, 7, 10]);
5177 // A path to nodes[6] does not exist if nodes[2] cannot be routed through.
5178 let scorer = BadNodeScorer { node_id: NodeId::from_pubkey(&nodes[2]) };
5180 &our_id, &payment_params, &network_graph, None, 100, 42,
5181 Arc::clone(&logger), &scorer, &random_seed_bytes
5183 Err(LightningError { err, .. } ) => {
5184 assert_eq!(err, "Failed to find a path to the given destination");
5186 Ok(_) => panic!("Expected error"),
5191 fn total_fees_single_path() {
5195 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5196 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5197 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5200 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5201 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5202 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5205 pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
5206 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5207 short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0
5210 payment_params: None,
5213 assert_eq!(route.get_total_fees(), 250);
5214 assert_eq!(route.get_total_amount(), 225);
5218 fn total_fees_multi_path() {
5222 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5223 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5224 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5227 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5228 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5229 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5233 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5234 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5235 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5238 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5239 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5240 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5243 payment_params: None,
5246 assert_eq!(route.get_total_fees(), 200);
5247 assert_eq!(route.get_total_amount(), 300);
5251 fn total_empty_route_no_panic() {
5252 // In an earlier version of `Route::get_total_fees` and `Route::get_total_amount`, they
5253 // would both panic if the route was completely empty. We test to ensure they return 0
5254 // here, even though its somewhat nonsensical as a route.
5255 let route = Route { paths: Vec::new(), payment_params: None };
5257 assert_eq!(route.get_total_fees(), 0);
5258 assert_eq!(route.get_total_amount(), 0);
5262 fn limits_total_cltv_delta() {
5263 let (secp_ctx, network, _, _, logger) = build_graph();
5264 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5265 let network_graph = network.read_only();
5267 let scorer = ln_test_utils::TestScorer::with_penalty(0);
5269 // Make sure that generally there is at least one route available
5270 let feasible_max_total_cltv_delta = 1008;
5271 let feasible_payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes))
5272 .with_max_total_cltv_expiry_delta(feasible_max_total_cltv_delta);
5273 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5274 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5275 let route = get_route(&our_id, &feasible_payment_params, &network_graph, None, 100, 0, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5276 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5277 assert_ne!(path.len(), 0);
5279 // But not if we exclude all paths on the basis of their accumulated CLTV delta
5280 let fail_max_total_cltv_delta = 23;
5281 let fail_payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes))
5282 .with_max_total_cltv_expiry_delta(fail_max_total_cltv_delta);
5283 match get_route(&our_id, &fail_payment_params, &network_graph, None, 100, 0, Arc::clone(&logger), &scorer, &random_seed_bytes)
5285 Err(LightningError { err, .. } ) => {
5286 assert_eq!(err, "Failed to find a path to the given destination");
5288 Ok(_) => panic!("Expected error"),
5293 fn avoids_recently_failed_paths() {
5294 // Ensure that the router always avoids all of the `previously_failed_channels` channels by
5295 // randomly inserting channels into it until we can't find a route anymore.
5296 let (secp_ctx, network, _, _, logger) = build_graph();
5297 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5298 let network_graph = network.read_only();
5300 let scorer = ln_test_utils::TestScorer::with_penalty(0);
5301 let mut payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes))
5302 .with_max_path_count(1);
5303 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5304 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5306 // We should be able to find a route initially, and then after we fail a few random
5307 // channels eventually we won't be able to any longer.
5308 assert!(get_route(&our_id, &payment_params, &network_graph, None, 100, 0, Arc::clone(&logger), &scorer, &random_seed_bytes).is_ok());
5310 if let Ok(route) = get_route(&our_id, &payment_params, &network_graph, None, 100, 0, Arc::clone(&logger), &scorer, &random_seed_bytes) {
5311 for chan in route.paths[0].iter() {
5312 assert!(!payment_params.previously_failed_channels.contains(&chan.short_channel_id));
5314 let victim = (u64::from_ne_bytes(random_seed_bytes[0..8].try_into().unwrap()) as usize)
5315 % route.paths[0].len();
5316 payment_params.previously_failed_channels.push(route.paths[0][victim].short_channel_id);
5322 fn limits_path_length() {
5323 let (secp_ctx, network, _, _, logger) = build_line_graph();
5324 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5325 let network_graph = network.read_only();
5327 let scorer = ln_test_utils::TestScorer::with_penalty(0);
5328 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5329 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5331 // First check we can actually create a long route on this graph.
5332 let feasible_payment_params = PaymentParameters::from_node_id(nodes[18]);
5333 let route = get_route(&our_id, &feasible_payment_params, &network_graph, None, 100, 0,
5334 Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5335 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5336 assert!(path.len() == MAX_PATH_LENGTH_ESTIMATE.into());
5338 // But we can't create a path surpassing the MAX_PATH_LENGTH_ESTIMATE limit.
5339 let fail_payment_params = PaymentParameters::from_node_id(nodes[19]);
5340 match get_route(&our_id, &fail_payment_params, &network_graph, None, 100, 0,
5341 Arc::clone(&logger), &scorer, &random_seed_bytes)
5343 Err(LightningError { err, .. } ) => {
5344 assert_eq!(err, "Failed to find a path to the given destination");
5346 Ok(_) => panic!("Expected error"),
5351 fn adds_and_limits_cltv_offset() {
5352 let (secp_ctx, network_graph, _, _, logger) = build_graph();
5353 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5355 let scorer = ln_test_utils::TestScorer::with_penalty(0);
5357 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
5358 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5359 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5360 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5361 assert_eq!(route.paths.len(), 1);
5363 let cltv_expiry_deltas_before = route.paths[0].iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5365 // Check whether the offset added to the last hop by default is in [1 .. DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA]
5366 let mut route_default = route.clone();
5367 add_random_cltv_offset(&mut route_default, &payment_params, &network_graph.read_only(), &random_seed_bytes);
5368 let cltv_expiry_deltas_default = route_default.paths[0].iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5369 assert_eq!(cltv_expiry_deltas_before.split_last().unwrap().1, cltv_expiry_deltas_default.split_last().unwrap().1);
5370 assert!(cltv_expiry_deltas_default.last() > cltv_expiry_deltas_before.last());
5371 assert!(cltv_expiry_deltas_default.last().unwrap() <= &DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA);
5373 // Check that no offset is added when we restrict the max_total_cltv_expiry_delta
5374 let mut route_limited = route.clone();
5375 let limited_max_total_cltv_expiry_delta = cltv_expiry_deltas_before.iter().sum();
5376 let limited_payment_params = payment_params.with_max_total_cltv_expiry_delta(limited_max_total_cltv_expiry_delta);
5377 add_random_cltv_offset(&mut route_limited, &limited_payment_params, &network_graph.read_only(), &random_seed_bytes);
5378 let cltv_expiry_deltas_limited = route_limited.paths[0].iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5379 assert_eq!(cltv_expiry_deltas_before, cltv_expiry_deltas_limited);
5383 fn adds_plausible_cltv_offset() {
5384 let (secp_ctx, network, _, _, logger) = build_graph();
5385 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5386 let network_graph = network.read_only();
5387 let network_nodes = network_graph.nodes();
5388 let network_channels = network_graph.channels();
5389 let scorer = ln_test_utils::TestScorer::with_penalty(0);
5390 let payment_params = PaymentParameters::from_node_id(nodes[3]);
5391 let keys_manager = ln_test_utils::TestKeysInterface::new(&[4u8; 32], Network::Testnet);
5392 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5394 let mut route = get_route(&our_id, &payment_params, &network_graph, None, 100, 0,
5395 Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5396 add_random_cltv_offset(&mut route, &payment_params, &network_graph, &random_seed_bytes);
5398 let mut path_plausibility = vec![];
5400 for p in route.paths {
5401 // 1. Select random observation point
5402 let mut prng = ChaCha20::new(&random_seed_bytes, &[0u8; 12]);
5403 let mut random_bytes = [0u8; ::core::mem::size_of::<usize>()];
5405 prng.process_in_place(&mut random_bytes);
5406 let random_path_index = usize::from_be_bytes(random_bytes).wrapping_rem(p.len());
5407 let observation_point = NodeId::from_pubkey(&p.get(random_path_index).unwrap().pubkey);
5409 // 2. Calculate what CLTV expiry delta we would observe there
5410 let observed_cltv_expiry_delta: u32 = p[random_path_index..].iter().map(|h| h.cltv_expiry_delta).sum();
5412 // 3. Starting from the observation point, find candidate paths
5413 let mut candidates: VecDeque<(NodeId, Vec<u32>)> = VecDeque::new();
5414 candidates.push_back((observation_point, vec![]));
5416 let mut found_plausible_candidate = false;
5418 'candidate_loop: while let Some((cur_node_id, cur_path_cltv_deltas)) = candidates.pop_front() {
5419 if let Some(remaining) = observed_cltv_expiry_delta.checked_sub(cur_path_cltv_deltas.iter().sum::<u32>()) {
5420 if remaining == 0 || remaining.wrapping_rem(40) == 0 || remaining.wrapping_rem(144) == 0 {
5421 found_plausible_candidate = true;
5422 break 'candidate_loop;
5426 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
5427 for channel_id in &cur_node.channels {
5428 if let Some(channel_info) = network_channels.get(&channel_id) {
5429 if let Some((dir_info, next_id)) = channel_info.as_directed_from(&cur_node_id) {
5430 let next_cltv_expiry_delta = dir_info.direction().cltv_expiry_delta as u32;
5431 if cur_path_cltv_deltas.iter().sum::<u32>()
5432 .saturating_add(next_cltv_expiry_delta) <= observed_cltv_expiry_delta {
5433 let mut new_path_cltv_deltas = cur_path_cltv_deltas.clone();
5434 new_path_cltv_deltas.push(next_cltv_expiry_delta);
5435 candidates.push_back((*next_id, new_path_cltv_deltas));
5443 path_plausibility.push(found_plausible_candidate);
5445 assert!(path_plausibility.iter().all(|x| *x));
5449 fn builds_correct_path_from_hops() {
5450 let (secp_ctx, network, _, _, logger) = build_graph();
5451 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5452 let network_graph = network.read_only();
5454 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5455 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5457 let payment_params = PaymentParameters::from_node_id(nodes[3]);
5458 let hops = [nodes[1], nodes[2], nodes[4], nodes[3]];
5459 let route = build_route_from_hops_internal(&our_id, &hops, &payment_params,
5460 &network_graph, 100, 0, Arc::clone(&logger), &random_seed_bytes).unwrap();
5461 let route_hop_pubkeys = route.paths[0].iter().map(|hop| hop.pubkey).collect::<Vec<_>>();
5462 assert_eq!(hops.len(), route.paths[0].len());
5463 for (idx, hop_pubkey) in hops.iter().enumerate() {
5464 assert!(*hop_pubkey == route_hop_pubkeys[idx]);
5469 fn avoids_saturating_channels() {
5470 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5471 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5473 let scorer = ProbabilisticScorer::new(Default::default(), &*network_graph, Arc::clone(&logger));
5475 // Set the fee on channel 13 to 100% to match channel 4 giving us two equivalent paths (us
5476 // -> node 7 -> node2 and us -> node 1 -> node 2) which we should balance over.
5477 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5478 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5479 short_channel_id: 4,
5482 cltv_expiry_delta: (4 << 4) | 1,
5483 htlc_minimum_msat: 0,
5484 htlc_maximum_msat: 250_000_000,
5486 fee_proportional_millionths: 0,
5487 excess_data: Vec::new()
5489 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5490 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5491 short_channel_id: 13,
5494 cltv_expiry_delta: (13 << 4) | 1,
5495 htlc_minimum_msat: 0,
5496 htlc_maximum_msat: 250_000_000,
5498 fee_proportional_millionths: 0,
5499 excess_data: Vec::new()
5502 let config = UserConfig::default();
5503 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(channelmanager::provided_invoice_features(&config));
5504 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5505 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5506 // 100,000 sats is less than the available liquidity on each channel, set above.
5507 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100_000_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5508 assert_eq!(route.paths.len(), 2);
5509 assert!((route.paths[0][1].short_channel_id == 4 && route.paths[1][1].short_channel_id == 13) ||
5510 (route.paths[1][1].short_channel_id == 4 && route.paths[0][1].short_channel_id == 13));
5513 #[cfg(not(feature = "no-std"))]
5514 pub(super) fn random_init_seed() -> u64 {
5515 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
5516 use core::hash::{BuildHasher, Hasher};
5517 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
5518 println!("Using seed of {}", seed);
5521 #[cfg(not(feature = "no-std"))]
5522 use crate::util::ser::ReadableArgs;
5525 #[cfg(not(feature = "no-std"))]
5526 fn generate_routes() {
5527 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringParameters};
5529 let mut d = match super::bench_utils::get_route_file() {
5536 let logger = ln_test_utils::TestLogger::new();
5537 let graph = NetworkGraph::read(&mut d, &logger).unwrap();
5538 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5539 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5541 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
5542 let mut seed = random_init_seed() as usize;
5543 let nodes = graph.read_only().nodes().clone();
5544 'load_endpoints: for _ in 0..10 {
5546 seed = seed.overflowing_mul(0xdeadbeef).0;
5547 let src = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5548 seed = seed.overflowing_mul(0xdeadbeef).0;
5549 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5550 let payment_params = PaymentParameters::from_node_id(dst);
5551 let amt = seed as u64 % 200_000_000;
5552 let params = ProbabilisticScoringParameters::default();
5553 let scorer = ProbabilisticScorer::new(params, &graph, &logger);
5554 if get_route(src, &payment_params, &graph.read_only(), None, amt, 42, &logger, &scorer, &random_seed_bytes).is_ok() {
5555 continue 'load_endpoints;
5562 #[cfg(not(feature = "no-std"))]
5563 fn generate_routes_mpp() {
5564 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringParameters};
5566 let mut d = match super::bench_utils::get_route_file() {
5573 let logger = ln_test_utils::TestLogger::new();
5574 let graph = NetworkGraph::read(&mut d, &logger).unwrap();
5575 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5576 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5577 let config = UserConfig::default();
5579 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
5580 let mut seed = random_init_seed() as usize;
5581 let nodes = graph.read_only().nodes().clone();
5582 'load_endpoints: for _ in 0..10 {
5584 seed = seed.overflowing_mul(0xdeadbeef).0;
5585 let src = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5586 seed = seed.overflowing_mul(0xdeadbeef).0;
5587 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5588 let payment_params = PaymentParameters::from_node_id(dst).with_features(channelmanager::provided_invoice_features(&config));
5589 let amt = seed as u64 % 200_000_000;
5590 let params = ProbabilisticScoringParameters::default();
5591 let scorer = ProbabilisticScorer::new(params, &graph, &logger);
5592 if get_route(src, &payment_params, &graph.read_only(), None, amt, 42, &logger, &scorer, &random_seed_bytes).is_ok() {
5593 continue 'load_endpoints;
5600 fn honors_manual_penalties() {
5601 let (secp_ctx, network_graph, _, _, logger) = build_line_graph();
5602 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5604 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5605 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5607 let scorer_params = ProbabilisticScoringParameters::default();
5608 let mut scorer = ProbabilisticScorer::new(scorer_params, Arc::clone(&network_graph), Arc::clone(&logger));
5610 // First check set manual penalties are returned by the scorer.
5611 let usage = ChannelUsage {
5613 inflight_htlc_msat: 0,
5614 effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_024_000, htlc_maximum_msat: 1_000 },
5616 scorer.set_manual_penalty(&NodeId::from_pubkey(&nodes[3]), 123);
5617 scorer.set_manual_penalty(&NodeId::from_pubkey(&nodes[4]), 456);
5618 assert_eq!(scorer.channel_penalty_msat(42, &NodeId::from_pubkey(&nodes[3]), &NodeId::from_pubkey(&nodes[4]), usage), 456);
5620 // Then check we can get a normal route
5621 let payment_params = PaymentParameters::from_node_id(nodes[10]);
5622 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes);
5623 assert!(route.is_ok());
5625 // Then check that we can't get a route if we ban an intermediate node.
5626 scorer.add_banned(&NodeId::from_pubkey(&nodes[3]));
5627 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes);
5628 assert!(route.is_err());
5630 // Finally make sure we can route again, when we remove the ban.
5631 scorer.remove_banned(&NodeId::from_pubkey(&nodes[3]));
5632 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes);
5633 assert!(route.is_ok());
5637 #[cfg(all(test, not(feature = "no-std")))]
5638 pub(crate) mod bench_utils {
5640 /// Tries to open a network graph file, or panics with a URL to fetch it.
5641 pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
5642 let res = File::open("net_graph-2021-05-31.bin") // By default we're run in RL/lightning
5643 .or_else(|_| File::open("lightning/net_graph-2021-05-31.bin")) // We may be run manually in RL/
5644 .or_else(|_| { // Fall back to guessing based on the binary location
5645 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
5646 let mut path = std::env::current_exe().unwrap();
5647 path.pop(); // lightning-...
5649 path.pop(); // debug
5650 path.pop(); // target
5651 path.push("lightning");
5652 path.push("net_graph-2021-05-31.bin");
5653 eprintln!("{}", path.to_str().unwrap());
5656 .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");
5657 #[cfg(require_route_graph_test)]
5658 return Ok(res.unwrap());
5659 #[cfg(not(require_route_graph_test))]
5664 #[cfg(all(test, feature = "_bench_unstable", not(feature = "no-std")))]
5667 use bitcoin::hashes::Hash;
5668 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
5669 use crate::chain::transaction::OutPoint;
5670 use crate::chain::keysinterface::{EntropySource, KeysManager};
5671 use crate::ln::channelmanager::{self, ChannelCounterparty, ChannelDetails};
5672 use crate::ln::features::InvoiceFeatures;
5673 use crate::routing::gossip::NetworkGraph;
5674 use crate::routing::scoring::{FixedPenaltyScorer, ProbabilisticScorer, ProbabilisticScoringParameters};
5675 use crate::util::config::UserConfig;
5676 use crate::util::logger::{Logger, Record};
5677 use crate::util::ser::ReadableArgs;
5681 struct DummyLogger {}
5682 impl Logger for DummyLogger {
5683 fn log(&self, _record: &Record) {}
5686 fn read_network_graph(logger: &DummyLogger) -> NetworkGraph<&DummyLogger> {
5687 let mut d = bench_utils::get_route_file().unwrap();
5688 NetworkGraph::read(&mut d, logger).unwrap()
5691 fn payer_pubkey() -> PublicKey {
5692 let secp_ctx = Secp256k1::new();
5693 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
5697 fn first_hop(node_id: PublicKey) -> ChannelDetails {
5699 channel_id: [0; 32],
5700 counterparty: ChannelCounterparty {
5701 features: channelmanager::provided_init_features(&UserConfig::default()),
5703 unspendable_punishment_reserve: 0,
5704 forwarding_info: None,
5705 outbound_htlc_minimum_msat: None,
5706 outbound_htlc_maximum_msat: None,
5708 funding_txo: Some(OutPoint {
5709 txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0
5712 short_channel_id: Some(1),
5713 inbound_scid_alias: None,
5714 outbound_scid_alias: None,
5715 channel_value_satoshis: 10_000_000,
5717 balance_msat: 10_000_000,
5718 outbound_capacity_msat: 10_000_000,
5719 next_outbound_htlc_limit_msat: 10_000_000,
5720 inbound_capacity_msat: 0,
5721 unspendable_punishment_reserve: None,
5722 confirmations_required: None,
5723 confirmations: None,
5724 force_close_spend_delay: None,
5726 is_channel_ready: true,
5729 inbound_htlc_minimum_msat: None,
5730 inbound_htlc_maximum_msat: None,
5736 fn generate_routes_with_zero_penalty_scorer(bench: &mut Bencher) {
5737 let logger = DummyLogger {};
5738 let network_graph = read_network_graph(&logger);
5739 let scorer = FixedPenaltyScorer::with_penalty(0);
5740 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::empty());
5744 fn generate_mpp_routes_with_zero_penalty_scorer(bench: &mut Bencher) {
5745 let logger = DummyLogger {};
5746 let network_graph = read_network_graph(&logger);
5747 let scorer = FixedPenaltyScorer::with_penalty(0);
5748 generate_routes(bench, &network_graph, scorer, channelmanager::provided_invoice_features(&UserConfig::default()));
5752 fn generate_routes_with_probabilistic_scorer(bench: &mut Bencher) {
5753 let logger = DummyLogger {};
5754 let network_graph = read_network_graph(&logger);
5755 let params = ProbabilisticScoringParameters::default();
5756 let scorer = ProbabilisticScorer::new(params, &network_graph, &logger);
5757 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::empty());
5761 fn generate_mpp_routes_with_probabilistic_scorer(bench: &mut Bencher) {
5762 let logger = DummyLogger {};
5763 let network_graph = read_network_graph(&logger);
5764 let params = ProbabilisticScoringParameters::default();
5765 let scorer = ProbabilisticScorer::new(params, &network_graph, &logger);
5766 generate_routes(bench, &network_graph, scorer, channelmanager::provided_invoice_features(&UserConfig::default()));
5769 fn generate_routes<S: Score>(
5770 bench: &mut Bencher, graph: &NetworkGraph<&DummyLogger>, mut scorer: S,
5771 features: InvoiceFeatures
5773 let nodes = graph.read_only().nodes().clone();
5774 let payer = payer_pubkey();
5775 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
5776 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5778 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
5779 let mut routes = Vec::new();
5780 let mut route_endpoints = Vec::new();
5781 let mut seed: usize = 0xdeadbeef;
5782 'load_endpoints: for _ in 0..150 {
5785 let src = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5787 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5788 let params = PaymentParameters::from_node_id(dst).with_features(features.clone());
5789 let first_hop = first_hop(src);
5790 let amt = seed as u64 % 1_000_000;
5791 if let Ok(route) = get_route(&payer, ¶ms, &graph.read_only(), Some(&[&first_hop]), amt, 42, &DummyLogger{}, &scorer, &random_seed_bytes) {
5793 route_endpoints.push((first_hop, params, amt));
5794 continue 'load_endpoints;
5799 // ...and seed the scorer with success and failure data...
5800 for route in routes {
5801 let amount = route.get_total_amount();
5802 if amount < 250_000 {
5803 for path in route.paths {
5804 scorer.payment_path_successful(&path.iter().collect::<Vec<_>>());
5806 } else if amount > 750_000 {
5807 for path in route.paths {
5808 let short_channel_id = path[path.len() / 2].short_channel_id;
5809 scorer.payment_path_failed(&path.iter().collect::<Vec<_>>(), short_channel_id);
5814 // Because we've changed channel scores, its possible we'll take different routes to the
5815 // selected destinations, possibly causing us to fail because, eg, the newly-selected path
5816 // requires a too-high CLTV delta.
5817 route_endpoints.retain(|(first_hop, params, amt)| {
5818 get_route(&payer, params, &graph.read_only(), Some(&[first_hop]), *amt, 42, &DummyLogger{}, &scorer, &random_seed_bytes).is_ok()
5820 route_endpoints.truncate(100);
5821 assert_eq!(route_endpoints.len(), 100);
5823 // ...then benchmark finding paths between the nodes we learned.
5826 let (first_hop, params, amt) = &route_endpoints[idx % route_endpoints.len()];
5827 assert!(get_route(&payer, params, &graph.read_only(), Some(&[first_hop]), *amt, 42, &DummyLogger{}, &scorer, &random_seed_bytes).is_ok());