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(&mut 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: InFlightHtlcs,
134 impl<'a, S: Score> ScorerAccountingForInFlightHtlcs<'a, S> {
135 /// Initialize a new `ScorerAccountingForInFlightHtlcs`.
136 pub fn new(scorer: &'a mut S, inflight_htlcs: 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.
184 pub struct InFlightHtlcs(
185 // A map with liquidity value (in msat) keyed by a short channel id and the direction the HTLC
186 // is traveling in. The direction boolean is determined by checking if the HTLC source's public
187 // key is less than its destination. See `InFlightHtlcs::used_liquidity_msat` for more
189 HashMap<(u64, bool), u64>
193 /// Constructs an empty `InFlightHtlcs`.
194 pub fn new() -> Self { InFlightHtlcs(HashMap::new()) }
196 /// Takes in a path with payer's node id and adds the path's details to `InFlightHtlcs`.
197 pub fn process_path(&mut self, path: &[RouteHop], payer_node_id: PublicKey) {
198 if path.is_empty() { return };
199 // total_inflight_map needs to be direction-sensitive when keeping track of the HTLC value
200 // that is held up. However, the `hops` array, which is a path returned by `find_route` in
201 // the router excludes the payer node. In the following lines, the payer's information is
202 // hardcoded with an inflight value of 0 so that we can correctly represent the first hop
203 // in our sliding window of two.
204 let reversed_hops_with_payer = path.iter().rev().skip(1)
205 .map(|hop| hop.pubkey)
206 .chain(core::iter::once(payer_node_id));
207 let mut cumulative_msat = 0;
209 // Taking the reversed vector from above, we zip it with just the reversed hops list to
210 // work "backwards" of the given path, since the last hop's `fee_msat` actually represents
211 // the total amount sent.
212 for (next_hop, prev_hop) in path.iter().rev().zip(reversed_hops_with_payer) {
213 cumulative_msat += next_hop.fee_msat;
215 .entry((next_hop.short_channel_id, NodeId::from_pubkey(&prev_hop) < NodeId::from_pubkey(&next_hop.pubkey)))
216 .and_modify(|used_liquidity_msat| *used_liquidity_msat += cumulative_msat)
217 .or_insert(cumulative_msat);
221 /// Adds a known HTLC given the public key of the HTLC source, target, and short channel
223 pub fn add_inflight_htlc(&mut self, source: &NodeId, target: &NodeId, channel_scid: u64, used_msat: u64){
225 .entry((channel_scid, source < target))
226 .and_modify(|used_liquidity_msat| *used_liquidity_msat += used_msat)
227 .or_insert(used_msat);
230 /// Returns liquidity in msat given the public key of the HTLC source, target, and short channel
232 pub fn used_liquidity_msat(&self, source: &NodeId, target: &NodeId, channel_scid: u64) -> Option<u64> {
233 self.0.get(&(channel_scid, source < target)).map(|v| *v)
237 impl Writeable for InFlightHtlcs {
238 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> { self.0.write(writer) }
241 impl Readable for InFlightHtlcs {
242 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
243 let infight_map: HashMap<(u64, bool), u64> = Readable::read(reader)?;
244 Ok(Self(infight_map))
249 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
250 pub struct RouteHop {
251 /// The node_id of the node at this hop.
252 pub pubkey: PublicKey,
253 /// The node_announcement features of the node at this hop. For the last hop, these may be
254 /// amended to match the features present in the invoice this node generated.
255 pub node_features: NodeFeatures,
256 /// The channel that should be used from the previous hop to reach this node.
257 pub short_channel_id: u64,
258 /// The channel_announcement features of the channel that should be used from the previous hop
259 /// to reach this node.
260 pub channel_features: ChannelFeatures,
261 /// The fee taken on this hop (for paying for the use of the *next* channel in the path).
262 /// For the last hop, this should be the full value of the payment (might be more than
263 /// requested if we had to match htlc_minimum_msat).
265 /// The CLTV delta added for this hop. For the last hop, this should be the full CLTV value
266 /// expected at the destination, in excess of the current block height.
267 pub cltv_expiry_delta: u32,
270 impl_writeable_tlv_based!(RouteHop, {
271 (0, pubkey, required),
272 (2, node_features, required),
273 (4, short_channel_id, required),
274 (6, channel_features, required),
275 (8, fee_msat, required),
276 (10, cltv_expiry_delta, required),
279 /// A route directs a payment from the sender (us) to the recipient. If the recipient supports MPP,
280 /// it can take multiple paths. Each path is composed of one or more hops through the network.
281 #[derive(Clone, Hash, PartialEq, Eq)]
283 /// The list of routes taken for a single (potentially-)multi-part payment. The pubkey of the
284 /// last RouteHop in each path must be the same. Each entry represents a list of hops, NOT
285 /// INCLUDING our own, where the last hop is the destination. Thus, this must always be at
286 /// least length one. While the maximum length of any given path is variable, keeping the length
287 /// of any path less or equal to 19 should currently ensure it is viable.
288 pub paths: Vec<Vec<RouteHop>>,
289 /// The `payment_params` parameter passed to [`find_route`].
290 /// This is used by `ChannelManager` to track information which may be required for retries,
291 /// provided back to you via [`Event::PaymentPathFailed`].
293 /// [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed
294 pub payment_params: Option<PaymentParameters>,
297 pub(crate) trait RoutePath {
298 /// Gets the fees for a given path, excluding any excess paid to the recipient.
299 fn get_path_fees(&self) -> u64;
301 impl RoutePath for Vec<RouteHop> {
302 fn get_path_fees(&self) -> u64 {
303 // Do not count last hop of each path since that's the full value of the payment
304 self.split_last().map(|(_, path_prefix)| path_prefix).unwrap_or(&[])
305 .iter().map(|hop| &hop.fee_msat)
311 /// Returns the total amount of fees paid on this [`Route`].
313 /// This doesn't include any extra payment made to the recipient, which can happen in excess of
314 /// the amount passed to [`find_route`]'s `params.final_value_msat`.
315 pub fn get_total_fees(&self) -> u64 {
316 self.paths.iter().map(|path| path.get_path_fees()).sum()
319 /// Returns the total amount paid on this [`Route`], excluding the fees.
320 pub fn get_total_amount(&self) -> u64 {
321 return self.paths.iter()
322 .map(|path| path.split_last().map(|(hop, _)| hop.fee_msat).unwrap_or(0))
327 const SERIALIZATION_VERSION: u8 = 1;
328 const MIN_SERIALIZATION_VERSION: u8 = 1;
330 impl Writeable for Route {
331 fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
332 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
333 (self.paths.len() as u64).write(writer)?;
334 for hops in self.paths.iter() {
335 (hops.len() as u8).write(writer)?;
336 for hop in hops.iter() {
340 write_tlv_fields!(writer, {
341 (1, self.payment_params, option),
347 impl Readable for Route {
348 fn read<R: io::Read>(reader: &mut R) -> Result<Route, DecodeError> {
349 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
350 let path_count: u64 = Readable::read(reader)?;
351 let mut paths = Vec::with_capacity(cmp::min(path_count, 128) as usize);
352 for _ in 0..path_count {
353 let hop_count: u8 = Readable::read(reader)?;
354 let mut hops = Vec::with_capacity(hop_count as usize);
355 for _ in 0..hop_count {
356 hops.push(Readable::read(reader)?);
360 let mut payment_params = None;
361 read_tlv_fields!(reader, {
362 (1, payment_params, option),
364 Ok(Route { paths, payment_params })
368 /// Parameters needed to find a [`Route`].
370 /// Passed to [`find_route`] and [`build_route_from_hops`], but also provided in
371 /// [`Event::PaymentPathFailed`] for retrying a failed payment path.
373 /// [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed
374 #[derive(Clone, Debug)]
375 pub struct RouteParameters {
376 /// The parameters of the failed payment path.
377 pub payment_params: PaymentParameters,
379 /// The amount in msats sent on the failed payment path.
380 pub final_value_msat: u64,
382 /// The CLTV on the final hop of the failed payment path.
383 pub final_cltv_expiry_delta: u32,
386 impl_writeable_tlv_based!(RouteParameters, {
387 (0, payment_params, required),
388 (2, final_value_msat, required),
389 (4, final_cltv_expiry_delta, required),
392 /// Maximum total CTLV difference we allow for a full payment path.
393 pub const DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA: u32 = 1008;
395 /// Maximum number of paths we allow an (MPP) payment to have.
396 // The default limit is currently set rather arbitrary - there aren't any real fundamental path-count
397 // limits, but for now more than 10 paths likely carries too much one-path failure.
398 pub const DEFAULT_MAX_PATH_COUNT: u8 = 10;
400 // The median hop CLTV expiry delta currently seen in the network.
401 const MEDIAN_HOP_CLTV_EXPIRY_DELTA: u32 = 40;
403 // During routing, we only consider paths shorter than our maximum length estimate.
404 // In the TLV onion format, there is no fixed maximum length, but the `hop_payloads`
405 // field is always 1300 bytes. As the `tlv_payload` for each hop may vary in length, we have to
406 // estimate how many hops the route may have so that it actually fits the `hop_payloads` field.
408 // We estimate 3+32 (payload length and HMAC) + 2+8 (amt_to_forward) + 2+4 (outgoing_cltv_value) +
409 // 2+8 (short_channel_id) = 61 bytes for each intermediate hop and 3+32
410 // (payload length and HMAC) + 2+8 (amt_to_forward) + 2+4 (outgoing_cltv_value) + 2+32+8
411 // (payment_secret and total_msat) = 93 bytes for the final hop.
412 // Since the length of the potentially included `payment_metadata` is unknown to us, we round
413 // down from (1300-93) / 61 = 19.78... to arrive at a conservative estimate of 19.
414 const MAX_PATH_LENGTH_ESTIMATE: u8 = 19;
416 /// The recipient of a payment.
417 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
418 pub struct PaymentParameters {
419 /// The node id of the payee.
420 pub payee_pubkey: PublicKey,
422 /// Features supported by the payee.
424 /// May be set from the payee's invoice or via [`for_keysend`]. May be `None` if the invoice
425 /// does not contain any features.
427 /// [`for_keysend`]: Self::for_keysend
428 pub features: Option<InvoiceFeatures>,
430 /// Hints for routing to the payee, containing channels connecting the payee to public nodes.
431 pub route_hints: Vec<RouteHint>,
433 /// Expiration of a payment to the payee, in seconds relative to the UNIX epoch.
434 pub expiry_time: Option<u64>,
436 /// The maximum total CLTV delta we accept for the route.
437 /// Defaults to [`DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA`].
438 pub max_total_cltv_expiry_delta: u32,
440 /// The maximum number of paths that may be used by (MPP) payments.
441 /// Defaults to [`DEFAULT_MAX_PATH_COUNT`].
442 pub max_path_count: u8,
444 /// Selects the maximum share of a channel's total capacity which will be sent over a channel,
445 /// as a power of 1/2. A higher value prefers to send the payment using more MPP parts whereas
446 /// a lower value prefers to send larger MPP parts, potentially saturating channels and
447 /// increasing failure probability for those paths.
449 /// Note that this restriction will be relaxed during pathfinding after paths which meet this
450 /// restriction have been found. While paths which meet this criteria will be searched for, it
451 /// is ultimately up to the scorer to select them over other paths.
453 /// A value of 0 will allow payments up to and including a channel's total announced usable
454 /// capacity, a value of one will only use up to half its capacity, two 1/4, etc.
457 pub max_channel_saturation_power_of_half: u8,
459 /// A list of SCIDs which this payment was previously attempted over and which caused the
460 /// payment to fail. Future attempts for the same payment shouldn't be relayed through any of
462 pub previously_failed_channels: Vec<u64>,
465 impl_writeable_tlv_based!(PaymentParameters, {
466 (0, payee_pubkey, required),
467 (1, max_total_cltv_expiry_delta, (default_value, DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA)),
468 (2, features, option),
469 (3, max_path_count, (default_value, DEFAULT_MAX_PATH_COUNT)),
470 (4, route_hints, vec_type),
471 (5, max_channel_saturation_power_of_half, (default_value, 2)),
472 (6, expiry_time, option),
473 (7, previously_failed_channels, vec_type),
476 impl PaymentParameters {
477 /// Creates a payee with the node id of the given `pubkey`.
478 pub fn from_node_id(payee_pubkey: PublicKey) -> Self {
484 max_total_cltv_expiry_delta: DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA,
485 max_path_count: DEFAULT_MAX_PATH_COUNT,
486 max_channel_saturation_power_of_half: 2,
487 previously_failed_channels: Vec::new(),
491 /// Creates a payee with the node id of the given `pubkey` to use for keysend payments.
492 pub fn for_keysend(payee_pubkey: PublicKey) -> Self {
493 Self::from_node_id(payee_pubkey).with_features(InvoiceFeatures::for_keysend())
496 /// Includes the payee's features.
498 /// (C-not exported) since bindings don't support move semantics
499 pub fn with_features(self, features: InvoiceFeatures) -> Self {
500 Self { features: Some(features), ..self }
503 /// Includes hints for routing to the payee.
505 /// (C-not exported) since bindings don't support move semantics
506 pub fn with_route_hints(self, route_hints: Vec<RouteHint>) -> Self {
507 Self { route_hints, ..self }
510 /// Includes a payment expiration in seconds relative to the UNIX epoch.
512 /// (C-not exported) since bindings don't support move semantics
513 pub fn with_expiry_time(self, expiry_time: u64) -> Self {
514 Self { expiry_time: Some(expiry_time), ..self }
517 /// Includes a limit for the total CLTV expiry delta which is considered during routing
519 /// (C-not exported) since bindings don't support move semantics
520 pub fn with_max_total_cltv_expiry_delta(self, max_total_cltv_expiry_delta: u32) -> Self {
521 Self { max_total_cltv_expiry_delta, ..self }
524 /// Includes a limit for the maximum number of payment paths that may be used.
526 /// (C-not exported) since bindings don't support move semantics
527 pub fn with_max_path_count(self, max_path_count: u8) -> Self {
528 Self { max_path_count, ..self }
531 /// Includes a limit for the maximum number of payment paths that may be used.
533 /// (C-not exported) since bindings don't support move semantics
534 pub fn with_max_channel_saturation_power_of_half(self, max_channel_saturation_power_of_half: u8) -> Self {
535 Self { max_channel_saturation_power_of_half, ..self }
539 /// A list of hops along a payment path terminating with a channel to the recipient.
540 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
541 pub struct RouteHint(pub Vec<RouteHintHop>);
543 impl Writeable for RouteHint {
544 fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
545 (self.0.len() as u64).write(writer)?;
546 for hop in self.0.iter() {
553 impl Readable for RouteHint {
554 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
555 let hop_count: u64 = Readable::read(reader)?;
556 let mut hops = Vec::with_capacity(cmp::min(hop_count, 16) as usize);
557 for _ in 0..hop_count {
558 hops.push(Readable::read(reader)?);
564 /// A channel descriptor for a hop along a payment path.
565 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
566 pub struct RouteHintHop {
567 /// The node_id of the non-target end of the route
568 pub src_node_id: PublicKey,
569 /// The short_channel_id of this channel
570 pub short_channel_id: u64,
571 /// The fees which must be paid to use this channel
572 pub fees: RoutingFees,
573 /// The difference in CLTV values between this node and the next node.
574 pub cltv_expiry_delta: u16,
575 /// The minimum value, in msat, which must be relayed to the next hop.
576 pub htlc_minimum_msat: Option<u64>,
577 /// The maximum value in msat available for routing with a single HTLC.
578 pub htlc_maximum_msat: Option<u64>,
581 impl_writeable_tlv_based!(RouteHintHop, {
582 (0, src_node_id, required),
583 (1, htlc_minimum_msat, option),
584 (2, short_channel_id, required),
585 (3, htlc_maximum_msat, option),
587 (6, cltv_expiry_delta, required),
590 #[derive(Eq, PartialEq)]
591 struct RouteGraphNode {
593 lowest_fee_to_peer_through_node: u64,
594 lowest_fee_to_node: u64,
595 total_cltv_delta: u32,
596 // The maximum value a yet-to-be-constructed payment path might flow through this node.
597 // This value is upper-bounded by us by:
598 // - how much is needed for a path being constructed
599 // - how much value can channels following this node (up to the destination) can contribute,
600 // considering their capacity and fees
601 value_contribution_msat: u64,
602 /// The effective htlc_minimum_msat at this hop. If a later hop on the path had a higher HTLC
603 /// minimum, we use it, plus the fees required at each earlier hop to meet it.
604 path_htlc_minimum_msat: u64,
605 /// All penalties incurred from this hop on the way to the destination, as calculated using
607 path_penalty_msat: u64,
608 /// The number of hops walked up to this node.
609 path_length_to_node: u8,
612 impl cmp::Ord for RouteGraphNode {
613 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
614 let other_score = cmp::max(other.lowest_fee_to_peer_through_node, other.path_htlc_minimum_msat)
615 .saturating_add(other.path_penalty_msat);
616 let self_score = cmp::max(self.lowest_fee_to_peer_through_node, self.path_htlc_minimum_msat)
617 .saturating_add(self.path_penalty_msat);
618 other_score.cmp(&self_score).then_with(|| other.node_id.cmp(&self.node_id))
622 impl cmp::PartialOrd for RouteGraphNode {
623 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
624 Some(self.cmp(other))
628 /// A wrapper around the various hop representations.
630 /// Used to construct a [`PathBuildingHop`] and to estimate [`EffectiveCapacity`].
631 #[derive(Clone, Debug)]
632 enum CandidateRouteHop<'a> {
633 /// A hop from the payer, where the outbound liquidity is known.
635 details: &'a ChannelDetails,
637 /// A hop found in the [`ReadOnlyNetworkGraph`], where the channel capacity may be unknown.
639 info: DirectedChannelInfo<'a>,
640 short_channel_id: u64,
642 /// A hop to the payee found in the payment invoice, though not necessarily a direct channel.
644 hint: &'a RouteHintHop,
648 impl<'a> CandidateRouteHop<'a> {
649 fn short_channel_id(&self) -> u64 {
651 CandidateRouteHop::FirstHop { details } => details.get_outbound_payment_scid().unwrap(),
652 CandidateRouteHop::PublicHop { short_channel_id, .. } => *short_channel_id,
653 CandidateRouteHop::PrivateHop { hint } => hint.short_channel_id,
657 // NOTE: This may alloc memory so avoid calling it in a hot code path.
658 fn features(&self) -> ChannelFeatures {
660 CandidateRouteHop::FirstHop { details } => details.counterparty.features.to_context(),
661 CandidateRouteHop::PublicHop { info, .. } => info.channel().features.clone(),
662 CandidateRouteHop::PrivateHop { .. } => ChannelFeatures::empty(),
666 fn cltv_expiry_delta(&self) -> u32 {
668 CandidateRouteHop::FirstHop { .. } => 0,
669 CandidateRouteHop::PublicHop { info, .. } => info.direction().cltv_expiry_delta as u32,
670 CandidateRouteHop::PrivateHop { hint } => hint.cltv_expiry_delta as u32,
674 fn htlc_minimum_msat(&self) -> u64 {
676 CandidateRouteHop::FirstHop { .. } => 0,
677 CandidateRouteHop::PublicHop { info, .. } => info.direction().htlc_minimum_msat,
678 CandidateRouteHop::PrivateHop { hint } => hint.htlc_minimum_msat.unwrap_or(0),
682 fn fees(&self) -> RoutingFees {
684 CandidateRouteHop::FirstHop { .. } => RoutingFees {
685 base_msat: 0, proportional_millionths: 0,
687 CandidateRouteHop::PublicHop { info, .. } => info.direction().fees,
688 CandidateRouteHop::PrivateHop { hint } => hint.fees,
692 fn effective_capacity(&self) -> EffectiveCapacity {
694 CandidateRouteHop::FirstHop { details } => EffectiveCapacity::ExactLiquidity {
695 liquidity_msat: details.next_outbound_htlc_limit_msat,
697 CandidateRouteHop::PublicHop { info, .. } => info.effective_capacity(),
698 CandidateRouteHop::PrivateHop { .. } => EffectiveCapacity::Infinite,
704 fn max_htlc_from_capacity(capacity: EffectiveCapacity, max_channel_saturation_power_of_half: u8) -> u64 {
705 let saturation_shift: u32 = max_channel_saturation_power_of_half as u32;
707 EffectiveCapacity::ExactLiquidity { liquidity_msat } => liquidity_msat,
708 EffectiveCapacity::Infinite => u64::max_value(),
709 EffectiveCapacity::Unknown => EffectiveCapacity::Unknown.as_msat(),
710 EffectiveCapacity::MaximumHTLC { amount_msat } =>
711 amount_msat.checked_shr(saturation_shift).unwrap_or(0),
712 EffectiveCapacity::Total { capacity_msat, htlc_maximum_msat } =>
713 cmp::min(capacity_msat.checked_shr(saturation_shift).unwrap_or(0), htlc_maximum_msat),
717 fn iter_equal<I1: Iterator, I2: Iterator>(mut iter_a: I1, mut iter_b: I2)
718 -> bool where I1::Item: PartialEq<I2::Item> {
720 let a = iter_a.next();
721 let b = iter_b.next();
722 if a.is_none() && b.is_none() { return true; }
723 if a.is_none() || b.is_none() { return false; }
724 if a.unwrap().ne(&b.unwrap()) { return false; }
728 /// It's useful to keep track of the hops associated with the fees required to use them,
729 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
730 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
731 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
733 struct PathBuildingHop<'a> {
734 // Note that this should be dropped in favor of loading it from CandidateRouteHop, but doing so
735 // is a larger refactor and will require careful performance analysis.
737 candidate: CandidateRouteHop<'a>,
740 /// Minimal fees required to route to the source node of the current hop via any of its inbound channels.
741 src_lowest_inbound_fees: RoutingFees,
742 /// All the fees paid *after* this channel on the way to the destination
743 next_hops_fee_msat: u64,
744 /// Fee paid for the use of the current channel (see candidate.fees()).
745 /// The value will be actually deducted from the counterparty balance on the previous link.
746 hop_use_fee_msat: u64,
747 /// Used to compare channels when choosing the for routing.
748 /// Includes paying for the use of a hop and the following hops, as well as
749 /// an estimated cost of reaching this hop.
750 /// Might get stale when fees are recomputed. Primarily for internal use.
752 /// A mirror of the same field in RouteGraphNode. Note that this is only used during the graph
753 /// walk and may be invalid thereafter.
754 path_htlc_minimum_msat: u64,
755 /// All penalties incurred from this channel on the way to the destination, as calculated using
757 path_penalty_msat: u64,
758 /// If we've already processed a node as the best node, we shouldn't process it again. Normally
759 /// we'd just ignore it if we did as all channels would have a higher new fee, but because we
760 /// may decrease the amounts in use as we walk the graph, the actual calculated fee may
761 /// decrease as well. Thus, we have to explicitly track which nodes have been processed and
762 /// avoid processing them again.
764 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
765 // In tests, we apply further sanity checks on cases where we skip nodes we already processed
766 // to ensure it is specifically in cases where the fee has gone down because of a decrease in
767 // value_contribution_msat, which requires tracking it here. See comments below where it is
768 // used for more info.
769 value_contribution_msat: u64,
772 impl<'a> core::fmt::Debug for PathBuildingHop<'a> {
773 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
774 let mut debug_struct = f.debug_struct("PathBuildingHop");
776 .field("node_id", &self.node_id)
777 .field("short_channel_id", &self.candidate.short_channel_id())
778 .field("total_fee_msat", &self.total_fee_msat)
779 .field("next_hops_fee_msat", &self.next_hops_fee_msat)
780 .field("hop_use_fee_msat", &self.hop_use_fee_msat)
781 .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)))
782 .field("path_penalty_msat", &self.path_penalty_msat)
783 .field("path_htlc_minimum_msat", &self.path_htlc_minimum_msat)
784 .field("cltv_expiry_delta", &self.candidate.cltv_expiry_delta());
785 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
786 let debug_struct = debug_struct
787 .field("value_contribution_msat", &self.value_contribution_msat);
788 debug_struct.finish()
792 // Instantiated with a list of hops with correct data in them collected during path finding,
793 // an instance of this struct should be further modified only via given methods.
795 struct PaymentPath<'a> {
796 hops: Vec<(PathBuildingHop<'a>, NodeFeatures)>,
799 impl<'a> PaymentPath<'a> {
800 // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
801 fn get_value_msat(&self) -> u64 {
802 self.hops.last().unwrap().0.fee_msat
805 fn get_path_penalty_msat(&self) -> u64 {
806 self.hops.first().map(|h| h.0.path_penalty_msat).unwrap_or(u64::max_value())
809 fn get_total_fee_paid_msat(&self) -> u64 {
810 if self.hops.len() < 1 {
814 // Can't use next_hops_fee_msat because it gets outdated.
815 for (i, (hop, _)) in self.hops.iter().enumerate() {
816 if i != self.hops.len() - 1 {
817 result += hop.fee_msat;
823 fn get_cost_msat(&self) -> u64 {
824 self.get_total_fee_paid_msat().saturating_add(self.get_path_penalty_msat())
827 // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
828 // to change fees may result in an inconsistency.
830 // Sometimes we call this function right after constructing a path which is inconsistent in
831 // that it the value being transferred has decreased while we were doing path finding, leading
832 // to the fees being paid not lining up with the actual limits.
834 // Note that this function is not aware of the available_liquidity limit, and thus does not
835 // support increasing the value being transferred beyond what was selected during the initial
837 fn update_value_and_recompute_fees(&mut self, value_msat: u64) {
838 let mut total_fee_paid_msat = 0 as u64;
839 for i in (0..self.hops.len()).rev() {
840 let last_hop = i == self.hops.len() - 1;
842 // For non-last-hop, this value will represent the fees paid on the current hop. It
843 // will consist of the fees for the use of the next hop, and extra fees to match
844 // htlc_minimum_msat of the current channel. Last hop is handled separately.
845 let mut cur_hop_fees_msat = 0;
847 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().0.hop_use_fee_msat;
850 let mut cur_hop = &mut self.hops.get_mut(i).unwrap().0;
851 cur_hop.next_hops_fee_msat = total_fee_paid_msat;
852 // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
853 // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
854 // set it too high just to maliciously take more fees by exploiting this
855 // match htlc_minimum_msat logic.
856 let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
857 if let Some(extra_fees_msat) = cur_hop.candidate.htlc_minimum_msat().checked_sub(cur_hop_transferred_amount_msat) {
858 // Note that there is a risk that *previous hops* (those closer to us, as we go
859 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
861 // This might make us end up with a broken route, although this should be super-rare
862 // in practice, both because of how healthy channels look like, and how we pick
863 // channels in add_entry.
864 // Also, this can't be exploited more heavily than *announce a free path and fail
866 cur_hop_transferred_amount_msat += extra_fees_msat;
867 total_fee_paid_msat += extra_fees_msat;
868 cur_hop_fees_msat += extra_fees_msat;
872 // Final hop is a special case: it usually has just value_msat (by design), but also
873 // it still could overpay for the htlc_minimum_msat.
874 cur_hop.fee_msat = cur_hop_transferred_amount_msat;
876 // Propagate updated fees for the use of the channels to one hop back, where they
877 // will be actually paid (fee_msat). The last hop is handled above separately.
878 cur_hop.fee_msat = cur_hop_fees_msat;
881 // Fee for the use of the current hop which will be deducted on the previous hop.
882 // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
883 // this channel is free for us.
885 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.candidate.fees()) {
886 cur_hop.hop_use_fee_msat = new_fee;
887 total_fee_paid_msat += new_fee;
889 // It should not be possible because this function is called only to reduce the
890 // value. In that case, compute_fee was already called with the same fees for
891 // larger amount and there was no overflow.
899 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
900 let proportional_fee_millions =
901 amount_msat.checked_mul(channel_fees.proportional_millionths as u64);
902 if let Some(new_fee) = proportional_fee_millions.and_then(|part| {
903 (channel_fees.base_msat as u64).checked_add(part / 1_000_000) }) {
907 // This function may be (indirectly) called without any verification,
908 // with channel_fees provided by a caller. We should handle it gracefully.
913 /// The default `features` we assume for a node in a route, when no `features` are known about that
916 /// Default features are:
917 /// * variable_length_onion_optional
918 fn default_node_features() -> NodeFeatures {
919 let mut features = NodeFeatures::empty();
920 features.set_variable_length_onion_optional();
924 /// Finds a route from us (payer) to the given target node (payee).
926 /// If the payee provided features in their invoice, they should be provided via `params.payee`.
927 /// Without this, MPP will only be used if the payee's features are available in the network graph.
929 /// Private routing paths between a public node and the target may be included in `params.payee`.
931 /// If some channels aren't announced, it may be useful to fill in `first_hops` with the results
932 /// from [`ChannelManager::list_usable_channels`]. If it is filled in, the view of these channels
933 /// from `network_graph` will be ignored, and only those in `first_hops` will be used.
935 /// The fees on channels from us to the next hop are ignored as they are assumed to all be equal.
936 /// However, the enabled/disabled bit on such channels as well as the `htlc_minimum_msat` /
937 /// `htlc_maximum_msat` *are* checked as they may change based on the receiving node.
941 /// May be used to re-compute a [`Route`] when handling a [`Event::PaymentPathFailed`]. Any
942 /// adjustments to the [`NetworkGraph`] and channel scores should be made prior to calling this
947 /// Panics if first_hops contains channels without short_channel_ids;
948 /// [`ChannelManager::list_usable_channels`] will never include such channels.
950 /// [`ChannelManager::list_usable_channels`]: crate::ln::channelmanager::ChannelManager::list_usable_channels
951 /// [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed
952 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
953 pub fn find_route<L: Deref, GL: Deref, S: Score>(
954 our_node_pubkey: &PublicKey, route_params: &RouteParameters,
955 network_graph: &NetworkGraph<GL>, first_hops: Option<&[&ChannelDetails]>, logger: L,
956 scorer: &S, random_seed_bytes: &[u8; 32]
957 ) -> Result<Route, LightningError>
958 where L::Target: Logger, GL::Target: Logger {
959 let graph_lock = network_graph.read_only();
960 let mut route = get_route(our_node_pubkey, &route_params.payment_params, &graph_lock, first_hops,
961 route_params.final_value_msat, route_params.final_cltv_expiry_delta, logger, scorer,
963 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
967 pub(crate) fn get_route<L: Deref, S: Score>(
968 our_node_pubkey: &PublicKey, payment_params: &PaymentParameters, network_graph: &ReadOnlyNetworkGraph,
969 first_hops: Option<&[&ChannelDetails]>, final_value_msat: u64, final_cltv_expiry_delta: u32,
970 logger: L, scorer: &S, _random_seed_bytes: &[u8; 32]
971 ) -> Result<Route, LightningError>
972 where L::Target: Logger {
973 let payee_node_id = NodeId::from_pubkey(&payment_params.payee_pubkey);
974 let our_node_id = NodeId::from_pubkey(&our_node_pubkey);
976 if payee_node_id == our_node_id {
977 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
980 if final_value_msat > MAX_VALUE_MSAT {
981 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
984 if final_value_msat == 0 {
985 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
988 for route in payment_params.route_hints.iter() {
989 for hop in &route.0 {
990 if hop.src_node_id == payment_params.payee_pubkey {
991 return Err(LightningError{err: "Route hint cannot have the payee as the source.".to_owned(), action: ErrorAction::IgnoreError});
995 if payment_params.max_total_cltv_expiry_delta <= final_cltv_expiry_delta {
996 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});
999 // The general routing idea is the following:
1000 // 1. Fill first/last hops communicated by the caller.
1001 // 2. Attempt to construct a path from payer to payee for transferring
1002 // any ~sufficient (described later) value.
1003 // If succeed, remember which channels were used and how much liquidity they have available,
1004 // so that future paths don't rely on the same liquidity.
1005 // 3. Proceed to the next step if:
1006 // - we hit the recommended target value;
1007 // - OR if we could not construct a new path. Any next attempt will fail too.
1008 // Otherwise, repeat step 2.
1009 // 4. See if we managed to collect paths which aggregately are able to transfer target value
1010 // (not recommended value).
1011 // 5. If yes, proceed. If not, fail routing.
1012 // 6. Select the paths which have the lowest cost (fee plus scorer penalty) per amount
1013 // transferred up to the transfer target value.
1014 // 7. Reduce the value of the last path until we are sending only the target value.
1015 // 8. If our maximum channel saturation limit caused us to pick two identical paths, combine
1016 // them so that we're not sending two HTLCs along the same path.
1018 // As for the actual search algorithm,
1019 // we do a payee-to-payer pseudo-Dijkstra's sorting by each node's distance from the payee
1020 // plus the minimum per-HTLC fee to get from it to another node (aka "shitty pseudo-A*").
1022 // We are not a faithful Dijkstra's implementation because we can change values which impact
1023 // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
1024 // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) than
1025 // the value we are currently attempting to send over a path, we simply reduce the value being
1026 // sent along the path for any hops after that channel. This may imply that later fees (which
1027 // we've already tabulated) are lower because a smaller value is passing through the channels
1028 // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
1029 // channels which were selected earlier (and which may still be used for other paths without a
1030 // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
1033 // One potentially problematic case for this algorithm would be if there are many
1034 // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
1035 // graph walking), we may never find a path which is not liquidity-limited and has lower
1036 // proportional fee (and only lower absolute fee when considering the ultimate value sent).
1037 // Because we only consider paths with at least 5% of the total value being sent, the damage
1038 // from such a case should be limited, however this could be further reduced in the future by
1039 // calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
1040 // limits for the purposes of fee calculation.
1042 // Alternatively, we could store more detailed path information in the heap (targets, below)
1043 // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
1044 // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
1045 // and practically (as we would need to store dynamically-allocated path information in heap
1046 // objects, increasing malloc traffic and indirect memory access significantly). Further, the
1047 // results of such an algorithm would likely be biased towards lower-value paths.
1049 // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
1050 // outside of our current search value, running a path search more times to gather candidate
1051 // paths at different values. While this may be acceptable, further path searches may increase
1052 // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
1053 // graph for candidate paths, calculating the maximum value which can realistically be sent at
1054 // the same time, remaining generic across different payment values.
1056 // TODO: There are a few tweaks we could do, including possibly pre-calculating more stuff
1057 // to use as the A* heuristic beyond just the cost to get one node further than the current
1060 let network_channels = network_graph.channels();
1061 let network_nodes = network_graph.nodes();
1063 if payment_params.max_path_count == 0 {
1064 return Err(LightningError{err: "Can't find a route with no paths allowed.".to_owned(), action: ErrorAction::IgnoreError});
1067 // Allow MPP only if we have a features set from somewhere that indicates the payee supports
1068 // it. If the payee supports it they're supposed to include it in the invoice, so that should
1070 let allow_mpp = if payment_params.max_path_count == 1 {
1072 } else if let Some(features) = &payment_params.features {
1073 features.supports_basic_mpp()
1074 } else if let Some(node) = network_nodes.get(&payee_node_id) {
1075 if let Some(node_info) = node.announcement_info.as_ref() {
1076 node_info.features.supports_basic_mpp()
1080 log_trace!(logger, "Searching for a route from payer {} to payee {} {} MPP and {} first hops {}overriding the network graph", our_node_pubkey,
1081 payment_params.payee_pubkey, if allow_mpp { "with" } else { "without" },
1082 first_hops.map(|hops| hops.len()).unwrap_or(0), if first_hops.is_some() { "" } else { "not " });
1085 // Prepare the data we'll use for payee-to-payer search by
1086 // inserting first hops suggested by the caller as targets.
1087 // Our search will then attempt to reach them while traversing from the payee node.
1088 let mut first_hop_targets: HashMap<_, Vec<&ChannelDetails>> =
1089 HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
1090 if let Some(hops) = first_hops {
1092 if chan.get_outbound_payment_scid().is_none() {
1093 panic!("first_hops should be filled in with usable channels, not pending ones");
1095 if chan.counterparty.node_id == *our_node_pubkey {
1096 return Err(LightningError{err: "First hop cannot have our_node_pubkey as a destination.".to_owned(), action: ErrorAction::IgnoreError});
1099 .entry(NodeId::from_pubkey(&chan.counterparty.node_id))
1100 .or_insert(Vec::new())
1103 if first_hop_targets.is_empty() {
1104 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
1108 // The main heap containing all candidate next-hops sorted by their score (max(A* fee,
1109 // htlc_minimum)). Ideally this would be a heap which allowed cheap score reduction instead of
1110 // adding duplicate entries when we find a better path to a given node.
1111 let mut targets: BinaryHeap<RouteGraphNode> = BinaryHeap::new();
1113 // Map from node_id to information about the best current path to that node, including feerate
1115 let mut dist: HashMap<NodeId, PathBuildingHop> = HashMap::with_capacity(network_nodes.len());
1117 // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
1118 // indicating that we may wish to try again with a higher value, potentially paying to meet an
1119 // htlc_minimum with extra fees while still finding a cheaper path.
1120 let mut hit_minimum_limit;
1122 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
1123 // We start with a path_value of the exact amount we want, and if that generates a route we may
1124 // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
1125 // amount we want in total across paths, selecting the best subset at the end.
1126 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
1127 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
1128 let mut path_value_msat = final_value_msat;
1130 // Routing Fragmentation Mitigation heuristic:
1132 // Routing fragmentation across many payment paths increases the overall routing
1133 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
1134 // Taking too many smaller paths also increases the chance of payment failure.
1135 // Thus to avoid this effect, we require from our collected links to provide
1136 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
1137 // This requirement is currently set to be 1/max_path_count of the payment
1138 // value to ensure we only ever return routes that do not violate this limit.
1139 let minimal_value_contribution_msat: u64 = if allow_mpp {
1140 (final_value_msat + (payment_params.max_path_count as u64 - 1)) / payment_params.max_path_count as u64
1145 // When we start collecting routes we enforce the max_channel_saturation_power_of_half
1146 // requirement strictly. After we've collected enough (or if we fail to find new routes) we
1147 // drop the requirement by setting this to 0.
1148 let mut channel_saturation_pow_half = payment_params.max_channel_saturation_power_of_half;
1150 // Keep track of how much liquidity has been used in selected channels. Used to determine
1151 // if the channel can be used by additional MPP paths or to inform path finding decisions. It is
1152 // aware of direction *only* to ensure that the correct htlc_maximum_msat value is used. Hence,
1153 // liquidity used in one direction will not offset any used in the opposite direction.
1154 let mut used_channel_liquidities: HashMap<(u64, bool), u64> =
1155 HashMap::with_capacity(network_nodes.len());
1157 // Keeping track of how much value we already collected across other paths. Helps to decide
1158 // when we want to stop looking for new paths.
1159 let mut already_collected_value_msat = 0;
1161 for (_, channels) in first_hop_targets.iter_mut() {
1162 // Sort the first_hops channels to the same node(s) in priority order of which channel we'd
1163 // most like to use.
1165 // First, if channels are below `recommended_value_msat`, sort them in descending order,
1166 // preferring larger channels to avoid splitting the payment into more MPP parts than is
1169 // Second, because simply always sorting in descending order would always use our largest
1170 // available outbound capacity, needlessly fragmenting our available channel capacities,
1171 // sort channels above `recommended_value_msat` in ascending order, preferring channels
1172 // which have enough, but not too much, capacity for the payment.
1173 channels.sort_unstable_by(|chan_a, chan_b| {
1174 if chan_b.next_outbound_htlc_limit_msat < recommended_value_msat || chan_a.next_outbound_htlc_limit_msat < recommended_value_msat {
1175 // Sort in descending order
1176 chan_b.next_outbound_htlc_limit_msat.cmp(&chan_a.next_outbound_htlc_limit_msat)
1178 // Sort in ascending order
1179 chan_a.next_outbound_htlc_limit_msat.cmp(&chan_b.next_outbound_htlc_limit_msat)
1184 log_trace!(logger, "Building path from {} (payee) to {} (us/payer) for value {} msat.", payment_params.payee_pubkey, our_node_pubkey, final_value_msat);
1186 macro_rules! add_entry {
1187 // Adds entry which goes from $src_node_id to $dest_node_id over the $candidate hop.
1188 // $next_hops_fee_msat represents the fees paid for using all the channels *after* this one,
1189 // since that value has to be transferred over this channel.
1190 // Returns whether this channel caused an update to `targets`.
1191 ( $candidate: expr, $src_node_id: expr, $dest_node_id: expr, $next_hops_fee_msat: expr,
1192 $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr,
1193 $next_hops_path_penalty_msat: expr, $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => { {
1194 // We "return" whether we updated the path at the end, via this:
1195 let mut did_add_update_path_to_src_node = false;
1196 // Channels to self should not be used. This is more of belt-and-suspenders, because in
1197 // practice these cases should be caught earlier:
1198 // - for regular channels at channel announcement (TODO)
1199 // - for first and last hops early in get_route
1200 if $src_node_id != $dest_node_id {
1201 let short_channel_id = $candidate.short_channel_id();
1202 let effective_capacity = $candidate.effective_capacity();
1203 let htlc_maximum_msat = max_htlc_from_capacity(effective_capacity, channel_saturation_pow_half);
1205 // It is tricky to subtract $next_hops_fee_msat from available liquidity here.
1206 // It may be misleading because we might later choose to reduce the value transferred
1207 // over these channels, and the channel which was insufficient might become sufficient.
1208 // Worst case: we drop a good channel here because it can't cover the high following
1209 // fees caused by one expensive channel, but then this channel could have been used
1210 // if the amount being transferred over this path is lower.
1211 // We do this for now, but this is a subject for removal.
1212 if let Some(mut available_value_contribution_msat) = htlc_maximum_msat.checked_sub($next_hops_fee_msat) {
1213 let used_liquidity_msat = used_channel_liquidities
1214 .get(&(short_channel_id, $src_node_id < $dest_node_id))
1215 .map_or(0, |used_liquidity_msat| {
1216 available_value_contribution_msat = available_value_contribution_msat
1217 .saturating_sub(*used_liquidity_msat);
1218 *used_liquidity_msat
1221 // Verify the liquidity offered by this channel complies to the minimal contribution.
1222 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
1223 // Do not consider candidate hops that would exceed the maximum path length.
1224 let path_length_to_node = $next_hops_path_length + 1;
1225 let exceeds_max_path_length = path_length_to_node > MAX_PATH_LENGTH_ESTIMATE;
1227 // Do not consider candidates that exceed the maximum total cltv expiry limit.
1228 // In order to already account for some of the privacy enhancing random CLTV
1229 // expiry delta offset we add on top later, we subtract a rough estimate
1230 // (2*MEDIAN_HOP_CLTV_EXPIRY_DELTA) here.
1231 let max_total_cltv_expiry_delta = (payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta)
1232 .checked_sub(2*MEDIAN_HOP_CLTV_EXPIRY_DELTA)
1233 .unwrap_or(payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta);
1234 let hop_total_cltv_delta = ($next_hops_cltv_delta as u32)
1235 .saturating_add($candidate.cltv_expiry_delta());
1236 let exceeds_cltv_delta_limit = hop_total_cltv_delta > max_total_cltv_expiry_delta;
1238 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
1239 // Includes paying fees for the use of the following channels.
1240 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
1241 Some(result) => result,
1242 // Can't overflow due to how the values were computed right above.
1243 None => unreachable!(),
1245 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
1246 let over_path_minimum_msat = amount_to_transfer_over_msat >= $candidate.htlc_minimum_msat() &&
1247 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
1249 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
1250 let may_overpay_to_meet_path_minimum_msat =
1251 ((amount_to_transfer_over_msat < $candidate.htlc_minimum_msat() &&
1252 recommended_value_msat > $candidate.htlc_minimum_msat()) ||
1253 (amount_to_transfer_over_msat < $next_hops_path_htlc_minimum_msat &&
1254 recommended_value_msat > $next_hops_path_htlc_minimum_msat));
1256 let payment_failed_on_this_channel =
1257 payment_params.previously_failed_channels.contains(&short_channel_id);
1259 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
1260 // bother considering this channel. If retrying with recommended_value_msat may
1261 // allow us to hit the HTLC minimum limit, set htlc_minimum_limit so that we go
1262 // around again with a higher amount.
1263 if !contributes_sufficient_value || exceeds_max_path_length ||
1264 exceeds_cltv_delta_limit || payment_failed_on_this_channel {
1265 // Path isn't useful, ignore it and move on.
1266 } else if may_overpay_to_meet_path_minimum_msat {
1267 hit_minimum_limit = true;
1268 } else if over_path_minimum_msat {
1269 // Note that low contribution here (limited by available_liquidity_msat)
1270 // might violate htlc_minimum_msat on the hops which are next along the
1271 // payment path (upstream to the payee). To avoid that, we recompute
1272 // path fees knowing the final path contribution after constructing it.
1273 let path_htlc_minimum_msat = compute_fees($next_hops_path_htlc_minimum_msat, $candidate.fees())
1274 .and_then(|fee_msat| fee_msat.checked_add($next_hops_path_htlc_minimum_msat))
1275 .map(|fee_msat| cmp::max(fee_msat, $candidate.htlc_minimum_msat()))
1276 .unwrap_or_else(|| u64::max_value());
1277 let hm_entry = dist.entry($src_node_id);
1278 let old_entry = hm_entry.or_insert_with(|| {
1279 // If there was previously no known way to access the source node
1280 // (recall it goes payee-to-payer) of short_channel_id, first add a
1281 // semi-dummy record just to compute the fees to reach the source node.
1282 // This will affect our decision on selecting short_channel_id
1283 // as a way to reach the $dest_node_id.
1284 let mut fee_base_msat = 0;
1285 let mut fee_proportional_millionths = 0;
1286 if let Some(Some(fees)) = network_nodes.get(&$src_node_id).map(|node| node.lowest_inbound_channel_fees) {
1287 fee_base_msat = fees.base_msat;
1288 fee_proportional_millionths = fees.proportional_millionths;
1291 node_id: $dest_node_id.clone(),
1292 candidate: $candidate.clone(),
1294 src_lowest_inbound_fees: RoutingFees {
1295 base_msat: fee_base_msat,
1296 proportional_millionths: fee_proportional_millionths,
1298 next_hops_fee_msat: u64::max_value(),
1299 hop_use_fee_msat: u64::max_value(),
1300 total_fee_msat: u64::max_value(),
1301 path_htlc_minimum_msat,
1302 path_penalty_msat: u64::max_value(),
1303 was_processed: false,
1304 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
1305 value_contribution_msat,
1309 #[allow(unused_mut)] // We only use the mut in cfg(test)
1310 let mut should_process = !old_entry.was_processed;
1311 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
1313 // In test/fuzzing builds, we do extra checks to make sure the skipping
1314 // of already-seen nodes only happens in cases we expect (see below).
1315 if !should_process { should_process = true; }
1319 let mut hop_use_fee_msat = 0;
1320 let mut total_fee_msat = $next_hops_fee_msat;
1322 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
1323 // will have the same effective-fee
1324 if $src_node_id != our_node_id {
1325 match compute_fees(amount_to_transfer_over_msat, $candidate.fees()) {
1326 // max_value means we'll always fail
1327 // the old_entry.total_fee_msat > total_fee_msat check
1328 None => total_fee_msat = u64::max_value(),
1330 hop_use_fee_msat = fee_msat;
1331 total_fee_msat += hop_use_fee_msat;
1332 // When calculating the lowest inbound fees to a node, we
1333 // calculate fees here not based on the actual value we think
1334 // will flow over this channel, but on the minimum value that
1335 // we'll accept flowing over it. The minimum accepted value
1336 // is a constant through each path collection run, ensuring
1337 // consistent basis. Otherwise we may later find a
1338 // different path to the source node that is more expensive,
1339 // but which we consider to be cheaper because we are capacity
1340 // constrained and the relative fee becomes lower.
1341 match compute_fees(minimal_value_contribution_msat, old_entry.src_lowest_inbound_fees)
1342 .map(|a| a.checked_add(total_fee_msat)) {
1347 total_fee_msat = u64::max_value();
1354 let channel_usage = ChannelUsage {
1355 amount_msat: amount_to_transfer_over_msat,
1356 inflight_htlc_msat: used_liquidity_msat,
1359 let channel_penalty_msat = scorer.channel_penalty_msat(
1360 short_channel_id, &$src_node_id, &$dest_node_id, channel_usage
1362 let path_penalty_msat = $next_hops_path_penalty_msat
1363 .saturating_add(channel_penalty_msat);
1364 let new_graph_node = RouteGraphNode {
1365 node_id: $src_node_id,
1366 lowest_fee_to_peer_through_node: total_fee_msat,
1367 lowest_fee_to_node: $next_hops_fee_msat as u64 + hop_use_fee_msat,
1368 total_cltv_delta: hop_total_cltv_delta,
1369 value_contribution_msat,
1370 path_htlc_minimum_msat,
1372 path_length_to_node,
1375 // Update the way of reaching $src_node_id with the given short_channel_id (from $dest_node_id),
1376 // if this way is cheaper than the already known
1377 // (considering the cost to "reach" this channel from the route destination,
1378 // the cost of using this channel,
1379 // and the cost of routing to the source node of this channel).
1380 // Also, consider that htlc_minimum_msat_difference, because we might end up
1381 // paying it. Consider the following exploit:
1382 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
1383 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
1384 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
1385 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
1387 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
1388 // but it may require additional tracking - we don't want to double-count
1389 // the fees included in $next_hops_path_htlc_minimum_msat, but also
1390 // can't use something that may decrease on future hops.
1391 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat)
1392 .saturating_add(old_entry.path_penalty_msat);
1393 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat)
1394 .saturating_add(path_penalty_msat);
1396 if !old_entry.was_processed && new_cost < old_cost {
1397 targets.push(new_graph_node);
1398 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
1399 old_entry.hop_use_fee_msat = hop_use_fee_msat;
1400 old_entry.total_fee_msat = total_fee_msat;
1401 old_entry.node_id = $dest_node_id.clone();
1402 old_entry.candidate = $candidate.clone();
1403 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
1404 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
1405 old_entry.path_penalty_msat = path_penalty_msat;
1406 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
1408 old_entry.value_contribution_msat = value_contribution_msat;
1410 did_add_update_path_to_src_node = true;
1411 } else if old_entry.was_processed && new_cost < old_cost {
1412 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
1414 // If we're skipping processing a node which was previously
1415 // processed even though we found another path to it with a
1416 // cheaper fee, check that it was because the second path we
1417 // found (which we are processing now) has a lower value
1418 // contribution due to an HTLC minimum limit.
1420 // e.g. take a graph with two paths from node 1 to node 2, one
1421 // through channel A, and one through channel B. Channel A and
1422 // B are both in the to-process heap, with their scores set by
1423 // a higher htlc_minimum than fee.
1424 // Channel A is processed first, and the channels onwards from
1425 // node 1 are added to the to-process heap. Thereafter, we pop
1426 // Channel B off of the heap, note that it has a much more
1427 // restrictive htlc_maximum_msat, and recalculate the fees for
1428 // all of node 1's channels using the new, reduced, amount.
1430 // This would be bogus - we'd be selecting a higher-fee path
1431 // with a lower htlc_maximum_msat instead of the one we'd
1432 // already decided to use.
1433 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
1435 value_contribution_msat + path_penalty_msat <
1436 old_entry.value_contribution_msat + old_entry.path_penalty_msat
1444 did_add_update_path_to_src_node
1448 let default_node_features = default_node_features();
1450 // Find ways (channels with destination) to reach a given node and store them
1451 // in the corresponding data structures (routing graph etc).
1452 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
1453 // meaning how much will be paid in fees after this node (to the best of our knowledge).
1454 // This data can later be helpful to optimize routing (pay lower fees).
1455 macro_rules! add_entries_to_cheapest_to_target_node {
1456 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr, $next_hops_value_contribution: expr,
1457 $next_hops_path_htlc_minimum_msat: expr, $next_hops_path_penalty_msat: expr,
1458 $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => {
1459 let skip_node = if let Some(elem) = dist.get_mut(&$node_id) {
1460 let was_processed = elem.was_processed;
1461 elem.was_processed = true;
1464 // Entries are added to dist in add_entry!() when there is a channel from a node.
1465 // Because there are no channels from payee, it will not have a dist entry at this point.
1466 // If we're processing any other node, it is always be the result of a channel from it.
1467 assert_eq!($node_id, payee_node_id);
1472 if let Some(first_channels) = first_hop_targets.get(&$node_id) {
1473 for details in first_channels {
1474 let candidate = CandidateRouteHop::FirstHop { details };
1475 add_entry!(candidate, our_node_id, $node_id, $fee_to_target_msat,
1476 $next_hops_value_contribution,
1477 $next_hops_path_htlc_minimum_msat, $next_hops_path_penalty_msat,
1478 $next_hops_cltv_delta, $next_hops_path_length);
1482 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
1485 &default_node_features
1488 if !features.requires_unknown_bits() {
1489 for chan_id in $node.channels.iter() {
1490 let chan = network_channels.get(chan_id).unwrap();
1491 if !chan.features.requires_unknown_bits() {
1492 if let Some((directed_channel, source)) = chan.as_directed_to(&$node_id) {
1493 if first_hops.is_none() || *source != our_node_id {
1494 if directed_channel.direction().enabled {
1495 let candidate = CandidateRouteHop::PublicHop {
1496 info: directed_channel,
1497 short_channel_id: *chan_id,
1499 add_entry!(candidate, *source, $node_id,
1500 $fee_to_target_msat,
1501 $next_hops_value_contribution,
1502 $next_hops_path_htlc_minimum_msat,
1503 $next_hops_path_penalty_msat,
1504 $next_hops_cltv_delta, $next_hops_path_length);
1515 let mut payment_paths = Vec::<PaymentPath>::new();
1517 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
1518 'paths_collection: loop {
1519 // For every new path, start from scratch, except for used_channel_liquidities, which
1520 // helps to avoid reusing previously selected paths in future iterations.
1523 hit_minimum_limit = false;
1525 // If first hop is a private channel and the only way to reach the payee, this is the only
1526 // place where it could be added.
1527 if let Some(first_channels) = first_hop_targets.get(&payee_node_id) {
1528 for details in first_channels {
1529 let candidate = CandidateRouteHop::FirstHop { details };
1530 let added = add_entry!(candidate, our_node_id, payee_node_id, 0, path_value_msat,
1532 log_trace!(logger, "{} direct route to payee via SCID {}",
1533 if added { "Added" } else { "Skipped" }, candidate.short_channel_id());
1537 // Add the payee as a target, so that the payee-to-payer
1538 // search algorithm knows what to start with.
1539 match network_nodes.get(&payee_node_id) {
1540 // The payee is not in our network graph, so nothing to add here.
1541 // There is still a chance of reaching them via last_hops though,
1542 // so don't yet fail the payment here.
1543 // If not, targets.pop() will not even let us enter the loop in step 2.
1546 add_entries_to_cheapest_to_target_node!(node, payee_node_id, 0, path_value_msat, 0, 0u64, 0, 0);
1551 // If a caller provided us with last hops, add them to routing targets. Since this happens
1552 // earlier than general path finding, they will be somewhat prioritized, although currently
1553 // it matters only if the fees are exactly the same.
1554 for route in payment_params.route_hints.iter().filter(|route| !route.0.is_empty()) {
1555 let first_hop_in_route = &(route.0)[0];
1556 let have_hop_src_in_graph =
1557 // Only add the hops in this route to our candidate set if either
1558 // we have a direct channel to the first hop or the first hop is
1559 // in the regular network graph.
1560 first_hop_targets.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some() ||
1561 network_nodes.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some();
1562 if have_hop_src_in_graph {
1563 // We start building the path from reverse, i.e., from payee
1564 // to the first RouteHintHop in the path.
1565 let hop_iter = route.0.iter().rev();
1566 let prev_hop_iter = core::iter::once(&payment_params.payee_pubkey).chain(
1567 route.0.iter().skip(1).rev().map(|hop| &hop.src_node_id));
1568 let mut hop_used = true;
1569 let mut aggregate_next_hops_fee_msat: u64 = 0;
1570 let mut aggregate_next_hops_path_htlc_minimum_msat: u64 = 0;
1571 let mut aggregate_next_hops_path_penalty_msat: u64 = 0;
1572 let mut aggregate_next_hops_cltv_delta: u32 = 0;
1573 let mut aggregate_next_hops_path_length: u8 = 0;
1575 for (idx, (hop, prev_hop_id)) in hop_iter.zip(prev_hop_iter).enumerate() {
1576 let source = NodeId::from_pubkey(&hop.src_node_id);
1577 let target = NodeId::from_pubkey(&prev_hop_id);
1578 let candidate = network_channels
1579 .get(&hop.short_channel_id)
1580 .and_then(|channel| channel.as_directed_to(&target))
1581 .map(|(info, _)| CandidateRouteHop::PublicHop {
1583 short_channel_id: hop.short_channel_id,
1585 .unwrap_or_else(|| CandidateRouteHop::PrivateHop { hint: hop });
1587 if !add_entry!(candidate, source, target, aggregate_next_hops_fee_msat,
1588 path_value_msat, aggregate_next_hops_path_htlc_minimum_msat,
1589 aggregate_next_hops_path_penalty_msat,
1590 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length) {
1591 // If this hop was not used then there is no use checking the preceding
1592 // hops in the RouteHint. We can break by just searching for a direct
1593 // channel between last checked hop and first_hop_targets.
1597 let used_liquidity_msat = used_channel_liquidities
1598 .get(&(hop.short_channel_id, source < target)).copied().unwrap_or(0);
1599 let channel_usage = ChannelUsage {
1600 amount_msat: final_value_msat + aggregate_next_hops_fee_msat,
1601 inflight_htlc_msat: used_liquidity_msat,
1602 effective_capacity: candidate.effective_capacity(),
1604 let channel_penalty_msat = scorer.channel_penalty_msat(
1605 hop.short_channel_id, &source, &target, channel_usage
1607 aggregate_next_hops_path_penalty_msat = aggregate_next_hops_path_penalty_msat
1608 .saturating_add(channel_penalty_msat);
1610 aggregate_next_hops_cltv_delta = aggregate_next_hops_cltv_delta
1611 .saturating_add(hop.cltv_expiry_delta as u32);
1613 aggregate_next_hops_path_length = aggregate_next_hops_path_length
1616 // Searching for a direct channel between last checked hop and first_hop_targets
1617 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&prev_hop_id)) {
1618 for details in first_channels {
1619 let candidate = CandidateRouteHop::FirstHop { details };
1620 add_entry!(candidate, our_node_id, NodeId::from_pubkey(&prev_hop_id),
1621 aggregate_next_hops_fee_msat, path_value_msat,
1622 aggregate_next_hops_path_htlc_minimum_msat,
1623 aggregate_next_hops_path_penalty_msat, aggregate_next_hops_cltv_delta,
1624 aggregate_next_hops_path_length);
1632 // In the next values of the iterator, the aggregate fees already reflects
1633 // the sum of value sent from payer (final_value_msat) and routing fees
1634 // for the last node in the RouteHint. We need to just add the fees to
1635 // route through the current node so that the preceding node (next iteration)
1637 let hops_fee = compute_fees(aggregate_next_hops_fee_msat + final_value_msat, hop.fees)
1638 .map_or(None, |inc| inc.checked_add(aggregate_next_hops_fee_msat));
1639 aggregate_next_hops_fee_msat = if let Some(val) = hops_fee { val } else { break; };
1641 let hop_htlc_minimum_msat = candidate.htlc_minimum_msat();
1642 let hop_htlc_minimum_msat_inc = if let Some(val) = compute_fees(aggregate_next_hops_path_htlc_minimum_msat, hop.fees) { val } else { break; };
1643 let hops_path_htlc_minimum = aggregate_next_hops_path_htlc_minimum_msat
1644 .checked_add(hop_htlc_minimum_msat_inc);
1645 aggregate_next_hops_path_htlc_minimum_msat = if let Some(val) = hops_path_htlc_minimum { cmp::max(hop_htlc_minimum_msat, val) } else { break; };
1647 if idx == route.0.len() - 1 {
1648 // The last hop in this iterator is the first hop in
1649 // overall RouteHint.
1650 // If this hop connects to a node with which we have a direct channel,
1651 // ignore the network graph and, if the last hop was added, add our
1652 // direct channel to the candidate set.
1654 // Note that we *must* check if the last hop was added as `add_entry`
1655 // always assumes that the third argument is a node to which we have a
1657 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&hop.src_node_id)) {
1658 for details in first_channels {
1659 let candidate = CandidateRouteHop::FirstHop { details };
1660 add_entry!(candidate, our_node_id,
1661 NodeId::from_pubkey(&hop.src_node_id),
1662 aggregate_next_hops_fee_msat, path_value_msat,
1663 aggregate_next_hops_path_htlc_minimum_msat,
1664 aggregate_next_hops_path_penalty_msat,
1665 aggregate_next_hops_cltv_delta,
1666 aggregate_next_hops_path_length);
1674 log_trace!(logger, "Starting main path collection loop with {} nodes pre-filled from first/last hops.", targets.len());
1676 // At this point, targets are filled with the data from first and
1677 // last hops communicated by the caller, and the payment receiver.
1678 let mut found_new_path = false;
1681 // If this loop terminates due the exhaustion of targets, two situations are possible:
1682 // - not enough outgoing liquidity:
1683 // 0 < already_collected_value_msat < final_value_msat
1684 // - enough outgoing liquidity:
1685 // final_value_msat <= already_collected_value_msat < recommended_value_msat
1686 // Both these cases (and other cases except reaching recommended_value_msat) mean that
1687 // paths_collection will be stopped because found_new_path==false.
1688 // This is not necessarily a routing failure.
1689 '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() {
1691 // Since we're going payee-to-payer, hitting our node as a target means we should stop
1692 // traversing the graph and arrange the path out of what we found.
1693 if node_id == our_node_id {
1694 let mut new_entry = dist.remove(&our_node_id).unwrap();
1695 let mut ordered_hops: Vec<(PathBuildingHop, NodeFeatures)> = vec!((new_entry.clone(), default_node_features.clone()));
1698 let mut features_set = false;
1699 if let Some(first_channels) = first_hop_targets.get(&ordered_hops.last().unwrap().0.node_id) {
1700 for details in first_channels {
1701 if details.get_outbound_payment_scid().unwrap() == ordered_hops.last().unwrap().0.candidate.short_channel_id() {
1702 ordered_hops.last_mut().unwrap().1 = details.counterparty.features.to_context();
1703 features_set = true;
1709 if let Some(node) = network_nodes.get(&ordered_hops.last().unwrap().0.node_id) {
1710 if let Some(node_info) = node.announcement_info.as_ref() {
1711 ordered_hops.last_mut().unwrap().1 = node_info.features.clone();
1713 ordered_hops.last_mut().unwrap().1 = default_node_features.clone();
1716 // We can fill in features for everything except hops which were
1717 // provided via the invoice we're paying. We could guess based on the
1718 // recipient's features but for now we simply avoid guessing at all.
1722 // Means we succesfully traversed from the payer to the payee, now
1723 // save this path for the payment route. Also, update the liquidity
1724 // remaining on the used hops, so that we take them into account
1725 // while looking for more paths.
1726 if ordered_hops.last().unwrap().0.node_id == payee_node_id {
1730 new_entry = match dist.remove(&ordered_hops.last().unwrap().0.node_id) {
1731 Some(payment_hop) => payment_hop,
1732 // We can't arrive at None because, if we ever add an entry to targets,
1733 // we also fill in the entry in dist (see add_entry!).
1734 None => unreachable!(),
1736 // We "propagate" the fees one hop backward (topologically) here,
1737 // so that fees paid for a HTLC forwarding on the current channel are
1738 // associated with the previous channel (where they will be subtracted).
1739 ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
1740 ordered_hops.push((new_entry.clone(), default_node_features.clone()));
1742 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
1743 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
1745 log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: \n {:#?}",
1746 ordered_hops.len(), value_contribution_msat, ordered_hops.iter().map(|h| &(h.0)).collect::<Vec<&PathBuildingHop>>());
1748 let mut payment_path = PaymentPath {hops: ordered_hops};
1750 // We could have possibly constructed a slightly inconsistent path: since we reduce
1751 // value being transferred along the way, we could have violated htlc_minimum_msat
1752 // on some channels we already passed (assuming dest->source direction). Here, we
1753 // recompute the fees again, so that if that's the case, we match the currently
1754 // underpaid htlc_minimum_msat with fees.
1755 debug_assert_eq!(payment_path.get_value_msat(), value_contribution_msat);
1756 value_contribution_msat = cmp::min(value_contribution_msat, final_value_msat);
1757 payment_path.update_value_and_recompute_fees(value_contribution_msat);
1759 // Since a path allows to transfer as much value as
1760 // the smallest channel it has ("bottleneck"), we should recompute
1761 // the fees so sender HTLC don't overpay fees when traversing
1762 // larger channels than the bottleneck. This may happen because
1763 // when we were selecting those channels we were not aware how much value
1764 // this path will transfer, and the relative fee for them
1765 // might have been computed considering a larger value.
1766 // Remember that we used these channels so that we don't rely
1767 // on the same liquidity in future paths.
1768 let mut prevented_redundant_path_selection = false;
1769 let prev_hop_iter = core::iter::once(&our_node_id)
1770 .chain(payment_path.hops.iter().map(|(hop, _)| &hop.node_id));
1771 for (prev_hop, (hop, _)) in prev_hop_iter.zip(payment_path.hops.iter()) {
1772 let spent_on_hop_msat = value_contribution_msat + hop.next_hops_fee_msat;
1773 let used_liquidity_msat = used_channel_liquidities
1774 .entry((hop.candidate.short_channel_id(), *prev_hop < hop.node_id))
1775 .and_modify(|used_liquidity_msat| *used_liquidity_msat += spent_on_hop_msat)
1776 .or_insert(spent_on_hop_msat);
1777 let hop_capacity = hop.candidate.effective_capacity();
1778 let hop_max_msat = max_htlc_from_capacity(hop_capacity, channel_saturation_pow_half);
1779 if *used_liquidity_msat == hop_max_msat {
1780 // If this path used all of this channel's available liquidity, we know
1781 // this path will not be selected again in the next loop iteration.
1782 prevented_redundant_path_selection = true;
1784 debug_assert!(*used_liquidity_msat <= hop_max_msat);
1786 if !prevented_redundant_path_selection {
1787 // If we weren't capped by hitting a liquidity limit on a channel in the path,
1788 // we'll probably end up picking the same path again on the next iteration.
1789 // Decrease the available liquidity of a hop in the middle of the path.
1790 let victim_scid = payment_path.hops[(payment_path.hops.len()) / 2].0.candidate.short_channel_id();
1791 let exhausted = u64::max_value();
1792 log_trace!(logger, "Disabling channel {} for future path building iterations to avoid duplicates.", victim_scid);
1793 *used_channel_liquidities.entry((victim_scid, false)).or_default() = exhausted;
1794 *used_channel_liquidities.entry((victim_scid, true)).or_default() = exhausted;
1797 // Track the total amount all our collected paths allow to send so that we know
1798 // when to stop looking for more paths
1799 already_collected_value_msat += value_contribution_msat;
1801 payment_paths.push(payment_path);
1802 found_new_path = true;
1803 break 'path_construction;
1806 // If we found a path back to the payee, we shouldn't try to process it again. This is
1807 // the equivalent of the `elem.was_processed` check in
1808 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
1809 if node_id == payee_node_id { continue 'path_construction; }
1811 // Otherwise, since the current target node is not us,
1812 // keep "unrolling" the payment graph from payee to payer by
1813 // finding a way to reach the current target from the payer side.
1814 match network_nodes.get(&node_id) {
1817 add_entries_to_cheapest_to_target_node!(node, node_id, lowest_fee_to_node,
1818 value_contribution_msat, path_htlc_minimum_msat, path_penalty_msat,
1819 total_cltv_delta, path_length_to_node);
1825 if !found_new_path && channel_saturation_pow_half != 0 {
1826 channel_saturation_pow_half = 0;
1827 continue 'paths_collection;
1829 // If we don't support MPP, no use trying to gather more value ever.
1830 break 'paths_collection;
1834 // Stop either when the recommended value is reached or if no new path was found in this
1836 // In the latter case, making another path finding attempt won't help,
1837 // because we deterministically terminated the search due to low liquidity.
1838 if !found_new_path && channel_saturation_pow_half != 0 {
1839 channel_saturation_pow_half = 0;
1840 } else if already_collected_value_msat >= recommended_value_msat || !found_new_path {
1841 log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
1842 already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
1843 break 'paths_collection;
1844 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
1845 // Further, if this was our first walk of the graph, and we weren't limited by an
1846 // htlc_minimum_msat, return immediately because this path should suffice. If we were
1847 // limited by an htlc_minimum_msat value, find another path with a higher value,
1848 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
1849 // still keeping a lower total fee than this path.
1850 if !hit_minimum_limit {
1851 log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
1852 break 'paths_collection;
1854 log_trace!(logger, "Collected our payment amount on the first pass, but running again to collect extra paths with a potentially higher limit.");
1855 path_value_msat = recommended_value_msat;
1860 if payment_paths.len() == 0 {
1861 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1864 if already_collected_value_msat < final_value_msat {
1865 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1869 let mut selected_route = payment_paths;
1871 debug_assert_eq!(selected_route.iter().map(|p| p.get_value_msat()).sum::<u64>(), already_collected_value_msat);
1872 let mut overpaid_value_msat = already_collected_value_msat - final_value_msat;
1874 // First, sort by the cost-per-value of the path, dropping the paths that cost the most for
1875 // the value they contribute towards the payment amount.
1876 // We sort in descending order as we will remove from the front in `retain`, next.
1877 selected_route.sort_unstable_by(|a, b|
1878 (((b.get_cost_msat() as u128) << 64) / (b.get_value_msat() as u128))
1879 .cmp(&(((a.get_cost_msat() as u128) << 64) / (a.get_value_msat() as u128)))
1882 // We should make sure that at least 1 path left.
1883 let mut paths_left = selected_route.len();
1884 selected_route.retain(|path| {
1885 if paths_left == 1 {
1888 let path_value_msat = path.get_value_msat();
1889 if path_value_msat <= overpaid_value_msat {
1890 overpaid_value_msat -= path_value_msat;
1896 debug_assert!(selected_route.len() > 0);
1898 if overpaid_value_msat != 0 {
1900 // Now, subtract the remaining overpaid value from the most-expensive path.
1901 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1902 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1903 selected_route.sort_unstable_by(|a, b| {
1904 let a_f = a.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
1905 let b_f = b.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
1906 a_f.cmp(&b_f).then_with(|| b.get_cost_msat().cmp(&a.get_cost_msat()))
1908 let expensive_payment_path = selected_route.first_mut().unwrap();
1910 // We already dropped all the paths with value below `overpaid_value_msat` above, thus this
1911 // can't go negative.
1912 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
1913 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
1917 // Sort by the path itself and combine redundant paths.
1918 // Note that we sort by SCIDs alone as its simpler but when combining we have to ensure we
1919 // compare both SCIDs and NodeIds as individual nodes may use random aliases causing collisions
1921 selected_route.sort_unstable_by_key(|path| {
1922 let mut key = [0u64; MAX_PATH_LENGTH_ESTIMATE as usize];
1923 debug_assert!(path.hops.len() <= key.len());
1924 for (scid, key) in path.hops.iter().map(|h| h.0.candidate.short_channel_id()).zip(key.iter_mut()) {
1929 for idx in 0..(selected_route.len() - 1) {
1930 if idx + 1 >= selected_route.len() { break; }
1931 if iter_equal(selected_route[idx ].hops.iter().map(|h| (h.0.candidate.short_channel_id(), h.0.node_id)),
1932 selected_route[idx + 1].hops.iter().map(|h| (h.0.candidate.short_channel_id(), h.0.node_id))) {
1933 let new_value = selected_route[idx].get_value_msat() + selected_route[idx + 1].get_value_msat();
1934 selected_route[idx].update_value_and_recompute_fees(new_value);
1935 selected_route.remove(idx + 1);
1939 let mut selected_paths = Vec::<Vec<Result<RouteHop, LightningError>>>::new();
1940 for payment_path in selected_route {
1941 let mut path = payment_path.hops.iter().map(|(payment_hop, node_features)| {
1943 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)})?,
1944 node_features: node_features.clone(),
1945 short_channel_id: payment_hop.candidate.short_channel_id(),
1946 channel_features: payment_hop.candidate.features(),
1947 fee_msat: payment_hop.fee_msat,
1948 cltv_expiry_delta: payment_hop.candidate.cltv_expiry_delta(),
1950 }).collect::<Vec<_>>();
1951 // Propagate the cltv_expiry_delta one hop backwards since the delta from the current hop is
1952 // applicable for the previous hop.
1953 path.iter_mut().rev().fold(final_cltv_expiry_delta, |prev_cltv_expiry_delta, hop| {
1954 core::mem::replace(&mut hop.as_mut().unwrap().cltv_expiry_delta, prev_cltv_expiry_delta)
1956 selected_paths.push(path);
1958 // Make sure we would never create a route with more paths than we allow.
1959 debug_assert!(selected_paths.len() <= payment_params.max_path_count.into());
1961 if let Some(features) = &payment_params.features {
1962 for path in selected_paths.iter_mut() {
1963 if let Ok(route_hop) = path.last_mut().unwrap() {
1964 route_hop.node_features = features.to_context();
1970 paths: selected_paths.into_iter().map(|path| path.into_iter().collect()).collect::<Result<Vec<_>, _>>()?,
1971 payment_params: Some(payment_params.clone()),
1973 log_info!(logger, "Got route to {}: {}", payment_params.payee_pubkey, log_route!(route));
1977 // When an adversarial intermediary node observes a payment, it may be able to infer its
1978 // destination, if the remaining CLTV expiry delta exactly matches a feasible path in the network
1979 // graph. In order to improve privacy, this method obfuscates the CLTV expiry deltas along the
1980 // payment path by adding a randomized 'shadow route' offset to the final hop.
1981 fn add_random_cltv_offset(route: &mut Route, payment_params: &PaymentParameters,
1982 network_graph: &ReadOnlyNetworkGraph, random_seed_bytes: &[u8; 32]
1984 let network_channels = network_graph.channels();
1985 let network_nodes = network_graph.nodes();
1987 for path in route.paths.iter_mut() {
1988 let mut shadow_ctlv_expiry_delta_offset: u32 = 0;
1990 // Remember the last three nodes of the random walk and avoid looping back on them.
1991 // Init with the last three nodes from the actual path, if possible.
1992 let mut nodes_to_avoid: [NodeId; 3] = [NodeId::from_pubkey(&path.last().unwrap().pubkey),
1993 NodeId::from_pubkey(&path.get(path.len().saturating_sub(2)).unwrap().pubkey),
1994 NodeId::from_pubkey(&path.get(path.len().saturating_sub(3)).unwrap().pubkey)];
1996 // Choose the last publicly known node as the starting point for the random walk.
1997 let mut cur_hop: Option<NodeId> = None;
1998 let mut path_nonce = [0u8; 12];
1999 if let Some(starting_hop) = path.iter().rev()
2000 .find(|h| network_nodes.contains_key(&NodeId::from_pubkey(&h.pubkey))) {
2001 cur_hop = Some(NodeId::from_pubkey(&starting_hop.pubkey));
2002 path_nonce.copy_from_slice(&cur_hop.unwrap().as_slice()[..12]);
2005 // Init PRNG with the path-dependant nonce, which is static for private paths.
2006 let mut prng = ChaCha20::new(random_seed_bytes, &path_nonce);
2007 let mut random_path_bytes = [0u8; ::core::mem::size_of::<usize>()];
2009 // Pick a random path length in [1 .. 3]
2010 prng.process_in_place(&mut random_path_bytes);
2011 let random_walk_length = usize::from_be_bytes(random_path_bytes).wrapping_rem(3).wrapping_add(1);
2013 for random_hop in 0..random_walk_length {
2014 // If we don't find a suitable offset in the public network graph, we default to
2015 // MEDIAN_HOP_CLTV_EXPIRY_DELTA.
2016 let mut random_hop_offset = MEDIAN_HOP_CLTV_EXPIRY_DELTA;
2018 if let Some(cur_node_id) = cur_hop {
2019 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
2020 // Randomly choose the next unvisited hop.
2021 prng.process_in_place(&mut random_path_bytes);
2022 if let Some(random_channel) = usize::from_be_bytes(random_path_bytes)
2023 .checked_rem(cur_node.channels.len())
2024 .and_then(|index| cur_node.channels.get(index))
2025 .and_then(|id| network_channels.get(id)) {
2026 random_channel.as_directed_from(&cur_node_id).map(|(dir_info, next_id)| {
2027 if !nodes_to_avoid.iter().any(|x| x == next_id) {
2028 nodes_to_avoid[random_hop] = *next_id;
2029 random_hop_offset = dir_info.direction().cltv_expiry_delta.into();
2030 cur_hop = Some(*next_id);
2037 shadow_ctlv_expiry_delta_offset = shadow_ctlv_expiry_delta_offset
2038 .checked_add(random_hop_offset)
2039 .unwrap_or(shadow_ctlv_expiry_delta_offset);
2042 // Limit the total offset to reduce the worst-case locked liquidity timevalue
2043 const MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET: u32 = 3*144;
2044 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET);
2046 // Limit the offset so we never exceed the max_total_cltv_expiry_delta. To improve plausibility,
2047 // we choose the limit to be the largest possible multiple of MEDIAN_HOP_CLTV_EXPIRY_DELTA.
2048 let path_total_cltv_expiry_delta: u32 = path.iter().map(|h| h.cltv_expiry_delta).sum();
2049 let mut max_path_offset = payment_params.max_total_cltv_expiry_delta - path_total_cltv_expiry_delta;
2050 max_path_offset = cmp::max(
2051 max_path_offset - (max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA),
2052 max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA);
2053 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, max_path_offset);
2055 // Add 'shadow' CLTV offset to the final hop
2056 if let Some(last_hop) = path.last_mut() {
2057 last_hop.cltv_expiry_delta = last_hop.cltv_expiry_delta
2058 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(last_hop.cltv_expiry_delta);
2063 /// Construct a route from us (payer) to the target node (payee) via the given hops (which should
2064 /// exclude the payer, but include the payee). This may be useful, e.g., for probing the chosen path.
2066 /// Re-uses logic from `find_route`, so the restrictions described there also apply here.
2067 pub fn build_route_from_hops<L: Deref, GL: Deref>(
2068 our_node_pubkey: &PublicKey, hops: &[PublicKey], route_params: &RouteParameters,
2069 network_graph: &NetworkGraph<GL>, logger: L, random_seed_bytes: &[u8; 32]
2070 ) -> Result<Route, LightningError>
2071 where L::Target: Logger, GL::Target: Logger {
2072 let graph_lock = network_graph.read_only();
2073 let mut route = build_route_from_hops_internal(
2074 our_node_pubkey, hops, &route_params.payment_params, &graph_lock,
2075 route_params.final_value_msat, route_params.final_cltv_expiry_delta, logger, random_seed_bytes)?;
2076 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
2080 fn build_route_from_hops_internal<L: Deref>(
2081 our_node_pubkey: &PublicKey, hops: &[PublicKey], payment_params: &PaymentParameters,
2082 network_graph: &ReadOnlyNetworkGraph, final_value_msat: u64, final_cltv_expiry_delta: u32,
2083 logger: L, random_seed_bytes: &[u8; 32]
2084 ) -> Result<Route, LightningError> where L::Target: Logger {
2087 our_node_id: NodeId,
2088 hop_ids: [Option<NodeId>; MAX_PATH_LENGTH_ESTIMATE as usize],
2091 impl Score for HopScorer {
2092 fn channel_penalty_msat(&self, _short_channel_id: u64, source: &NodeId, target: &NodeId,
2093 _usage: ChannelUsage) -> u64
2095 let mut cur_id = self.our_node_id;
2096 for i in 0..self.hop_ids.len() {
2097 if let Some(next_id) = self.hop_ids[i] {
2098 if cur_id == *source && next_id == *target {
2109 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
2111 fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
2113 fn probe_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
2115 fn probe_successful(&mut self, _path: &[&RouteHop]) {}
2118 impl<'a> Writeable for HopScorer {
2120 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), io::Error> {
2125 if hops.len() > MAX_PATH_LENGTH_ESTIMATE.into() {
2126 return Err(LightningError{err: "Cannot build a route exceeding the maximum path length.".to_owned(), action: ErrorAction::IgnoreError});
2129 let our_node_id = NodeId::from_pubkey(our_node_pubkey);
2130 let mut hop_ids = [None; MAX_PATH_LENGTH_ESTIMATE as usize];
2131 for i in 0..hops.len() {
2132 hop_ids[i] = Some(NodeId::from_pubkey(&hops[i]));
2135 let scorer = HopScorer { our_node_id, hop_ids };
2137 get_route(our_node_pubkey, payment_params, network_graph, None, final_value_msat,
2138 final_cltv_expiry_delta, logger, &scorer, random_seed_bytes)
2143 use crate::routing::gossip::{NetworkGraph, P2PGossipSync, NodeId, EffectiveCapacity};
2144 use crate::routing::router::{get_route, build_route_from_hops_internal, add_random_cltv_offset, default_node_features,
2145 PaymentParameters, Route, RouteHint, RouteHintHop, RouteHop, RoutingFees,
2146 DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA, MAX_PATH_LENGTH_ESTIMATE};
2147 use crate::routing::scoring::{ChannelUsage, Score, ProbabilisticScorer, ProbabilisticScoringParameters};
2148 use crate::routing::test_utils::{add_channel, add_or_update_node, build_graph, build_line_graph, id_to_feature_flags, get_nodes, update_channel};
2149 use crate::chain::transaction::OutPoint;
2150 use crate::chain::keysinterface::KeysInterface;
2151 use crate::ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
2152 use crate::ln::msgs::{ErrorAction, LightningError, UnsignedChannelUpdate, MAX_VALUE_MSAT};
2153 use crate::ln::channelmanager;
2154 use crate::util::test_utils as ln_test_utils;
2155 use crate::util::chacha20::ChaCha20;
2157 use crate::util::ser::{Writeable, Writer};
2159 use bitcoin::hashes::Hash;
2160 use bitcoin::network::constants::Network;
2161 use bitcoin::blockdata::constants::genesis_block;
2162 use bitcoin::blockdata::script::Builder;
2163 use bitcoin::blockdata::opcodes;
2164 use bitcoin::blockdata::transaction::TxOut;
2168 use bitcoin::secp256k1::{PublicKey,SecretKey};
2169 use bitcoin::secp256k1::Secp256k1;
2171 use crate::prelude::*;
2172 use crate::sync::Arc;
2174 use core::convert::TryInto;
2176 fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
2177 features: InitFeatures, outbound_capacity_msat: u64) -> channelmanager::ChannelDetails {
2178 channelmanager::ChannelDetails {
2179 channel_id: [0; 32],
2180 counterparty: channelmanager::ChannelCounterparty {
2183 unspendable_punishment_reserve: 0,
2184 forwarding_info: None,
2185 outbound_htlc_minimum_msat: None,
2186 outbound_htlc_maximum_msat: None,
2188 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
2191 outbound_scid_alias: None,
2192 inbound_scid_alias: None,
2193 channel_value_satoshis: 0,
2196 outbound_capacity_msat,
2197 next_outbound_htlc_limit_msat: outbound_capacity_msat,
2198 inbound_capacity_msat: 42,
2199 unspendable_punishment_reserve: None,
2200 confirmations_required: None,
2201 confirmations: None,
2202 force_close_spend_delay: None,
2203 is_outbound: true, is_channel_ready: true,
2204 is_usable: true, is_public: true,
2205 inbound_htlc_minimum_msat: None,
2206 inbound_htlc_maximum_msat: None,
2212 fn simple_route_test() {
2213 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2214 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2215 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2216 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2217 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2218 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2220 // Simple route to 2 via 1
2222 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) {
2223 assert_eq!(err, "Cannot send a payment of 0 msat");
2224 } else { panic!(); }
2226 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2227 assert_eq!(route.paths[0].len(), 2);
2229 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2230 assert_eq!(route.paths[0][0].short_channel_id, 2);
2231 assert_eq!(route.paths[0][0].fee_msat, 100);
2232 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2233 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2234 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2236 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2237 assert_eq!(route.paths[0][1].short_channel_id, 4);
2238 assert_eq!(route.paths[0][1].fee_msat, 100);
2239 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2240 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2241 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2245 fn invalid_first_hop_test() {
2246 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2247 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2248 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2249 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2250 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2251 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2253 // Simple route to 2 via 1
2255 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
2257 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) =
2258 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) {
2259 assert_eq!(err, "First hop cannot have our_node_pubkey as a destination.");
2260 } else { panic!(); }
2262 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2263 assert_eq!(route.paths[0].len(), 2);
2267 fn htlc_minimum_test() {
2268 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2269 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2270 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2271 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2272 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2273 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2275 // Simple route to 2 via 1
2277 // Disable other paths
2278 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2279 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2280 short_channel_id: 12,
2282 flags: 2, // to disable
2283 cltv_expiry_delta: 0,
2284 htlc_minimum_msat: 0,
2285 htlc_maximum_msat: MAX_VALUE_MSAT,
2287 fee_proportional_millionths: 0,
2288 excess_data: Vec::new()
2290 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2291 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2292 short_channel_id: 3,
2294 flags: 2, // to disable
2295 cltv_expiry_delta: 0,
2296 htlc_minimum_msat: 0,
2297 htlc_maximum_msat: MAX_VALUE_MSAT,
2299 fee_proportional_millionths: 0,
2300 excess_data: Vec::new()
2302 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2303 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2304 short_channel_id: 13,
2306 flags: 2, // to disable
2307 cltv_expiry_delta: 0,
2308 htlc_minimum_msat: 0,
2309 htlc_maximum_msat: MAX_VALUE_MSAT,
2311 fee_proportional_millionths: 0,
2312 excess_data: Vec::new()
2314 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2315 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2316 short_channel_id: 6,
2318 flags: 2, // to disable
2319 cltv_expiry_delta: 0,
2320 htlc_minimum_msat: 0,
2321 htlc_maximum_msat: MAX_VALUE_MSAT,
2323 fee_proportional_millionths: 0,
2324 excess_data: Vec::new()
2326 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2327 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2328 short_channel_id: 7,
2330 flags: 2, // to disable
2331 cltv_expiry_delta: 0,
2332 htlc_minimum_msat: 0,
2333 htlc_maximum_msat: MAX_VALUE_MSAT,
2335 fee_proportional_millionths: 0,
2336 excess_data: Vec::new()
2339 // Check against amount_to_transfer_over_msat.
2340 // Set minimal HTLC of 200_000_000 msat.
2341 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2342 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2343 short_channel_id: 2,
2346 cltv_expiry_delta: 0,
2347 htlc_minimum_msat: 200_000_000,
2348 htlc_maximum_msat: MAX_VALUE_MSAT,
2350 fee_proportional_millionths: 0,
2351 excess_data: Vec::new()
2354 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
2356 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2357 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2358 short_channel_id: 4,
2361 cltv_expiry_delta: 0,
2362 htlc_minimum_msat: 0,
2363 htlc_maximum_msat: 199_999_999,
2365 fee_proportional_millionths: 0,
2366 excess_data: Vec::new()
2369 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
2370 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) {
2371 assert_eq!(err, "Failed to find a path to the given destination");
2372 } else { panic!(); }
2374 // Lift the restriction on the first hop.
2375 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2376 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2377 short_channel_id: 2,
2380 cltv_expiry_delta: 0,
2381 htlc_minimum_msat: 0,
2382 htlc_maximum_msat: MAX_VALUE_MSAT,
2384 fee_proportional_millionths: 0,
2385 excess_data: Vec::new()
2388 // A payment above the minimum should pass
2389 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();
2390 assert_eq!(route.paths[0].len(), 2);
2394 fn htlc_minimum_overpay_test() {
2395 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2396 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2397 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(channelmanager::provided_invoice_features());
2398 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2399 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2400 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2402 // A route to node#2 via two paths.
2403 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
2404 // Thus, they can't send 60 without overpaying.
2405 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2406 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2407 short_channel_id: 2,
2410 cltv_expiry_delta: 0,
2411 htlc_minimum_msat: 35_000,
2412 htlc_maximum_msat: 40_000,
2414 fee_proportional_millionths: 0,
2415 excess_data: Vec::new()
2417 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2418 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2419 short_channel_id: 12,
2422 cltv_expiry_delta: 0,
2423 htlc_minimum_msat: 35_000,
2424 htlc_maximum_msat: 40_000,
2426 fee_proportional_millionths: 0,
2427 excess_data: Vec::new()
2431 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2432 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2433 short_channel_id: 13,
2436 cltv_expiry_delta: 0,
2437 htlc_minimum_msat: 0,
2438 htlc_maximum_msat: MAX_VALUE_MSAT,
2440 fee_proportional_millionths: 0,
2441 excess_data: Vec::new()
2443 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2444 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2445 short_channel_id: 4,
2448 cltv_expiry_delta: 0,
2449 htlc_minimum_msat: 0,
2450 htlc_maximum_msat: MAX_VALUE_MSAT,
2452 fee_proportional_millionths: 0,
2453 excess_data: Vec::new()
2456 // Disable other paths
2457 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2458 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2459 short_channel_id: 1,
2461 flags: 2, // to disable
2462 cltv_expiry_delta: 0,
2463 htlc_minimum_msat: 0,
2464 htlc_maximum_msat: MAX_VALUE_MSAT,
2466 fee_proportional_millionths: 0,
2467 excess_data: Vec::new()
2470 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 60_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2471 // Overpay fees to hit htlc_minimum_msat.
2472 let overpaid_fees = route.paths[0][0].fee_msat + route.paths[1][0].fee_msat;
2473 // TODO: this could be better balanced to overpay 10k and not 15k.
2474 assert_eq!(overpaid_fees, 15_000);
2476 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
2477 // while taking even more fee to match htlc_minimum_msat.
2478 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2479 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2480 short_channel_id: 12,
2483 cltv_expiry_delta: 0,
2484 htlc_minimum_msat: 65_000,
2485 htlc_maximum_msat: 80_000,
2487 fee_proportional_millionths: 0,
2488 excess_data: Vec::new()
2490 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2491 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2492 short_channel_id: 2,
2495 cltv_expiry_delta: 0,
2496 htlc_minimum_msat: 0,
2497 htlc_maximum_msat: MAX_VALUE_MSAT,
2499 fee_proportional_millionths: 0,
2500 excess_data: Vec::new()
2502 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2503 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2504 short_channel_id: 4,
2507 cltv_expiry_delta: 0,
2508 htlc_minimum_msat: 0,
2509 htlc_maximum_msat: MAX_VALUE_MSAT,
2511 fee_proportional_millionths: 100_000,
2512 excess_data: Vec::new()
2515 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 60_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2516 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
2517 assert_eq!(route.paths.len(), 1);
2518 assert_eq!(route.paths[0][0].short_channel_id, 12);
2519 let fees = route.paths[0][0].fee_msat;
2520 assert_eq!(fees, 5_000);
2522 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2523 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
2524 // the other channel.
2525 assert_eq!(route.paths.len(), 1);
2526 assert_eq!(route.paths[0][0].short_channel_id, 2);
2527 let fees = route.paths[0][0].fee_msat;
2528 assert_eq!(fees, 5_000);
2532 fn disable_channels_test() {
2533 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2534 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2535 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2536 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2537 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2538 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2540 // // Disable channels 4 and 12 by flags=2
2541 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2542 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2543 short_channel_id: 4,
2545 flags: 2, // to disable
2546 cltv_expiry_delta: 0,
2547 htlc_minimum_msat: 0,
2548 htlc_maximum_msat: MAX_VALUE_MSAT,
2550 fee_proportional_millionths: 0,
2551 excess_data: Vec::new()
2553 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2554 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2555 short_channel_id: 12,
2557 flags: 2, // to disable
2558 cltv_expiry_delta: 0,
2559 htlc_minimum_msat: 0,
2560 htlc_maximum_msat: MAX_VALUE_MSAT,
2562 fee_proportional_millionths: 0,
2563 excess_data: Vec::new()
2566 // If all the channels require some features we don't understand, route should fail
2567 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) {
2568 assert_eq!(err, "Failed to find a path to the given destination");
2569 } else { panic!(); }
2571 // If we specify a channel to node7, that overrides our local channel view and that gets used
2572 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2573 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();
2574 assert_eq!(route.paths[0].len(), 2);
2576 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2577 assert_eq!(route.paths[0][0].short_channel_id, 42);
2578 assert_eq!(route.paths[0][0].fee_msat, 200);
2579 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2580 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2581 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2583 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2584 assert_eq!(route.paths[0][1].short_channel_id, 13);
2585 assert_eq!(route.paths[0][1].fee_msat, 100);
2586 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2587 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2588 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2592 fn disable_node_test() {
2593 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2594 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2595 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2596 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2597 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2598 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2600 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
2601 let mut unknown_features = NodeFeatures::empty();
2602 unknown_features.set_unknown_feature_required();
2603 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
2604 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
2605 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
2607 // If all nodes require some features we don't understand, route should fail
2608 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) {
2609 assert_eq!(err, "Failed to find a path to the given destination");
2610 } else { panic!(); }
2612 // If we specify a channel to node7, that overrides our local channel view and that gets used
2613 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2614 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();
2615 assert_eq!(route.paths[0].len(), 2);
2617 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2618 assert_eq!(route.paths[0][0].short_channel_id, 42);
2619 assert_eq!(route.paths[0][0].fee_msat, 200);
2620 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2621 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2622 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2624 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2625 assert_eq!(route.paths[0][1].short_channel_id, 13);
2626 assert_eq!(route.paths[0][1].fee_msat, 100);
2627 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2628 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2629 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2631 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
2632 // naively) assume that the user checked the feature bits on the invoice, which override
2633 // the node_announcement.
2637 fn our_chans_test() {
2638 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2639 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2640 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2641 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2642 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2644 // Route to 1 via 2 and 3 because our channel to 1 is disabled
2645 let payment_params = PaymentParameters::from_node_id(nodes[0]);
2646 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2647 assert_eq!(route.paths[0].len(), 3);
2649 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2650 assert_eq!(route.paths[0][0].short_channel_id, 2);
2651 assert_eq!(route.paths[0][0].fee_msat, 200);
2652 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2653 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2654 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2656 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2657 assert_eq!(route.paths[0][1].short_channel_id, 4);
2658 assert_eq!(route.paths[0][1].fee_msat, 100);
2659 assert_eq!(route.paths[0][1].cltv_expiry_delta, (3 << 4) | 2);
2660 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2661 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2663 assert_eq!(route.paths[0][2].pubkey, nodes[0]);
2664 assert_eq!(route.paths[0][2].short_channel_id, 3);
2665 assert_eq!(route.paths[0][2].fee_msat, 100);
2666 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
2667 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(1));
2668 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(3));
2670 // If we specify a channel to node7, that overrides our local channel view and that gets used
2671 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2672 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2673 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();
2674 assert_eq!(route.paths[0].len(), 2);
2676 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2677 assert_eq!(route.paths[0][0].short_channel_id, 42);
2678 assert_eq!(route.paths[0][0].fee_msat, 200);
2679 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2680 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2681 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2683 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2684 assert_eq!(route.paths[0][1].short_channel_id, 13);
2685 assert_eq!(route.paths[0][1].fee_msat, 100);
2686 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2687 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2688 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2691 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2692 let zero_fees = RoutingFees {
2694 proportional_millionths: 0,
2696 vec![RouteHint(vec![RouteHintHop {
2697 src_node_id: nodes[3],
2698 short_channel_id: 8,
2700 cltv_expiry_delta: (8 << 4) | 1,
2701 htlc_minimum_msat: None,
2702 htlc_maximum_msat: None,
2704 ]), RouteHint(vec![RouteHintHop {
2705 src_node_id: nodes[4],
2706 short_channel_id: 9,
2709 proportional_millionths: 0,
2711 cltv_expiry_delta: (9 << 4) | 1,
2712 htlc_minimum_msat: None,
2713 htlc_maximum_msat: None,
2714 }]), RouteHint(vec![RouteHintHop {
2715 src_node_id: nodes[5],
2716 short_channel_id: 10,
2718 cltv_expiry_delta: (10 << 4) | 1,
2719 htlc_minimum_msat: None,
2720 htlc_maximum_msat: None,
2724 fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2725 let zero_fees = RoutingFees {
2727 proportional_millionths: 0,
2729 vec![RouteHint(vec![RouteHintHop {
2730 src_node_id: nodes[2],
2731 short_channel_id: 5,
2734 proportional_millionths: 0,
2736 cltv_expiry_delta: (5 << 4) | 1,
2737 htlc_minimum_msat: None,
2738 htlc_maximum_msat: None,
2740 src_node_id: nodes[3],
2741 short_channel_id: 8,
2743 cltv_expiry_delta: (8 << 4) | 1,
2744 htlc_minimum_msat: None,
2745 htlc_maximum_msat: None,
2747 ]), RouteHint(vec![RouteHintHop {
2748 src_node_id: nodes[4],
2749 short_channel_id: 9,
2752 proportional_millionths: 0,
2754 cltv_expiry_delta: (9 << 4) | 1,
2755 htlc_minimum_msat: None,
2756 htlc_maximum_msat: None,
2757 }]), RouteHint(vec![RouteHintHop {
2758 src_node_id: nodes[5],
2759 short_channel_id: 10,
2761 cltv_expiry_delta: (10 << 4) | 1,
2762 htlc_minimum_msat: None,
2763 htlc_maximum_msat: None,
2768 fn partial_route_hint_test() {
2769 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2770 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2771 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2772 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2773 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2775 // Simple test across 2, 3, 5, and 4 via a last_hop channel
2776 // Tests the behaviour when the RouteHint contains a suboptimal hop.
2777 // RouteHint may be partially used by the algo to build the best path.
2779 // First check that last hop can't have its source as the payee.
2780 let invalid_last_hop = RouteHint(vec![RouteHintHop {
2781 src_node_id: nodes[6],
2782 short_channel_id: 8,
2785 proportional_millionths: 0,
2787 cltv_expiry_delta: (8 << 4) | 1,
2788 htlc_minimum_msat: None,
2789 htlc_maximum_msat: None,
2792 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
2793 invalid_last_hops.push(invalid_last_hop);
2795 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(invalid_last_hops);
2796 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) {
2797 assert_eq!(err, "Route hint cannot have the payee as the source.");
2798 } else { panic!(); }
2801 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops_multi_private_channels(&nodes));
2802 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2803 assert_eq!(route.paths[0].len(), 5);
2805 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2806 assert_eq!(route.paths[0][0].short_channel_id, 2);
2807 assert_eq!(route.paths[0][0].fee_msat, 100);
2808 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2809 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2810 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2812 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2813 assert_eq!(route.paths[0][1].short_channel_id, 4);
2814 assert_eq!(route.paths[0][1].fee_msat, 0);
2815 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
2816 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2817 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2819 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2820 assert_eq!(route.paths[0][2].short_channel_id, 6);
2821 assert_eq!(route.paths[0][2].fee_msat, 0);
2822 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
2823 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2824 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2826 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2827 assert_eq!(route.paths[0][3].short_channel_id, 11);
2828 assert_eq!(route.paths[0][3].fee_msat, 0);
2829 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
2830 // If we have a peer in the node map, we'll use their features here since we don't have
2831 // a way of figuring out their features from the invoice:
2832 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2833 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2835 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2836 assert_eq!(route.paths[0][4].short_channel_id, 8);
2837 assert_eq!(route.paths[0][4].fee_msat, 100);
2838 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2839 assert_eq!(route.paths[0][4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
2840 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2843 fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2844 let zero_fees = RoutingFees {
2846 proportional_millionths: 0,
2848 vec![RouteHint(vec![RouteHintHop {
2849 src_node_id: nodes[3],
2850 short_channel_id: 8,
2852 cltv_expiry_delta: (8 << 4) | 1,
2853 htlc_minimum_msat: None,
2854 htlc_maximum_msat: None,
2855 }]), RouteHint(vec![
2857 ]), RouteHint(vec![RouteHintHop {
2858 src_node_id: nodes[5],
2859 short_channel_id: 10,
2861 cltv_expiry_delta: (10 << 4) | 1,
2862 htlc_minimum_msat: None,
2863 htlc_maximum_msat: None,
2868 fn ignores_empty_last_hops_test() {
2869 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2870 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2871 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(empty_last_hop(&nodes));
2872 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2873 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2874 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2876 // Test handling of an empty RouteHint passed in Invoice.
2878 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2879 assert_eq!(route.paths[0].len(), 5);
2881 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2882 assert_eq!(route.paths[0][0].short_channel_id, 2);
2883 assert_eq!(route.paths[0][0].fee_msat, 100);
2884 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2885 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2886 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2888 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2889 assert_eq!(route.paths[0][1].short_channel_id, 4);
2890 assert_eq!(route.paths[0][1].fee_msat, 0);
2891 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
2892 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2893 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2895 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2896 assert_eq!(route.paths[0][2].short_channel_id, 6);
2897 assert_eq!(route.paths[0][2].fee_msat, 0);
2898 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
2899 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2900 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2902 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2903 assert_eq!(route.paths[0][3].short_channel_id, 11);
2904 assert_eq!(route.paths[0][3].fee_msat, 0);
2905 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
2906 // If we have a peer in the node map, we'll use their features here since we don't have
2907 // a way of figuring out their features from the invoice:
2908 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2909 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2911 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2912 assert_eq!(route.paths[0][4].short_channel_id, 8);
2913 assert_eq!(route.paths[0][4].fee_msat, 100);
2914 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2915 assert_eq!(route.paths[0][4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
2916 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2919 /// Builds a trivial last-hop hint that passes through the two nodes given, with channel 0xff00
2921 fn multi_hop_last_hops_hint(hint_hops: [PublicKey; 2]) -> Vec<RouteHint> {
2922 let zero_fees = RoutingFees {
2924 proportional_millionths: 0,
2926 vec![RouteHint(vec![RouteHintHop {
2927 src_node_id: hint_hops[0],
2928 short_channel_id: 0xff00,
2931 proportional_millionths: 0,
2933 cltv_expiry_delta: (5 << 4) | 1,
2934 htlc_minimum_msat: None,
2935 htlc_maximum_msat: None,
2937 src_node_id: hint_hops[1],
2938 short_channel_id: 0xff01,
2940 cltv_expiry_delta: (8 << 4) | 1,
2941 htlc_minimum_msat: None,
2942 htlc_maximum_msat: None,
2947 fn multi_hint_last_hops_test() {
2948 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2949 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2950 let last_hops = multi_hop_last_hops_hint([nodes[2], nodes[3]]);
2951 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops.clone());
2952 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2953 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2954 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2955 // Test through channels 2, 3, 0xff00, 0xff01.
2956 // Test shows that multiple hop hints are considered.
2958 // Disabling channels 6 & 7 by flags=2
2959 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2960 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2961 short_channel_id: 6,
2963 flags: 2, // to disable
2964 cltv_expiry_delta: 0,
2965 htlc_minimum_msat: 0,
2966 htlc_maximum_msat: MAX_VALUE_MSAT,
2968 fee_proportional_millionths: 0,
2969 excess_data: Vec::new()
2971 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2972 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2973 short_channel_id: 7,
2975 flags: 2, // to disable
2976 cltv_expiry_delta: 0,
2977 htlc_minimum_msat: 0,
2978 htlc_maximum_msat: MAX_VALUE_MSAT,
2980 fee_proportional_millionths: 0,
2981 excess_data: Vec::new()
2984 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2985 assert_eq!(route.paths[0].len(), 4);
2987 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2988 assert_eq!(route.paths[0][0].short_channel_id, 2);
2989 assert_eq!(route.paths[0][0].fee_msat, 200);
2990 assert_eq!(route.paths[0][0].cltv_expiry_delta, 65);
2991 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2992 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2994 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2995 assert_eq!(route.paths[0][1].short_channel_id, 4);
2996 assert_eq!(route.paths[0][1].fee_msat, 100);
2997 assert_eq!(route.paths[0][1].cltv_expiry_delta, 81);
2998 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2999 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3001 assert_eq!(route.paths[0][2].pubkey, nodes[3]);
3002 assert_eq!(route.paths[0][2].short_channel_id, last_hops[0].0[0].short_channel_id);
3003 assert_eq!(route.paths[0][2].fee_msat, 0);
3004 assert_eq!(route.paths[0][2].cltv_expiry_delta, 129);
3005 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(4));
3006 assert_eq!(route.paths[0][2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3008 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
3009 assert_eq!(route.paths[0][3].short_channel_id, last_hops[0].0[1].short_channel_id);
3010 assert_eq!(route.paths[0][3].fee_msat, 100);
3011 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
3012 assert_eq!(route.paths[0][3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3013 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3017 fn private_multi_hint_last_hops_test() {
3018 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3019 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3021 let non_announced_privkey = SecretKey::from_slice(&hex::decode(format!("{:02x}", 0xf0).repeat(32)).unwrap()[..]).unwrap();
3022 let non_announced_pubkey = PublicKey::from_secret_key(&secp_ctx, &non_announced_privkey);
3024 let last_hops = multi_hop_last_hops_hint([nodes[2], non_announced_pubkey]);
3025 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops.clone());
3026 let scorer = ln_test_utils::TestScorer::with_penalty(0);
3027 // Test through channels 2, 3, 0xff00, 0xff01.
3028 // Test shows that multiple hop hints are considered.
3030 // Disabling channels 6 & 7 by flags=2
3031 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3032 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3033 short_channel_id: 6,
3035 flags: 2, // to disable
3036 cltv_expiry_delta: 0,
3037 htlc_minimum_msat: 0,
3038 htlc_maximum_msat: MAX_VALUE_MSAT,
3040 fee_proportional_millionths: 0,
3041 excess_data: Vec::new()
3043 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3044 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3045 short_channel_id: 7,
3047 flags: 2, // to disable
3048 cltv_expiry_delta: 0,
3049 htlc_minimum_msat: 0,
3050 htlc_maximum_msat: MAX_VALUE_MSAT,
3052 fee_proportional_millionths: 0,
3053 excess_data: Vec::new()
3056 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &[42u8; 32]).unwrap();
3057 assert_eq!(route.paths[0].len(), 4);
3059 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3060 assert_eq!(route.paths[0][0].short_channel_id, 2);
3061 assert_eq!(route.paths[0][0].fee_msat, 200);
3062 assert_eq!(route.paths[0][0].cltv_expiry_delta, 65);
3063 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3064 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3066 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3067 assert_eq!(route.paths[0][1].short_channel_id, 4);
3068 assert_eq!(route.paths[0][1].fee_msat, 100);
3069 assert_eq!(route.paths[0][1].cltv_expiry_delta, 81);
3070 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3071 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3073 assert_eq!(route.paths[0][2].pubkey, non_announced_pubkey);
3074 assert_eq!(route.paths[0][2].short_channel_id, last_hops[0].0[0].short_channel_id);
3075 assert_eq!(route.paths[0][2].fee_msat, 0);
3076 assert_eq!(route.paths[0][2].cltv_expiry_delta, 129);
3077 assert_eq!(route.paths[0][2].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3078 assert_eq!(route.paths[0][2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3080 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
3081 assert_eq!(route.paths[0][3].short_channel_id, last_hops[0].0[1].short_channel_id);
3082 assert_eq!(route.paths[0][3].fee_msat, 100);
3083 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
3084 assert_eq!(route.paths[0][3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3085 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3088 fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3089 let zero_fees = RoutingFees {
3091 proportional_millionths: 0,
3093 vec![RouteHint(vec![RouteHintHop {
3094 src_node_id: nodes[4],
3095 short_channel_id: 11,
3097 cltv_expiry_delta: (11 << 4) | 1,
3098 htlc_minimum_msat: None,
3099 htlc_maximum_msat: None,
3101 src_node_id: nodes[3],
3102 short_channel_id: 8,
3104 cltv_expiry_delta: (8 << 4) | 1,
3105 htlc_minimum_msat: None,
3106 htlc_maximum_msat: None,
3107 }]), RouteHint(vec![RouteHintHop {
3108 src_node_id: nodes[4],
3109 short_channel_id: 9,
3112 proportional_millionths: 0,
3114 cltv_expiry_delta: (9 << 4) | 1,
3115 htlc_minimum_msat: None,
3116 htlc_maximum_msat: None,
3117 }]), RouteHint(vec![RouteHintHop {
3118 src_node_id: nodes[5],
3119 short_channel_id: 10,
3121 cltv_expiry_delta: (10 << 4) | 1,
3122 htlc_minimum_msat: None,
3123 htlc_maximum_msat: None,
3128 fn last_hops_with_public_channel_test() {
3129 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3130 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3131 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops_with_public_channel(&nodes));
3132 let scorer = ln_test_utils::TestScorer::with_penalty(0);
3133 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3134 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3135 // This test shows that public routes can be present in the invoice
3136 // which would be handled in the same manner.
3138 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3139 assert_eq!(route.paths[0].len(), 5);
3141 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3142 assert_eq!(route.paths[0][0].short_channel_id, 2);
3143 assert_eq!(route.paths[0][0].fee_msat, 100);
3144 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
3145 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3146 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3148 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3149 assert_eq!(route.paths[0][1].short_channel_id, 4);
3150 assert_eq!(route.paths[0][1].fee_msat, 0);
3151 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
3152 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3153 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3155 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
3156 assert_eq!(route.paths[0][2].short_channel_id, 6);
3157 assert_eq!(route.paths[0][2].fee_msat, 0);
3158 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
3159 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
3160 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
3162 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
3163 assert_eq!(route.paths[0][3].short_channel_id, 11);
3164 assert_eq!(route.paths[0][3].fee_msat, 0);
3165 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
3166 // If we have a peer in the node map, we'll use their features here since we don't have
3167 // a way of figuring out their features from the invoice:
3168 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
3169 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
3171 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
3172 assert_eq!(route.paths[0][4].short_channel_id, 8);
3173 assert_eq!(route.paths[0][4].fee_msat, 100);
3174 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
3175 assert_eq!(route.paths[0][4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3176 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3180 fn our_chans_last_hop_connect_test() {
3181 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3182 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3183 let scorer = ln_test_utils::TestScorer::with_penalty(0);
3184 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3185 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3187 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
3188 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3189 let mut last_hops = last_hops(&nodes);
3190 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops.clone());
3191 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();
3192 assert_eq!(route.paths[0].len(), 2);
3194 assert_eq!(route.paths[0][0].pubkey, nodes[3]);
3195 assert_eq!(route.paths[0][0].short_channel_id, 42);
3196 assert_eq!(route.paths[0][0].fee_msat, 0);
3197 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 4) | 1);
3198 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
3199 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3201 assert_eq!(route.paths[0][1].pubkey, nodes[6]);
3202 assert_eq!(route.paths[0][1].short_channel_id, 8);
3203 assert_eq!(route.paths[0][1].fee_msat, 100);
3204 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
3205 assert_eq!(route.paths[0][1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3206 assert_eq!(route.paths[0][1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3208 last_hops[0].0[0].fees.base_msat = 1000;
3210 // Revert to via 6 as the fee on 8 goes up
3211 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops);
3212 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3213 assert_eq!(route.paths[0].len(), 4);
3215 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3216 assert_eq!(route.paths[0][0].short_channel_id, 2);
3217 assert_eq!(route.paths[0][0].fee_msat, 200); // fee increased as its % of value transferred across node
3218 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
3219 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3220 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3222 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3223 assert_eq!(route.paths[0][1].short_channel_id, 4);
3224 assert_eq!(route.paths[0][1].fee_msat, 100);
3225 assert_eq!(route.paths[0][1].cltv_expiry_delta, (7 << 4) | 1);
3226 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3227 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3229 assert_eq!(route.paths[0][2].pubkey, nodes[5]);
3230 assert_eq!(route.paths[0][2].short_channel_id, 7);
3231 assert_eq!(route.paths[0][2].fee_msat, 0);
3232 assert_eq!(route.paths[0][2].cltv_expiry_delta, (10 << 4) | 1);
3233 // If we have a peer in the node map, we'll use their features here since we don't have
3234 // a way of figuring out their features from the invoice:
3235 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
3236 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(7));
3238 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
3239 assert_eq!(route.paths[0][3].short_channel_id, 10);
3240 assert_eq!(route.paths[0][3].fee_msat, 100);
3241 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
3242 assert_eq!(route.paths[0][3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3243 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3245 // ...but still use 8 for larger payments as 6 has a variable feerate
3246 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 2000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3247 assert_eq!(route.paths[0].len(), 5);
3249 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3250 assert_eq!(route.paths[0][0].short_channel_id, 2);
3251 assert_eq!(route.paths[0][0].fee_msat, 3000);
3252 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
3253 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3254 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3256 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3257 assert_eq!(route.paths[0][1].short_channel_id, 4);
3258 assert_eq!(route.paths[0][1].fee_msat, 0);
3259 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
3260 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3261 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3263 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
3264 assert_eq!(route.paths[0][2].short_channel_id, 6);
3265 assert_eq!(route.paths[0][2].fee_msat, 0);
3266 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
3267 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
3268 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
3270 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
3271 assert_eq!(route.paths[0][3].short_channel_id, 11);
3272 assert_eq!(route.paths[0][3].fee_msat, 1000);
3273 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
3274 // If we have a peer in the node map, we'll use their features here since we don't have
3275 // a way of figuring out their features from the invoice:
3276 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
3277 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
3279 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
3280 assert_eq!(route.paths[0][4].short_channel_id, 8);
3281 assert_eq!(route.paths[0][4].fee_msat, 2000);
3282 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
3283 assert_eq!(route.paths[0][4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3284 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3287 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> {
3288 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
3289 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3290 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3292 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
3293 let last_hops = RouteHint(vec![RouteHintHop {
3294 src_node_id: middle_node_id,
3295 short_channel_id: 8,
3298 proportional_millionths: last_hop_fee_prop,
3300 cltv_expiry_delta: (8 << 4) | 1,
3301 htlc_minimum_msat: None,
3302 htlc_maximum_msat: last_hop_htlc_max,
3304 let payment_params = PaymentParameters::from_node_id(target_node_id).with_route_hints(vec![last_hops]);
3305 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
3306 let scorer = ln_test_utils::TestScorer::with_penalty(0);
3307 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3308 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3309 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
3310 let logger = ln_test_utils::TestLogger::new();
3311 let network_graph = NetworkGraph::new(genesis_hash, &logger);
3312 let route = get_route(&source_node_id, &payment_params, &network_graph.read_only(),
3313 Some(&our_chans.iter().collect::<Vec<_>>()), route_val, 42, &logger, &scorer, &random_seed_bytes);
3318 fn unannounced_path_test() {
3319 // We should be able to send a payment to a destination without any help of a routing graph
3320 // if we have a channel with a common counterparty that appears in the first and last hop
3322 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
3324 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3325 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3326 assert_eq!(route.paths[0].len(), 2);
3328 assert_eq!(route.paths[0][0].pubkey, middle_node_id);
3329 assert_eq!(route.paths[0][0].short_channel_id, 42);
3330 assert_eq!(route.paths[0][0].fee_msat, 1001);
3331 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 4) | 1);
3332 assert_eq!(route.paths[0][0].node_features.le_flags(), &[0b11]);
3333 assert_eq!(route.paths[0][0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3335 assert_eq!(route.paths[0][1].pubkey, target_node_id);
3336 assert_eq!(route.paths[0][1].short_channel_id, 8);
3337 assert_eq!(route.paths[0][1].fee_msat, 1000000);
3338 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
3339 assert_eq!(route.paths[0][1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3340 assert_eq!(route.paths[0][1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3344 fn overflow_unannounced_path_test_liquidity_underflow() {
3345 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
3346 // the last-hop had a fee which overflowed a u64, we'd panic.
3347 // This was due to us adding the first-hop from us unconditionally, causing us to think
3348 // we'd built a path (as our node is in the "best candidate" set), when we had not.
3349 // In this test, we previously hit a subtraction underflow due to having less available
3350 // liquidity at the last hop than 0.
3351 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());
3355 fn overflow_unannounced_path_test_feerate_overflow() {
3356 // This tests for the same case as above, except instead of hitting a subtraction
3357 // underflow, we hit a case where the fee charged at a hop overflowed.
3358 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());
3362 fn available_amount_while_routing_test() {
3363 // Tests whether we choose the correct available channel amount while routing.
3365 let (secp_ctx, network_graph, mut gossip_sync, chain_monitor, logger) = build_graph();
3366 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3367 let scorer = ln_test_utils::TestScorer::with_penalty(0);
3368 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3369 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3370 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(channelmanager::provided_invoice_features());
3372 // We will use a simple single-path route from
3373 // our node to node2 via node0: channels {1, 3}.
3375 // First disable all other paths.
3376 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3377 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3378 short_channel_id: 2,
3381 cltv_expiry_delta: 0,
3382 htlc_minimum_msat: 0,
3383 htlc_maximum_msat: 100_000,
3385 fee_proportional_millionths: 0,
3386 excess_data: Vec::new()
3388 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3389 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3390 short_channel_id: 12,
3393 cltv_expiry_delta: 0,
3394 htlc_minimum_msat: 0,
3395 htlc_maximum_msat: 100_000,
3397 fee_proportional_millionths: 0,
3398 excess_data: Vec::new()
3401 // Make the first channel (#1) very permissive,
3402 // and we will be testing all limits on the second channel.
3403 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3404 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3405 short_channel_id: 1,
3408 cltv_expiry_delta: 0,
3409 htlc_minimum_msat: 0,
3410 htlc_maximum_msat: 1_000_000_000,
3412 fee_proportional_millionths: 0,
3413 excess_data: Vec::new()
3416 // First, let's see if routing works if we have absolutely no idea about the available amount.
3417 // In this case, it should be set to 250_000 sats.
3418 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3419 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3420 short_channel_id: 3,
3423 cltv_expiry_delta: 0,
3424 htlc_minimum_msat: 0,
3425 htlc_maximum_msat: 250_000_000,
3427 fee_proportional_millionths: 0,
3428 excess_data: Vec::new()
3432 // Attempt to route more than available results in a failure.
3433 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3434 &our_id, &payment_params, &network_graph.read_only(), None, 250_000_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3435 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3436 } else { panic!(); }
3440 // Now, attempt to route an exact amount we have should be fine.
3441 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();
3442 assert_eq!(route.paths.len(), 1);
3443 let path = route.paths.last().unwrap();
3444 assert_eq!(path.len(), 2);
3445 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3446 assert_eq!(path.last().unwrap().fee_msat, 250_000_000);
3449 // Check that setting next_outbound_htlc_limit_msat in first_hops limits the channels.
3450 // Disable channel #1 and use another first hop.
3451 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3452 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3453 short_channel_id: 1,
3456 cltv_expiry_delta: 0,
3457 htlc_minimum_msat: 0,
3458 htlc_maximum_msat: 1_000_000_000,
3460 fee_proportional_millionths: 0,
3461 excess_data: Vec::new()
3464 // Now, limit the first_hop by the next_outbound_htlc_limit_msat of 200_000 sats.
3465 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
3468 // Attempt to route more than available results in a failure.
3469 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3470 &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) {
3471 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3472 } else { panic!(); }
3476 // Now, attempt to route an exact amount we have should be fine.
3477 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();
3478 assert_eq!(route.paths.len(), 1);
3479 let path = route.paths.last().unwrap();
3480 assert_eq!(path.len(), 2);
3481 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3482 assert_eq!(path.last().unwrap().fee_msat, 200_000_000);
3485 // Enable channel #1 back.
3486 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3487 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3488 short_channel_id: 1,
3491 cltv_expiry_delta: 0,
3492 htlc_minimum_msat: 0,
3493 htlc_maximum_msat: 1_000_000_000,
3495 fee_proportional_millionths: 0,
3496 excess_data: Vec::new()
3500 // Now let's see if routing works if we know only htlc_maximum_msat.
3501 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3502 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3503 short_channel_id: 3,
3506 cltv_expiry_delta: 0,
3507 htlc_minimum_msat: 0,
3508 htlc_maximum_msat: 15_000,
3510 fee_proportional_millionths: 0,
3511 excess_data: Vec::new()
3515 // Attempt to route more than available results in a failure.
3516 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3517 &our_id, &payment_params, &network_graph.read_only(), None, 15_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3518 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3519 } else { panic!(); }
3523 // Now, attempt to route an exact amount we have should be fine.
3524 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 15_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3525 assert_eq!(route.paths.len(), 1);
3526 let path = route.paths.last().unwrap();
3527 assert_eq!(path.len(), 2);
3528 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3529 assert_eq!(path.last().unwrap().fee_msat, 15_000);
3532 // Now let's see if routing works if we know only capacity from the UTXO.
3534 // We can't change UTXO capacity on the fly, so we'll disable
3535 // the existing channel and add another one with the capacity we need.
3536 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3537 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3538 short_channel_id: 3,
3541 cltv_expiry_delta: 0,
3542 htlc_minimum_msat: 0,
3543 htlc_maximum_msat: MAX_VALUE_MSAT,
3545 fee_proportional_millionths: 0,
3546 excess_data: Vec::new()
3549 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
3550 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
3551 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
3552 .push_opcode(opcodes::all::OP_PUSHNUM_2)
3553 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
3555 *chain_monitor.utxo_ret.lock().unwrap() = Ok(TxOut { value: 15, script_pubkey: good_script.clone() });
3556 gossip_sync.add_chain_access(Some(chain_monitor));
3558 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
3559 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3560 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3561 short_channel_id: 333,
3564 cltv_expiry_delta: (3 << 4) | 1,
3565 htlc_minimum_msat: 0,
3566 htlc_maximum_msat: 15_000,
3568 fee_proportional_millionths: 0,
3569 excess_data: Vec::new()
3571 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3572 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3573 short_channel_id: 333,
3576 cltv_expiry_delta: (3 << 4) | 2,
3577 htlc_minimum_msat: 0,
3578 htlc_maximum_msat: 15_000,
3580 fee_proportional_millionths: 0,
3581 excess_data: Vec::new()
3585 // Attempt to route more than available results in a failure.
3586 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3587 &our_id, &payment_params, &network_graph.read_only(), None, 15_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3588 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3589 } else { panic!(); }
3593 // Now, attempt to route an exact amount we have should be fine.
3594 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 15_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3595 assert_eq!(route.paths.len(), 1);
3596 let path = route.paths.last().unwrap();
3597 assert_eq!(path.len(), 2);
3598 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3599 assert_eq!(path.last().unwrap().fee_msat, 15_000);
3602 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
3603 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3604 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3605 short_channel_id: 333,
3608 cltv_expiry_delta: 0,
3609 htlc_minimum_msat: 0,
3610 htlc_maximum_msat: 10_000,
3612 fee_proportional_millionths: 0,
3613 excess_data: Vec::new()
3617 // Attempt to route more than available results in a failure.
3618 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3619 &our_id, &payment_params, &network_graph.read_only(), None, 10_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3620 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3621 } else { panic!(); }
3625 // Now, attempt to route an exact amount we have should be fine.
3626 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 10_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3627 assert_eq!(route.paths.len(), 1);
3628 let path = route.paths.last().unwrap();
3629 assert_eq!(path.len(), 2);
3630 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3631 assert_eq!(path.last().unwrap().fee_msat, 10_000);
3636 fn available_liquidity_last_hop_test() {
3637 // Check that available liquidity properly limits the path even when only
3638 // one of the latter hops is limited.
3639 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3640 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3641 let scorer = ln_test_utils::TestScorer::with_penalty(0);
3642 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3643 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3644 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(channelmanager::provided_invoice_features());
3646 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3647 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
3648 // Total capacity: 50 sats.
3650 // Disable other potential paths.
3651 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3652 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3653 short_channel_id: 2,
3656 cltv_expiry_delta: 0,
3657 htlc_minimum_msat: 0,
3658 htlc_maximum_msat: 100_000,
3660 fee_proportional_millionths: 0,
3661 excess_data: Vec::new()
3663 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3664 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3665 short_channel_id: 7,
3668 cltv_expiry_delta: 0,
3669 htlc_minimum_msat: 0,
3670 htlc_maximum_msat: 100_000,
3672 fee_proportional_millionths: 0,
3673 excess_data: Vec::new()
3678 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3679 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3680 short_channel_id: 12,
3683 cltv_expiry_delta: 0,
3684 htlc_minimum_msat: 0,
3685 htlc_maximum_msat: 100_000,
3687 fee_proportional_millionths: 0,
3688 excess_data: Vec::new()
3690 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3691 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3692 short_channel_id: 13,
3695 cltv_expiry_delta: 0,
3696 htlc_minimum_msat: 0,
3697 htlc_maximum_msat: 100_000,
3699 fee_proportional_millionths: 0,
3700 excess_data: Vec::new()
3703 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3704 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3705 short_channel_id: 6,
3708 cltv_expiry_delta: 0,
3709 htlc_minimum_msat: 0,
3710 htlc_maximum_msat: 50_000,
3712 fee_proportional_millionths: 0,
3713 excess_data: Vec::new()
3715 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3716 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3717 short_channel_id: 11,
3720 cltv_expiry_delta: 0,
3721 htlc_minimum_msat: 0,
3722 htlc_maximum_msat: 100_000,
3724 fee_proportional_millionths: 0,
3725 excess_data: Vec::new()
3728 // Attempt to route more than available results in a failure.
3729 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3730 &our_id, &payment_params, &network_graph.read_only(), None, 60_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3731 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3732 } else { panic!(); }
3736 // Now, attempt to route 49 sats (just a bit below the capacity).
3737 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 49_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3738 assert_eq!(route.paths.len(), 1);
3739 let mut total_amount_paid_msat = 0;
3740 for path in &route.paths {
3741 assert_eq!(path.len(), 4);
3742 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3743 total_amount_paid_msat += path.last().unwrap().fee_msat;
3745 assert_eq!(total_amount_paid_msat, 49_000);
3749 // Attempt to route an exact amount is also fine
3750 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3751 assert_eq!(route.paths.len(), 1);
3752 let mut total_amount_paid_msat = 0;
3753 for path in &route.paths {
3754 assert_eq!(path.len(), 4);
3755 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3756 total_amount_paid_msat += path.last().unwrap().fee_msat;
3758 assert_eq!(total_amount_paid_msat, 50_000);
3763 fn ignore_fee_first_hop_test() {
3764 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3765 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3766 let scorer = ln_test_utils::TestScorer::with_penalty(0);
3767 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3768 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3769 let payment_params = PaymentParameters::from_node_id(nodes[2]);
3771 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3772 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3773 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3774 short_channel_id: 1,
3777 cltv_expiry_delta: 0,
3778 htlc_minimum_msat: 0,
3779 htlc_maximum_msat: 100_000,
3780 fee_base_msat: 1_000_000,
3781 fee_proportional_millionths: 0,
3782 excess_data: Vec::new()
3784 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3785 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3786 short_channel_id: 3,
3789 cltv_expiry_delta: 0,
3790 htlc_minimum_msat: 0,
3791 htlc_maximum_msat: 50_000,
3793 fee_proportional_millionths: 0,
3794 excess_data: Vec::new()
3798 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3799 assert_eq!(route.paths.len(), 1);
3800 let mut total_amount_paid_msat = 0;
3801 for path in &route.paths {
3802 assert_eq!(path.len(), 2);
3803 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3804 total_amount_paid_msat += path.last().unwrap().fee_msat;
3806 assert_eq!(total_amount_paid_msat, 50_000);
3811 fn simple_mpp_route_test() {
3812 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3813 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3814 let scorer = ln_test_utils::TestScorer::with_penalty(0);
3815 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3816 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3817 let payment_params = PaymentParameters::from_node_id(nodes[2])
3818 .with_features(channelmanager::provided_invoice_features());
3820 // We need a route consisting of 3 paths:
3821 // From our node to node2 via node0, node7, node1 (three paths one hop each).
3822 // To achieve this, the amount being transferred should be around
3823 // the total capacity of these 3 paths.
3825 // First, we set limits on these (previously unlimited) channels.
3826 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
3828 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3829 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3830 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3831 short_channel_id: 1,
3834 cltv_expiry_delta: 0,
3835 htlc_minimum_msat: 0,
3836 htlc_maximum_msat: 100_000,
3838 fee_proportional_millionths: 0,
3839 excess_data: Vec::new()
3841 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3842 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3843 short_channel_id: 3,
3846 cltv_expiry_delta: 0,
3847 htlc_minimum_msat: 0,
3848 htlc_maximum_msat: 50_000,
3850 fee_proportional_millionths: 0,
3851 excess_data: Vec::new()
3854 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
3855 // (total limit 60).
3856 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3857 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3858 short_channel_id: 12,
3861 cltv_expiry_delta: 0,
3862 htlc_minimum_msat: 0,
3863 htlc_maximum_msat: 60_000,
3865 fee_proportional_millionths: 0,
3866 excess_data: Vec::new()
3868 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3869 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3870 short_channel_id: 13,
3873 cltv_expiry_delta: 0,
3874 htlc_minimum_msat: 0,
3875 htlc_maximum_msat: 60_000,
3877 fee_proportional_millionths: 0,
3878 excess_data: Vec::new()
3881 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
3882 // (total capacity 180 sats).
3883 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3884 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3885 short_channel_id: 2,
3888 cltv_expiry_delta: 0,
3889 htlc_minimum_msat: 0,
3890 htlc_maximum_msat: 200_000,
3892 fee_proportional_millionths: 0,
3893 excess_data: Vec::new()
3895 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3896 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3897 short_channel_id: 4,
3900 cltv_expiry_delta: 0,
3901 htlc_minimum_msat: 0,
3902 htlc_maximum_msat: 180_000,
3904 fee_proportional_millionths: 0,
3905 excess_data: Vec::new()
3909 // Attempt to route more than available results in a failure.
3910 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3911 &our_id, &payment_params, &network_graph.read_only(), None, 300_000, 42,
3912 Arc::clone(&logger), &scorer, &random_seed_bytes) {
3913 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3914 } else { panic!(); }
3918 // Attempt to route while setting max_path_count to 0 results in a failure.
3919 let zero_payment_params = payment_params.clone().with_max_path_count(0);
3920 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3921 &our_id, &zero_payment_params, &network_graph.read_only(), None, 100, 42,
3922 Arc::clone(&logger), &scorer, &random_seed_bytes) {
3923 assert_eq!(err, "Can't find a route with no paths allowed.");
3924 } else { panic!(); }
3928 // Attempt to route while setting max_path_count to 3 results in a failure.
3929 // This is the case because the minimal_value_contribution_msat would require each path
3930 // to account for 1/3 of the total value, which is violated by 2 out of 3 paths.
3931 let fail_payment_params = payment_params.clone().with_max_path_count(3);
3932 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3933 &our_id, &fail_payment_params, &network_graph.read_only(), None, 250_000, 42,
3934 Arc::clone(&logger), &scorer, &random_seed_bytes) {
3935 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3936 } else { panic!(); }
3940 // Now, attempt to route 250 sats (just a bit below the capacity).
3941 // Our algorithm should provide us with these 3 paths.
3942 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None,
3943 250_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3944 assert_eq!(route.paths.len(), 3);
3945 let mut total_amount_paid_msat = 0;
3946 for path in &route.paths {
3947 assert_eq!(path.len(), 2);
3948 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3949 total_amount_paid_msat += path.last().unwrap().fee_msat;
3951 assert_eq!(total_amount_paid_msat, 250_000);
3955 // Attempt to route an exact amount is also fine
3956 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None,
3957 290_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3958 assert_eq!(route.paths.len(), 3);
3959 let mut total_amount_paid_msat = 0;
3960 for path in &route.paths {
3961 assert_eq!(path.len(), 2);
3962 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3963 total_amount_paid_msat += path.last().unwrap().fee_msat;
3965 assert_eq!(total_amount_paid_msat, 290_000);
3970 fn long_mpp_route_test() {
3971 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3972 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3973 let scorer = ln_test_utils::TestScorer::with_penalty(0);
3974 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3975 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3976 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(channelmanager::provided_invoice_features());
3978 // We need a route consisting of 3 paths:
3979 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3980 // Note that these paths overlap (channels 5, 12, 13).
3981 // We will route 300 sats.
3982 // Each path will have 100 sats capacity, those channels which
3983 // are used twice will have 200 sats capacity.
3985 // Disable other potential paths.
3986 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3987 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3988 short_channel_id: 2,
3991 cltv_expiry_delta: 0,
3992 htlc_minimum_msat: 0,
3993 htlc_maximum_msat: 100_000,
3995 fee_proportional_millionths: 0,
3996 excess_data: Vec::new()
3998 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3999 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4000 short_channel_id: 7,
4003 cltv_expiry_delta: 0,
4004 htlc_minimum_msat: 0,
4005 htlc_maximum_msat: 100_000,
4007 fee_proportional_millionths: 0,
4008 excess_data: Vec::new()
4011 // Path via {node0, node2} is channels {1, 3, 5}.
4012 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4013 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4014 short_channel_id: 1,
4017 cltv_expiry_delta: 0,
4018 htlc_minimum_msat: 0,
4019 htlc_maximum_msat: 100_000,
4021 fee_proportional_millionths: 0,
4022 excess_data: Vec::new()
4024 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4025 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4026 short_channel_id: 3,
4029 cltv_expiry_delta: 0,
4030 htlc_minimum_msat: 0,
4031 htlc_maximum_msat: 100_000,
4033 fee_proportional_millionths: 0,
4034 excess_data: Vec::new()
4037 // Capacity of 200 sats because this channel will be used by 3rd path as well.
4038 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4039 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4040 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4041 short_channel_id: 5,
4044 cltv_expiry_delta: 0,
4045 htlc_minimum_msat: 0,
4046 htlc_maximum_msat: 200_000,
4048 fee_proportional_millionths: 0,
4049 excess_data: Vec::new()
4052 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4053 // Add 100 sats to the capacities of {12, 13}, because these channels
4054 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
4055 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4056 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4057 short_channel_id: 12,
4060 cltv_expiry_delta: 0,
4061 htlc_minimum_msat: 0,
4062 htlc_maximum_msat: 200_000,
4064 fee_proportional_millionths: 0,
4065 excess_data: Vec::new()
4067 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4068 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4069 short_channel_id: 13,
4072 cltv_expiry_delta: 0,
4073 htlc_minimum_msat: 0,
4074 htlc_maximum_msat: 200_000,
4076 fee_proportional_millionths: 0,
4077 excess_data: Vec::new()
4080 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4081 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4082 short_channel_id: 6,
4085 cltv_expiry_delta: 0,
4086 htlc_minimum_msat: 0,
4087 htlc_maximum_msat: 100_000,
4089 fee_proportional_millionths: 0,
4090 excess_data: Vec::new()
4092 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4093 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4094 short_channel_id: 11,
4097 cltv_expiry_delta: 0,
4098 htlc_minimum_msat: 0,
4099 htlc_maximum_msat: 100_000,
4101 fee_proportional_millionths: 0,
4102 excess_data: Vec::new()
4105 // Path via {node7, node2} is channels {12, 13, 5}.
4106 // We already limited them to 200 sats (they are used twice for 100 sats).
4107 // Nothing to do here.
4110 // Attempt to route more than available results in a failure.
4111 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4112 &our_id, &payment_params, &network_graph.read_only(), None, 350_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
4113 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4114 } else { panic!(); }
4118 // Now, attempt to route 300 sats (exact amount we can route).
4119 // Our algorithm should provide us with these 3 paths, 100 sats each.
4120 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 300_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4121 assert_eq!(route.paths.len(), 3);
4123 let mut total_amount_paid_msat = 0;
4124 for path in &route.paths {
4125 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
4126 total_amount_paid_msat += path.last().unwrap().fee_msat;
4128 assert_eq!(total_amount_paid_msat, 300_000);
4134 fn mpp_cheaper_route_test() {
4135 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4136 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4137 let scorer = ln_test_utils::TestScorer::with_penalty(0);
4138 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4139 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4140 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(channelmanager::provided_invoice_features());
4142 // This test checks that if we have two cheaper paths and one more expensive path,
4143 // so that liquidity-wise any 2 of 3 combination is sufficient,
4144 // two cheaper paths will be taken.
4145 // These paths have equal available liquidity.
4147 // We need a combination of 3 paths:
4148 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
4149 // Note that these paths overlap (channels 5, 12, 13).
4150 // Each path will have 100 sats capacity, those channels which
4151 // are used twice will have 200 sats capacity.
4153 // Disable other potential paths.
4154 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4155 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4156 short_channel_id: 2,
4159 cltv_expiry_delta: 0,
4160 htlc_minimum_msat: 0,
4161 htlc_maximum_msat: 100_000,
4163 fee_proportional_millionths: 0,
4164 excess_data: Vec::new()
4166 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4167 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4168 short_channel_id: 7,
4171 cltv_expiry_delta: 0,
4172 htlc_minimum_msat: 0,
4173 htlc_maximum_msat: 100_000,
4175 fee_proportional_millionths: 0,
4176 excess_data: Vec::new()
4179 // Path via {node0, node2} is channels {1, 3, 5}.
4180 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4181 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4182 short_channel_id: 1,
4185 cltv_expiry_delta: 0,
4186 htlc_minimum_msat: 0,
4187 htlc_maximum_msat: 100_000,
4189 fee_proportional_millionths: 0,
4190 excess_data: Vec::new()
4192 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4193 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4194 short_channel_id: 3,
4197 cltv_expiry_delta: 0,
4198 htlc_minimum_msat: 0,
4199 htlc_maximum_msat: 100_000,
4201 fee_proportional_millionths: 0,
4202 excess_data: Vec::new()
4205 // Capacity of 200 sats because this channel will be used by 3rd path as well.
4206 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4207 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4208 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4209 short_channel_id: 5,
4212 cltv_expiry_delta: 0,
4213 htlc_minimum_msat: 0,
4214 htlc_maximum_msat: 200_000,
4216 fee_proportional_millionths: 0,
4217 excess_data: Vec::new()
4220 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4221 // Add 100 sats to the capacities of {12, 13}, because these channels
4222 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
4223 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4224 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4225 short_channel_id: 12,
4228 cltv_expiry_delta: 0,
4229 htlc_minimum_msat: 0,
4230 htlc_maximum_msat: 200_000,
4232 fee_proportional_millionths: 0,
4233 excess_data: Vec::new()
4235 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4236 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4237 short_channel_id: 13,
4240 cltv_expiry_delta: 0,
4241 htlc_minimum_msat: 0,
4242 htlc_maximum_msat: 200_000,
4244 fee_proportional_millionths: 0,
4245 excess_data: Vec::new()
4248 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4249 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4250 short_channel_id: 6,
4253 cltv_expiry_delta: 0,
4254 htlc_minimum_msat: 0,
4255 htlc_maximum_msat: 100_000,
4256 fee_base_msat: 1_000,
4257 fee_proportional_millionths: 0,
4258 excess_data: Vec::new()
4260 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4261 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4262 short_channel_id: 11,
4265 cltv_expiry_delta: 0,
4266 htlc_minimum_msat: 0,
4267 htlc_maximum_msat: 100_000,
4269 fee_proportional_millionths: 0,
4270 excess_data: Vec::new()
4273 // Path via {node7, node2} is channels {12, 13, 5}.
4274 // We already limited them to 200 sats (they are used twice for 100 sats).
4275 // Nothing to do here.
4278 // Now, attempt to route 180 sats.
4279 // Our algorithm should provide us with these 2 paths.
4280 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 180_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4281 assert_eq!(route.paths.len(), 2);
4283 let mut total_value_transferred_msat = 0;
4284 let mut total_paid_msat = 0;
4285 for path in &route.paths {
4286 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
4287 total_value_transferred_msat += path.last().unwrap().fee_msat;
4289 total_paid_msat += hop.fee_msat;
4292 // If we paid fee, this would be higher.
4293 assert_eq!(total_value_transferred_msat, 180_000);
4294 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
4295 assert_eq!(total_fees_paid, 0);
4300 fn fees_on_mpp_route_test() {
4301 // This test makes sure that MPP algorithm properly takes into account
4302 // fees charged on the channels, by making the fees impactful:
4303 // if the fee is not properly accounted for, the behavior is different.
4304 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4305 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4306 let scorer = ln_test_utils::TestScorer::with_penalty(0);
4307 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4308 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4309 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(channelmanager::provided_invoice_features());
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 payment_params = PaymentParameters::from_node_id(PublicKey::from_slice(&[02; 33]).unwrap()).with_features(channelmanager::provided_invoice_features())
4491 .with_route_hints(vec![RouteHint(vec![RouteHintHop {
4492 src_node_id: nodes[2],
4493 short_channel_id: 42,
4494 fees: RoutingFees { base_msat: 0, proportional_millionths: 0 },
4495 cltv_expiry_delta: 42,
4496 htlc_minimum_msat: None,
4497 htlc_maximum_msat: None,
4498 }])]).with_max_channel_saturation_power_of_half(0);
4500 // Keep only two paths from us to nodes[2], both with a 99sat HTLC maximum, with one with
4501 // no fee and one with a 1msat fee. Previously, trying to route 100 sats to nodes[2] here
4502 // would first use the no-fee route and then fail to find a path along the second route as
4503 // we think we can only send up to 1 additional sat over the last-hop but refuse to as its
4504 // under 5% of our payment amount.
4505 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4506 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4507 short_channel_id: 1,
4510 cltv_expiry_delta: (5 << 4) | 5,
4511 htlc_minimum_msat: 0,
4512 htlc_maximum_msat: 99_000,
4513 fee_base_msat: u32::max_value(),
4514 fee_proportional_millionths: u32::max_value(),
4515 excess_data: Vec::new()
4517 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4518 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4519 short_channel_id: 2,
4522 cltv_expiry_delta: (5 << 4) | 3,
4523 htlc_minimum_msat: 0,
4524 htlc_maximum_msat: 99_000,
4525 fee_base_msat: u32::max_value(),
4526 fee_proportional_millionths: u32::max_value(),
4527 excess_data: Vec::new()
4529 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4530 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4531 short_channel_id: 4,
4534 cltv_expiry_delta: (4 << 4) | 1,
4535 htlc_minimum_msat: 0,
4536 htlc_maximum_msat: MAX_VALUE_MSAT,
4538 fee_proportional_millionths: 0,
4539 excess_data: Vec::new()
4541 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4542 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4543 short_channel_id: 13,
4545 flags: 0|2, // Channel disabled
4546 cltv_expiry_delta: (13 << 4) | 1,
4547 htlc_minimum_msat: 0,
4548 htlc_maximum_msat: MAX_VALUE_MSAT,
4550 fee_proportional_millionths: 2000000,
4551 excess_data: Vec::new()
4554 // Get a route for 100 sats and check that we found the MPP route no problem and didn't
4556 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();
4557 assert_eq!(route.paths.len(), 2);
4558 route.paths.sort_by_key(|path| path[0].short_channel_id);
4559 // Paths are manually ordered ordered by SCID, so:
4560 // * the first is channel 1 (0 fee, but 99 sat maximum) -> channel 3 -> channel 42
4561 // * the second is channel 2 (1 msat fee) -> channel 4 -> channel 42
4562 assert_eq!(route.paths[0][0].short_channel_id, 1);
4563 assert_eq!(route.paths[0][0].fee_msat, 0);
4564 assert_eq!(route.paths[0][2].fee_msat, 99_000);
4565 assert_eq!(route.paths[1][0].short_channel_id, 2);
4566 assert_eq!(route.paths[1][0].fee_msat, 1);
4567 assert_eq!(route.paths[1][2].fee_msat, 1_000);
4568 assert_eq!(route.get_total_fees(), 1);
4569 assert_eq!(route.get_total_amount(), 100_000);
4573 fn drop_lowest_channel_mpp_route_test() {
4574 // This test checks that low-capacity channel is dropped when after
4575 // path finding we realize that we found more capacity than we need.
4576 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4577 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4578 let scorer = ln_test_utils::TestScorer::with_penalty(0);
4579 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4580 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4581 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(channelmanager::provided_invoice_features())
4582 .with_max_channel_saturation_power_of_half(0);
4584 // We need a route consisting of 3 paths:
4585 // From our node to node2 via node0, node7, node1 (three paths one hop each).
4587 // The first and the second paths should be sufficient, but the third should be
4588 // cheaper, so that we select it but drop later.
4590 // First, we set limits on these (previously unlimited) channels.
4591 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
4593 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
4594 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4595 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4596 short_channel_id: 1,
4599 cltv_expiry_delta: 0,
4600 htlc_minimum_msat: 0,
4601 htlc_maximum_msat: 100_000,
4603 fee_proportional_millionths: 0,
4604 excess_data: Vec::new()
4606 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4607 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4608 short_channel_id: 3,
4611 cltv_expiry_delta: 0,
4612 htlc_minimum_msat: 0,
4613 htlc_maximum_msat: 50_000,
4615 fee_proportional_millionths: 0,
4616 excess_data: Vec::new()
4619 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
4620 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4621 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4622 short_channel_id: 12,
4625 cltv_expiry_delta: 0,
4626 htlc_minimum_msat: 0,
4627 htlc_maximum_msat: 60_000,
4629 fee_proportional_millionths: 0,
4630 excess_data: Vec::new()
4632 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4633 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4634 short_channel_id: 13,
4637 cltv_expiry_delta: 0,
4638 htlc_minimum_msat: 0,
4639 htlc_maximum_msat: 60_000,
4641 fee_proportional_millionths: 0,
4642 excess_data: Vec::new()
4645 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
4646 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4647 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4648 short_channel_id: 2,
4651 cltv_expiry_delta: 0,
4652 htlc_minimum_msat: 0,
4653 htlc_maximum_msat: 20_000,
4655 fee_proportional_millionths: 0,
4656 excess_data: Vec::new()
4658 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4659 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4660 short_channel_id: 4,
4663 cltv_expiry_delta: 0,
4664 htlc_minimum_msat: 0,
4665 htlc_maximum_msat: 20_000,
4667 fee_proportional_millionths: 0,
4668 excess_data: Vec::new()
4672 // Attempt to route more than available results in a failure.
4673 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4674 &our_id, &payment_params, &network_graph.read_only(), None, 150_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
4675 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4676 } else { panic!(); }
4680 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
4681 // Our algorithm should provide us with these 3 paths.
4682 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 125_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4683 assert_eq!(route.paths.len(), 3);
4684 let mut total_amount_paid_msat = 0;
4685 for path in &route.paths {
4686 assert_eq!(path.len(), 2);
4687 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4688 total_amount_paid_msat += path.last().unwrap().fee_msat;
4690 assert_eq!(total_amount_paid_msat, 125_000);
4694 // Attempt to route without the last small cheap channel
4695 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4696 assert_eq!(route.paths.len(), 2);
4697 let mut total_amount_paid_msat = 0;
4698 for path in &route.paths {
4699 assert_eq!(path.len(), 2);
4700 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4701 total_amount_paid_msat += path.last().unwrap().fee_msat;
4703 assert_eq!(total_amount_paid_msat, 90_000);
4708 fn min_criteria_consistency() {
4709 // Test that we don't use an inconsistent metric between updating and walking nodes during
4710 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
4711 // was updated with a different criterion from the heap sorting, resulting in loops in
4712 // calculated paths. We test for that specific case here.
4714 // We construct a network that looks like this:
4716 // node2 -1(3)2- node3
4720 // node1 -1(5)2- node4 -1(1)2- node6
4726 // We create a loop on the side of our real path - our destination is node 6, with a
4727 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
4728 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
4729 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
4730 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
4731 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
4732 // "previous hop" being set to node 3, creating a loop in the path.
4733 let secp_ctx = Secp256k1::new();
4734 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
4735 let logger = Arc::new(ln_test_utils::TestLogger::new());
4736 let network = Arc::new(NetworkGraph::new(genesis_hash, Arc::clone(&logger)));
4737 let gossip_sync = P2PGossipSync::new(Arc::clone(&network), None, Arc::clone(&logger));
4738 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4739 let scorer = ln_test_utils::TestScorer::with_penalty(0);
4740 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4741 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4742 let payment_params = PaymentParameters::from_node_id(nodes[6]);
4744 add_channel(&gossip_sync, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
4745 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4746 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4747 short_channel_id: 6,
4750 cltv_expiry_delta: (6 << 4) | 0,
4751 htlc_minimum_msat: 0,
4752 htlc_maximum_msat: MAX_VALUE_MSAT,
4754 fee_proportional_millionths: 0,
4755 excess_data: Vec::new()
4757 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
4759 add_channel(&gossip_sync, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4760 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4761 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4762 short_channel_id: 5,
4765 cltv_expiry_delta: (5 << 4) | 0,
4766 htlc_minimum_msat: 0,
4767 htlc_maximum_msat: MAX_VALUE_MSAT,
4769 fee_proportional_millionths: 0,
4770 excess_data: Vec::new()
4772 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
4774 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
4775 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4776 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4777 short_channel_id: 4,
4780 cltv_expiry_delta: (4 << 4) | 0,
4781 htlc_minimum_msat: 0,
4782 htlc_maximum_msat: MAX_VALUE_MSAT,
4784 fee_proportional_millionths: 0,
4785 excess_data: Vec::new()
4787 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
4789 add_channel(&gossip_sync, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
4790 update_channel(&gossip_sync, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
4791 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4792 short_channel_id: 3,
4795 cltv_expiry_delta: (3 << 4) | 0,
4796 htlc_minimum_msat: 0,
4797 htlc_maximum_msat: MAX_VALUE_MSAT,
4799 fee_proportional_millionths: 0,
4800 excess_data: Vec::new()
4802 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
4804 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
4805 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4806 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4807 short_channel_id: 2,
4810 cltv_expiry_delta: (2 << 4) | 0,
4811 htlc_minimum_msat: 0,
4812 htlc_maximum_msat: MAX_VALUE_MSAT,
4814 fee_proportional_millionths: 0,
4815 excess_data: Vec::new()
4818 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
4819 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4820 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4821 short_channel_id: 1,
4824 cltv_expiry_delta: (1 << 4) | 0,
4825 htlc_minimum_msat: 100,
4826 htlc_maximum_msat: MAX_VALUE_MSAT,
4828 fee_proportional_millionths: 0,
4829 excess_data: Vec::new()
4831 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
4834 // Now ensure the route flows simply over nodes 1 and 4 to 6.
4835 let route = get_route(&our_id, &payment_params, &network.read_only(), None, 10_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4836 assert_eq!(route.paths.len(), 1);
4837 assert_eq!(route.paths[0].len(), 3);
4839 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
4840 assert_eq!(route.paths[0][0].short_channel_id, 6);
4841 assert_eq!(route.paths[0][0].fee_msat, 100);
4842 assert_eq!(route.paths[0][0].cltv_expiry_delta, (5 << 4) | 0);
4843 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(1));
4844 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(6));
4846 assert_eq!(route.paths[0][1].pubkey, nodes[4]);
4847 assert_eq!(route.paths[0][1].short_channel_id, 5);
4848 assert_eq!(route.paths[0][1].fee_msat, 0);
4849 assert_eq!(route.paths[0][1].cltv_expiry_delta, (1 << 4) | 0);
4850 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(4));
4851 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(5));
4853 assert_eq!(route.paths[0][2].pubkey, nodes[6]);
4854 assert_eq!(route.paths[0][2].short_channel_id, 1);
4855 assert_eq!(route.paths[0][2].fee_msat, 10_000);
4856 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
4857 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
4858 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(1));
4864 fn exact_fee_liquidity_limit() {
4865 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
4866 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
4867 // we calculated fees on a higher value, resulting in us ignoring such paths.
4868 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4869 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
4870 let scorer = ln_test_utils::TestScorer::with_penalty(0);
4871 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4872 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4873 let payment_params = PaymentParameters::from_node_id(nodes[2]);
4875 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
4877 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4878 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4879 short_channel_id: 2,
4882 cltv_expiry_delta: 0,
4883 htlc_minimum_msat: 0,
4884 htlc_maximum_msat: 85_000,
4886 fee_proportional_millionths: 0,
4887 excess_data: Vec::new()
4890 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4891 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4892 short_channel_id: 12,
4895 cltv_expiry_delta: (4 << 4) | 1,
4896 htlc_minimum_msat: 0,
4897 htlc_maximum_msat: 270_000,
4899 fee_proportional_millionths: 1000000,
4900 excess_data: Vec::new()
4904 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
4905 // 200% fee charged channel 13 in the 1-to-2 direction.
4906 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4907 assert_eq!(route.paths.len(), 1);
4908 assert_eq!(route.paths[0].len(), 2);
4910 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
4911 assert_eq!(route.paths[0][0].short_channel_id, 12);
4912 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
4913 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
4914 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
4915 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
4917 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
4918 assert_eq!(route.paths[0][1].short_channel_id, 13);
4919 assert_eq!(route.paths[0][1].fee_msat, 90_000);
4920 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
4921 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
4922 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
4927 fn htlc_max_reduction_below_min() {
4928 // Test that if, while walking the graph, we reduce the value being sent to meet an
4929 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
4930 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
4931 // resulting in us thinking there is no possible path, even if other paths exist.
4932 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4933 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4934 let scorer = ln_test_utils::TestScorer::with_penalty(0);
4935 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4936 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4937 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(channelmanager::provided_invoice_features());
4939 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
4940 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
4941 // then try to send 90_000.
4942 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4943 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4944 short_channel_id: 2,
4947 cltv_expiry_delta: 0,
4948 htlc_minimum_msat: 0,
4949 htlc_maximum_msat: 80_000,
4951 fee_proportional_millionths: 0,
4952 excess_data: Vec::new()
4954 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4955 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4956 short_channel_id: 4,
4959 cltv_expiry_delta: (4 << 4) | 1,
4960 htlc_minimum_msat: 90_000,
4961 htlc_maximum_msat: MAX_VALUE_MSAT,
4963 fee_proportional_millionths: 0,
4964 excess_data: Vec::new()
4968 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
4969 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
4970 // expensive) channels 12-13 path.
4971 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4972 assert_eq!(route.paths.len(), 1);
4973 assert_eq!(route.paths[0].len(), 2);
4975 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
4976 assert_eq!(route.paths[0][0].short_channel_id, 12);
4977 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
4978 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
4979 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
4980 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
4982 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
4983 assert_eq!(route.paths[0][1].short_channel_id, 13);
4984 assert_eq!(route.paths[0][1].fee_msat, 90_000);
4985 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
4986 assert_eq!(route.paths[0][1].node_features.le_flags(), channelmanager::provided_invoice_features().le_flags());
4987 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
4992 fn multiple_direct_first_hops() {
4993 // Previously we'd only ever considered one first hop path per counterparty.
4994 // However, as we don't restrict users to one channel per peer, we really need to support
4995 // looking at all first hop paths.
4996 // Here we test that we do not ignore all-but-the-last first hop paths per counterparty (as
4997 // we used to do by overwriting the `first_hop_targets` hashmap entry) and that we can MPP
4998 // route over multiple channels with the same first hop.
4999 let secp_ctx = Secp256k1::new();
5000 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5001 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
5002 let logger = Arc::new(ln_test_utils::TestLogger::new());
5003 let network_graph = NetworkGraph::new(genesis_hash, Arc::clone(&logger));
5004 let scorer = ln_test_utils::TestScorer::with_penalty(0);
5005 let payment_params = PaymentParameters::from_node_id(nodes[0]).with_features(channelmanager::provided_invoice_features());
5006 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5007 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5010 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
5011 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(), 200_000),
5012 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(), 10_000),
5013 ]), 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5014 assert_eq!(route.paths.len(), 1);
5015 assert_eq!(route.paths[0].len(), 1);
5017 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
5018 assert_eq!(route.paths[0][0].short_channel_id, 3);
5019 assert_eq!(route.paths[0][0].fee_msat, 100_000);
5022 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
5023 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(), 50_000),
5024 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(), 50_000),
5025 ]), 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5026 assert_eq!(route.paths.len(), 2);
5027 assert_eq!(route.paths[0].len(), 1);
5028 assert_eq!(route.paths[1].len(), 1);
5030 assert!((route.paths[0][0].short_channel_id == 3 && route.paths[1][0].short_channel_id == 2) ||
5031 (route.paths[0][0].short_channel_id == 2 && route.paths[1][0].short_channel_id == 3));
5033 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
5034 assert_eq!(route.paths[0][0].fee_msat, 50_000);
5036 assert_eq!(route.paths[1][0].pubkey, nodes[0]);
5037 assert_eq!(route.paths[1][0].fee_msat, 50_000);
5041 // If we have a bunch of outbound channels to the same node, where most are not
5042 // sufficient to pay the full payment, but one is, we should default to just using the
5043 // one single channel that has sufficient balance, avoiding MPP.
5045 // If we have several options above the 3xpayment value threshold, we should pick the
5046 // smallest of them, avoiding further fragmenting our available outbound balance to
5048 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
5049 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(), 50_000),
5050 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(), 50_000),
5051 &get_channel_details(Some(5), nodes[0], channelmanager::provided_init_features(), 50_000),
5052 &get_channel_details(Some(6), nodes[0], channelmanager::provided_init_features(), 300_000),
5053 &get_channel_details(Some(7), nodes[0], channelmanager::provided_init_features(), 50_000),
5054 &get_channel_details(Some(8), nodes[0], channelmanager::provided_init_features(), 50_000),
5055 &get_channel_details(Some(9), nodes[0], channelmanager::provided_init_features(), 50_000),
5056 &get_channel_details(Some(4), nodes[0], channelmanager::provided_init_features(), 1_000_000),
5057 ]), 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5058 assert_eq!(route.paths.len(), 1);
5059 assert_eq!(route.paths[0].len(), 1);
5061 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
5062 assert_eq!(route.paths[0][0].short_channel_id, 6);
5063 assert_eq!(route.paths[0][0].fee_msat, 100_000);
5068 fn prefers_shorter_route_with_higher_fees() {
5069 let (secp_ctx, network_graph, _, _, logger) = build_graph();
5070 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5071 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
5073 // Without penalizing each hop 100 msats, a longer path with lower fees is chosen.
5074 let scorer = ln_test_utils::TestScorer::with_penalty(0);
5075 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5076 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5077 let route = get_route(
5078 &our_id, &payment_params, &network_graph.read_only(), None, 100, 42,
5079 Arc::clone(&logger), &scorer, &random_seed_bytes
5081 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5083 assert_eq!(route.get_total_fees(), 100);
5084 assert_eq!(route.get_total_amount(), 100);
5085 assert_eq!(path, vec![2, 4, 6, 11, 8]);
5087 // Applying a 100 msat penalty to each hop results in taking channels 7 and 10 to nodes[6]
5088 // from nodes[2] rather than channel 6, 11, and 8, even though the longer path is cheaper.
5089 let scorer = ln_test_utils::TestScorer::with_penalty(100);
5090 let route = get_route(
5091 &our_id, &payment_params, &network_graph.read_only(), None, 100, 42,
5092 Arc::clone(&logger), &scorer, &random_seed_bytes
5094 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5096 assert_eq!(route.get_total_fees(), 300);
5097 assert_eq!(route.get_total_amount(), 100);
5098 assert_eq!(path, vec![2, 4, 7, 10]);
5101 struct BadChannelScorer {
5102 short_channel_id: u64,
5106 impl Writeable for BadChannelScorer {
5107 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
5109 impl Score for BadChannelScorer {
5110 fn channel_penalty_msat(&self, short_channel_id: u64, _: &NodeId, _: &NodeId, _: ChannelUsage) -> u64 {
5111 if short_channel_id == self.short_channel_id { u64::max_value() } else { 0 }
5114 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
5115 fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
5116 fn probe_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
5117 fn probe_successful(&mut self, _path: &[&RouteHop]) {}
5120 struct BadNodeScorer {
5125 impl Writeable for BadNodeScorer {
5126 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
5129 impl Score for BadNodeScorer {
5130 fn channel_penalty_msat(&self, _: u64, _: &NodeId, target: &NodeId, _: ChannelUsage) -> u64 {
5131 if *target == self.node_id { u64::max_value() } else { 0 }
5134 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
5135 fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
5136 fn probe_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
5137 fn probe_successful(&mut self, _path: &[&RouteHop]) {}
5141 fn avoids_routing_through_bad_channels_and_nodes() {
5142 let (secp_ctx, network, _, _, logger) = build_graph();
5143 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5144 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
5145 let network_graph = network.read_only();
5147 // A path to nodes[6] exists when no penalties are applied to any channel.
5148 let scorer = ln_test_utils::TestScorer::with_penalty(0);
5149 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5150 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5151 let route = get_route(
5152 &our_id, &payment_params, &network_graph, None, 100, 42,
5153 Arc::clone(&logger), &scorer, &random_seed_bytes
5155 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5157 assert_eq!(route.get_total_fees(), 100);
5158 assert_eq!(route.get_total_amount(), 100);
5159 assert_eq!(path, vec![2, 4, 6, 11, 8]);
5161 // A different path to nodes[6] exists if channel 6 cannot be routed over.
5162 let scorer = BadChannelScorer { short_channel_id: 6 };
5163 let route = get_route(
5164 &our_id, &payment_params, &network_graph, None, 100, 42,
5165 Arc::clone(&logger), &scorer, &random_seed_bytes
5167 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5169 assert_eq!(route.get_total_fees(), 300);
5170 assert_eq!(route.get_total_amount(), 100);
5171 assert_eq!(path, vec![2, 4, 7, 10]);
5173 // A path to nodes[6] does not exist if nodes[2] cannot be routed through.
5174 let scorer = BadNodeScorer { node_id: NodeId::from_pubkey(&nodes[2]) };
5176 &our_id, &payment_params, &network_graph, None, 100, 42,
5177 Arc::clone(&logger), &scorer, &random_seed_bytes
5179 Err(LightningError { err, .. } ) => {
5180 assert_eq!(err, "Failed to find a path to the given destination");
5182 Ok(_) => panic!("Expected error"),
5187 fn total_fees_single_path() {
5191 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5192 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5193 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5196 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5197 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5198 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5201 pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
5202 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5203 short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0
5206 payment_params: None,
5209 assert_eq!(route.get_total_fees(), 250);
5210 assert_eq!(route.get_total_amount(), 225);
5214 fn total_fees_multi_path() {
5218 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5219 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5220 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5223 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5224 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5225 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5229 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5230 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5231 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5234 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5235 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5236 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5239 payment_params: None,
5242 assert_eq!(route.get_total_fees(), 200);
5243 assert_eq!(route.get_total_amount(), 300);
5247 fn total_empty_route_no_panic() {
5248 // In an earlier version of `Route::get_total_fees` and `Route::get_total_amount`, they
5249 // would both panic if the route was completely empty. We test to ensure they return 0
5250 // here, even though its somewhat nonsensical as a route.
5251 let route = Route { paths: Vec::new(), payment_params: None };
5253 assert_eq!(route.get_total_fees(), 0);
5254 assert_eq!(route.get_total_amount(), 0);
5258 fn limits_total_cltv_delta() {
5259 let (secp_ctx, network, _, _, logger) = build_graph();
5260 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5261 let network_graph = network.read_only();
5263 let scorer = ln_test_utils::TestScorer::with_penalty(0);
5265 // Make sure that generally there is at least one route available
5266 let feasible_max_total_cltv_delta = 1008;
5267 let feasible_payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes))
5268 .with_max_total_cltv_expiry_delta(feasible_max_total_cltv_delta);
5269 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5270 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5271 let route = get_route(&our_id, &feasible_payment_params, &network_graph, None, 100, 0, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5272 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5273 assert_ne!(path.len(), 0);
5275 // But not if we exclude all paths on the basis of their accumulated CLTV delta
5276 let fail_max_total_cltv_delta = 23;
5277 let fail_payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes))
5278 .with_max_total_cltv_expiry_delta(fail_max_total_cltv_delta);
5279 match get_route(&our_id, &fail_payment_params, &network_graph, None, 100, 0, Arc::clone(&logger), &scorer, &random_seed_bytes)
5281 Err(LightningError { err, .. } ) => {
5282 assert_eq!(err, "Failed to find a path to the given destination");
5284 Ok(_) => panic!("Expected error"),
5289 fn avoids_recently_failed_paths() {
5290 // Ensure that the router always avoids all of the `previously_failed_channels` channels by
5291 // randomly inserting channels into it until we can't find a route anymore.
5292 let (secp_ctx, network, _, _, logger) = build_graph();
5293 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5294 let network_graph = network.read_only();
5296 let scorer = ln_test_utils::TestScorer::with_penalty(0);
5297 let mut payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes))
5298 .with_max_path_count(1);
5299 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5300 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5302 // We should be able to find a route initially, and then after we fail a few random
5303 // channels eventually we won't be able to any longer.
5304 assert!(get_route(&our_id, &payment_params, &network_graph, None, 100, 0, Arc::clone(&logger), &scorer, &random_seed_bytes).is_ok());
5306 if let Ok(route) = get_route(&our_id, &payment_params, &network_graph, None, 100, 0, Arc::clone(&logger), &scorer, &random_seed_bytes) {
5307 for chan in route.paths[0].iter() {
5308 assert!(!payment_params.previously_failed_channels.contains(&chan.short_channel_id));
5310 let victim = (u64::from_ne_bytes(random_seed_bytes[0..8].try_into().unwrap()) as usize)
5311 % route.paths[0].len();
5312 payment_params.previously_failed_channels.push(route.paths[0][victim].short_channel_id);
5318 fn limits_path_length() {
5319 let (secp_ctx, network, _, _, logger) = build_line_graph();
5320 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5321 let network_graph = network.read_only();
5323 let scorer = ln_test_utils::TestScorer::with_penalty(0);
5324 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5325 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5327 // First check we can actually create a long route on this graph.
5328 let feasible_payment_params = PaymentParameters::from_node_id(nodes[18]);
5329 let route = get_route(&our_id, &feasible_payment_params, &network_graph, None, 100, 0,
5330 Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5331 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5332 assert!(path.len() == MAX_PATH_LENGTH_ESTIMATE.into());
5334 // But we can't create a path surpassing the MAX_PATH_LENGTH_ESTIMATE limit.
5335 let fail_payment_params = PaymentParameters::from_node_id(nodes[19]);
5336 match get_route(&our_id, &fail_payment_params, &network_graph, None, 100, 0,
5337 Arc::clone(&logger), &scorer, &random_seed_bytes)
5339 Err(LightningError { err, .. } ) => {
5340 assert_eq!(err, "Failed to find a path to the given destination");
5342 Ok(_) => panic!("Expected error"),
5347 fn adds_and_limits_cltv_offset() {
5348 let (secp_ctx, network_graph, _, _, logger) = build_graph();
5349 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5351 let scorer = ln_test_utils::TestScorer::with_penalty(0);
5353 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
5354 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5355 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5356 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5357 assert_eq!(route.paths.len(), 1);
5359 let cltv_expiry_deltas_before = route.paths[0].iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5361 // Check whether the offset added to the last hop by default is in [1 .. DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA]
5362 let mut route_default = route.clone();
5363 add_random_cltv_offset(&mut route_default, &payment_params, &network_graph.read_only(), &random_seed_bytes);
5364 let cltv_expiry_deltas_default = route_default.paths[0].iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5365 assert_eq!(cltv_expiry_deltas_before.split_last().unwrap().1, cltv_expiry_deltas_default.split_last().unwrap().1);
5366 assert!(cltv_expiry_deltas_default.last() > cltv_expiry_deltas_before.last());
5367 assert!(cltv_expiry_deltas_default.last().unwrap() <= &DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA);
5369 // Check that no offset is added when we restrict the max_total_cltv_expiry_delta
5370 let mut route_limited = route.clone();
5371 let limited_max_total_cltv_expiry_delta = cltv_expiry_deltas_before.iter().sum();
5372 let limited_payment_params = payment_params.with_max_total_cltv_expiry_delta(limited_max_total_cltv_expiry_delta);
5373 add_random_cltv_offset(&mut route_limited, &limited_payment_params, &network_graph.read_only(), &random_seed_bytes);
5374 let cltv_expiry_deltas_limited = route_limited.paths[0].iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5375 assert_eq!(cltv_expiry_deltas_before, cltv_expiry_deltas_limited);
5379 fn adds_plausible_cltv_offset() {
5380 let (secp_ctx, network, _, _, logger) = build_graph();
5381 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5382 let network_graph = network.read_only();
5383 let network_nodes = network_graph.nodes();
5384 let network_channels = network_graph.channels();
5385 let scorer = ln_test_utils::TestScorer::with_penalty(0);
5386 let payment_params = PaymentParameters::from_node_id(nodes[3]);
5387 let keys_manager = ln_test_utils::TestKeysInterface::new(&[4u8; 32], Network::Testnet);
5388 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5390 let mut route = get_route(&our_id, &payment_params, &network_graph, None, 100, 0,
5391 Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5392 add_random_cltv_offset(&mut route, &payment_params, &network_graph, &random_seed_bytes);
5394 let mut path_plausibility = vec![];
5396 for p in route.paths {
5397 // 1. Select random observation point
5398 let mut prng = ChaCha20::new(&random_seed_bytes, &[0u8; 12]);
5399 let mut random_bytes = [0u8; ::core::mem::size_of::<usize>()];
5401 prng.process_in_place(&mut random_bytes);
5402 let random_path_index = usize::from_be_bytes(random_bytes).wrapping_rem(p.len());
5403 let observation_point = NodeId::from_pubkey(&p.get(random_path_index).unwrap().pubkey);
5405 // 2. Calculate what CLTV expiry delta we would observe there
5406 let observed_cltv_expiry_delta: u32 = p[random_path_index..].iter().map(|h| h.cltv_expiry_delta).sum();
5408 // 3. Starting from the observation point, find candidate paths
5409 let mut candidates: VecDeque<(NodeId, Vec<u32>)> = VecDeque::new();
5410 candidates.push_back((observation_point, vec![]));
5412 let mut found_plausible_candidate = false;
5414 'candidate_loop: while let Some((cur_node_id, cur_path_cltv_deltas)) = candidates.pop_front() {
5415 if let Some(remaining) = observed_cltv_expiry_delta.checked_sub(cur_path_cltv_deltas.iter().sum::<u32>()) {
5416 if remaining == 0 || remaining.wrapping_rem(40) == 0 || remaining.wrapping_rem(144) == 0 {
5417 found_plausible_candidate = true;
5418 break 'candidate_loop;
5422 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
5423 for channel_id in &cur_node.channels {
5424 if let Some(channel_info) = network_channels.get(&channel_id) {
5425 if let Some((dir_info, next_id)) = channel_info.as_directed_from(&cur_node_id) {
5426 let next_cltv_expiry_delta = dir_info.direction().cltv_expiry_delta as u32;
5427 if cur_path_cltv_deltas.iter().sum::<u32>()
5428 .saturating_add(next_cltv_expiry_delta) <= observed_cltv_expiry_delta {
5429 let mut new_path_cltv_deltas = cur_path_cltv_deltas.clone();
5430 new_path_cltv_deltas.push(next_cltv_expiry_delta);
5431 candidates.push_back((*next_id, new_path_cltv_deltas));
5439 path_plausibility.push(found_plausible_candidate);
5441 assert!(path_plausibility.iter().all(|x| *x));
5445 fn builds_correct_path_from_hops() {
5446 let (secp_ctx, network, _, _, logger) = build_graph();
5447 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5448 let network_graph = network.read_only();
5450 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5451 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5453 let payment_params = PaymentParameters::from_node_id(nodes[3]);
5454 let hops = [nodes[1], nodes[2], nodes[4], nodes[3]];
5455 let route = build_route_from_hops_internal(&our_id, &hops, &payment_params,
5456 &network_graph, 100, 0, Arc::clone(&logger), &random_seed_bytes).unwrap();
5457 let route_hop_pubkeys = route.paths[0].iter().map(|hop| hop.pubkey).collect::<Vec<_>>();
5458 assert_eq!(hops.len(), route.paths[0].len());
5459 for (idx, hop_pubkey) in hops.iter().enumerate() {
5460 assert!(*hop_pubkey == route_hop_pubkeys[idx]);
5465 fn avoids_saturating_channels() {
5466 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5467 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5469 let scorer = ProbabilisticScorer::new(Default::default(), &*network_graph, Arc::clone(&logger));
5471 // Set the fee on channel 13 to 100% to match channel 4 giving us two equivalent paths (us
5472 // -> node 7 -> node2 and us -> node 1 -> node 2) which we should balance over.
5473 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5474 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5475 short_channel_id: 4,
5478 cltv_expiry_delta: (4 << 4) | 1,
5479 htlc_minimum_msat: 0,
5480 htlc_maximum_msat: 250_000_000,
5482 fee_proportional_millionths: 0,
5483 excess_data: Vec::new()
5485 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5486 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5487 short_channel_id: 13,
5490 cltv_expiry_delta: (13 << 4) | 1,
5491 htlc_minimum_msat: 0,
5492 htlc_maximum_msat: 250_000_000,
5494 fee_proportional_millionths: 0,
5495 excess_data: Vec::new()
5498 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(channelmanager::provided_invoice_features());
5499 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5500 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5501 // 100,000 sats is less than the available liquidity on each channel, set above.
5502 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();
5503 assert_eq!(route.paths.len(), 2);
5504 assert!((route.paths[0][1].short_channel_id == 4 && route.paths[1][1].short_channel_id == 13) ||
5505 (route.paths[1][1].short_channel_id == 4 && route.paths[0][1].short_channel_id == 13));
5508 #[cfg(not(feature = "no-std"))]
5509 pub(super) fn random_init_seed() -> u64 {
5510 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
5511 use core::hash::{BuildHasher, Hasher};
5512 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
5513 println!("Using seed of {}", seed);
5516 #[cfg(not(feature = "no-std"))]
5517 use crate::util::ser::ReadableArgs;
5520 #[cfg(not(feature = "no-std"))]
5521 fn generate_routes() {
5522 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringParameters};
5524 let mut d = match super::bench_utils::get_route_file() {
5531 let logger = ln_test_utils::TestLogger::new();
5532 let graph = NetworkGraph::read(&mut d, &logger).unwrap();
5533 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5534 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5536 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
5537 let mut seed = random_init_seed() as usize;
5538 let nodes = graph.read_only().nodes().clone();
5539 'load_endpoints: for _ in 0..10 {
5541 seed = seed.overflowing_mul(0xdeadbeef).0;
5542 let src = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5543 seed = seed.overflowing_mul(0xdeadbeef).0;
5544 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5545 let payment_params = PaymentParameters::from_node_id(dst);
5546 let amt = seed as u64 % 200_000_000;
5547 let params = ProbabilisticScoringParameters::default();
5548 let scorer = ProbabilisticScorer::new(params, &graph, &logger);
5549 if get_route(src, &payment_params, &graph.read_only(), None, amt, 42, &logger, &scorer, &random_seed_bytes).is_ok() {
5550 continue 'load_endpoints;
5557 #[cfg(not(feature = "no-std"))]
5558 fn generate_routes_mpp() {
5559 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringParameters};
5561 let mut d = match super::bench_utils::get_route_file() {
5568 let logger = ln_test_utils::TestLogger::new();
5569 let graph = NetworkGraph::read(&mut d, &logger).unwrap();
5570 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5571 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5573 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
5574 let mut seed = random_init_seed() as usize;
5575 let nodes = graph.read_only().nodes().clone();
5576 'load_endpoints: for _ in 0..10 {
5578 seed = seed.overflowing_mul(0xdeadbeef).0;
5579 let src = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5580 seed = seed.overflowing_mul(0xdeadbeef).0;
5581 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5582 let payment_params = PaymentParameters::from_node_id(dst).with_features(channelmanager::provided_invoice_features());
5583 let amt = seed as u64 % 200_000_000;
5584 let params = ProbabilisticScoringParameters::default();
5585 let scorer = ProbabilisticScorer::new(params, &graph, &logger);
5586 if get_route(src, &payment_params, &graph.read_only(), None, amt, 42, &logger, &scorer, &random_seed_bytes).is_ok() {
5587 continue 'load_endpoints;
5594 fn honors_manual_penalties() {
5595 let (secp_ctx, network_graph, _, _, logger) = build_line_graph();
5596 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5598 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5599 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5601 let scorer_params = ProbabilisticScoringParameters::default();
5602 let mut scorer = ProbabilisticScorer::new(scorer_params, Arc::clone(&network_graph), Arc::clone(&logger));
5604 // First check set manual penalties are returned by the scorer.
5605 let usage = ChannelUsage {
5607 inflight_htlc_msat: 0,
5608 effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_024_000, htlc_maximum_msat: 1_000 },
5610 scorer.set_manual_penalty(&NodeId::from_pubkey(&nodes[3]), 123);
5611 scorer.set_manual_penalty(&NodeId::from_pubkey(&nodes[4]), 456);
5612 assert_eq!(scorer.channel_penalty_msat(42, &NodeId::from_pubkey(&nodes[3]), &NodeId::from_pubkey(&nodes[4]), usage), 456);
5614 // Then check we can get a normal route
5615 let payment_params = PaymentParameters::from_node_id(nodes[10]);
5616 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes);
5617 assert!(route.is_ok());
5619 // Then check that we can't get a route if we ban an intermediate node.
5620 scorer.add_banned(&NodeId::from_pubkey(&nodes[3]));
5621 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes);
5622 assert!(route.is_err());
5624 // Finally make sure we can route again, when we remove the ban.
5625 scorer.remove_banned(&NodeId::from_pubkey(&nodes[3]));
5626 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes);
5627 assert!(route.is_ok());
5631 #[cfg(all(test, not(feature = "no-std")))]
5632 pub(crate) mod bench_utils {
5634 /// Tries to open a network graph file, or panics with a URL to fetch it.
5635 pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
5636 let res = File::open("net_graph-2021-05-31.bin") // By default we're run in RL/lightning
5637 .or_else(|_| File::open("lightning/net_graph-2021-05-31.bin")) // We may be run manually in RL/
5638 .or_else(|_| { // Fall back to guessing based on the binary location
5639 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
5640 let mut path = std::env::current_exe().unwrap();
5641 path.pop(); // lightning-...
5643 path.pop(); // debug
5644 path.pop(); // target
5645 path.push("lightning");
5646 path.push("net_graph-2021-05-31.bin");
5647 eprintln!("{}", path.to_str().unwrap());
5650 .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");
5651 #[cfg(require_route_graph_test)]
5652 return Ok(res.unwrap());
5653 #[cfg(not(require_route_graph_test))]
5658 #[cfg(all(test, feature = "_bench_unstable", not(feature = "no-std")))]
5661 use bitcoin::hashes::Hash;
5662 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
5663 use crate::chain::transaction::OutPoint;
5664 use crate::chain::keysinterface::{KeysManager,KeysInterface};
5665 use crate::ln::channelmanager::{self, ChannelCounterparty, ChannelDetails};
5666 use crate::ln::features::InvoiceFeatures;
5667 use crate::routing::gossip::NetworkGraph;
5668 use crate::routing::scoring::{FixedPenaltyScorer, ProbabilisticScorer, ProbabilisticScoringParameters};
5669 use crate::util::logger::{Logger, Record};
5670 use crate::util::ser::ReadableArgs;
5674 struct DummyLogger {}
5675 impl Logger for DummyLogger {
5676 fn log(&self, _record: &Record) {}
5679 fn read_network_graph(logger: &DummyLogger) -> NetworkGraph<&DummyLogger> {
5680 let mut d = bench_utils::get_route_file().unwrap();
5681 NetworkGraph::read(&mut d, logger).unwrap()
5684 fn payer_pubkey() -> PublicKey {
5685 let secp_ctx = Secp256k1::new();
5686 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
5690 fn first_hop(node_id: PublicKey) -> ChannelDetails {
5692 channel_id: [0; 32],
5693 counterparty: ChannelCounterparty {
5694 features: channelmanager::provided_init_features(),
5696 unspendable_punishment_reserve: 0,
5697 forwarding_info: None,
5698 outbound_htlc_minimum_msat: None,
5699 outbound_htlc_maximum_msat: None,
5701 funding_txo: Some(OutPoint {
5702 txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0
5705 short_channel_id: Some(1),
5706 inbound_scid_alias: None,
5707 outbound_scid_alias: None,
5708 channel_value_satoshis: 10_000_000,
5710 balance_msat: 10_000_000,
5711 outbound_capacity_msat: 10_000_000,
5712 next_outbound_htlc_limit_msat: 10_000_000,
5713 inbound_capacity_msat: 0,
5714 unspendable_punishment_reserve: None,
5715 confirmations_required: None,
5716 confirmations: None,
5717 force_close_spend_delay: None,
5719 is_channel_ready: true,
5722 inbound_htlc_minimum_msat: None,
5723 inbound_htlc_maximum_msat: None,
5729 fn generate_routes_with_zero_penalty_scorer(bench: &mut Bencher) {
5730 let logger = DummyLogger {};
5731 let network_graph = read_network_graph(&logger);
5732 let scorer = FixedPenaltyScorer::with_penalty(0);
5733 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::empty());
5737 fn generate_mpp_routes_with_zero_penalty_scorer(bench: &mut Bencher) {
5738 let logger = DummyLogger {};
5739 let network_graph = read_network_graph(&logger);
5740 let scorer = FixedPenaltyScorer::with_penalty(0);
5741 generate_routes(bench, &network_graph, scorer, channelmanager::provided_invoice_features());
5745 fn generate_routes_with_probabilistic_scorer(bench: &mut Bencher) {
5746 let logger = DummyLogger {};
5747 let network_graph = read_network_graph(&logger);
5748 let params = ProbabilisticScoringParameters::default();
5749 let scorer = ProbabilisticScorer::new(params, &network_graph, &logger);
5750 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::empty());
5754 fn generate_mpp_routes_with_probabilistic_scorer(bench: &mut Bencher) {
5755 let logger = DummyLogger {};
5756 let network_graph = read_network_graph(&logger);
5757 let params = ProbabilisticScoringParameters::default();
5758 let scorer = ProbabilisticScorer::new(params, &network_graph, &logger);
5759 generate_routes(bench, &network_graph, scorer, channelmanager::provided_invoice_features());
5762 fn generate_routes<S: Score>(
5763 bench: &mut Bencher, graph: &NetworkGraph<&DummyLogger>, mut scorer: S,
5764 features: InvoiceFeatures
5766 let nodes = graph.read_only().nodes().clone();
5767 let payer = payer_pubkey();
5768 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
5769 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5771 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
5772 let mut routes = Vec::new();
5773 let mut route_endpoints = Vec::new();
5774 let mut seed: usize = 0xdeadbeef;
5775 'load_endpoints: for _ in 0..150 {
5778 let src = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5780 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5781 let params = PaymentParameters::from_node_id(dst).with_features(features.clone());
5782 let first_hop = first_hop(src);
5783 let amt = seed as u64 % 1_000_000;
5784 if let Ok(route) = get_route(&payer, ¶ms, &graph.read_only(), Some(&[&first_hop]), amt, 42, &DummyLogger{}, &scorer, &random_seed_bytes) {
5786 route_endpoints.push((first_hop, params, amt));
5787 continue 'load_endpoints;
5792 // ...and seed the scorer with success and failure data...
5793 for route in routes {
5794 let amount = route.get_total_amount();
5795 if amount < 250_000 {
5796 for path in route.paths {
5797 scorer.payment_path_successful(&path.iter().collect::<Vec<_>>());
5799 } else if amount > 750_000 {
5800 for path in route.paths {
5801 let short_channel_id = path[path.len() / 2].short_channel_id;
5802 scorer.payment_path_failed(&path.iter().collect::<Vec<_>>(), short_channel_id);
5807 // Because we've changed channel scores, its possible we'll take different routes to the
5808 // selected destinations, possibly causing us to fail because, eg, the newly-selected path
5809 // requires a too-high CLTV delta.
5810 route_endpoints.retain(|(first_hop, params, amt)| {
5811 get_route(&payer, params, &graph.read_only(), Some(&[first_hop]), *amt, 42, &DummyLogger{}, &scorer, &random_seed_bytes).is_ok()
5813 route_endpoints.truncate(100);
5814 assert_eq!(route_endpoints.len(), 100);
5816 // ...then benchmark finding paths between the nodes we learned.
5819 let (first_hop, params, amt) = &route_endpoints[idx % route_endpoints.len()];
5820 assert!(get_route(&payer, params, &graph.read_only(), Some(&[first_hop]), *amt, 42, &DummyLogger{}, &scorer, &random_seed_bytes).is_ok());