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 router finds paths within a [`NetworkGraph`] for a payment.
12 use bitcoin::secp256k1::{PublicKey, Secp256k1, self};
13 use bitcoin::hashes::Hash;
14 use bitcoin::hashes::sha256::Hash as Sha256;
16 use crate::blinded_path::{BlindedHop, BlindedPath};
17 use crate::blinded_path::payment::{ForwardNode, ForwardTlvs, PaymentConstraints, PaymentRelay, ReceiveTlvs};
18 use crate::ln::PaymentHash;
19 use crate::ln::channelmanager::{ChannelDetails, PaymentId};
20 use crate::ln::features::{BlindedHopFeatures, Bolt11InvoiceFeatures, Bolt12InvoiceFeatures, ChannelFeatures, NodeFeatures};
21 use crate::ln::msgs::{DecodeError, ErrorAction, LightningError, MAX_VALUE_MSAT};
22 use crate::offers::invoice::{BlindedPayInfo, Bolt12Invoice};
23 use crate::onion_message::{DefaultMessageRouter, Destination, MessageRouter, OnionMessagePath};
24 use crate::routing::gossip::{DirectedChannelInfo, EffectiveCapacity, ReadOnlyNetworkGraph, NetworkGraph, NodeId, RoutingFees};
25 use crate::routing::scoring::{ChannelUsage, LockableScore, ScoreLookUp};
26 use crate::sign::EntropySource;
27 use crate::util::ser::{Writeable, Readable, ReadableArgs, Writer};
28 use crate::util::logger::{Level, Logger};
29 use crate::util::chacha20::ChaCha20;
32 use crate::prelude::*;
33 use crate::sync::Mutex;
34 use alloc::collections::BinaryHeap;
38 /// A [`Router`] implemented using [`find_route`].
39 pub struct DefaultRouter<G: Deref<Target = NetworkGraph<L>> + Clone, L: Deref, S: Deref, SP: Sized, Sc: ScoreLookUp<ScoreParams = SP>> where
41 S::Target: for <'a> LockableScore<'a, ScoreLookUp = Sc>,
45 random_seed_bytes: Mutex<[u8; 32]>,
48 message_router: DefaultMessageRouter<G, L>,
51 impl<G: Deref<Target = NetworkGraph<L>> + Clone, L: Deref, S: Deref, SP: Sized, Sc: ScoreLookUp<ScoreParams = SP>> DefaultRouter<G, L, S, SP, Sc> where
53 S::Target: for <'a> LockableScore<'a, ScoreLookUp = Sc>,
55 /// Creates a new router.
56 pub fn new(network_graph: G, logger: L, random_seed_bytes: [u8; 32], scorer: S, score_params: SP) -> Self {
57 let random_seed_bytes = Mutex::new(random_seed_bytes);
58 let message_router = DefaultMessageRouter::new(network_graph.clone());
59 Self { network_graph, logger, random_seed_bytes, scorer, score_params, message_router }
63 impl<G: Deref<Target = NetworkGraph<L>> + Clone, L: Deref, S: Deref, SP: Sized, Sc: ScoreLookUp<ScoreParams = SP>> Router for DefaultRouter<G, L, S, SP, Sc> where
65 S::Target: for <'a> LockableScore<'a, ScoreLookUp = Sc>,
70 params: &RouteParameters,
71 first_hops: Option<&[&ChannelDetails]>,
72 inflight_htlcs: InFlightHtlcs
73 ) -> Result<Route, LightningError> {
74 let random_seed_bytes = {
75 let mut locked_random_seed_bytes = self.random_seed_bytes.lock().unwrap();
76 *locked_random_seed_bytes = Sha256::hash(&*locked_random_seed_bytes).to_byte_array();
77 *locked_random_seed_bytes
80 payer, params, &self.network_graph, first_hops, &*self.logger,
81 &ScorerAccountingForInFlightHtlcs::new(self.scorer.read_lock(), &inflight_htlcs),
87 fn create_blinded_payment_paths<
88 ES: EntropySource + ?Sized, T: secp256k1::Signing + secp256k1::Verification
90 &self, recipient: PublicKey, first_hops: Vec<ChannelDetails>, tlvs: ReceiveTlvs,
91 amount_msats: u64, entropy_source: &ES, secp_ctx: &Secp256k1<T>
92 ) -> Result<Vec<(BlindedPayInfo, BlindedPath)>, ()> {
93 // Limit the number of blinded paths that are computed.
94 const MAX_PAYMENT_PATHS: usize = 3;
96 // Ensure peers have at least three channels so that it is more difficult to infer the
97 // recipient's node_id.
98 const MIN_PEER_CHANNELS: usize = 3;
100 let network_graph = self.network_graph.deref().read_only();
101 let paths = first_hops.into_iter()
102 .filter(|details| details.counterparty.features.supports_route_blinding())
103 .filter(|details| amount_msats <= details.inbound_capacity_msat)
104 .filter(|details| amount_msats >= details.inbound_htlc_minimum_msat.unwrap_or(0))
105 .filter(|details| amount_msats <= details.inbound_htlc_maximum_msat.unwrap_or(u64::MAX))
106 .filter(|details| network_graph
107 .node(&NodeId::from_pubkey(&details.counterparty.node_id))
108 .map(|node_info| node_info.channels.len() >= MIN_PEER_CHANNELS)
111 .filter_map(|details| {
112 let short_channel_id = match details.get_inbound_payment_scid() {
113 Some(short_channel_id) => short_channel_id,
116 let payment_relay: PaymentRelay = match details.counterparty.forwarding_info {
117 Some(forwarding_info) => forwarding_info.into(),
121 // Avoid exposing esoteric CLTV expiry deltas
122 let cltv_expiry_delta = match payment_relay.cltv_expiry_delta {
130 let payment_constraints = PaymentConstraints {
131 max_cltv_expiry: tlvs.payment_constraints.max_cltv_expiry + cltv_expiry_delta,
132 htlc_minimum_msat: details.inbound_htlc_minimum_msat.unwrap_or(0),
139 features: BlindedHopFeatures::empty(),
141 node_id: details.counterparty.node_id,
142 htlc_maximum_msat: details.inbound_htlc_maximum_msat.unwrap_or(u64::MAX),
145 .map(|forward_node| {
146 BlindedPath::new_for_payment(
147 &[forward_node], recipient, tlvs.clone(), u64::MAX, entropy_source, secp_ctx
150 .take(MAX_PAYMENT_PATHS)
151 .collect::<Result<Vec<_>, _>>();
154 Ok(paths) if !paths.is_empty() => Ok(paths),
156 if network_graph.nodes().contains_key(&NodeId::from_pubkey(&recipient)) {
157 BlindedPath::one_hop_for_payment(recipient, tlvs, entropy_source, secp_ctx)
158 .map(|path| vec![path])
167 impl< G: Deref<Target = NetworkGraph<L>> + Clone, L: Deref, S: Deref, SP: Sized, Sc: ScoreLookUp<ScoreParams = SP>> MessageRouter for DefaultRouter<G, L, S, SP, Sc> where
169 S::Target: for <'a> LockableScore<'a, ScoreLookUp = Sc>,
172 &self, sender: PublicKey, peers: Vec<PublicKey>, destination: Destination
173 ) -> Result<OnionMessagePath, ()> {
174 self.message_router.find_path(sender, peers, destination)
177 fn create_blinded_paths<
178 ES: EntropySource + ?Sized, T: secp256k1::Signing + secp256k1::Verification
180 &self, recipient: PublicKey, peers: Vec<PublicKey>, entropy_source: &ES,
181 secp_ctx: &Secp256k1<T>
182 ) -> Result<Vec<BlindedPath>, ()> {
183 self.message_router.create_blinded_paths(recipient, peers, entropy_source, secp_ctx)
187 /// A trait defining behavior for routing a payment.
188 pub trait Router: MessageRouter {
189 /// Finds a [`Route`] for a payment between the given `payer` and a payee.
191 /// The `payee` and the payment's value are given in [`RouteParameters::payment_params`]
192 /// and [`RouteParameters::final_value_msat`], respectively.
194 &self, payer: &PublicKey, route_params: &RouteParameters,
195 first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: InFlightHtlcs
196 ) -> Result<Route, LightningError>;
198 /// Finds a [`Route`] for a payment between the given `payer` and a payee.
200 /// The `payee` and the payment's value are given in [`RouteParameters::payment_params`]
201 /// and [`RouteParameters::final_value_msat`], respectively.
203 /// Includes a [`PaymentHash`] and a [`PaymentId`] to be able to correlate the request with a specific
205 fn find_route_with_id(
206 &self, payer: &PublicKey, route_params: &RouteParameters,
207 first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: InFlightHtlcs,
208 _payment_hash: PaymentHash, _payment_id: PaymentId
209 ) -> Result<Route, LightningError> {
210 self.find_route(payer, route_params, first_hops, inflight_htlcs)
213 /// Creates [`BlindedPath`]s for payment to the `recipient` node. The channels in `first_hops`
214 /// are assumed to be with the `recipient`'s peers. The payment secret and any constraints are
216 fn create_blinded_payment_paths<
217 ES: EntropySource + ?Sized, T: secp256k1::Signing + secp256k1::Verification
219 &self, recipient: PublicKey, first_hops: Vec<ChannelDetails>, tlvs: ReceiveTlvs,
220 amount_msats: u64, entropy_source: &ES, secp_ctx: &Secp256k1<T>
221 ) -> Result<Vec<(BlindedPayInfo, BlindedPath)>, ()>;
224 /// [`ScoreLookUp`] implementation that factors in in-flight HTLC liquidity.
226 /// Useful for custom [`Router`] implementations to wrap their [`ScoreLookUp`] on-the-fly when calling
229 /// [`ScoreLookUp`]: crate::routing::scoring::ScoreLookUp
230 pub struct ScorerAccountingForInFlightHtlcs<'a, S: Deref> where S::Target: ScoreLookUp {
232 // Maps a channel's short channel id and its direction to the liquidity used up.
233 inflight_htlcs: &'a InFlightHtlcs,
235 impl<'a, S: Deref> ScorerAccountingForInFlightHtlcs<'a, S> where S::Target: ScoreLookUp {
236 /// Initialize a new `ScorerAccountingForInFlightHtlcs`.
237 pub fn new(scorer: S, inflight_htlcs: &'a InFlightHtlcs) -> Self {
238 ScorerAccountingForInFlightHtlcs {
245 impl<'a, S: Deref> ScoreLookUp for ScorerAccountingForInFlightHtlcs<'a, S> where S::Target: ScoreLookUp {
246 type ScoreParams = <S::Target as ScoreLookUp>::ScoreParams;
247 fn channel_penalty_msat(&self, candidate: &CandidateRouteHop, usage: ChannelUsage, score_params: &Self::ScoreParams) -> u64 {
248 let target = match candidate.target() {
249 Some(target) => target,
250 None => return self.scorer.channel_penalty_msat(candidate, usage, score_params),
252 let short_channel_id = match candidate.short_channel_id() {
253 Some(short_channel_id) => short_channel_id,
254 None => return self.scorer.channel_penalty_msat(candidate, usage, score_params),
256 let source = candidate.source();
257 if let Some(used_liquidity) = self.inflight_htlcs.used_liquidity_msat(
258 &source, &target, short_channel_id
260 let usage = ChannelUsage {
261 inflight_htlc_msat: usage.inflight_htlc_msat.saturating_add(used_liquidity),
265 self.scorer.channel_penalty_msat(candidate, usage, score_params)
267 self.scorer.channel_penalty_msat(candidate, usage, score_params)
272 /// A data structure for tracking in-flight HTLCs. May be used during pathfinding to account for
273 /// in-use channel liquidity.
275 pub struct InFlightHtlcs(
276 // A map with liquidity value (in msat) keyed by a short channel id and the direction the HTLC
277 // is traveling in. The direction boolean is determined by checking if the HTLC source's public
278 // key is less than its destination. See `InFlightHtlcs::used_liquidity_msat` for more
280 HashMap<(u64, bool), u64>
284 /// Constructs an empty `InFlightHtlcs`.
285 pub fn new() -> Self { InFlightHtlcs(HashMap::new()) }
287 /// Takes in a path with payer's node id and adds the path's details to `InFlightHtlcs`.
288 pub fn process_path(&mut self, path: &Path, payer_node_id: PublicKey) {
289 if path.hops.is_empty() { return };
291 let mut cumulative_msat = 0;
292 if let Some(tail) = &path.blinded_tail {
293 cumulative_msat += tail.final_value_msat;
296 // total_inflight_map needs to be direction-sensitive when keeping track of the HTLC value
297 // that is held up. However, the `hops` array, which is a path returned by `find_route` in
298 // the router excludes the payer node. In the following lines, the payer's information is
299 // hardcoded with an inflight value of 0 so that we can correctly represent the first hop
300 // in our sliding window of two.
301 let reversed_hops_with_payer = path.hops.iter().rev().skip(1)
302 .map(|hop| hop.pubkey)
303 .chain(core::iter::once(payer_node_id));
305 // Taking the reversed vector from above, we zip it with just the reversed hops list to
306 // work "backwards" of the given path, since the last hop's `fee_msat` actually represents
307 // the total amount sent.
308 for (next_hop, prev_hop) in path.hops.iter().rev().zip(reversed_hops_with_payer) {
309 cumulative_msat += next_hop.fee_msat;
311 .entry((next_hop.short_channel_id, NodeId::from_pubkey(&prev_hop) < NodeId::from_pubkey(&next_hop.pubkey)))
312 .and_modify(|used_liquidity_msat| *used_liquidity_msat += cumulative_msat)
313 .or_insert(cumulative_msat);
317 /// Adds a known HTLC given the public key of the HTLC source, target, and short channel
319 pub fn add_inflight_htlc(&mut self, source: &NodeId, target: &NodeId, channel_scid: u64, used_msat: u64){
321 .entry((channel_scid, source < target))
322 .and_modify(|used_liquidity_msat| *used_liquidity_msat += used_msat)
323 .or_insert(used_msat);
326 /// Returns liquidity in msat given the public key of the HTLC source, target, and short channel
328 pub fn used_liquidity_msat(&self, source: &NodeId, target: &NodeId, channel_scid: u64) -> Option<u64> {
329 self.0.get(&(channel_scid, source < target)).map(|v| *v)
333 impl Writeable for InFlightHtlcs {
334 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> { self.0.write(writer) }
337 impl Readable for InFlightHtlcs {
338 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
339 let infight_map: HashMap<(u64, bool), u64> = Readable::read(reader)?;
340 Ok(Self(infight_map))
344 /// A hop in a route, and additional metadata about it. "Hop" is defined as a node and the channel
345 /// that leads to it.
346 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
347 pub struct RouteHop {
348 /// The node_id of the node at this hop.
349 pub pubkey: PublicKey,
350 /// The node_announcement features of the node at this hop. For the last hop, these may be
351 /// amended to match the features present in the invoice this node generated.
352 pub node_features: NodeFeatures,
353 /// The channel that should be used from the previous hop to reach this node.
354 pub short_channel_id: u64,
355 /// The channel_announcement features of the channel that should be used from the previous hop
356 /// to reach this node.
357 pub channel_features: ChannelFeatures,
358 /// The fee taken on this hop (for paying for the use of the *next* channel in the path).
359 /// If this is the last hop in [`Path::hops`]:
360 /// * if we're sending to a [`BlindedPath`], this is the fee paid for use of the entire blinded path
361 /// * otherwise, this is the full value of this [`Path`]'s part of the payment
363 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
365 /// The CLTV delta added for this hop.
366 /// If this is the last hop in [`Path::hops`]:
367 /// * if we're sending to a [`BlindedPath`], this is the CLTV delta for the entire blinded path
368 /// * otherwise, this is the CLTV delta expected at the destination
370 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
371 pub cltv_expiry_delta: u32,
372 /// Indicates whether this hop is possibly announced in the public network graph.
374 /// Will be `true` if there is a possibility that the channel is publicly known, i.e., if we
375 /// either know for sure it's announced in the public graph, or if any public channels exist
376 /// for which the given `short_channel_id` could be an alias for. Will be `false` if we believe
377 /// the channel to be unannounced.
379 /// Will be `true` for objects serialized with LDK version 0.0.116 and before.
380 pub maybe_announced_channel: bool,
383 impl_writeable_tlv_based!(RouteHop, {
384 (0, pubkey, required),
385 (1, maybe_announced_channel, (default_value, true)),
386 (2, node_features, required),
387 (4, short_channel_id, required),
388 (6, channel_features, required),
389 (8, fee_msat, required),
390 (10, cltv_expiry_delta, required),
393 /// The blinded portion of a [`Path`], if we're routing to a recipient who provided blinded paths in
394 /// their [`Bolt12Invoice`].
396 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
397 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
398 pub struct BlindedTail {
399 /// The hops of the [`BlindedPath`] provided by the recipient.
401 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
402 pub hops: Vec<BlindedHop>,
403 /// The blinding point of the [`BlindedPath`] provided by the recipient.
405 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
406 pub blinding_point: PublicKey,
407 /// Excess CLTV delta added to the recipient's CLTV expiry to deter intermediate nodes from
408 /// inferring the destination. May be 0.
409 pub excess_final_cltv_expiry_delta: u32,
410 /// The total amount paid on this [`Path`], excluding the fees.
411 pub final_value_msat: u64,
414 impl_writeable_tlv_based!(BlindedTail, {
415 (0, hops, required_vec),
416 (2, blinding_point, required),
417 (4, excess_final_cltv_expiry_delta, required),
418 (6, final_value_msat, required),
421 /// A path in a [`Route`] to the payment recipient. Must always be at least length one.
422 /// If no [`Path::blinded_tail`] is present, then [`Path::hops`] length may be up to 19.
423 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
425 /// The list of unblinded hops in this [`Path`]. Must be at least length one.
426 pub hops: Vec<RouteHop>,
427 /// The blinded path at which this path terminates, if we're sending to one, and its metadata.
428 pub blinded_tail: Option<BlindedTail>,
432 /// Gets the fees for a given path, excluding any excess paid to the recipient.
433 pub fn fee_msat(&self) -> u64 {
434 match &self.blinded_tail {
435 Some(_) => self.hops.iter().map(|hop| hop.fee_msat).sum::<u64>(),
437 // Do not count last hop of each path since that's the full value of the payment
438 self.hops.split_last().map_or(0,
439 |(_, path_prefix)| path_prefix.iter().map(|hop| hop.fee_msat).sum())
444 /// Gets the total amount paid on this [`Path`], excluding the fees.
445 pub fn final_value_msat(&self) -> u64 {
446 match &self.blinded_tail {
447 Some(blinded_tail) => blinded_tail.final_value_msat,
448 None => self.hops.last().map_or(0, |hop| hop.fee_msat)
452 /// Gets the final hop's CLTV expiry delta.
453 pub fn final_cltv_expiry_delta(&self) -> Option<u32> {
454 match &self.blinded_tail {
456 None => self.hops.last().map(|hop| hop.cltv_expiry_delta)
461 /// A route directs a payment from the sender (us) to the recipient. If the recipient supports MPP,
462 /// it can take multiple paths. Each path is composed of one or more hops through the network.
463 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
465 /// The list of [`Path`]s taken for a single (potentially-)multi-part payment. If no
466 /// [`BlindedTail`]s are present, then the pubkey of the last [`RouteHop`] in each path must be
468 pub paths: Vec<Path>,
469 /// The `route_params` parameter passed to [`find_route`].
471 /// This is used by `ChannelManager` to track information which may be required for retries.
473 /// Will be `None` for objects serialized with LDK versions prior to 0.0.117.
474 pub route_params: Option<RouteParameters>,
478 /// Returns the total amount of fees paid on this [`Route`].
480 /// For objects serialized with LDK 0.0.117 and after, this includes any extra payment made to
481 /// the recipient, which can happen in excess of the amount passed to [`find_route`] via
482 /// [`RouteParameters::final_value_msat`], if we had to reach the [`htlc_minimum_msat`] limits.
484 /// [`htlc_minimum_msat`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-channel_update-message
485 pub fn get_total_fees(&self) -> u64 {
486 let overpaid_value_msat = self.route_params.as_ref()
487 .map_or(0, |p| self.get_total_amount().saturating_sub(p.final_value_msat));
488 overpaid_value_msat + self.paths.iter().map(|path| path.fee_msat()).sum::<u64>()
491 /// Returns the total amount paid on this [`Route`], excluding the fees.
493 /// Might be more than requested as part of the given [`RouteParameters::final_value_msat`] if
494 /// we had to reach the [`htlc_minimum_msat`] limits.
496 /// [`htlc_minimum_msat`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-channel_update-message
497 pub fn get_total_amount(&self) -> u64 {
498 self.paths.iter().map(|path| path.final_value_msat()).sum()
502 impl fmt::Display for Route {
503 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
504 log_route!(self).fmt(f)
508 const SERIALIZATION_VERSION: u8 = 1;
509 const MIN_SERIALIZATION_VERSION: u8 = 1;
511 impl Writeable for Route {
512 fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
513 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
514 (self.paths.len() as u64).write(writer)?;
515 let mut blinded_tails = Vec::new();
516 for path in self.paths.iter() {
517 (path.hops.len() as u8).write(writer)?;
518 for (idx, hop) in path.hops.iter().enumerate() {
520 if let Some(blinded_tail) = &path.blinded_tail {
521 if blinded_tails.is_empty() {
522 blinded_tails = Vec::with_capacity(path.hops.len());
524 blinded_tails.push(None);
527 blinded_tails.push(Some(blinded_tail));
528 } else if !blinded_tails.is_empty() { blinded_tails.push(None); }
531 write_tlv_fields!(writer, {
532 // For compatibility with LDK versions prior to 0.0.117, we take the individual
533 // RouteParameters' fields and reconstruct them on read.
534 (1, self.route_params.as_ref().map(|p| &p.payment_params), option),
535 (2, blinded_tails, optional_vec),
536 (3, self.route_params.as_ref().map(|p| p.final_value_msat), option),
537 (5, self.route_params.as_ref().map(|p| p.max_total_routing_fee_msat), option),
543 impl Readable for Route {
544 fn read<R: io::Read>(reader: &mut R) -> Result<Route, DecodeError> {
545 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
546 let path_count: u64 = Readable::read(reader)?;
547 if path_count == 0 { return Err(DecodeError::InvalidValue); }
548 let mut paths = Vec::with_capacity(cmp::min(path_count, 128) as usize);
549 let mut min_final_cltv_expiry_delta = u32::max_value();
550 for _ in 0..path_count {
551 let hop_count: u8 = Readable::read(reader)?;
552 let mut hops: Vec<RouteHop> = Vec::with_capacity(hop_count as usize);
553 for _ in 0..hop_count {
554 hops.push(Readable::read(reader)?);
556 if hops.is_empty() { return Err(DecodeError::InvalidValue); }
557 min_final_cltv_expiry_delta =
558 cmp::min(min_final_cltv_expiry_delta, hops.last().unwrap().cltv_expiry_delta);
559 paths.push(Path { hops, blinded_tail: None });
561 _init_and_read_len_prefixed_tlv_fields!(reader, {
562 (1, payment_params, (option: ReadableArgs, min_final_cltv_expiry_delta)),
563 (2, blinded_tails, optional_vec),
564 (3, final_value_msat, option),
565 (5, max_total_routing_fee_msat, option)
567 let blinded_tails = blinded_tails.unwrap_or(Vec::new());
568 if blinded_tails.len() != 0 {
569 if blinded_tails.len() != paths.len() { return Err(DecodeError::InvalidValue) }
570 for (path, blinded_tail_opt) in paths.iter_mut().zip(blinded_tails.into_iter()) {
571 path.blinded_tail = blinded_tail_opt;
575 // If we previously wrote the corresponding fields, reconstruct RouteParameters.
576 let route_params = match (payment_params, final_value_msat) {
577 (Some(payment_params), Some(final_value_msat)) => {
578 Some(RouteParameters { payment_params, final_value_msat, max_total_routing_fee_msat })
583 Ok(Route { paths, route_params })
587 /// Parameters needed to find a [`Route`].
589 /// Passed to [`find_route`] and [`build_route_from_hops`].
590 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
591 pub struct RouteParameters {
592 /// The parameters of the failed payment path.
593 pub payment_params: PaymentParameters,
595 /// The amount in msats sent on the failed payment path.
596 pub final_value_msat: u64,
598 /// The maximum total fees, in millisatoshi, that may accrue during route finding.
600 /// This limit also applies to the total fees that may arise while retrying failed payment
603 /// Note that values below a few sats may result in some paths being spuriously ignored.
604 pub max_total_routing_fee_msat: Option<u64>,
607 impl RouteParameters {
608 /// Constructs [`RouteParameters`] from the given [`PaymentParameters`] and a payment amount.
610 /// [`Self::max_total_routing_fee_msat`] defaults to 1% of the payment amount + 50 sats
611 pub fn from_payment_params_and_value(payment_params: PaymentParameters, final_value_msat: u64) -> Self {
612 Self { payment_params, final_value_msat, max_total_routing_fee_msat: Some(final_value_msat / 100 + 50_000) }
616 impl Writeable for RouteParameters {
617 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
618 write_tlv_fields!(writer, {
619 (0, self.payment_params, required),
620 (1, self.max_total_routing_fee_msat, option),
621 (2, self.final_value_msat, required),
622 // LDK versions prior to 0.0.114 had the `final_cltv_expiry_delta` parameter in
623 // `RouteParameters` directly. For compatibility, we write it here.
624 (4, self.payment_params.payee.final_cltv_expiry_delta(), option),
630 impl Readable for RouteParameters {
631 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
632 _init_and_read_len_prefixed_tlv_fields!(reader, {
633 (0, payment_params, (required: ReadableArgs, 0)),
634 (1, max_total_routing_fee_msat, option),
635 (2, final_value_msat, required),
636 (4, final_cltv_delta, option),
638 let mut payment_params: PaymentParameters = payment_params.0.unwrap();
639 if let Payee::Clear { ref mut final_cltv_expiry_delta, .. } = payment_params.payee {
640 if final_cltv_expiry_delta == &0 {
641 *final_cltv_expiry_delta = final_cltv_delta.ok_or(DecodeError::InvalidValue)?;
646 final_value_msat: final_value_msat.0.unwrap(),
647 max_total_routing_fee_msat,
652 /// Maximum total CTLV difference we allow for a full payment path.
653 pub const DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA: u32 = 1008;
655 /// Maximum number of paths we allow an (MPP) payment to have.
656 // The default limit is currently set rather arbitrary - there aren't any real fundamental path-count
657 // limits, but for now more than 10 paths likely carries too much one-path failure.
658 pub const DEFAULT_MAX_PATH_COUNT: u8 = 10;
660 const DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF: u8 = 2;
662 // The median hop CLTV expiry delta currently seen in the network.
663 const MEDIAN_HOP_CLTV_EXPIRY_DELTA: u32 = 40;
665 // During routing, we only consider paths shorter than our maximum length estimate.
666 // In the TLV onion format, there is no fixed maximum length, but the `hop_payloads`
667 // field is always 1300 bytes. As the `tlv_payload` for each hop may vary in length, we have to
668 // estimate how many hops the route may have so that it actually fits the `hop_payloads` field.
670 // We estimate 3+32 (payload length and HMAC) + 2+8 (amt_to_forward) + 2+4 (outgoing_cltv_value) +
671 // 2+8 (short_channel_id) = 61 bytes for each intermediate hop and 3+32
672 // (payload length and HMAC) + 2+8 (amt_to_forward) + 2+4 (outgoing_cltv_value) + 2+32+8
673 // (payment_secret and total_msat) = 93 bytes for the final hop.
674 // Since the length of the potentially included `payment_metadata` is unknown to us, we round
675 // down from (1300-93) / 61 = 19.78... to arrive at a conservative estimate of 19.
676 const MAX_PATH_LENGTH_ESTIMATE: u8 = 19;
678 /// Information used to route a payment.
679 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
680 pub struct PaymentParameters {
681 /// Information about the payee, such as their features and route hints for their channels.
684 /// Expiration of a payment to the payee, in seconds relative to the UNIX epoch.
685 pub expiry_time: Option<u64>,
687 /// The maximum total CLTV delta we accept for the route.
688 /// Defaults to [`DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA`].
689 pub max_total_cltv_expiry_delta: u32,
691 /// The maximum number of paths that may be used by (MPP) payments.
692 /// Defaults to [`DEFAULT_MAX_PATH_COUNT`].
693 pub max_path_count: u8,
695 /// Selects the maximum share of a channel's total capacity which will be sent over a channel,
696 /// as a power of 1/2. A higher value prefers to send the payment using more MPP parts whereas
697 /// a lower value prefers to send larger MPP parts, potentially saturating channels and
698 /// increasing failure probability for those paths.
700 /// Note that this restriction will be relaxed during pathfinding after paths which meet this
701 /// restriction have been found. While paths which meet this criteria will be searched for, it
702 /// is ultimately up to the scorer to select them over other paths.
704 /// A value of 0 will allow payments up to and including a channel's total announced usable
705 /// capacity, a value of one will only use up to half its capacity, two 1/4, etc.
708 pub max_channel_saturation_power_of_half: u8,
710 /// A list of SCIDs which this payment was previously attempted over and which caused the
711 /// payment to fail. Future attempts for the same payment shouldn't be relayed through any of
713 pub previously_failed_channels: Vec<u64>,
716 impl Writeable for PaymentParameters {
717 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
718 let mut clear_hints = &vec![];
719 let mut blinded_hints = &vec![];
721 Payee::Clear { route_hints, .. } => clear_hints = route_hints,
722 Payee::Blinded { route_hints, .. } => blinded_hints = route_hints,
724 write_tlv_fields!(writer, {
725 (0, self.payee.node_id(), option),
726 (1, self.max_total_cltv_expiry_delta, required),
727 (2, self.payee.features(), option),
728 (3, self.max_path_count, required),
729 (4, *clear_hints, required_vec),
730 (5, self.max_channel_saturation_power_of_half, required),
731 (6, self.expiry_time, option),
732 (7, self.previously_failed_channels, required_vec),
733 (8, *blinded_hints, optional_vec),
734 (9, self.payee.final_cltv_expiry_delta(), option),
740 impl ReadableArgs<u32> for PaymentParameters {
741 fn read<R: io::Read>(reader: &mut R, default_final_cltv_expiry_delta: u32) -> Result<Self, DecodeError> {
742 _init_and_read_len_prefixed_tlv_fields!(reader, {
743 (0, payee_pubkey, option),
744 (1, max_total_cltv_expiry_delta, (default_value, DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA)),
745 (2, features, (option: ReadableArgs, payee_pubkey.is_some())),
746 (3, max_path_count, (default_value, DEFAULT_MAX_PATH_COUNT)),
747 (4, clear_route_hints, required_vec),
748 (5, max_channel_saturation_power_of_half, (default_value, DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF)),
749 (6, expiry_time, option),
750 (7, previously_failed_channels, optional_vec),
751 (8, blinded_route_hints, optional_vec),
752 (9, final_cltv_expiry_delta, (default_value, default_final_cltv_expiry_delta)),
754 let blinded_route_hints = blinded_route_hints.unwrap_or(vec![]);
755 let payee = if blinded_route_hints.len() != 0 {
756 if clear_route_hints.len() != 0 || payee_pubkey.is_some() { return Err(DecodeError::InvalidValue) }
758 route_hints: blinded_route_hints,
759 features: features.and_then(|f: Features| f.bolt12()),
763 route_hints: clear_route_hints,
764 node_id: payee_pubkey.ok_or(DecodeError::InvalidValue)?,
765 features: features.and_then(|f| f.bolt11()),
766 final_cltv_expiry_delta: final_cltv_expiry_delta.0.unwrap(),
770 max_total_cltv_expiry_delta: _init_tlv_based_struct_field!(max_total_cltv_expiry_delta, (default_value, unused)),
771 max_path_count: _init_tlv_based_struct_field!(max_path_count, (default_value, unused)),
773 max_channel_saturation_power_of_half: _init_tlv_based_struct_field!(max_channel_saturation_power_of_half, (default_value, unused)),
775 previously_failed_channels: previously_failed_channels.unwrap_or(Vec::new()),
781 impl PaymentParameters {
782 /// Creates a payee with the node id of the given `pubkey`.
784 /// The `final_cltv_expiry_delta` should match the expected final CLTV delta the recipient has
786 pub fn from_node_id(payee_pubkey: PublicKey, final_cltv_expiry_delta: u32) -> Self {
788 payee: Payee::Clear { node_id: payee_pubkey, route_hints: vec![], features: None, final_cltv_expiry_delta },
790 max_total_cltv_expiry_delta: DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA,
791 max_path_count: DEFAULT_MAX_PATH_COUNT,
792 max_channel_saturation_power_of_half: DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF,
793 previously_failed_channels: Vec::new(),
797 /// Creates a payee with the node id of the given `pubkey` to use for keysend payments.
799 /// The `final_cltv_expiry_delta` should match the expected final CLTV delta the recipient has
802 /// Note that MPP keysend is not widely supported yet. The `allow_mpp` lets you choose
803 /// whether your router will be allowed to find a multi-part route for this payment. If you
804 /// set `allow_mpp` to true, you should ensure a payment secret is set on send, likely via
805 /// [`RecipientOnionFields::secret_only`].
807 /// [`RecipientOnionFields::secret_only`]: crate::ln::channelmanager::RecipientOnionFields::secret_only
808 pub fn for_keysend(payee_pubkey: PublicKey, final_cltv_expiry_delta: u32, allow_mpp: bool) -> Self {
809 Self::from_node_id(payee_pubkey, final_cltv_expiry_delta)
810 .with_bolt11_features(Bolt11InvoiceFeatures::for_keysend(allow_mpp))
811 .expect("PaymentParameters::from_node_id should always initialize the payee as unblinded")
814 /// Creates parameters for paying to a blinded payee from the provided invoice. Sets
815 /// [`Payee::Blinded::route_hints`], [`Payee::Blinded::features`], and
816 /// [`PaymentParameters::expiry_time`].
817 pub fn from_bolt12_invoice(invoice: &Bolt12Invoice) -> Self {
818 Self::blinded(invoice.payment_paths().to_vec())
819 .with_bolt12_features(invoice.invoice_features().clone()).unwrap()
820 .with_expiry_time(invoice.created_at().as_secs().saturating_add(invoice.relative_expiry().as_secs()))
823 /// Creates parameters for paying to a blinded payee from the provided blinded route hints.
824 pub fn blinded(blinded_route_hints: Vec<(BlindedPayInfo, BlindedPath)>) -> Self {
826 payee: Payee::Blinded { route_hints: blinded_route_hints, features: None },
828 max_total_cltv_expiry_delta: DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA,
829 max_path_count: DEFAULT_MAX_PATH_COUNT,
830 max_channel_saturation_power_of_half: DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF,
831 previously_failed_channels: Vec::new(),
835 /// Includes the payee's features. Errors if the parameters were not initialized with
836 /// [`PaymentParameters::from_bolt12_invoice`].
838 /// This is not exported to bindings users since bindings don't support move semantics
839 pub fn with_bolt12_features(self, features: Bolt12InvoiceFeatures) -> Result<Self, ()> {
841 Payee::Clear { .. } => Err(()),
842 Payee::Blinded { route_hints, .. } =>
843 Ok(Self { payee: Payee::Blinded { route_hints, features: Some(features) }, ..self })
847 /// Includes the payee's features. Errors if the parameters were initialized with
848 /// [`PaymentParameters::from_bolt12_invoice`].
850 /// This is not exported to bindings users since bindings don't support move semantics
851 pub fn with_bolt11_features(self, features: Bolt11InvoiceFeatures) -> Result<Self, ()> {
853 Payee::Blinded { .. } => Err(()),
854 Payee::Clear { route_hints, node_id, final_cltv_expiry_delta, .. } =>
856 payee: Payee::Clear {
857 route_hints, node_id, features: Some(features), final_cltv_expiry_delta
863 /// Includes hints for routing to the payee. Errors if the parameters were initialized with
864 /// [`PaymentParameters::from_bolt12_invoice`].
866 /// This is not exported to bindings users since bindings don't support move semantics
867 pub fn with_route_hints(self, route_hints: Vec<RouteHint>) -> Result<Self, ()> {
869 Payee::Blinded { .. } => Err(()),
870 Payee::Clear { node_id, features, final_cltv_expiry_delta, .. } =>
872 payee: Payee::Clear {
873 route_hints, node_id, features, final_cltv_expiry_delta,
879 /// Includes a payment expiration in seconds relative to the UNIX epoch.
881 /// This is not exported to bindings users since bindings don't support move semantics
882 pub fn with_expiry_time(self, expiry_time: u64) -> Self {
883 Self { expiry_time: Some(expiry_time), ..self }
886 /// Includes a limit for the total CLTV expiry delta which is considered during routing
888 /// This is not exported to bindings users since bindings don't support move semantics
889 pub fn with_max_total_cltv_expiry_delta(self, max_total_cltv_expiry_delta: u32) -> Self {
890 Self { max_total_cltv_expiry_delta, ..self }
893 /// Includes a limit for the maximum number of payment paths that may be used.
895 /// This is not exported to bindings users since bindings don't support move semantics
896 pub fn with_max_path_count(self, max_path_count: u8) -> Self {
897 Self { max_path_count, ..self }
900 /// Includes a limit for the maximum share of a channel's total capacity that can be sent over, as
901 /// a power of 1/2. See [`PaymentParameters::max_channel_saturation_power_of_half`].
903 /// This is not exported to bindings users since bindings don't support move semantics
904 pub fn with_max_channel_saturation_power_of_half(self, max_channel_saturation_power_of_half: u8) -> Self {
905 Self { max_channel_saturation_power_of_half, ..self }
909 /// The recipient of a payment, differing based on whether they've hidden their identity with route
911 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
913 /// The recipient provided blinded paths and payinfo to reach them. The blinded paths themselves
914 /// will be included in the final [`Route`].
916 /// Aggregated routing info and blinded paths, for routing to the payee without knowing their
918 route_hints: Vec<(BlindedPayInfo, BlindedPath)>,
919 /// Features supported by the payee.
921 /// May be set from the payee's invoice. May be `None` if the invoice does not contain any
923 features: Option<Bolt12InvoiceFeatures>,
925 /// The recipient included these route hints in their BOLT11 invoice.
927 /// The node id of the payee.
929 /// Hints for routing to the payee, containing channels connecting the payee to public nodes.
930 route_hints: Vec<RouteHint>,
931 /// Features supported by the payee.
933 /// May be set from the payee's invoice or via [`for_keysend`]. May be `None` if the invoice
934 /// does not contain any features.
936 /// [`for_keysend`]: PaymentParameters::for_keysend
937 features: Option<Bolt11InvoiceFeatures>,
938 /// The minimum CLTV delta at the end of the route. This value must not be zero.
939 final_cltv_expiry_delta: u32,
944 fn node_id(&self) -> Option<PublicKey> {
946 Self::Clear { node_id, .. } => Some(*node_id),
950 fn node_features(&self) -> Option<NodeFeatures> {
952 Self::Clear { features, .. } => features.as_ref().map(|f| f.to_context()),
953 Self::Blinded { features, .. } => features.as_ref().map(|f| f.to_context()),
956 fn supports_basic_mpp(&self) -> bool {
958 Self::Clear { features, .. } => features.as_ref().map_or(false, |f| f.supports_basic_mpp()),
959 Self::Blinded { features, .. } => features.as_ref().map_or(false, |f| f.supports_basic_mpp()),
962 fn features(&self) -> Option<FeaturesRef> {
964 Self::Clear { features, .. } => features.as_ref().map(|f| FeaturesRef::Bolt11(f)),
965 Self::Blinded { features, .. } => features.as_ref().map(|f| FeaturesRef::Bolt12(f)),
968 fn final_cltv_expiry_delta(&self) -> Option<u32> {
970 Self::Clear { final_cltv_expiry_delta, .. } => Some(*final_cltv_expiry_delta),
974 fn blinded_route_hints(&self) -> &[(BlindedPayInfo, BlindedPath)] {
976 Self::Blinded { route_hints, .. } => &route_hints[..],
977 Self::Clear { .. } => &[]
981 fn unblinded_route_hints(&self) -> &[RouteHint] {
983 Self::Blinded { .. } => &[],
984 Self::Clear { route_hints, .. } => &route_hints[..]
989 enum FeaturesRef<'a> {
990 Bolt11(&'a Bolt11InvoiceFeatures),
991 Bolt12(&'a Bolt12InvoiceFeatures),
994 Bolt11(Bolt11InvoiceFeatures),
995 Bolt12(Bolt12InvoiceFeatures),
999 fn bolt12(self) -> Option<Bolt12InvoiceFeatures> {
1001 Self::Bolt12(f) => Some(f),
1005 fn bolt11(self) -> Option<Bolt11InvoiceFeatures> {
1007 Self::Bolt11(f) => Some(f),
1013 impl<'a> Writeable for FeaturesRef<'a> {
1014 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1016 Self::Bolt11(f) => Ok(f.write(w)?),
1017 Self::Bolt12(f) => Ok(f.write(w)?),
1022 impl ReadableArgs<bool> for Features {
1023 fn read<R: io::Read>(reader: &mut R, bolt11: bool) -> Result<Self, DecodeError> {
1024 if bolt11 { return Ok(Self::Bolt11(Readable::read(reader)?)) }
1025 Ok(Self::Bolt12(Readable::read(reader)?))
1029 /// A list of hops along a payment path terminating with a channel to the recipient.
1030 #[derive(Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
1031 pub struct RouteHint(pub Vec<RouteHintHop>);
1033 impl Writeable for RouteHint {
1034 fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1035 (self.0.len() as u64).write(writer)?;
1036 for hop in self.0.iter() {
1043 impl Readable for RouteHint {
1044 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
1045 let hop_count: u64 = Readable::read(reader)?;
1046 let mut hops = Vec::with_capacity(cmp::min(hop_count, 16) as usize);
1047 for _ in 0..hop_count {
1048 hops.push(Readable::read(reader)?);
1054 /// A channel descriptor for a hop along a payment path.
1056 /// While this generally comes from BOLT 11's `r` field, this struct includes more fields than are
1057 /// available in BOLT 11. Thus, encoding and decoding this via `lightning-invoice` is lossy, as
1058 /// fields not supported in BOLT 11 will be stripped.
1059 #[derive(Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
1060 pub struct RouteHintHop {
1061 /// The node_id of the non-target end of the route
1062 pub src_node_id: PublicKey,
1063 /// The short_channel_id of this channel
1064 pub short_channel_id: u64,
1065 /// The fees which must be paid to use this channel
1066 pub fees: RoutingFees,
1067 /// The difference in CLTV values between this node and the next node.
1068 pub cltv_expiry_delta: u16,
1069 /// The minimum value, in msat, which must be relayed to the next hop.
1070 pub htlc_minimum_msat: Option<u64>,
1071 /// The maximum value in msat available for routing with a single HTLC.
1072 pub htlc_maximum_msat: Option<u64>,
1075 impl_writeable_tlv_based!(RouteHintHop, {
1076 (0, src_node_id, required),
1077 (1, htlc_minimum_msat, option),
1078 (2, short_channel_id, required),
1079 (3, htlc_maximum_msat, option),
1080 (4, fees, required),
1081 (6, cltv_expiry_delta, required),
1084 #[derive(Eq, PartialEq)]
1085 #[repr(align(64))] // Force the size to 64 bytes
1086 struct RouteGraphNode {
1089 // The maximum value a yet-to-be-constructed payment path might flow through this node.
1090 // This value is upper-bounded by us by:
1091 // - how much is needed for a path being constructed
1092 // - how much value can channels following this node (up to the destination) can contribute,
1093 // considering their capacity and fees
1094 value_contribution_msat: u64,
1095 total_cltv_delta: u32,
1096 /// The number of hops walked up to this node.
1097 path_length_to_node: u8,
1100 impl cmp::Ord for RouteGraphNode {
1101 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
1102 other.score.cmp(&self.score).then_with(|| other.node_id.cmp(&self.node_id))
1106 impl cmp::PartialOrd for RouteGraphNode {
1107 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
1108 Some(self.cmp(other))
1112 // While RouteGraphNode can be laid out with fewer bytes, performance appears to be improved
1113 // substantially when it is laid out at exactly 64 bytes.
1114 const _GRAPH_NODE_SMALL: usize = 64 - core::mem::size_of::<RouteGraphNode>();
1115 const _GRAPH_NODE_FIXED_SIZE: usize = core::mem::size_of::<RouteGraphNode>() - 64;
1117 /// A [`CandidateRouteHop::FirstHop`] entry.
1118 #[derive(Clone, Debug)]
1119 pub struct CandidateFirstHop<'a> {
1120 /// Channel details of the first hop
1122 /// [`ChannelDetails::get_outbound_payment_scid`] MUST be `Some` (indicating the channel
1123 /// has been funded and is able to pay), and accessor methods may panic otherwise.
1125 /// [`find_route`] validates this prior to constructing a [`CandidateRouteHop`].
1126 pub details: &'a ChannelDetails,
1127 /// The node id of the payer, which is also the source side of this candidate route hop.
1128 pub payer_node_id: &'a NodeId,
1129 /// A unique ID which describes the payer. It will not conlict with any
1130 /// [`NodeInfo::node_counter`]s, but may be equal to one if the payer is a public node.
1131 payer_node_counter: u32,
1132 /// A unique ID which describes the first hop counterparty. It will not conlict with any
1133 /// [`NodeInfo::node_counter`]s, but may be equal to one if the counterparty is a public node.
1134 target_node_counter: u32,
1137 /// A [`CandidateRouteHop::PublicHop`] entry.
1138 #[derive(Clone, Debug)]
1139 pub struct CandidatePublicHop<'a> {
1140 /// Information about the channel, including potentially its capacity and
1141 /// direction-specific information.
1142 pub info: DirectedChannelInfo<'a>,
1143 /// The short channel ID of the channel, i.e. the identifier by which we refer to this
1145 pub short_channel_id: u64,
1148 /// A [`CandidateRouteHop::PrivateHop`] entry.
1149 #[derive(Clone, Debug)]
1150 pub struct CandidatePrivateHop<'a> {
1151 /// Information about the private hop communicated via BOLT 11.
1152 pub hint: &'a RouteHintHop,
1153 /// Node id of the next hop in BOLT 11 route hint.
1154 pub target_node_id: &'a NodeId,
1155 /// A unique ID which describes the source node of the hop (further from the payment target).
1156 /// It will not conlict with any [`NodeInfo::node_counter`]s, but may be equal to one if the
1157 /// node is a public node.
1158 source_node_counter: u32,
1159 /// A unique ID which describes the destination node of the hop (towards the payment target).
1160 /// It will not conlict with any [`NodeInfo::node_counter`]s, but may be equal to one if the
1161 /// node is a public node.
1162 target_node_counter: u32,
1166 /// A [`CandidateRouteHop::Blinded`] entry.
1167 #[derive(Clone, Debug)]
1168 pub struct CandidateBlindedPath<'a> {
1169 /// Information about the blinded path including the fee, HTLC amount limits, and
1170 /// cryptographic material required to build an HTLC through the given path.
1171 pub hint: &'a (BlindedPayInfo, BlindedPath),
1172 /// Index of the hint in the original list of blinded hints.
1174 /// This is used to cheaply uniquely identify this blinded path, even though we don't have
1175 /// a short channel ID for this hop.
1177 /// A unique ID which describes the introduction point of the blinded path.
1178 /// It will not conlict with any [`NodeInfo::node_counter`]s, but will generally be equal to
1179 /// one from the public network graph (assuming the introduction point is a public node).
1180 source_node_counter: u32,
1183 /// A [`CandidateRouteHop::OneHopBlinded`] entry.
1184 #[derive(Clone, Debug)]
1185 pub struct CandidateOneHopBlindedPath<'a> {
1186 /// Information about the blinded path including the fee, HTLC amount limits, and
1187 /// cryptographic material required to build an HTLC terminating with the given path.
1189 /// Note that the [`BlindedPayInfo`] is ignored here.
1190 pub hint: &'a (BlindedPayInfo, BlindedPath),
1191 /// Index of the hint in the original list of blinded hints.
1193 /// This is used to cheaply uniquely identify this blinded path, even though we don't have
1194 /// a short channel ID for this hop.
1196 /// A unique ID which describes the introduction point of the blinded path.
1197 /// It will not conlict with any [`NodeInfo::node_counter`]s, but will generally be equal to
1198 /// one from the public network graph (assuming the introduction point is a public node).
1199 source_node_counter: u32,
1202 /// A wrapper around the various hop representations.
1204 /// Can be used to examine the properties of a hop,
1205 /// potentially to decide whether to include it in a route.
1206 #[derive(Clone, Debug)]
1207 pub enum CandidateRouteHop<'a> {
1208 /// A hop from the payer, where the outbound liquidity is known.
1209 FirstHop(CandidateFirstHop<'a>),
1210 /// A hop found in the [`ReadOnlyNetworkGraph`].
1211 PublicHop(CandidatePublicHop<'a>),
1212 /// A private hop communicated by the payee, generally via a BOLT 11 invoice.
1214 /// Because BOLT 11 route hints can take multiple hops to get to the destination, this may not
1215 /// terminate at the payee.
1216 PrivateHop(CandidatePrivateHop<'a>),
1217 /// A blinded path which starts with an introduction point and ultimately terminates with the
1220 /// Because we don't know the payee's identity, [`CandidateRouteHop::target`] will return
1221 /// `None` in this state.
1223 /// Because blinded paths are "all or nothing", and we cannot use just one part of a blinded
1224 /// path, the full path is treated as a single [`CandidateRouteHop`].
1225 Blinded(CandidateBlindedPath<'a>),
1226 /// Similar to [`Self::Blinded`], but the path here only has one hop.
1228 /// While we treat this similarly to [`CandidateRouteHop::Blinded`] in many respects (e.g.
1229 /// returning `None` from [`CandidateRouteHop::target`]), in this case we do actually know the
1230 /// payee's identity - it's the introduction point!
1232 /// [`BlindedPayInfo`] provided for 1-hop blinded paths is ignored because it is meant to apply
1233 /// to the hops *between* the introduction node and the destination.
1235 /// This primarily exists to track that we need to included a blinded path at the end of our
1236 /// [`Route`], even though it doesn't actually add an additional hop in the payment.
1237 OneHopBlinded(CandidateOneHopBlindedPath<'a>),
1240 impl<'a> CandidateRouteHop<'a> {
1241 /// Returns the short channel ID for this hop, if one is known.
1243 /// This SCID could be an alias or a globally unique SCID, and thus is only expected to
1244 /// uniquely identify this channel in conjunction with the [`CandidateRouteHop::source`].
1246 /// Returns `Some` as long as the candidate is a [`CandidateRouteHop::PublicHop`], a
1247 /// [`CandidateRouteHop::PrivateHop`] from a BOLT 11 route hint, or a
1248 /// [`CandidateRouteHop::FirstHop`] with a known [`ChannelDetails::get_outbound_payment_scid`]
1249 /// (which is always true for channels which are funded and ready for use).
1251 /// In other words, this should always return `Some` as long as the candidate hop is not a
1252 /// [`CandidateRouteHop::Blinded`] or a [`CandidateRouteHop::OneHopBlinded`].
1254 /// Note that this is deliberately not public as it is somewhat of a footgun because it doesn't
1255 /// define a global namespace.
1257 fn short_channel_id(&self) -> Option<u64> {
1259 CandidateRouteHop::FirstHop(hop) => hop.details.get_outbound_payment_scid(),
1260 CandidateRouteHop::PublicHop(hop) => Some(hop.short_channel_id),
1261 CandidateRouteHop::PrivateHop(hop) => Some(hop.hint.short_channel_id),
1262 CandidateRouteHop::Blinded(_) => None,
1263 CandidateRouteHop::OneHopBlinded(_) => None,
1267 /// Returns the globally unique short channel ID for this hop, if one is known.
1269 /// This only returns `Some` if the channel is public (either our own, or one we've learned
1270 /// from the public network graph), and thus the short channel ID we have for this channel is
1271 /// globally unique and identifies this channel in a global namespace.
1273 pub fn globally_unique_short_channel_id(&self) -> Option<u64> {
1275 CandidateRouteHop::FirstHop(hop) => if hop.details.is_public { hop.details.short_channel_id } else { None },
1276 CandidateRouteHop::PublicHop(hop) => Some(hop.short_channel_id),
1277 CandidateRouteHop::PrivateHop(_) => None,
1278 CandidateRouteHop::Blinded(_) => None,
1279 CandidateRouteHop::OneHopBlinded(_) => None,
1283 // NOTE: This may alloc memory so avoid calling it in a hot code path.
1284 fn features(&self) -> ChannelFeatures {
1286 CandidateRouteHop::FirstHop(hop) => hop.details.counterparty.features.to_context(),
1287 CandidateRouteHop::PublicHop(hop) => hop.info.channel().features.clone(),
1288 CandidateRouteHop::PrivateHop(_) => ChannelFeatures::empty(),
1289 CandidateRouteHop::Blinded(_) => ChannelFeatures::empty(),
1290 CandidateRouteHop::OneHopBlinded(_) => ChannelFeatures::empty(),
1294 /// Returns the required difference in HTLC CLTV expiry between the [`Self::source`] and the
1295 /// next-hop for an HTLC taking this hop.
1297 /// This is the time that the node(s) in this hop have to claim the HTLC on-chain if the
1298 /// next-hop goes on chain with a payment preimage.
1300 pub fn cltv_expiry_delta(&self) -> u32 {
1302 CandidateRouteHop::FirstHop(_) => 0,
1303 CandidateRouteHop::PublicHop(hop) => hop.info.direction().cltv_expiry_delta as u32,
1304 CandidateRouteHop::PrivateHop(hop) => hop.hint.cltv_expiry_delta as u32,
1305 CandidateRouteHop::Blinded(hop) => hop.hint.0.cltv_expiry_delta as u32,
1306 CandidateRouteHop::OneHopBlinded(_) => 0,
1310 /// Returns the minimum amount that can be sent over this hop, in millisatoshis.
1312 pub fn htlc_minimum_msat(&self) -> u64 {
1314 CandidateRouteHop::FirstHop(hop) => hop.details.next_outbound_htlc_minimum_msat,
1315 CandidateRouteHop::PublicHop(hop) => hop.info.direction().htlc_minimum_msat,
1316 CandidateRouteHop::PrivateHop(hop) => hop.hint.htlc_minimum_msat.unwrap_or(0),
1317 CandidateRouteHop::Blinded(hop) => hop.hint.0.htlc_minimum_msat,
1318 CandidateRouteHop::OneHopBlinded { .. } => 0,
1323 fn src_node_counter(&self) -> u32 {
1325 CandidateRouteHop::FirstHop { payer_node_counter, .. } => *payer_node_counter,
1326 CandidateRouteHop::PublicHop { info, .. } => info.source_counter(),
1327 CandidateRouteHop::PrivateHop { source_node_counter, .. } => *source_node_counter,
1328 CandidateRouteHop::Blinded { source_node_counter, .. } => *source_node_counter,
1329 CandidateRouteHop::OneHopBlinded { source_node_counter, .. } => *source_node_counter,
1334 fn target_node_counter(&self) -> Option<u32> {
1336 CandidateRouteHop::FirstHop { target_node_counter, .. } => Some(*target_node_counter),
1337 CandidateRouteHop::PublicHop { info, .. } => Some(info.target_counter()),
1338 CandidateRouteHop::PrivateHop { target_node_counter, .. } => Some(*target_node_counter),
1339 CandidateRouteHop::Blinded { .. } => None,
1340 CandidateRouteHop::OneHopBlinded { .. } => None,
1344 /// Returns the fees that must be paid to route an HTLC over this channel.
1346 pub fn fees(&self) -> RoutingFees {
1348 CandidateRouteHop::FirstHop(_) => RoutingFees {
1349 base_msat: 0, proportional_millionths: 0,
1351 CandidateRouteHop::PublicHop(hop) => hop.info.direction().fees,
1352 CandidateRouteHop::PrivateHop(hop) => hop.hint.fees,
1353 CandidateRouteHop::Blinded(hop) => {
1355 base_msat: hop.hint.0.fee_base_msat,
1356 proportional_millionths: hop.hint.0.fee_proportional_millionths
1359 CandidateRouteHop::OneHopBlinded(_) =>
1360 RoutingFees { base_msat: 0, proportional_millionths: 0 },
1364 /// Fetch the effective capacity of this hop.
1366 /// Note that this may be somewhat expensive, so calls to this should be limited and results
1368 fn effective_capacity(&self) -> EffectiveCapacity {
1370 CandidateRouteHop::FirstHop(hop) => EffectiveCapacity::ExactLiquidity {
1371 liquidity_msat: hop.details.next_outbound_htlc_limit_msat,
1373 CandidateRouteHop::PublicHop(hop) => hop.info.effective_capacity(),
1374 CandidateRouteHop::PrivateHop(CandidatePrivateHop { hint: RouteHintHop { htlc_maximum_msat: Some(max), .. }, .. }) =>
1375 EffectiveCapacity::HintMaxHTLC { amount_msat: *max },
1376 CandidateRouteHop::PrivateHop(CandidatePrivateHop { hint: RouteHintHop { htlc_maximum_msat: None, .. }, .. }) =>
1377 EffectiveCapacity::Infinite,
1378 CandidateRouteHop::Blinded(hop) =>
1379 EffectiveCapacity::HintMaxHTLC { amount_msat: hop.hint.0.htlc_maximum_msat },
1380 CandidateRouteHop::OneHopBlinded(_) => EffectiveCapacity::Infinite,
1384 /// Returns an ID describing the given hop.
1386 /// See the docs on [`CandidateHopId`] for when this is, or is not, unique.
1388 fn id(&self) -> CandidateHopId {
1390 CandidateRouteHop::Blinded(hop) => CandidateHopId::Blinded(hop.hint_idx),
1391 CandidateRouteHop::OneHopBlinded(hop) => CandidateHopId::Blinded(hop.hint_idx),
1392 _ => CandidateHopId::Clear((self.short_channel_id().unwrap(), self.source() < self.target().unwrap())),
1395 fn blinded_path(&self) -> Option<&'a BlindedPath> {
1397 CandidateRouteHop::Blinded(CandidateBlindedPath { hint, .. }) | CandidateRouteHop::OneHopBlinded(CandidateOneHopBlindedPath { hint, .. }) => {
1403 /// Returns the source node id of current hop.
1405 /// Source node id refers to the node forwarding the HTLC through this hop.
1407 /// For [`Self::FirstHop`] we return payer's node id.
1409 pub fn source(&self) -> NodeId {
1411 CandidateRouteHop::FirstHop(hop) => *hop.payer_node_id,
1412 CandidateRouteHop::PublicHop(hop) => *hop.info.source(),
1413 CandidateRouteHop::PrivateHop(hop) => hop.hint.src_node_id.into(),
1414 CandidateRouteHop::Blinded(hop) => hop.hint.1.introduction_node_id.into(),
1415 CandidateRouteHop::OneHopBlinded(hop) => hop.hint.1.introduction_node_id.into(),
1418 /// Returns the target node id of this hop, if known.
1420 /// Target node id refers to the node receiving the HTLC after this hop.
1422 /// For [`Self::Blinded`] we return `None` because the ultimate destination after the blinded
1423 /// path is unknown.
1425 /// For [`Self::OneHopBlinded`] we return `None` because the target is the same as the source,
1426 /// and such a return value would be somewhat nonsensical.
1428 pub fn target(&self) -> Option<NodeId> {
1430 CandidateRouteHop::FirstHop(hop) => Some(hop.details.counterparty.node_id.into()),
1431 CandidateRouteHop::PublicHop(hop) => Some(*hop.info.target()),
1432 CandidateRouteHop::PrivateHop(hop) => Some(*hop.target_node_id),
1433 CandidateRouteHop::Blinded(_) => None,
1434 CandidateRouteHop::OneHopBlinded(_) => None,
1439 /// A unique(ish) identifier for a specific [`CandidateRouteHop`].
1441 /// For blinded paths, this ID is unique only within a given [`find_route`] call.
1443 /// For other hops, because SCIDs between private channels and public channels can conflict, this
1444 /// isn't guaranteed to be unique at all.
1446 /// For our uses, this is generally fine, but it is not public as it is otherwise a rather
1447 /// difficult-to-use API.
1448 #[derive(Clone, Copy, Eq, Hash, Ord, PartialOrd, PartialEq)]
1449 enum CandidateHopId {
1450 /// Contains (scid, src_node_id < target_node_id)
1452 /// Index of the blinded route hint in [`Payee::Blinded::route_hints`].
1457 fn max_htlc_from_capacity(capacity: EffectiveCapacity, max_channel_saturation_power_of_half: u8) -> u64 {
1458 let saturation_shift: u32 = max_channel_saturation_power_of_half as u32;
1460 EffectiveCapacity::ExactLiquidity { liquidity_msat } => liquidity_msat,
1461 EffectiveCapacity::Infinite => u64::max_value(),
1462 EffectiveCapacity::Unknown => EffectiveCapacity::Unknown.as_msat(),
1463 EffectiveCapacity::AdvertisedMaxHTLC { amount_msat } =>
1464 amount_msat.checked_shr(saturation_shift).unwrap_or(0),
1465 // Treat htlc_maximum_msat from a route hint as an exact liquidity amount, since the invoice is
1466 // expected to have been generated from up-to-date capacity information.
1467 EffectiveCapacity::HintMaxHTLC { amount_msat } => amount_msat,
1468 EffectiveCapacity::Total { capacity_msat, htlc_maximum_msat } =>
1469 cmp::min(capacity_msat.checked_shr(saturation_shift).unwrap_or(0), htlc_maximum_msat),
1473 fn iter_equal<I1: Iterator, I2: Iterator>(mut iter_a: I1, mut iter_b: I2)
1474 -> bool where I1::Item: PartialEq<I2::Item> {
1476 let a = iter_a.next();
1477 let b = iter_b.next();
1478 if a.is_none() && b.is_none() { return true; }
1479 if a.is_none() || b.is_none() { return false; }
1480 if a.unwrap().ne(&b.unwrap()) { return false; }
1484 #[cfg(target_feature = "sse")]
1486 unsafe fn do_prefetch<T>(ptr: *const T) {
1487 #[cfg(target_arch = "x86_64")]
1488 use core::arch::x86_64::*;
1489 #[cfg(target_arch = "x86")]
1490 use core::arch::x86::*;
1491 _mm_prefetch(ptr as *const i8, _MM_HINT_T0);
1494 #[cfg(not(target_feature = "sse"))]
1496 unsafe fn do_prefetch<T>(_: *const T) {}
1499 fn prefetch_first_byte<T>(t: &T) {
1500 // While X86's prefetch should be safe even on an invalid memory address (the ISA says
1501 // "PREFETCHh instruction is merely a hint and does not affect program behavior"), we take
1502 // an extra step towards safety here by requiring the pointer be valid (as Rust references
1503 // are always valid when accessed).
1505 // Note that a pointer in Rust could be to a zero sized type, in which case the pointer could
1506 // be NULL (or some other bogus value), so we explicitly check for that here.
1507 if ::core::mem::size_of::<T>() != 0 {
1508 unsafe { do_prefetch(t) }
1512 /// It's useful to keep track of the hops associated with the fees required to use them,
1513 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
1514 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
1515 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
1518 struct PathBuildingHop<'a> {
1519 candidate: CandidateRouteHop<'a>,
1520 target_node_counter: Option<u32>,
1521 /// If we've already processed a node as the best node, we shouldn't process it again. Normally
1522 /// we'd just ignore it if we did as all channels would have a higher new fee, but because we
1523 /// may decrease the amounts in use as we walk the graph, the actual calculated fee may
1524 /// decrease as well. Thus, we have to explicitly track which nodes have been processed and
1525 /// avoid processing them again.
1526 was_processed: bool,
1527 /// When processing a node as the next best-score candidate, we want to quickly check if it is
1528 /// a direct counterparty of ours, using our local channel information immediately if we can.
1530 /// In order to do so efficiently, we cache whether a node is a direct counterparty here at the
1531 /// start of a route-finding pass. Unlike all other fields in this struct, this field is never
1532 /// updated after being initialized - it is set at the start of a route-finding pass and only
1533 /// read thereafter.
1534 is_first_hop_target: bool,
1535 /// Used to compare channels when choosing the for routing.
1536 /// Includes paying for the use of a hop and the following hops, as well as
1537 /// an estimated cost of reaching this hop.
1538 /// Might get stale when fees are recomputed. Primarily for internal use.
1539 total_fee_msat: u64,
1540 /// A mirror of the same field in RouteGraphNode. Note that this is only used during the graph
1541 /// walk and may be invalid thereafter.
1542 path_htlc_minimum_msat: u64,
1543 /// All penalties incurred from this channel on the way to the destination, as calculated using
1544 /// channel scoring.
1545 path_penalty_msat: u64,
1549 /// All the fees paid *after* this channel on the way to the destination
1550 next_hops_fee_msat: u64,
1551 /// Fee paid for the use of the current channel (see candidate.fees()).
1552 /// The value will be actually deducted from the counterparty balance on the previous link.
1553 hop_use_fee_msat: u64,
1555 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1556 // In tests, we apply further sanity checks on cases where we skip nodes we already processed
1557 // to ensure it is specifically in cases where the fee has gone down because of a decrease in
1558 // value_contribution_msat, which requires tracking it here. See comments below where it is
1559 // used for more info.
1560 value_contribution_msat: u64,
1563 const _NODE_MAP_SIZE_TWO_CACHE_LINES: usize = 128 - core::mem::size_of::<Option<PathBuildingHop>>();
1564 const _NODE_MAP_SIZE_EXACTLY_TWO_CACHE_LINES: usize = core::mem::size_of::<Option<PathBuildingHop>>() - 128;
1566 impl<'a> core::fmt::Debug for PathBuildingHop<'a> {
1567 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
1568 let mut debug_struct = f.debug_struct("PathBuildingHop");
1570 .field("source_node_id", &self.candidate.source())
1571 .field("target_node_id", &self.candidate.target())
1572 .field("short_channel_id", &self.candidate.short_channel_id())
1573 .field("total_fee_msat", &self.total_fee_msat)
1574 .field("next_hops_fee_msat", &self.next_hops_fee_msat)
1575 .field("hop_use_fee_msat", &self.hop_use_fee_msat)
1576 .field("total_fee_msat - (next_hops_fee_msat + hop_use_fee_msat)", &(&self.total_fee_msat.saturating_sub(self.next_hops_fee_msat).saturating_sub(self.hop_use_fee_msat)))
1577 .field("path_penalty_msat", &self.path_penalty_msat)
1578 .field("path_htlc_minimum_msat", &self.path_htlc_minimum_msat)
1579 .field("cltv_expiry_delta", &self.candidate.cltv_expiry_delta());
1580 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1581 let debug_struct = debug_struct
1582 .field("value_contribution_msat", &self.value_contribution_msat);
1583 debug_struct.finish()
1587 // Instantiated with a list of hops with correct data in them collected during path finding,
1588 // an instance of this struct should be further modified only via given methods.
1590 struct PaymentPath<'a> {
1591 hops: Vec<(PathBuildingHop<'a>, NodeFeatures)>,
1594 impl<'a> PaymentPath<'a> {
1595 // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
1596 fn get_value_msat(&self) -> u64 {
1597 self.hops.last().unwrap().0.fee_msat
1600 fn get_path_penalty_msat(&self) -> u64 {
1601 self.hops.first().map(|h| h.0.path_penalty_msat).unwrap_or(u64::max_value())
1604 fn get_total_fee_paid_msat(&self) -> u64 {
1605 if self.hops.len() < 1 {
1609 // Can't use next_hops_fee_msat because it gets outdated.
1610 for (i, (hop, _)) in self.hops.iter().enumerate() {
1611 if i != self.hops.len() - 1 {
1612 result += hop.fee_msat;
1618 fn get_cost_msat(&self) -> u64 {
1619 self.get_total_fee_paid_msat().saturating_add(self.get_path_penalty_msat())
1622 // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
1623 // to change fees may result in an inconsistency.
1625 // Sometimes we call this function right after constructing a path which is inconsistent in
1626 // that it the value being transferred has decreased while we were doing path finding, leading
1627 // to the fees being paid not lining up with the actual limits.
1629 // Note that this function is not aware of the available_liquidity limit, and thus does not
1630 // support increasing the value being transferred beyond what was selected during the initial
1633 // Returns the amount that this path contributes to the total payment value, which may be greater
1634 // than `value_msat` if we had to overpay to meet the final node's `htlc_minimum_msat`.
1635 fn update_value_and_recompute_fees(&mut self, value_msat: u64) -> u64 {
1636 let mut extra_contribution_msat = 0;
1637 let mut total_fee_paid_msat = 0 as u64;
1638 for i in (0..self.hops.len()).rev() {
1639 let last_hop = i == self.hops.len() - 1;
1641 // For non-last-hop, this value will represent the fees paid on the current hop. It
1642 // will consist of the fees for the use of the next hop, and extra fees to match
1643 // htlc_minimum_msat of the current channel. Last hop is handled separately.
1644 let mut cur_hop_fees_msat = 0;
1646 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().0.hop_use_fee_msat;
1649 let cur_hop = &mut self.hops.get_mut(i).unwrap().0;
1650 cur_hop.next_hops_fee_msat = total_fee_paid_msat;
1651 cur_hop.path_penalty_msat += extra_contribution_msat;
1652 // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
1653 // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
1654 // set it too high just to maliciously take more fees by exploiting this
1655 // match htlc_minimum_msat logic.
1656 let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
1657 if let Some(extra_fees_msat) = cur_hop.candidate.htlc_minimum_msat().checked_sub(cur_hop_transferred_amount_msat) {
1658 // Note that there is a risk that *previous hops* (those closer to us, as we go
1659 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
1661 // This might make us end up with a broken route, although this should be super-rare
1662 // in practice, both because of how healthy channels look like, and how we pick
1663 // channels in add_entry.
1664 // Also, this can't be exploited more heavily than *announce a free path and fail
1666 cur_hop_transferred_amount_msat += extra_fees_msat;
1668 // We remember and return the extra fees on the final hop to allow accounting for
1669 // them in the path's value contribution.
1671 extra_contribution_msat = extra_fees_msat;
1673 total_fee_paid_msat += extra_fees_msat;
1674 cur_hop_fees_msat += extra_fees_msat;
1679 // Final hop is a special case: it usually has just value_msat (by design), but also
1680 // it still could overpay for the htlc_minimum_msat.
1681 cur_hop.fee_msat = cur_hop_transferred_amount_msat;
1683 // Propagate updated fees for the use of the channels to one hop back, where they
1684 // will be actually paid (fee_msat). The last hop is handled above separately.
1685 cur_hop.fee_msat = cur_hop_fees_msat;
1688 // Fee for the use of the current hop which will be deducted on the previous hop.
1689 // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
1690 // this channel is free for us.
1692 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.candidate.fees()) {
1693 cur_hop.hop_use_fee_msat = new_fee;
1694 total_fee_paid_msat += new_fee;
1696 // It should not be possible because this function is called only to reduce the
1697 // value. In that case, compute_fee was already called with the same fees for
1698 // larger amount and there was no overflow.
1703 value_msat + extra_contribution_msat
1708 /// Calculate the fees required to route the given amount over a channel with the given fees.
1709 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
1710 amount_msat.checked_mul(channel_fees.proportional_millionths as u64)
1711 .and_then(|part| (channel_fees.base_msat as u64).checked_add(part / 1_000_000))
1715 /// Calculate the fees required to route the given amount over a channel with the given fees,
1716 /// saturating to [`u64::max_value`].
1717 fn compute_fees_saturating(amount_msat: u64, channel_fees: RoutingFees) -> u64 {
1718 amount_msat.checked_mul(channel_fees.proportional_millionths as u64)
1719 .map(|prop| prop / 1_000_000).unwrap_or(u64::max_value())
1720 .saturating_add(channel_fees.base_msat as u64)
1723 /// The default `features` we assume for a node in a route, when no `features` are known about that
1726 /// Default features are:
1727 /// * variable_length_onion_optional
1728 fn default_node_features() -> NodeFeatures {
1729 let mut features = NodeFeatures::empty();
1730 features.set_variable_length_onion_optional();
1734 struct LoggedPayeePubkey(Option<PublicKey>);
1735 impl fmt::Display for LoggedPayeePubkey {
1736 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1739 "payee node id ".fmt(f)?;
1743 "blinded payee".fmt(f)
1749 struct LoggedCandidateHop<'a>(&'a CandidateRouteHop<'a>);
1750 impl<'a> fmt::Display for LoggedCandidateHop<'a> {
1751 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1753 CandidateRouteHop::Blinded(CandidateBlindedPath { hint, .. }) | CandidateRouteHop::OneHopBlinded(CandidateOneHopBlindedPath { hint, .. }) => {
1754 "blinded route hint with introduction node id ".fmt(f)?;
1755 hint.1.introduction_node_id.fmt(f)?;
1756 " and blinding point ".fmt(f)?;
1757 hint.1.blinding_point.fmt(f)
1759 CandidateRouteHop::FirstHop(_) => {
1760 "first hop with SCID ".fmt(f)?;
1761 self.0.short_channel_id().unwrap().fmt(f)
1763 CandidateRouteHop::PrivateHop(_) => {
1764 "route hint with SCID ".fmt(f)?;
1765 self.0.short_channel_id().unwrap().fmt(f)
1769 self.0.short_channel_id().unwrap().fmt(f)
1776 fn sort_first_hop_channels(
1777 channels: &mut Vec<&ChannelDetails>, used_liquidities: &HashMap<CandidateHopId, u64>,
1778 recommended_value_msat: u64, our_node_pubkey: &PublicKey
1780 // Sort the first_hops channels to the same node(s) in priority order of which channel we'd
1781 // most like to use.
1783 // First, if channels are below `recommended_value_msat`, sort them in descending order,
1784 // preferring larger channels to avoid splitting the payment into more MPP parts than is
1787 // Second, because simply always sorting in descending order would always use our largest
1788 // available outbound capacity, needlessly fragmenting our available channel capacities,
1789 // sort channels above `recommended_value_msat` in ascending order, preferring channels
1790 // which have enough, but not too much, capacity for the payment.
1792 // Available outbound balances factor in liquidity already reserved for previously found paths.
1793 channels.sort_unstable_by(|chan_a, chan_b| {
1794 let chan_a_outbound_limit_msat = chan_a.next_outbound_htlc_limit_msat
1795 .saturating_sub(*used_liquidities.get(&CandidateHopId::Clear((chan_a.get_outbound_payment_scid().unwrap(),
1796 our_node_pubkey < &chan_a.counterparty.node_id))).unwrap_or(&0));
1797 let chan_b_outbound_limit_msat = chan_b.next_outbound_htlc_limit_msat
1798 .saturating_sub(*used_liquidities.get(&CandidateHopId::Clear((chan_b.get_outbound_payment_scid().unwrap(),
1799 our_node_pubkey < &chan_b.counterparty.node_id))).unwrap_or(&0));
1800 if chan_b_outbound_limit_msat < recommended_value_msat || chan_a_outbound_limit_msat < recommended_value_msat {
1801 // Sort in descending order
1802 chan_b_outbound_limit_msat.cmp(&chan_a_outbound_limit_msat)
1804 // Sort in ascending order
1805 chan_a_outbound_limit_msat.cmp(&chan_b_outbound_limit_msat)
1810 /// Finds a route from us (payer) to the given target node (payee).
1812 /// If the payee provided features in their invoice, they should be provided via the `payee` field
1813 /// in the given [`RouteParameters::payment_params`].
1814 /// Without this, MPP will only be used if the payee's features are available in the network graph.
1816 /// Private routing paths between a public node and the target may be included in the `payee` field
1817 /// of [`RouteParameters::payment_params`].
1819 /// If some channels aren't announced, it may be useful to fill in `first_hops` with the results
1820 /// from [`ChannelManager::list_usable_channels`]. If it is filled in, the view of these channels
1821 /// from `network_graph` will be ignored, and only those in `first_hops` will be used.
1823 /// The fees on channels from us to the next hop are ignored as they are assumed to all be equal.
1824 /// However, the enabled/disabled bit on such channels as well as the `htlc_minimum_msat` /
1825 /// `htlc_maximum_msat` *are* checked as they may change based on the receiving node.
1829 /// Panics if first_hops contains channels without `short_channel_id`s;
1830 /// [`ChannelManager::list_usable_channels`] will never include such channels.
1832 /// [`ChannelManager::list_usable_channels`]: crate::ln::channelmanager::ChannelManager::list_usable_channels
1833 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
1834 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
1835 pub fn find_route<L: Deref, GL: Deref, S: ScoreLookUp>(
1836 our_node_pubkey: &PublicKey, route_params: &RouteParameters,
1837 network_graph: &NetworkGraph<GL>, first_hops: Option<&[&ChannelDetails]>, logger: L,
1838 scorer: &S, score_params: &S::ScoreParams, random_seed_bytes: &[u8; 32]
1839 ) -> Result<Route, LightningError>
1840 where L::Target: Logger, GL::Target: Logger {
1841 let graph_lock = network_graph.read_only();
1842 let mut route = get_route(our_node_pubkey, &route_params, &graph_lock, first_hops, logger,
1843 scorer, score_params, random_seed_bytes)?;
1844 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
1848 pub(crate) fn get_route<L: Deref, S: ScoreLookUp>(
1849 our_node_pubkey: &PublicKey, route_params: &RouteParameters, network_graph: &ReadOnlyNetworkGraph,
1850 first_hops: Option<&[&ChannelDetails]>, logger: L, scorer: &S, score_params: &S::ScoreParams,
1851 _random_seed_bytes: &[u8; 32]
1852 ) -> Result<Route, LightningError>
1853 where L::Target: Logger {
1855 let payment_params = &route_params.payment_params;
1856 let final_value_msat = route_params.final_value_msat;
1857 // If we're routing to a blinded recipient, we won't have their node id. Therefore, keep the
1858 // unblinded payee id as an option. We also need a non-optional "payee id" for path construction,
1859 // so use a dummy id for this in the blinded case.
1860 let payee_node_id_opt = payment_params.payee.node_id().map(|pk| NodeId::from_pubkey(&pk));
1861 const DUMMY_BLINDED_PAYEE_ID: [u8; 33] = [2; 33];
1862 let maybe_dummy_payee_pk = payment_params.payee.node_id().unwrap_or_else(|| PublicKey::from_slice(&DUMMY_BLINDED_PAYEE_ID).unwrap());
1863 let maybe_dummy_payee_node_id = NodeId::from_pubkey(&maybe_dummy_payee_pk);
1864 let our_node_id = NodeId::from_pubkey(&our_node_pubkey);
1866 if payee_node_id_opt.map_or(false, |payee| payee == our_node_id) {
1867 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
1869 if our_node_id == maybe_dummy_payee_node_id {
1870 return Err(LightningError{err: "Invalid origin node id provided, use a different one".to_owned(), action: ErrorAction::IgnoreError});
1873 if final_value_msat > MAX_VALUE_MSAT {
1874 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
1877 if final_value_msat == 0 {
1878 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
1881 match &payment_params.payee {
1882 Payee::Clear { route_hints, node_id, .. } => {
1883 for route in route_hints.iter() {
1884 for hop in &route.0 {
1885 if hop.src_node_id == *node_id {
1886 return Err(LightningError{err: "Route hint cannot have the payee as the source.".to_owned(), action: ErrorAction::IgnoreError});
1891 Payee::Blinded { route_hints, .. } => {
1892 if route_hints.iter().all(|(_, path)| &path.introduction_node_id == our_node_pubkey) {
1893 return Err(LightningError{err: "Cannot generate a route to blinded paths if we are the introduction node to all of them".to_owned(), action: ErrorAction::IgnoreError});
1895 for (_, blinded_path) in route_hints.iter() {
1896 if blinded_path.blinded_hops.len() == 0 {
1897 return Err(LightningError{err: "0-hop blinded path provided".to_owned(), action: ErrorAction::IgnoreError});
1898 } else if &blinded_path.introduction_node_id == our_node_pubkey {
1899 log_info!(logger, "Got blinded path with ourselves as the introduction node, ignoring");
1900 } else if blinded_path.blinded_hops.len() == 1 &&
1901 route_hints.iter().any( |(_, p)| p.blinded_hops.len() == 1
1902 && p.introduction_node_id != blinded_path.introduction_node_id)
1904 return Err(LightningError{err: format!("1-hop blinded paths must all have matching introduction node ids"), action: ErrorAction::IgnoreError});
1909 let final_cltv_expiry_delta = payment_params.payee.final_cltv_expiry_delta().unwrap_or(0);
1910 if payment_params.max_total_cltv_expiry_delta <= final_cltv_expiry_delta {
1911 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});
1914 // The general routing idea is the following:
1915 // 1. Fill first/last hops communicated by the caller.
1916 // 2. Attempt to construct a path from payer to payee for transferring
1917 // any ~sufficient (described later) value.
1918 // If succeed, remember which channels were used and how much liquidity they have available,
1919 // so that future paths don't rely on the same liquidity.
1920 // 3. Proceed to the next step if:
1921 // - we hit the recommended target value;
1922 // - OR if we could not construct a new path. Any next attempt will fail too.
1923 // Otherwise, repeat step 2.
1924 // 4. See if we managed to collect paths which aggregately are able to transfer target value
1925 // (not recommended value).
1926 // 5. If yes, proceed. If not, fail routing.
1927 // 6. Select the paths which have the lowest cost (fee plus scorer penalty) per amount
1928 // transferred up to the transfer target value.
1929 // 7. Reduce the value of the last path until we are sending only the target value.
1930 // 8. If our maximum channel saturation limit caused us to pick two identical paths, combine
1931 // them so that we're not sending two HTLCs along the same path.
1933 // As for the actual search algorithm, we do a payee-to-payer Dijkstra's sorting by each node's
1934 // distance from the payee
1936 // We are not a faithful Dijkstra's implementation because we can change values which impact
1937 // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
1938 // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) than
1939 // the value we are currently attempting to send over a path, we simply reduce the value being
1940 // sent along the path for any hops after that channel. This may imply that later fees (which
1941 // we've already tabulated) are lower because a smaller value is passing through the channels
1942 // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
1943 // channels which were selected earlier (and which may still be used for other paths without a
1944 // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
1947 // One potentially problematic case for this algorithm would be if there are many
1948 // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
1949 // graph walking), we may never find a path which is not liquidity-limited and has lower
1950 // proportional fee (and only lower absolute fee when considering the ultimate value sent).
1951 // Because we only consider paths with at least 5% of the total value being sent, the damage
1952 // from such a case should be limited, however this could be further reduced in the future by
1953 // calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
1954 // limits for the purposes of fee calculation.
1956 // Alternatively, we could store more detailed path information in the heap (targets, below)
1957 // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
1958 // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
1959 // and practically (as we would need to store dynamically-allocated path information in heap
1960 // objects, increasing malloc traffic and indirect memory access significantly). Further, the
1961 // results of such an algorithm would likely be biased towards lower-value paths.
1963 // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
1964 // outside of our current search value, running a path search more times to gather candidate
1965 // paths at different values. While this may be acceptable, further path searches may increase
1966 // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
1967 // graph for candidate paths, calculating the maximum value which can realistically be sent at
1968 // the same time, remaining generic across different payment values.
1970 let network_channels = network_graph.channels();
1971 let network_nodes = network_graph.nodes();
1973 if payment_params.max_path_count == 0 {
1974 return Err(LightningError{err: "Can't find a route with no paths allowed.".to_owned(), action: ErrorAction::IgnoreError});
1977 // Allow MPP only if we have a features set from somewhere that indicates the payee supports
1978 // it. If the payee supports it they're supposed to include it in the invoice, so that should
1980 let allow_mpp = if payment_params.max_path_count == 1 {
1982 } else if payment_params.payee.supports_basic_mpp() {
1984 } else if let Some(payee) = payee_node_id_opt {
1985 network_nodes.get(&payee).map_or(false, |node| node.announcement_info.as_ref().map_or(false,
1986 |info| info.features.supports_basic_mpp()))
1989 let max_total_routing_fee_msat = route_params.max_total_routing_fee_msat.unwrap_or(u64::max_value());
1991 log_trace!(logger, "Searching for a route from payer {} to {} {} MPP and {} first hops {}overriding the network graph with a fee limit of {} msat",
1992 our_node_pubkey, LoggedPayeePubkey(payment_params.payee.node_id()),
1993 if allow_mpp { "with" } else { "without" },
1994 first_hops.map(|hops| hops.len()).unwrap_or(0), if first_hops.is_some() { "" } else { "not " },
1995 max_total_routing_fee_msat);
1997 let private_hop_targets_node_counter_offset = network_graph.max_node_counter() + 2;
1998 let mut private_node_id_to_node_counter = HashMap::new();
2000 let mut private_hop_key_cache = HashMap::with_capacity(
2001 payment_params.payee.unblinded_route_hints().iter().map(|path| path.0.len()).sum()
2004 // Because we store references to private hop node_ids in `dist`, below, we need them to exist
2005 // (as `NodeId`, not `PublicKey`) for the lifetime of `dist`. Thus, we calculate all the keys
2006 // we'll need here and simply fetch them when routing.
2007 let payee_node_counter = payee_node_id_opt
2008 .and_then(|payee| network_nodes.get(&payee))
2009 .map(|node| node.node_counter)
2010 .unwrap_or(private_hop_targets_node_counter_offset);
2011 private_node_id_to_node_counter.insert(maybe_dummy_payee_node_id, payee_node_counter);
2012 private_hop_key_cache.insert(maybe_dummy_payee_pk, (NodeId::from_pubkey(&maybe_dummy_payee_pk), payee_node_counter));
2014 for route in payment_params.payee.unblinded_route_hints().iter() {
2015 for hop in route.0.iter() {
2016 let hop_node_id = NodeId::from_pubkey(&hop.src_node_id);
2017 let node_counter = if let Some(node) = network_nodes.get(&hop_node_id) {
2020 let next_node_counter = private_hop_targets_node_counter_offset + private_node_id_to_node_counter.len() as u32;
2021 *private_node_id_to_node_counter.entry(hop_node_id)
2022 .or_insert(next_node_counter)
2024 private_hop_key_cache.insert(hop.src_node_id, (hop_node_id, node_counter));
2029 // Prepare the data we'll use for payee-to-payer search by
2030 // inserting first hops suggested by the caller as targets.
2031 // Our search will then attempt to reach them while traversing from the payee node.
2032 let mut first_hop_targets: HashMap<_, (Vec<&ChannelDetails>, u32)> =
2033 HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
2034 if let Some(hops) = first_hops {
2036 if chan.get_outbound_payment_scid().is_none() {
2037 panic!("first_hops should be filled in with usable channels, not pending ones");
2039 if chan.counterparty.node_id == *our_node_pubkey {
2040 return Err(LightningError{err: "First hop cannot have our_node_pubkey as a destination.".to_owned(), action: ErrorAction::IgnoreError});
2042 let counterparty_node_id = NodeId::from_pubkey(&chan.counterparty.node_id);
2044 .entry(counterparty_node_id)
2045 .or_insert_with(|| {
2046 let node_counter = if let Some(node) = network_nodes.get(&counterparty_node_id) {
2049 let next_node_counter = private_hop_targets_node_counter_offset + private_node_id_to_node_counter.len() as u32;
2050 *private_node_id_to_node_counter.entry(counterparty_node_id)
2051 .or_insert(next_node_counter)
2053 (Vec::new(), node_counter)
2057 if first_hop_targets.is_empty() {
2058 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
2062 // The main heap containing all candidate next-hops sorted by their score (max(fee,
2063 // htlc_minimum)). Ideally this would be a heap which allowed cheap score reduction instead of
2064 // adding duplicate entries when we find a better path to a given node.
2065 let mut targets: BinaryHeap<RouteGraphNode> = BinaryHeap::new();
2067 // Map from node_id to information about the best current path to that node, including feerate
2069 let dist_len = private_hop_targets_node_counter_offset + private_hop_key_cache.len() as u32 + 1;
2070 let mut dist: Vec<Option<PathBuildingHop>> = vec![None; dist_len as usize];
2071 let payer_node_counter = network_nodes
2073 .map(|node| node.node_counter)
2075 private_node_id_to_node_counter.get(&our_node_id).map(|counter| *counter)
2077 .unwrap_or(network_graph.max_node_counter() + 1);
2079 // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
2080 // indicating that we may wish to try again with a higher value, potentially paying to meet an
2081 // htlc_minimum with extra fees while still finding a cheaper path.
2082 let mut hit_minimum_limit;
2084 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
2085 // We start with a path_value of the exact amount we want, and if that generates a route we may
2086 // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
2087 // amount we want in total across paths, selecting the best subset at the end.
2088 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
2089 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
2090 let mut path_value_msat = final_value_msat;
2092 // Routing Fragmentation Mitigation heuristic:
2094 // Routing fragmentation across many payment paths increases the overall routing
2095 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
2096 // Taking too many smaller paths also increases the chance of payment failure.
2097 // Thus to avoid this effect, we require from our collected links to provide
2098 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
2099 // This requirement is currently set to be 1/max_path_count of the payment
2100 // value to ensure we only ever return routes that do not violate this limit.
2101 let minimal_value_contribution_msat: u64 = if allow_mpp {
2102 (final_value_msat + (payment_params.max_path_count as u64 - 1)) / payment_params.max_path_count as u64
2107 // When we start collecting routes we enforce the max_channel_saturation_power_of_half
2108 // requirement strictly. After we've collected enough (or if we fail to find new routes) we
2109 // drop the requirement by setting this to 0.
2110 let mut channel_saturation_pow_half = payment_params.max_channel_saturation_power_of_half;
2112 // Keep track of how much liquidity has been used in selected channels or blinded paths. Used to
2113 // determine if the channel can be used by additional MPP paths or to inform path finding
2114 // decisions. It is aware of direction *only* to ensure that the correct htlc_maximum_msat value
2115 // is used. Hence, liquidity used in one direction will not offset any used in the opposite
2117 let mut used_liquidities: HashMap<CandidateHopId, u64> =
2118 HashMap::with_capacity(network_nodes.len());
2120 // Keeping track of how much value we already collected across other paths. Helps to decide
2121 // when we want to stop looking for new paths.
2122 let mut already_collected_value_msat = 0;
2124 for (_, (channels, _)) in first_hop_targets.iter_mut() {
2125 sort_first_hop_channels(channels, &used_liquidities, recommended_value_msat,
2129 log_trace!(logger, "Building path from {} to payer {} for value {} msat.",
2130 LoggedPayeePubkey(payment_params.payee.node_id()), our_node_pubkey, final_value_msat);
2132 // Remember how many candidates we ignored to allow for some logging afterwards.
2133 let mut num_ignored_value_contribution: u32 = 0;
2134 let mut num_ignored_path_length_limit: u32 = 0;
2135 let mut num_ignored_cltv_delta_limit: u32 = 0;
2136 let mut num_ignored_previously_failed: u32 = 0;
2137 let mut num_ignored_total_fee_limit: u32 = 0;
2138 let mut num_ignored_avoid_overpayment: u32 = 0;
2139 let mut num_ignored_htlc_minimum_msat_limit: u32 = 0;
2141 macro_rules! add_entry {
2142 // Adds entry which goes from $candidate.source() to $candidate.target() over the $candidate hop.
2143 // $next_hops_fee_msat represents the fees paid for using all the channels *after* this one,
2144 // since that value has to be transferred over this channel.
2145 // Returns the contribution amount of $candidate if the channel caused an update to `targets`.
2146 ( $candidate: expr, $next_hops_fee_msat: expr,
2147 $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr,
2148 $next_hops_path_penalty_msat: expr, $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => { {
2149 // We "return" whether we updated the path at the end, and how much we can route via
2150 // this channel, via this:
2151 let mut hop_contribution_amt_msat = None;
2152 // Channels to self should not be used. This is more of belt-and-suspenders, because in
2153 // practice these cases should be caught earlier:
2154 // - for regular channels at channel announcement (TODO)
2155 // - for first and last hops early in get_route
2156 let src_node_id = $candidate.source();
2157 if Some(src_node_id) != $candidate.target() {
2158 let scid_opt = $candidate.short_channel_id();
2159 let effective_capacity = $candidate.effective_capacity();
2160 let htlc_maximum_msat = max_htlc_from_capacity(effective_capacity, channel_saturation_pow_half);
2162 // It is tricky to subtract $next_hops_fee_msat from available liquidity here.
2163 // It may be misleading because we might later choose to reduce the value transferred
2164 // over these channels, and the channel which was insufficient might become sufficient.
2165 // Worst case: we drop a good channel here because it can't cover the high following
2166 // fees caused by one expensive channel, but then this channel could have been used
2167 // if the amount being transferred over this path is lower.
2168 // We do this for now, but this is a subject for removal.
2169 if let Some(mut available_value_contribution_msat) = htlc_maximum_msat.checked_sub($next_hops_fee_msat) {
2170 let cltv_expiry_delta = $candidate.cltv_expiry_delta();
2171 let htlc_minimum_msat = $candidate.htlc_minimum_msat();
2172 let used_liquidity_msat = used_liquidities
2173 .get(&$candidate.id())
2174 .map_or(0, |used_liquidity_msat| {
2175 available_value_contribution_msat = available_value_contribution_msat
2176 .saturating_sub(*used_liquidity_msat);
2177 *used_liquidity_msat
2180 // Verify the liquidity offered by this channel complies to the minimal contribution.
2181 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
2182 // Do not consider candidate hops that would exceed the maximum path length.
2183 let path_length_to_node = $next_hops_path_length + 1;
2184 let exceeds_max_path_length = path_length_to_node > MAX_PATH_LENGTH_ESTIMATE;
2186 // Do not consider candidates that exceed the maximum total cltv expiry limit.
2187 // In order to already account for some of the privacy enhancing random CLTV
2188 // expiry delta offset we add on top later, we subtract a rough estimate
2189 // (2*MEDIAN_HOP_CLTV_EXPIRY_DELTA) here.
2190 let max_total_cltv_expiry_delta = (payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta)
2191 .checked_sub(2*MEDIAN_HOP_CLTV_EXPIRY_DELTA)
2192 .unwrap_or(payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta);
2193 let hop_total_cltv_delta = ($next_hops_cltv_delta as u32)
2194 .saturating_add(cltv_expiry_delta);
2195 let exceeds_cltv_delta_limit = hop_total_cltv_delta > max_total_cltv_expiry_delta;
2197 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
2198 // Includes paying fees for the use of the following channels.
2199 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
2200 Some(result) => result,
2201 // Can't overflow due to how the values were computed right above.
2202 None => unreachable!(),
2204 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
2205 let over_path_minimum_msat = amount_to_transfer_over_msat >= htlc_minimum_msat &&
2206 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
2208 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
2209 let may_overpay_to_meet_path_minimum_msat =
2210 ((amount_to_transfer_over_msat < htlc_minimum_msat &&
2211 recommended_value_msat >= htlc_minimum_msat) ||
2212 (amount_to_transfer_over_msat < $next_hops_path_htlc_minimum_msat &&
2213 recommended_value_msat >= $next_hops_path_htlc_minimum_msat));
2215 let payment_failed_on_this_channel = scid_opt.map_or(false,
2216 |scid| payment_params.previously_failed_channels.contains(&scid));
2218 let (should_log_candidate, first_hop_details) = match $candidate {
2219 CandidateRouteHop::FirstHop(hop) => (true, Some(hop.details)),
2220 CandidateRouteHop::PrivateHop(_) => (true, None),
2221 CandidateRouteHop::Blinded(_) => (true, None),
2222 CandidateRouteHop::OneHopBlinded(_) => (true, None),
2226 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
2227 // bother considering this channel. If retrying with recommended_value_msat may
2228 // allow us to hit the HTLC minimum limit, set htlc_minimum_limit so that we go
2229 // around again with a higher amount.
2230 if !contributes_sufficient_value {
2231 if should_log_candidate {
2232 log_trace!(logger, "Ignoring {} due to insufficient value contribution.", LoggedCandidateHop(&$candidate));
2234 if let Some(details) = first_hop_details {
2236 "First hop candidate next_outbound_htlc_limit_msat: {}",
2237 details.next_outbound_htlc_limit_msat,
2241 num_ignored_value_contribution += 1;
2242 } else if exceeds_max_path_length {
2243 if should_log_candidate {
2244 log_trace!(logger, "Ignoring {} due to exceeding maximum path length limit.", LoggedCandidateHop(&$candidate));
2246 num_ignored_path_length_limit += 1;
2247 } else if exceeds_cltv_delta_limit {
2248 if should_log_candidate {
2249 log_trace!(logger, "Ignoring {} due to exceeding CLTV delta limit.", LoggedCandidateHop(&$candidate));
2251 if let Some(_) = first_hop_details {
2253 "First hop candidate cltv_expiry_delta: {}. Limit: {}",
2254 hop_total_cltv_delta,
2255 max_total_cltv_expiry_delta,
2259 num_ignored_cltv_delta_limit += 1;
2260 } else if payment_failed_on_this_channel {
2261 if should_log_candidate {
2262 log_trace!(logger, "Ignoring {} due to a failed previous payment attempt.", LoggedCandidateHop(&$candidate));
2264 num_ignored_previously_failed += 1;
2265 } else if may_overpay_to_meet_path_minimum_msat {
2266 if should_log_candidate {
2268 "Ignoring {} to avoid overpaying to meet htlc_minimum_msat limit.",
2269 LoggedCandidateHop(&$candidate));
2271 if let Some(details) = first_hop_details {
2273 "First hop candidate next_outbound_htlc_minimum_msat: {}",
2274 details.next_outbound_htlc_minimum_msat,
2278 num_ignored_avoid_overpayment += 1;
2279 hit_minimum_limit = true;
2280 } else if over_path_minimum_msat {
2281 // Note that low contribution here (limited by available_liquidity_msat)
2282 // might violate htlc_minimum_msat on the hops which are next along the
2283 // payment path (upstream to the payee). To avoid that, we recompute
2284 // path fees knowing the final path contribution after constructing it.
2285 let curr_min = cmp::max(
2286 $next_hops_path_htlc_minimum_msat, htlc_minimum_msat
2288 let candidate_fees = $candidate.fees();
2289 let src_node_counter = $candidate.src_node_counter();
2290 let path_htlc_minimum_msat = compute_fees_saturating(curr_min, candidate_fees)
2291 .saturating_add(curr_min);
2293 let dist_entry = &mut dist[src_node_counter as usize];
2294 let old_entry = if let Some(hop) = dist_entry {
2297 // If there was previously no known way to access the source node
2298 // (recall it goes payee-to-payer) of short_channel_id, first add a
2299 // semi-dummy record just to compute the fees to reach the source node.
2300 // This will affect our decision on selecting short_channel_id
2301 // as a way to reach the $candidate.target() node.
2302 *dist_entry = Some(PathBuildingHop {
2303 candidate: $candidate.clone(),
2304 target_node_counter: None,
2306 next_hops_fee_msat: u64::max_value(),
2307 hop_use_fee_msat: u64::max_value(),
2308 total_fee_msat: u64::max_value(),
2309 path_htlc_minimum_msat,
2310 path_penalty_msat: u64::max_value(),
2311 was_processed: false,
2312 is_first_hop_target: false,
2313 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
2314 value_contribution_msat,
2316 dist_entry.as_mut().unwrap()
2319 #[allow(unused_mut)] // We only use the mut in cfg(test)
2320 let mut should_process = !old_entry.was_processed;
2321 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
2323 // In test/fuzzing builds, we do extra checks to make sure the skipping
2324 // of already-seen nodes only happens in cases we expect (see below).
2325 if !should_process { should_process = true; }
2329 let mut hop_use_fee_msat = 0;
2330 let mut total_fee_msat: u64 = $next_hops_fee_msat;
2332 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
2333 // will have the same effective-fee
2334 if src_node_id != our_node_id {
2335 // Note that `u64::max_value` means we'll always fail the
2336 // `old_entry.total_fee_msat > total_fee_msat` check below
2337 hop_use_fee_msat = compute_fees_saturating(amount_to_transfer_over_msat, candidate_fees);
2338 total_fee_msat = total_fee_msat.saturating_add(hop_use_fee_msat);
2341 // Ignore hops if augmenting the current path to them would put us over `max_total_routing_fee_msat`
2342 if total_fee_msat > max_total_routing_fee_msat {
2343 if should_log_candidate {
2344 log_trace!(logger, "Ignoring {} due to exceeding max total routing fee limit.", LoggedCandidateHop(&$candidate));
2346 if let Some(_) = first_hop_details {
2348 "First hop candidate routing fee: {}. Limit: {}",
2350 max_total_routing_fee_msat,
2354 num_ignored_total_fee_limit += 1;
2356 let channel_usage = ChannelUsage {
2357 amount_msat: amount_to_transfer_over_msat,
2358 inflight_htlc_msat: used_liquidity_msat,
2361 let channel_penalty_msat =
2362 scorer.channel_penalty_msat($candidate,
2365 let path_penalty_msat = $next_hops_path_penalty_msat
2366 .saturating_add(channel_penalty_msat);
2368 // Update the way of reaching $candidate.source()
2369 // with the given short_channel_id (from $candidate.target()),
2370 // if this way is cheaper than the already known
2371 // (considering the cost to "reach" this channel from the route destination,
2372 // the cost of using this channel,
2373 // and the cost of routing to the source node of this channel).
2374 // Also, consider that htlc_minimum_msat_difference, because we might end up
2375 // paying it. Consider the following exploit:
2376 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
2377 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
2378 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
2379 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
2381 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
2382 // but it may require additional tracking - we don't want to double-count
2383 // the fees included in $next_hops_path_htlc_minimum_msat, but also
2384 // can't use something that may decrease on future hops.
2385 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat)
2386 .saturating_add(old_entry.path_penalty_msat);
2387 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat)
2388 .saturating_add(path_penalty_msat);
2390 if !old_entry.was_processed && new_cost < old_cost {
2391 let new_graph_node = RouteGraphNode {
2392 node_id: src_node_id,
2393 score: cmp::max(total_fee_msat, path_htlc_minimum_msat).saturating_add(path_penalty_msat),
2394 total_cltv_delta: hop_total_cltv_delta,
2395 value_contribution_msat,
2396 path_length_to_node,
2398 targets.push(new_graph_node);
2399 old_entry.target_node_counter = $candidate.target_node_counter();
2400 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
2401 old_entry.hop_use_fee_msat = hop_use_fee_msat;
2402 old_entry.total_fee_msat = total_fee_msat;
2403 old_entry.candidate = $candidate.clone();
2404 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
2405 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
2406 old_entry.path_penalty_msat = path_penalty_msat;
2407 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
2409 old_entry.value_contribution_msat = value_contribution_msat;
2411 hop_contribution_amt_msat = Some(value_contribution_msat);
2412 } else if old_entry.was_processed && new_cost < old_cost {
2413 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
2415 // If we're skipping processing a node which was previously
2416 // processed even though we found another path to it with a
2417 // cheaper fee, check that it was because the second path we
2418 // found (which we are processing now) has a lower value
2419 // contribution due to an HTLC minimum limit.
2421 // e.g. take a graph with two paths from node 1 to node 2, one
2422 // through channel A, and one through channel B. Channel A and
2423 // B are both in the to-process heap, with their scores set by
2424 // a higher htlc_minimum than fee.
2425 // Channel A is processed first, and the channels onwards from
2426 // node 1 are added to the to-process heap. Thereafter, we pop
2427 // Channel B off of the heap, note that it has a much more
2428 // restrictive htlc_maximum_msat, and recalculate the fees for
2429 // all of node 1's channels using the new, reduced, amount.
2431 // This would be bogus - we'd be selecting a higher-fee path
2432 // with a lower htlc_maximum_msat instead of the one we'd
2433 // already decided to use.
2434 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
2436 value_contribution_msat + path_penalty_msat <
2437 old_entry.value_contribution_msat + old_entry.path_penalty_msat
2444 if should_log_candidate {
2446 "Ignoring {} due to its htlc_minimum_msat limit.",
2447 LoggedCandidateHop(&$candidate));
2449 if let Some(details) = first_hop_details {
2451 "First hop candidate next_outbound_htlc_minimum_msat: {}",
2452 details.next_outbound_htlc_minimum_msat,
2456 num_ignored_htlc_minimum_msat_limit += 1;
2460 hop_contribution_amt_msat
2464 let default_node_features = default_node_features();
2466 // Find ways (channels with destination) to reach a given node and store them
2467 // in the corresponding data structures (routing graph etc).
2468 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
2469 // meaning how much will be paid in fees after this node (to the best of our knowledge).
2470 // This data can later be helpful to optimize routing (pay lower fees).
2471 macro_rules! add_entries_to_cheapest_to_target_node {
2472 ( $node: expr, $node_id: expr, $next_hops_value_contribution: expr,
2473 $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => {
2474 let fee_to_target_msat;
2475 let next_hops_path_htlc_minimum_msat;
2476 let next_hops_path_penalty_msat;
2477 let is_first_hop_target;
2478 let skip_node = if let Some(elem) = &mut dist[$node.node_counter as usize] {
2479 let was_processed = elem.was_processed;
2480 elem.was_processed = true;
2481 fee_to_target_msat = elem.total_fee_msat;
2482 next_hops_path_htlc_minimum_msat = elem.path_htlc_minimum_msat;
2483 next_hops_path_penalty_msat = elem.path_penalty_msat;
2484 is_first_hop_target = elem.is_first_hop_target;
2487 // Entries are added to dist in add_entry!() when there is a channel from a node.
2488 // Because there are no channels from payee, it will not have a dist entry at this point.
2489 // If we're processing any other node, it is always be the result of a channel from it.
2490 debug_assert_eq!($node_id, maybe_dummy_payee_node_id);
2492 fee_to_target_msat = 0;
2493 next_hops_path_htlc_minimum_msat = 0;
2494 next_hops_path_penalty_msat = 0;
2495 is_first_hop_target = false;
2500 if is_first_hop_target {
2501 if let Some((first_channels, peer_node_counter)) = first_hop_targets.get(&$node_id) {
2502 for details in first_channels {
2503 debug_assert_eq!(*peer_node_counter, $node.node_counter);
2504 let candidate = CandidateRouteHop::FirstHop(CandidateFirstHop {
2505 details, payer_node_id: &our_node_id, payer_node_counter,
2506 target_node_counter: $node.node_counter,
2508 add_entry!(&candidate, fee_to_target_msat,
2509 $next_hops_value_contribution,
2510 next_hops_path_htlc_minimum_msat, next_hops_path_penalty_msat,
2511 $next_hops_cltv_delta, $next_hops_path_length);
2516 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
2519 &default_node_features
2522 if !features.requires_unknown_bits() {
2523 for chan_id in $node.channels.iter() {
2524 let chan = network_channels.get(chan_id).unwrap();
2525 // Calling chan.as_directed_to, below, will require access to memory two
2526 // cache lines away from chan.features (in the form of `one_to_two` or
2527 // `two_to_one`, depending on our direction). Thus, while we're looking at
2528 // feature flags, go ahead and prefetch that memory, reducing the price we
2529 // pay for it later.
2530 prefetch_first_byte(&chan.one_to_two);
2531 prefetch_first_byte(&chan.two_to_one);
2532 if !chan.features.requires_unknown_bits() {
2533 if let Some((directed_channel, source)) = chan.as_directed_to(&$node_id) {
2534 if first_hops.is_none() || *source != our_node_id {
2535 if directed_channel.direction().enabled {
2536 let candidate = CandidateRouteHop::PublicHop(CandidatePublicHop {
2537 info: directed_channel,
2538 short_channel_id: *chan_id,
2540 add_entry!(&candidate,
2542 $next_hops_value_contribution,
2543 next_hops_path_htlc_minimum_msat,
2544 next_hops_path_penalty_msat,
2545 $next_hops_cltv_delta, $next_hops_path_length);
2556 let mut payment_paths = Vec::<PaymentPath>::new();
2558 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
2559 'paths_collection: loop {
2560 // For every new path, start from scratch, except for used_liquidities, which
2561 // helps to avoid reusing previously selected paths in future iterations.
2563 for e in dist.iter_mut() {
2566 for (node_id, (chans, peer_node_counter)) in first_hop_targets.iter() {
2567 // In order to avoid looking up whether each node is a first-hop target, we store a
2568 // dummy entry in dist for each first-hop target, allowing us to do this lookup for
2569 // free since we're already looking at the `was_processed` flag.
2571 // Note that all the fields (except `is_first_hop_target`) will be overwritten whenever
2572 // we find a path to the target, so are left as dummies here.
2573 dist[*peer_node_counter as usize] = Some(PathBuildingHop {
2574 candidate: CandidateRouteHop::FirstHop {
2576 payer_node_id: &our_node_id,
2577 target_node_counter: u32::max_value(),
2578 payer_node_counter: u32::max_value(),
2580 target_node_counter: None,
2582 next_hops_fee_msat: u64::max_value(),
2583 hop_use_fee_msat: u64::max_value(),
2584 total_fee_msat: u64::max_value(),
2585 path_htlc_minimum_msat: u64::max_value(),
2586 path_penalty_msat: u64::max_value(),
2587 was_processed: false,
2588 is_first_hop_target: true,
2589 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
2590 value_contribution_msat: 0,
2593 hit_minimum_limit = false;
2595 // If first hop is a private channel and the only way to reach the payee, this is the only
2596 // place where it could be added.
2597 payee_node_id_opt.map(|payee| first_hop_targets.get(&payee).map(|(first_channels, peer_node_counter)| {
2598 debug_assert_eq!(*peer_node_counter, payee_node_counter);
2599 for details in first_channels {
2600 let candidate = CandidateRouteHop::FirstHop(CandidateFirstHop {
2601 details, payer_node_id: &our_node_id, payer_node_counter,
2602 target_node_counter: payee_node_counter,
2604 let added = add_entry!(&candidate, 0, path_value_msat,
2605 0, 0u64, 0, 0).is_some();
2606 log_trace!(logger, "{} direct route to payee via {}",
2607 if added { "Added" } else { "Skipped" }, LoggedCandidateHop(&candidate));
2611 // Add the payee as a target, so that the payee-to-payer
2612 // search algorithm knows what to start with.
2613 payee_node_id_opt.map(|payee| match network_nodes.get(&payee) {
2614 // The payee is not in our network graph, so nothing to add here.
2615 // There is still a chance of reaching them via last_hops though,
2616 // so don't yet fail the payment here.
2617 // If not, targets.pop() will not even let us enter the loop in step 2.
2620 add_entries_to_cheapest_to_target_node!(node, payee, path_value_msat, 0, 0);
2625 // If a caller provided us with last hops, add them to routing targets. Since this happens
2626 // earlier than general path finding, they will be somewhat prioritized, although currently
2627 // it matters only if the fees are exactly the same.
2628 for (hint_idx, hint) in payment_params.payee.blinded_route_hints().iter().enumerate() {
2629 let intro_node_id = NodeId::from_pubkey(&hint.1.introduction_node_id);
2630 let intro_node_counter_opt =
2631 // Only add the hops in this route to our candidate set if either
2632 // we have a direct channel to the first hop or the first hop is
2633 // in the regular network graph.
2634 network_nodes.get(&intro_node_id).map(|node| node.node_counter)
2636 first_hop_targets.get(&intro_node_id).map(|(_, node_counter)| *node_counter)
2638 if intro_node_counter_opt.is_none() || our_node_id == intro_node_id { continue }
2639 let candidate = if hint.1.blinded_hops.len() == 1 {
2640 CandidateRouteHop::OneHopBlinded(CandidateOneHopBlindedPath {
2643 source_node_counter: intro_node_counter_opt.unwrap(),
2646 CandidateRouteHop::Blinded(CandidateBlindedPath {
2649 source_node_counter: intro_node_counter_opt.unwrap(),
2652 let mut path_contribution_msat = path_value_msat;
2653 if let Some(hop_used_msat) = add_entry!(&candidate,
2654 0, path_contribution_msat, 0, 0_u64, 0, 0)
2656 path_contribution_msat = hop_used_msat;
2658 if let Some((first_channels, peer_node_counter)) = first_hop_targets.get_mut(&NodeId::from_pubkey(&hint.1.introduction_node_id)) {
2659 sort_first_hop_channels(first_channels, &used_liquidities, recommended_value_msat,
2661 for details in first_channels {
2662 let first_hop_candidate = CandidateRouteHop::FirstHop(CandidateFirstHop {
2663 details, payer_node_id: &our_node_id, payer_node_counter,
2664 target_node_counter: *peer_node_counter,
2666 let blinded_path_fee = match compute_fees(path_contribution_msat, candidate.fees()) {
2670 let path_min = candidate.htlc_minimum_msat().saturating_add(
2671 compute_fees_saturating(candidate.htlc_minimum_msat(), candidate.fees()));
2672 add_entry!(&first_hop_candidate, blinded_path_fee,
2673 path_contribution_msat, path_min, 0_u64, candidate.cltv_expiry_delta(),
2674 candidate.blinded_path().map_or(1, |bp| bp.blinded_hops.len() as u8));
2678 for route in payment_params.payee.unblinded_route_hints().iter()
2679 .filter(|route| !route.0.is_empty())
2681 let first_hop_src_id = NodeId::from_pubkey(&route.0.first().unwrap().src_node_id);
2682 let first_hop_src_is_reachable =
2683 // Only add the hops in this route to our candidate set if either we are part of
2684 // the first hop, we have a direct channel to the first hop, or the first hop is in
2685 // the regular network graph.
2686 our_node_id == first_hop_src_id ||
2687 first_hop_targets.get(&first_hop_src_id).is_some() ||
2688 network_nodes.get(&first_hop_src_id).is_some();
2689 if first_hop_src_is_reachable {
2690 // We start building the path from reverse, i.e., from payee
2691 // to the first RouteHintHop in the path.
2692 let hop_iter = route.0.iter().rev();
2693 let prev_hop_iter = core::iter::once(&maybe_dummy_payee_pk).chain(
2694 route.0.iter().skip(1).rev().map(|hop| &hop.src_node_id));
2695 let mut hop_used = true;
2696 let mut aggregate_next_hops_fee_msat: u64 = 0;
2697 let mut aggregate_next_hops_path_htlc_minimum_msat: u64 = 0;
2698 let mut aggregate_next_hops_path_penalty_msat: u64 = 0;
2699 let mut aggregate_next_hops_cltv_delta: u32 = 0;
2700 let mut aggregate_next_hops_path_length: u8 = 0;
2701 let mut aggregate_path_contribution_msat = path_value_msat;
2703 for (idx, (hop, prev_hop_id)) in hop_iter.zip(prev_hop_iter).enumerate() {
2704 let (target, private_target_node_counter) = private_hop_key_cache.get(&prev_hop_id).unwrap();
2705 let (_src_id, private_source_node_counter) = private_hop_key_cache.get(&hop.src_node_id).unwrap();
2707 if let Some((first_channels, _)) = first_hop_targets.get(&target) {
2708 if first_channels.iter().any(|d| d.outbound_scid_alias == Some(hop.short_channel_id)) {
2709 log_trace!(logger, "Ignoring route hint with SCID {} (and any previous) due to it being a direct channel of ours.",
2710 hop.short_channel_id);
2715 let candidate = network_channels
2716 .get(&hop.short_channel_id)
2717 .and_then(|channel| channel.as_directed_to(&target))
2718 .map(|(info, _)| CandidateRouteHop::PublicHop(CandidatePublicHop {
2720 short_channel_id: hop.short_channel_id,
2722 .unwrap_or_else(|| CandidateRouteHop::PrivateHop(CandidatePrivateHop {
2723 hint: hop, target_node_id: target,
2724 source_node_counter: *private_source_node_counter,
2725 target_node_counter: *private_target_node_counter,
2728 if let Some(hop_used_msat) = add_entry!(&candidate,
2729 aggregate_next_hops_fee_msat, aggregate_path_contribution_msat,
2730 aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat,
2731 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length)
2733 aggregate_path_contribution_msat = hop_used_msat;
2735 // If this hop was not used then there is no use checking the preceding
2736 // hops in the RouteHint. We can break by just searching for a direct
2737 // channel between last checked hop and first_hop_targets.
2741 let used_liquidity_msat = used_liquidities
2742 .get(&candidate.id()).copied()
2744 let channel_usage = ChannelUsage {
2745 amount_msat: final_value_msat + aggregate_next_hops_fee_msat,
2746 inflight_htlc_msat: used_liquidity_msat,
2747 effective_capacity: candidate.effective_capacity(),
2749 let channel_penalty_msat = scorer.channel_penalty_msat(
2750 &candidate, channel_usage, score_params
2752 aggregate_next_hops_path_penalty_msat = aggregate_next_hops_path_penalty_msat
2753 .saturating_add(channel_penalty_msat);
2755 aggregate_next_hops_cltv_delta = aggregate_next_hops_cltv_delta
2756 .saturating_add(hop.cltv_expiry_delta as u32);
2758 aggregate_next_hops_path_length = aggregate_next_hops_path_length
2761 // Searching for a direct channel between last checked hop and first_hop_targets
2762 if let Some((first_channels, peer_node_counter)) = first_hop_targets.get_mut(&target) {
2763 sort_first_hop_channels(first_channels, &used_liquidities,
2764 recommended_value_msat, our_node_pubkey);
2765 for details in first_channels {
2766 let first_hop_candidate = CandidateRouteHop::FirstHop(CandidateFirstHop {
2767 details, payer_node_id: &our_node_id, payer_node_counter,
2768 target_node_counter: *peer_node_counter,
2770 add_entry!(&first_hop_candidate,
2771 aggregate_next_hops_fee_msat, aggregate_path_contribution_msat,
2772 aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat,
2773 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length);
2781 // In the next values of the iterator, the aggregate fees already reflects
2782 // the sum of value sent from payer (final_value_msat) and routing fees
2783 // for the last node in the RouteHint. We need to just add the fees to
2784 // route through the current node so that the preceding node (next iteration)
2786 let hops_fee = compute_fees(aggregate_next_hops_fee_msat + final_value_msat, hop.fees)
2787 .map_or(None, |inc| inc.checked_add(aggregate_next_hops_fee_msat));
2788 aggregate_next_hops_fee_msat = if let Some(val) = hops_fee { val } else { break; };
2790 // The next channel will need to relay this channel's min_htlc *plus* the fees taken by
2791 // this route hint's source node to forward said min over this channel.
2792 aggregate_next_hops_path_htlc_minimum_msat = {
2793 let curr_htlc_min = cmp::max(
2794 candidate.htlc_minimum_msat(), aggregate_next_hops_path_htlc_minimum_msat
2796 let curr_htlc_min_fee = if let Some(val) = compute_fees(curr_htlc_min, hop.fees) { val } else { break };
2797 if let Some(min) = curr_htlc_min.checked_add(curr_htlc_min_fee) { min } else { break }
2800 if idx == route.0.len() - 1 {
2801 // The last hop in this iterator is the first hop in
2802 // overall RouteHint.
2803 // If this hop connects to a node with which we have a direct channel,
2804 // ignore the network graph and, if the last hop was added, add our
2805 // direct channel to the candidate set.
2807 // Note that we *must* check if the last hop was added as `add_entry`
2808 // always assumes that the third argument is a node to which we have a
2810 if let Some((first_channels, peer_node_counter)) = first_hop_targets.get_mut(&NodeId::from_pubkey(&hop.src_node_id)) {
2811 sort_first_hop_channels(first_channels, &used_liquidities,
2812 recommended_value_msat, our_node_pubkey);
2813 for details in first_channels {
2814 let first_hop_candidate = CandidateRouteHop::FirstHop(CandidateFirstHop {
2815 details, payer_node_id: &our_node_id, payer_node_counter,
2816 target_node_counter: *peer_node_counter,
2818 add_entry!(&first_hop_candidate,
2819 aggregate_next_hops_fee_msat,
2820 aggregate_path_contribution_msat,
2821 aggregate_next_hops_path_htlc_minimum_msat,
2822 aggregate_next_hops_path_penalty_msat,
2823 aggregate_next_hops_cltv_delta,
2824 aggregate_next_hops_path_length);
2832 log_trace!(logger, "Starting main path collection loop with {} nodes pre-filled from first/last hops.", targets.len());
2834 // At this point, targets are filled with the data from first and
2835 // last hops communicated by the caller, and the payment receiver.
2836 let mut found_new_path = false;
2839 // If this loop terminates due the exhaustion of targets, two situations are possible:
2840 // - not enough outgoing liquidity:
2841 // 0 < already_collected_value_msat < final_value_msat
2842 // - enough outgoing liquidity:
2843 // final_value_msat <= already_collected_value_msat < recommended_value_msat
2844 // Both these cases (and other cases except reaching recommended_value_msat) mean that
2845 // paths_collection will be stopped because found_new_path==false.
2846 // This is not necessarily a routing failure.
2847 'path_construction: while let Some(RouteGraphNode { node_id, total_cltv_delta, mut value_contribution_msat, path_length_to_node, .. }) = targets.pop() {
2849 // Since we're going payee-to-payer, hitting our node as a target means we should stop
2850 // traversing the graph and arrange the path out of what we found.
2851 if node_id == our_node_id {
2852 let mut new_entry = dist[payer_node_counter as usize].take().unwrap();
2853 let mut ordered_hops: Vec<(PathBuildingHop, NodeFeatures)> = vec!((new_entry.clone(), default_node_features.clone()));
2856 let mut features_set = false;
2857 let candidate = &ordered_hops.last().unwrap().0.candidate;
2858 let target = candidate.target().unwrap_or(maybe_dummy_payee_node_id);
2859 let target_node_counter = candidate.target_node_counter();
2860 if let Some((first_channels, _)) = first_hop_targets.get(&target) {
2861 for details in first_channels {
2862 if let CandidateRouteHop::FirstHop(CandidateFirstHop { details: last_hop_details, .. })
2863 = ordered_hops.last().unwrap().0.candidate
2865 if details.get_outbound_payment_scid() == last_hop_details.get_outbound_payment_scid() {
2866 ordered_hops.last_mut().unwrap().1 = details.counterparty.features.to_context();
2867 features_set = true;
2874 if let Some(node) = network_nodes.get(&target) {
2875 if let Some(node_info) = node.announcement_info.as_ref() {
2876 ordered_hops.last_mut().unwrap().1 = node_info.features.clone();
2878 ordered_hops.last_mut().unwrap().1 = default_node_features.clone();
2881 // We can fill in features for everything except hops which were
2882 // provided via the invoice we're paying. We could guess based on the
2883 // recipient's features but for now we simply avoid guessing at all.
2887 // Means we succesfully traversed from the payer to the payee, now
2888 // save this path for the payment route. Also, update the liquidity
2889 // remaining on the used hops, so that we take them into account
2890 // while looking for more paths.
2891 if target_node_counter.is_none() {
2894 if target_node_counter == Some(payee_node_counter) { break 'path_walk; }
2896 new_entry = match dist[target_node_counter.unwrap() as usize].take() {
2897 Some(payment_hop) => payment_hop,
2898 // We can't arrive at None because, if we ever add an entry to targets,
2899 // we also fill in the entry in dist (see add_entry!).
2900 None => unreachable!(),
2902 // We "propagate" the fees one hop backward (topologically) here,
2903 // so that fees paid for a HTLC forwarding on the current channel are
2904 // associated with the previous channel (where they will be subtracted).
2905 ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
2906 ordered_hops.push((new_entry.clone(), default_node_features.clone()));
2908 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
2909 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
2911 log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: \n {:#?}",
2912 ordered_hops.len(), value_contribution_msat, ordered_hops.iter().map(|h| &(h.0)).collect::<Vec<&PathBuildingHop>>());
2914 let mut payment_path = PaymentPath {hops: ordered_hops};
2916 // We could have possibly constructed a slightly inconsistent path: since we reduce
2917 // value being transferred along the way, we could have violated htlc_minimum_msat
2918 // on some channels we already passed (assuming dest->source direction). Here, we
2919 // recompute the fees again, so that if that's the case, we match the currently
2920 // underpaid htlc_minimum_msat with fees.
2921 debug_assert_eq!(payment_path.get_value_msat(), value_contribution_msat);
2922 let desired_value_contribution = cmp::min(value_contribution_msat, final_value_msat);
2923 value_contribution_msat = payment_path.update_value_and_recompute_fees(desired_value_contribution);
2925 // Since a path allows to transfer as much value as
2926 // the smallest channel it has ("bottleneck"), we should recompute
2927 // the fees so sender HTLC don't overpay fees when traversing
2928 // larger channels than the bottleneck. This may happen because
2929 // when we were selecting those channels we were not aware how much value
2930 // this path will transfer, and the relative fee for them
2931 // might have been computed considering a larger value.
2932 // Remember that we used these channels so that we don't rely
2933 // on the same liquidity in future paths.
2934 let mut prevented_redundant_path_selection = false;
2935 for (hop, _) in payment_path.hops.iter() {
2936 let spent_on_hop_msat = value_contribution_msat + hop.next_hops_fee_msat;
2937 let used_liquidity_msat = used_liquidities
2938 .entry(hop.candidate.id())
2939 .and_modify(|used_liquidity_msat| *used_liquidity_msat += spent_on_hop_msat)
2940 .or_insert(spent_on_hop_msat);
2941 let hop_capacity = hop.candidate.effective_capacity();
2942 let hop_max_msat = max_htlc_from_capacity(hop_capacity, channel_saturation_pow_half);
2943 if *used_liquidity_msat == hop_max_msat {
2944 // If this path used all of this channel's available liquidity, we know
2945 // this path will not be selected again in the next loop iteration.
2946 prevented_redundant_path_selection = true;
2948 debug_assert!(*used_liquidity_msat <= hop_max_msat);
2950 if !prevented_redundant_path_selection {
2951 // If we weren't capped by hitting a liquidity limit on a channel in the path,
2952 // we'll probably end up picking the same path again on the next iteration.
2953 // Decrease the available liquidity of a hop in the middle of the path.
2954 let victim_candidate = &payment_path.hops[(payment_path.hops.len()) / 2].0.candidate;
2955 let exhausted = u64::max_value();
2957 "Disabling route candidate {} for future path building iterations to avoid duplicates.",
2958 LoggedCandidateHop(victim_candidate));
2959 if let Some(scid) = victim_candidate.short_channel_id() {
2960 *used_liquidities.entry(CandidateHopId::Clear((scid, false))).or_default() = exhausted;
2961 *used_liquidities.entry(CandidateHopId::Clear((scid, true))).or_default() = exhausted;
2965 // Track the total amount all our collected paths allow to send so that we know
2966 // when to stop looking for more paths
2967 already_collected_value_msat += value_contribution_msat;
2969 payment_paths.push(payment_path);
2970 found_new_path = true;
2971 break 'path_construction;
2974 // If we found a path back to the payee, we shouldn't try to process it again. This is
2975 // the equivalent of the `elem.was_processed` check in
2976 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
2977 if node_id == maybe_dummy_payee_node_id { continue 'path_construction; }
2979 // Otherwise, since the current target node is not us,
2980 // keep "unrolling" the payment graph from payee to payer by
2981 // finding a way to reach the current target from the payer side.
2982 match network_nodes.get(&node_id) {
2985 add_entries_to_cheapest_to_target_node!(node, node_id,
2986 value_contribution_msat,
2987 total_cltv_delta, path_length_to_node);
2993 if !found_new_path && channel_saturation_pow_half != 0 {
2994 channel_saturation_pow_half = 0;
2995 continue 'paths_collection;
2997 // If we don't support MPP, no use trying to gather more value ever.
2998 break 'paths_collection;
3002 // Stop either when the recommended value is reached or if no new path was found in this
3004 // In the latter case, making another path finding attempt won't help,
3005 // because we deterministically terminated the search due to low liquidity.
3006 if !found_new_path && channel_saturation_pow_half != 0 {
3007 channel_saturation_pow_half = 0;
3008 } else if !found_new_path && hit_minimum_limit && already_collected_value_msat < final_value_msat && path_value_msat != recommended_value_msat {
3009 log_trace!(logger, "Failed to collect enough value, but running again to collect extra paths with a potentially higher limit.");
3010 path_value_msat = recommended_value_msat;
3011 } else if already_collected_value_msat >= recommended_value_msat || !found_new_path {
3012 log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
3013 already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
3014 break 'paths_collection;
3015 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
3016 // Further, if this was our first walk of the graph, and we weren't limited by an
3017 // htlc_minimum_msat, return immediately because this path should suffice. If we were
3018 // limited by an htlc_minimum_msat value, find another path with a higher value,
3019 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
3020 // still keeping a lower total fee than this path.
3021 if !hit_minimum_limit {
3022 log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
3023 break 'paths_collection;
3025 log_trace!(logger, "Collected our payment amount on the first pass, but running again to collect extra paths with a potentially higher value to meet htlc_minimum_msat limit.");
3026 path_value_msat = recommended_value_msat;
3030 let num_ignored_total = num_ignored_value_contribution + num_ignored_path_length_limit +
3031 num_ignored_cltv_delta_limit + num_ignored_previously_failed +
3032 num_ignored_avoid_overpayment + num_ignored_htlc_minimum_msat_limit +
3033 num_ignored_total_fee_limit;
3034 if num_ignored_total > 0 {
3036 "Ignored {} candidate hops due to insufficient value contribution, {} due to path length limit, {} due to CLTV delta limit, {} due to previous payment failure, {} due to htlc_minimum_msat limit, {} to avoid overpaying, {} due to maximum total fee limit. Total: {} ignored candidates.",
3037 num_ignored_value_contribution, num_ignored_path_length_limit,
3038 num_ignored_cltv_delta_limit, num_ignored_previously_failed,
3039 num_ignored_htlc_minimum_msat_limit, num_ignored_avoid_overpayment,
3040 num_ignored_total_fee_limit, num_ignored_total);
3044 if payment_paths.len() == 0 {
3045 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
3048 if already_collected_value_msat < final_value_msat {
3049 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
3053 let mut selected_route = payment_paths;
3055 debug_assert_eq!(selected_route.iter().map(|p| p.get_value_msat()).sum::<u64>(), already_collected_value_msat);
3056 let mut overpaid_value_msat = already_collected_value_msat - final_value_msat;
3058 // First, sort by the cost-per-value of the path, dropping the paths that cost the most for
3059 // the value they contribute towards the payment amount.
3060 // We sort in descending order as we will remove from the front in `retain`, next.
3061 selected_route.sort_unstable_by(|a, b|
3062 (((b.get_cost_msat() as u128) << 64) / (b.get_value_msat() as u128))
3063 .cmp(&(((a.get_cost_msat() as u128) << 64) / (a.get_value_msat() as u128)))
3066 // We should make sure that at least 1 path left.
3067 let mut paths_left = selected_route.len();
3068 selected_route.retain(|path| {
3069 if paths_left == 1 {
3072 let path_value_msat = path.get_value_msat();
3073 if path_value_msat <= overpaid_value_msat {
3074 overpaid_value_msat -= path_value_msat;
3080 debug_assert!(selected_route.len() > 0);
3082 if overpaid_value_msat != 0 {
3084 // Now, subtract the remaining overpaid value from the most-expensive path.
3085 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
3086 // so that the sender pays less fees overall. And also htlc_minimum_msat.
3087 selected_route.sort_unstable_by(|a, b| {
3088 let a_f = a.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
3089 let b_f = b.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
3090 a_f.cmp(&b_f).then_with(|| b.get_cost_msat().cmp(&a.get_cost_msat()))
3092 let expensive_payment_path = selected_route.first_mut().unwrap();
3094 // We already dropped all the paths with value below `overpaid_value_msat` above, thus this
3095 // can't go negative.
3096 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
3097 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
3101 // Sort by the path itself and combine redundant paths.
3102 // Note that we sort by SCIDs alone as its simpler but when combining we have to ensure we
3103 // compare both SCIDs and NodeIds as individual nodes may use random aliases causing collisions
3105 selected_route.sort_unstable_by_key(|path| {
3106 let mut key = [CandidateHopId::Clear((42, true)) ; MAX_PATH_LENGTH_ESTIMATE as usize];
3107 debug_assert!(path.hops.len() <= key.len());
3108 for (scid, key) in path.hops.iter() .map(|h| h.0.candidate.id()).zip(key.iter_mut()) {
3113 for idx in 0..(selected_route.len() - 1) {
3114 if idx + 1 >= selected_route.len() { break; }
3115 if iter_equal(selected_route[idx ].hops.iter().map(|h| (h.0.candidate.id(), h.0.candidate.target())),
3116 selected_route[idx + 1].hops.iter().map(|h| (h.0.candidate.id(), h.0.candidate.target()))) {
3117 let new_value = selected_route[idx].get_value_msat() + selected_route[idx + 1].get_value_msat();
3118 selected_route[idx].update_value_and_recompute_fees(new_value);
3119 selected_route.remove(idx + 1);
3123 let mut paths = Vec::new();
3124 for payment_path in selected_route {
3125 let mut hops = Vec::with_capacity(payment_path.hops.len());
3126 for (hop, node_features) in payment_path.hops.iter()
3127 .filter(|(h, _)| h.candidate.short_channel_id().is_some())
3129 let target = hop.candidate.target().expect("target is defined when short_channel_id is defined");
3130 let maybe_announced_channel = if let CandidateRouteHop::PublicHop(_) = hop.candidate {
3131 // If we sourced the hop from the graph we're sure the target node is announced.
3133 } else if let CandidateRouteHop::FirstHop(first_hop) = &hop.candidate {
3134 // If this is a first hop we also know if it's announced.
3135 first_hop.details.is_public
3137 // If we sourced it any other way, we double-check the network graph to see if
3138 // there are announced channels between the endpoints. If so, the hop might be
3139 // referring to any of the announced channels, as its `short_channel_id` might be
3140 // an alias, in which case we don't take any chances here.
3141 network_graph.node(&target).map_or(false, |hop_node|
3142 hop_node.channels.iter().any(|scid| network_graph.channel(*scid)
3143 .map_or(false, |c| c.as_directed_from(&hop.candidate.source()).is_some()))
3147 hops.push(RouteHop {
3148 pubkey: PublicKey::from_slice(target.as_slice()).map_err(|_| LightningError{err: format!("Public key {:?} is invalid", &target), action: ErrorAction::IgnoreAndLog(Level::Trace)})?,
3149 node_features: node_features.clone(),
3150 short_channel_id: hop.candidate.short_channel_id().unwrap(),
3151 channel_features: hop.candidate.features(),
3152 fee_msat: hop.fee_msat,
3153 cltv_expiry_delta: hop.candidate.cltv_expiry_delta(),
3154 maybe_announced_channel,
3157 let mut final_cltv_delta = final_cltv_expiry_delta;
3158 let blinded_tail = payment_path.hops.last().and_then(|(h, _)| {
3159 if let Some(blinded_path) = h.candidate.blinded_path() {
3160 final_cltv_delta = h.candidate.cltv_expiry_delta();
3162 hops: blinded_path.blinded_hops.clone(),
3163 blinding_point: blinded_path.blinding_point,
3164 excess_final_cltv_expiry_delta: 0,
3165 final_value_msat: h.fee_msat,
3169 // Propagate the cltv_expiry_delta one hop backwards since the delta from the current hop is
3170 // applicable for the previous hop.
3171 hops.iter_mut().rev().fold(final_cltv_delta, |prev_cltv_expiry_delta, hop| {
3172 core::mem::replace(&mut hop.cltv_expiry_delta, prev_cltv_expiry_delta)
3175 paths.push(Path { hops, blinded_tail });
3177 // Make sure we would never create a route with more paths than we allow.
3178 debug_assert!(paths.len() <= payment_params.max_path_count.into());
3180 if let Some(node_features) = payment_params.payee.node_features() {
3181 for path in paths.iter_mut() {
3182 path.hops.last_mut().unwrap().node_features = node_features.clone();
3186 let route = Route { paths, route_params: Some(route_params.clone()) };
3188 // Make sure we would never create a route whose total fees exceed max_total_routing_fee_msat.
3189 if let Some(max_total_routing_fee_msat) = route_params.max_total_routing_fee_msat {
3190 if route.get_total_fees() > max_total_routing_fee_msat {
3191 return Err(LightningError{err: format!("Failed to find route that adheres to the maximum total fee limit of {}msat",
3192 max_total_routing_fee_msat), action: ErrorAction::IgnoreError});
3196 log_info!(logger, "Got route: {}", log_route!(route));
3200 // When an adversarial intermediary node observes a payment, it may be able to infer its
3201 // destination, if the remaining CLTV expiry delta exactly matches a feasible path in the network
3202 // graph. In order to improve privacy, this method obfuscates the CLTV expiry deltas along the
3203 // payment path by adding a randomized 'shadow route' offset to the final hop.
3204 fn add_random_cltv_offset(route: &mut Route, payment_params: &PaymentParameters,
3205 network_graph: &ReadOnlyNetworkGraph, random_seed_bytes: &[u8; 32]
3207 let network_channels = network_graph.channels();
3208 let network_nodes = network_graph.nodes();
3210 for path in route.paths.iter_mut() {
3211 let mut shadow_ctlv_expiry_delta_offset: u32 = 0;
3213 // Remember the last three nodes of the random walk and avoid looping back on them.
3214 // Init with the last three nodes from the actual path, if possible.
3215 let mut nodes_to_avoid: [NodeId; 3] = [NodeId::from_pubkey(&path.hops.last().unwrap().pubkey),
3216 NodeId::from_pubkey(&path.hops.get(path.hops.len().saturating_sub(2)).unwrap().pubkey),
3217 NodeId::from_pubkey(&path.hops.get(path.hops.len().saturating_sub(3)).unwrap().pubkey)];
3219 // Choose the last publicly known node as the starting point for the random walk.
3220 let mut cur_hop: Option<NodeId> = None;
3221 let mut path_nonce = [0u8; 12];
3222 if let Some(starting_hop) = path.hops.iter().rev()
3223 .find(|h| network_nodes.contains_key(&NodeId::from_pubkey(&h.pubkey))) {
3224 cur_hop = Some(NodeId::from_pubkey(&starting_hop.pubkey));
3225 path_nonce.copy_from_slice(&cur_hop.unwrap().as_slice()[..12]);
3228 // Init PRNG with the path-dependant nonce, which is static for private paths.
3229 let mut prng = ChaCha20::new(random_seed_bytes, &path_nonce);
3230 let mut random_path_bytes = [0u8; ::core::mem::size_of::<usize>()];
3232 // Pick a random path length in [1 .. 3]
3233 prng.process_in_place(&mut random_path_bytes);
3234 let random_walk_length = usize::from_be_bytes(random_path_bytes).wrapping_rem(3).wrapping_add(1);
3236 for random_hop in 0..random_walk_length {
3237 // If we don't find a suitable offset in the public network graph, we default to
3238 // MEDIAN_HOP_CLTV_EXPIRY_DELTA.
3239 let mut random_hop_offset = MEDIAN_HOP_CLTV_EXPIRY_DELTA;
3241 if let Some(cur_node_id) = cur_hop {
3242 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
3243 // Randomly choose the next unvisited hop.
3244 prng.process_in_place(&mut random_path_bytes);
3245 if let Some(random_channel) = usize::from_be_bytes(random_path_bytes)
3246 .checked_rem(cur_node.channels.len())
3247 .and_then(|index| cur_node.channels.get(index))
3248 .and_then(|id| network_channels.get(id)) {
3249 random_channel.as_directed_from(&cur_node_id).map(|(dir_info, next_id)| {
3250 if !nodes_to_avoid.iter().any(|x| x == next_id) {
3251 nodes_to_avoid[random_hop] = *next_id;
3252 random_hop_offset = dir_info.direction().cltv_expiry_delta.into();
3253 cur_hop = Some(*next_id);
3260 shadow_ctlv_expiry_delta_offset = shadow_ctlv_expiry_delta_offset
3261 .checked_add(random_hop_offset)
3262 .unwrap_or(shadow_ctlv_expiry_delta_offset);
3265 // Limit the total offset to reduce the worst-case locked liquidity timevalue
3266 const MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET: u32 = 3*144;
3267 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET);
3269 // Limit the offset so we never exceed the max_total_cltv_expiry_delta. To improve plausibility,
3270 // we choose the limit to be the largest possible multiple of MEDIAN_HOP_CLTV_EXPIRY_DELTA.
3271 let path_total_cltv_expiry_delta: u32 = path.hops.iter().map(|h| h.cltv_expiry_delta).sum();
3272 let mut max_path_offset = payment_params.max_total_cltv_expiry_delta - path_total_cltv_expiry_delta;
3273 max_path_offset = cmp::max(
3274 max_path_offset - (max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA),
3275 max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA);
3276 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, max_path_offset);
3278 // Add 'shadow' CLTV offset to the final hop
3279 if let Some(tail) = path.blinded_tail.as_mut() {
3280 tail.excess_final_cltv_expiry_delta = tail.excess_final_cltv_expiry_delta
3281 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(tail.excess_final_cltv_expiry_delta);
3283 if let Some(last_hop) = path.hops.last_mut() {
3284 last_hop.cltv_expiry_delta = last_hop.cltv_expiry_delta
3285 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(last_hop.cltv_expiry_delta);
3290 /// Construct a route from us (payer) to the target node (payee) via the given hops (which should
3291 /// exclude the payer, but include the payee). This may be useful, e.g., for probing the chosen path.
3293 /// Re-uses logic from `find_route`, so the restrictions described there also apply here.
3294 pub fn build_route_from_hops<L: Deref, GL: Deref>(
3295 our_node_pubkey: &PublicKey, hops: &[PublicKey], route_params: &RouteParameters,
3296 network_graph: &NetworkGraph<GL>, logger: L, random_seed_bytes: &[u8; 32]
3297 ) -> Result<Route, LightningError>
3298 where L::Target: Logger, GL::Target: Logger {
3299 let graph_lock = network_graph.read_only();
3300 let mut route = build_route_from_hops_internal(our_node_pubkey, hops, &route_params,
3301 &graph_lock, logger, random_seed_bytes)?;
3302 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
3306 fn build_route_from_hops_internal<L: Deref>(
3307 our_node_pubkey: &PublicKey, hops: &[PublicKey], route_params: &RouteParameters,
3308 network_graph: &ReadOnlyNetworkGraph, logger: L, random_seed_bytes: &[u8; 32],
3309 ) -> Result<Route, LightningError> where L::Target: Logger {
3312 our_node_id: NodeId,
3313 hop_ids: [Option<NodeId>; MAX_PATH_LENGTH_ESTIMATE as usize],
3316 impl ScoreLookUp for HopScorer {
3317 type ScoreParams = ();
3318 fn channel_penalty_msat(&self, candidate: &CandidateRouteHop,
3319 _usage: ChannelUsage, _score_params: &Self::ScoreParams) -> u64
3321 let mut cur_id = self.our_node_id;
3322 for i in 0..self.hop_ids.len() {
3323 if let Some(next_id) = self.hop_ids[i] {
3324 if cur_id == candidate.source() && Some(next_id) == candidate.target() {
3336 impl<'a> Writeable for HopScorer {
3338 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), io::Error> {
3343 if hops.len() > MAX_PATH_LENGTH_ESTIMATE.into() {
3344 return Err(LightningError{err: "Cannot build a route exceeding the maximum path length.".to_owned(), action: ErrorAction::IgnoreError});
3347 let our_node_id = NodeId::from_pubkey(our_node_pubkey);
3348 let mut hop_ids = [None; MAX_PATH_LENGTH_ESTIMATE as usize];
3349 for i in 0..hops.len() {
3350 hop_ids[i] = Some(NodeId::from_pubkey(&hops[i]));
3353 let scorer = HopScorer { our_node_id, hop_ids };
3355 get_route(our_node_pubkey, route_params, network_graph, None, logger, &scorer, &Default::default(), random_seed_bytes)
3360 use crate::blinded_path::{BlindedHop, BlindedPath};
3361 use crate::routing::gossip::{NetworkGraph, P2PGossipSync, NodeId, EffectiveCapacity};
3362 use crate::routing::utxo::UtxoResult;
3363 use crate::routing::router::{get_route, build_route_from_hops_internal, add_random_cltv_offset, default_node_features,
3364 BlindedTail, InFlightHtlcs, Path, PaymentParameters, Route, RouteHint, RouteHintHop, RouteHop, RoutingFees,
3365 DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA, MAX_PATH_LENGTH_ESTIMATE, RouteParameters, CandidateRouteHop, CandidatePublicHop};
3366 use crate::routing::scoring::{ChannelUsage, FixedPenaltyScorer, ScoreLookUp, ProbabilisticScorer, ProbabilisticScoringFeeParameters, ProbabilisticScoringDecayParameters};
3367 use crate::routing::test_utils::{add_channel, add_or_update_node, build_graph, build_line_graph, id_to_feature_flags, get_nodes, update_channel};
3368 use crate::chain::transaction::OutPoint;
3369 use crate::sign::EntropySource;
3370 use crate::ln::ChannelId;
3371 use crate::ln::features::{BlindedHopFeatures, ChannelFeatures, InitFeatures, NodeFeatures};
3372 use crate::ln::msgs::{ErrorAction, LightningError, UnsignedChannelUpdate, MAX_VALUE_MSAT};
3373 use crate::ln::channelmanager;
3374 use crate::offers::invoice::BlindedPayInfo;
3375 use crate::util::config::UserConfig;
3376 use crate::util::test_utils as ln_test_utils;
3377 use crate::util::chacha20::ChaCha20;
3378 use crate::util::ser::{Readable, Writeable};
3380 use crate::util::ser::Writer;
3382 use bitcoin::hashes::Hash;
3383 use bitcoin::network::constants::Network;
3384 use bitcoin::blockdata::constants::ChainHash;
3385 use bitcoin::blockdata::script::Builder;
3386 use bitcoin::blockdata::opcodes;
3387 use bitcoin::blockdata::transaction::TxOut;
3388 use bitcoin::hashes::hex::FromHex;
3389 use bitcoin::secp256k1::{PublicKey,SecretKey};
3390 use bitcoin::secp256k1::Secp256k1;
3392 use crate::io::Cursor;
3393 use crate::prelude::*;
3394 use crate::sync::Arc;
3396 use core::convert::TryInto;
3398 fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
3399 features: InitFeatures, outbound_capacity_msat: u64) -> channelmanager::ChannelDetails {
3400 channelmanager::ChannelDetails {
3401 channel_id: ChannelId::new_zero(),
3402 counterparty: channelmanager::ChannelCounterparty {
3405 unspendable_punishment_reserve: 0,
3406 forwarding_info: None,
3407 outbound_htlc_minimum_msat: None,
3408 outbound_htlc_maximum_msat: None,
3410 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
3413 outbound_scid_alias: None,
3414 inbound_scid_alias: None,
3415 channel_value_satoshis: 0,
3418 outbound_capacity_msat,
3419 next_outbound_htlc_limit_msat: outbound_capacity_msat,
3420 next_outbound_htlc_minimum_msat: 0,
3421 inbound_capacity_msat: 42,
3422 unspendable_punishment_reserve: None,
3423 confirmations_required: None,
3424 confirmations: None,
3425 force_close_spend_delay: None,
3426 is_outbound: true, is_channel_ready: true,
3427 is_usable: true, is_public: true,
3428 inbound_htlc_minimum_msat: None,
3429 inbound_htlc_maximum_msat: None,
3431 feerate_sat_per_1000_weight: None,
3432 channel_shutdown_state: Some(channelmanager::ChannelShutdownState::NotShuttingDown),
3437 fn simple_route_test() {
3438 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3439 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3440 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3441 let scorer = ln_test_utils::TestScorer::new();
3442 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3443 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3445 // Simple route to 2 via 1
3447 let route_params = RouteParameters::from_payment_params_and_value(
3448 payment_params.clone(), 0);
3449 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3450 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3451 &Default::default(), &random_seed_bytes) {
3452 assert_eq!(err, "Cannot send a payment of 0 msat");
3453 } else { panic!(); }
3455 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3456 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3457 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3458 assert_eq!(route.paths[0].hops.len(), 2);
3460 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3461 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3462 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3463 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3464 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3465 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3467 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3468 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3469 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3470 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3471 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3472 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3476 fn invalid_first_hop_test() {
3477 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3478 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3479 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3480 let scorer = ln_test_utils::TestScorer::new();
3481 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3482 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3484 // Simple route to 2 via 1
3486 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
3488 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3489 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3490 &route_params, &network_graph.read_only(), Some(&our_chans.iter().collect::<Vec<_>>()),
3491 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
3492 assert_eq!(err, "First hop cannot have our_node_pubkey as a destination.");
3493 } else { panic!(); }
3495 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3496 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3497 assert_eq!(route.paths[0].hops.len(), 2);
3501 fn htlc_minimum_test() {
3502 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3503 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3504 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3505 let scorer = ln_test_utils::TestScorer::new();
3506 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3507 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3509 // Simple route to 2 via 1
3511 // Disable other paths
3512 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3513 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3514 short_channel_id: 12,
3516 flags: 2, // to disable
3517 cltv_expiry_delta: 0,
3518 htlc_minimum_msat: 0,
3519 htlc_maximum_msat: MAX_VALUE_MSAT,
3521 fee_proportional_millionths: 0,
3522 excess_data: Vec::new()
3524 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3525 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3526 short_channel_id: 3,
3528 flags: 2, // to disable
3529 cltv_expiry_delta: 0,
3530 htlc_minimum_msat: 0,
3531 htlc_maximum_msat: MAX_VALUE_MSAT,
3533 fee_proportional_millionths: 0,
3534 excess_data: Vec::new()
3536 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3537 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3538 short_channel_id: 13,
3540 flags: 2, // to disable
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()
3548 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3549 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3550 short_channel_id: 6,
3552 flags: 2, // to disable
3553 cltv_expiry_delta: 0,
3554 htlc_minimum_msat: 0,
3555 htlc_maximum_msat: MAX_VALUE_MSAT,
3557 fee_proportional_millionths: 0,
3558 excess_data: Vec::new()
3560 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3561 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3562 short_channel_id: 7,
3564 flags: 2, // to disable
3565 cltv_expiry_delta: 0,
3566 htlc_minimum_msat: 0,
3567 htlc_maximum_msat: MAX_VALUE_MSAT,
3569 fee_proportional_millionths: 0,
3570 excess_data: Vec::new()
3573 // Check against amount_to_transfer_over_msat.
3574 // Set minimal HTLC of 200_000_000 msat.
3575 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3576 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3577 short_channel_id: 2,
3580 cltv_expiry_delta: 0,
3581 htlc_minimum_msat: 200_000_000,
3582 htlc_maximum_msat: MAX_VALUE_MSAT,
3584 fee_proportional_millionths: 0,
3585 excess_data: Vec::new()
3588 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
3590 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3591 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3592 short_channel_id: 4,
3595 cltv_expiry_delta: 0,
3596 htlc_minimum_msat: 0,
3597 htlc_maximum_msat: 199_999_999,
3599 fee_proportional_millionths: 0,
3600 excess_data: Vec::new()
3603 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
3604 let route_params = RouteParameters::from_payment_params_and_value(
3605 payment_params, 199_999_999);
3606 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3607 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3608 &Default::default(), &random_seed_bytes) {
3609 assert_eq!(err, "Failed to find a path to the given destination");
3610 } else { panic!(); }
3612 // Lift the restriction on the first hop.
3613 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3614 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3615 short_channel_id: 2,
3618 cltv_expiry_delta: 0,
3619 htlc_minimum_msat: 0,
3620 htlc_maximum_msat: MAX_VALUE_MSAT,
3622 fee_proportional_millionths: 0,
3623 excess_data: Vec::new()
3626 // A payment above the minimum should pass
3627 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3628 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3629 assert_eq!(route.paths[0].hops.len(), 2);
3633 fn htlc_minimum_overpay_test() {
3634 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3635 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3636 let config = UserConfig::default();
3637 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
3638 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
3640 let scorer = ln_test_utils::TestScorer::new();
3641 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3642 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3644 // A route to node#2 via two paths.
3645 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
3646 // Thus, they can't send 60 without overpaying.
3647 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3648 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3649 short_channel_id: 2,
3652 cltv_expiry_delta: 0,
3653 htlc_minimum_msat: 35_000,
3654 htlc_maximum_msat: 40_000,
3656 fee_proportional_millionths: 0,
3657 excess_data: Vec::new()
3659 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3660 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3661 short_channel_id: 12,
3664 cltv_expiry_delta: 0,
3665 htlc_minimum_msat: 35_000,
3666 htlc_maximum_msat: 40_000,
3668 fee_proportional_millionths: 0,
3669 excess_data: Vec::new()
3673 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3674 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3675 short_channel_id: 13,
3678 cltv_expiry_delta: 0,
3679 htlc_minimum_msat: 0,
3680 htlc_maximum_msat: MAX_VALUE_MSAT,
3682 fee_proportional_millionths: 0,
3683 excess_data: Vec::new()
3685 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3686 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3687 short_channel_id: 4,
3690 cltv_expiry_delta: 0,
3691 htlc_minimum_msat: 0,
3692 htlc_maximum_msat: MAX_VALUE_MSAT,
3694 fee_proportional_millionths: 0,
3695 excess_data: Vec::new()
3698 // Disable other paths
3699 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3700 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3701 short_channel_id: 1,
3703 flags: 2, // to disable
3704 cltv_expiry_delta: 0,
3705 htlc_minimum_msat: 0,
3706 htlc_maximum_msat: MAX_VALUE_MSAT,
3708 fee_proportional_millionths: 0,
3709 excess_data: Vec::new()
3712 let mut route_params = RouteParameters::from_payment_params_and_value(
3713 payment_params.clone(), 60_000);
3714 route_params.max_total_routing_fee_msat = Some(15_000);
3715 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3716 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3717 // Overpay fees to hit htlc_minimum_msat.
3718 let overpaid_fees = route.paths[0].hops[0].fee_msat + route.paths[1].hops[0].fee_msat;
3719 // TODO: this could be better balanced to overpay 10k and not 15k.
3720 assert_eq!(overpaid_fees, 15_000);
3722 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
3723 // while taking even more fee to match htlc_minimum_msat.
3724 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3725 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3726 short_channel_id: 12,
3729 cltv_expiry_delta: 0,
3730 htlc_minimum_msat: 65_000,
3731 htlc_maximum_msat: 80_000,
3733 fee_proportional_millionths: 0,
3734 excess_data: Vec::new()
3736 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3737 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3738 short_channel_id: 2,
3741 cltv_expiry_delta: 0,
3742 htlc_minimum_msat: 0,
3743 htlc_maximum_msat: MAX_VALUE_MSAT,
3745 fee_proportional_millionths: 0,
3746 excess_data: Vec::new()
3748 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3749 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3750 short_channel_id: 4,
3753 cltv_expiry_delta: 0,
3754 htlc_minimum_msat: 0,
3755 htlc_maximum_msat: MAX_VALUE_MSAT,
3757 fee_proportional_millionths: 100_000,
3758 excess_data: Vec::new()
3761 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3762 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3763 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
3764 assert_eq!(route.paths.len(), 1);
3765 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
3766 let fees = route.paths[0].hops[0].fee_msat;
3767 assert_eq!(fees, 5_000);
3769 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 50_000);
3770 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3771 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3772 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
3773 // the other channel.
3774 assert_eq!(route.paths.len(), 1);
3775 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3776 let fees = route.paths[0].hops[0].fee_msat;
3777 assert_eq!(fees, 5_000);
3781 fn htlc_minimum_recipient_overpay_test() {
3782 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3783 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3784 let config = UserConfig::default();
3785 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap();
3786 let scorer = ln_test_utils::TestScorer::new();
3787 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3788 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3790 // Route to node2 over a single path which requires overpaying the recipient themselves.
3792 // First disable all paths except the us -> node1 -> node2 path
3793 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3794 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3795 short_channel_id: 13,
3798 cltv_expiry_delta: 0,
3799 htlc_minimum_msat: 0,
3800 htlc_maximum_msat: 0,
3802 fee_proportional_millionths: 0,
3803 excess_data: Vec::new()
3806 // Set channel 4 to free but with a high htlc_minimum_msat
3807 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3808 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3809 short_channel_id: 4,
3812 cltv_expiry_delta: 0,
3813 htlc_minimum_msat: 15_000,
3814 htlc_maximum_msat: MAX_VALUE_MSAT,
3816 fee_proportional_millionths: 0,
3817 excess_data: Vec::new()
3820 // Now check that we'll fail to find a path if we fail to find a path if the htlc_minimum
3821 // is overrun. Note that the fees are actually calculated on 3*payment amount as that's
3822 // what we try to find a route for, so this test only just happens to work out to exactly
3824 let mut route_params = RouteParameters::from_payment_params_and_value(
3825 payment_params.clone(), 5_000);
3826 route_params.max_total_routing_fee_msat = Some(9_999);
3827 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3828 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3829 &Default::default(), &random_seed_bytes) {
3830 assert_eq!(err, "Failed to find route that adheres to the maximum total fee limit of 9999msat");
3831 } else { panic!(); }
3833 let mut route_params = RouteParameters::from_payment_params_and_value(
3834 payment_params.clone(), 5_000);
3835 route_params.max_total_routing_fee_msat = Some(10_000);
3836 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3837 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3838 assert_eq!(route.get_total_fees(), 10_000);
3842 fn disable_channels_test() {
3843 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3844 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3845 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3846 let scorer = ln_test_utils::TestScorer::new();
3847 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3848 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3850 // // Disable channels 4 and 12 by flags=2
3851 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3852 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3853 short_channel_id: 4,
3855 flags: 2, // to disable
3856 cltv_expiry_delta: 0,
3857 htlc_minimum_msat: 0,
3858 htlc_maximum_msat: MAX_VALUE_MSAT,
3860 fee_proportional_millionths: 0,
3861 excess_data: Vec::new()
3863 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3864 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3865 short_channel_id: 12,
3867 flags: 2, // to disable
3868 cltv_expiry_delta: 0,
3869 htlc_minimum_msat: 0,
3870 htlc_maximum_msat: MAX_VALUE_MSAT,
3872 fee_proportional_millionths: 0,
3873 excess_data: Vec::new()
3876 // If all the channels require some features we don't understand, route should fail
3877 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3878 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3879 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3880 &Default::default(), &random_seed_bytes) {
3881 assert_eq!(err, "Failed to find a path to the given destination");
3882 } else { panic!(); }
3884 // If we specify a channel to node7, that overrides our local channel view and that gets used
3885 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
3886 InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3887 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3888 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
3889 &Default::default(), &random_seed_bytes).unwrap();
3890 assert_eq!(route.paths[0].hops.len(), 2);
3892 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3893 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3894 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3895 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3896 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
3897 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3899 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3900 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3901 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3902 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3903 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3904 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3908 fn disable_node_test() {
3909 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3910 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3911 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3912 let scorer = ln_test_utils::TestScorer::new();
3913 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3914 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3916 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
3917 let mut unknown_features = NodeFeatures::empty();
3918 unknown_features.set_unknown_feature_required();
3919 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
3920 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
3921 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
3923 // If all nodes require some features we don't understand, route should fail
3924 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3925 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3926 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3927 &Default::default(), &random_seed_bytes) {
3928 assert_eq!(err, "Failed to find a path to the given destination");
3929 } else { panic!(); }
3931 // If we specify a channel to node7, that overrides our local channel view and that gets used
3932 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
3933 InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3934 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3935 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
3936 &Default::default(), &random_seed_bytes).unwrap();
3937 assert_eq!(route.paths[0].hops.len(), 2);
3939 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3940 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3941 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3942 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3943 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
3944 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3946 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3947 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3948 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3949 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3950 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3951 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3953 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
3954 // naively) assume that the user checked the feature bits on the invoice, which override
3955 // the node_announcement.
3959 fn our_chans_test() {
3960 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3961 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3962 let scorer = ln_test_utils::TestScorer::new();
3963 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3964 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3966 // Route to 1 via 2 and 3 because our channel to 1 is disabled
3967 let payment_params = PaymentParameters::from_node_id(nodes[0], 42);
3968 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3969 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3970 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3971 assert_eq!(route.paths[0].hops.len(), 3);
3973 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3974 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3975 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3976 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3977 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3978 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3980 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3981 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3982 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3983 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (3 << 4) | 2);
3984 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3985 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3987 assert_eq!(route.paths[0].hops[2].pubkey, nodes[0]);
3988 assert_eq!(route.paths[0].hops[2].short_channel_id, 3);
3989 assert_eq!(route.paths[0].hops[2].fee_msat, 100);
3990 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 42);
3991 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(1));
3992 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(3));
3994 // If we specify a channel to node7, that overrides our local channel view and that gets used
3995 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3996 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3997 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
3998 InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3999 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
4000 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
4001 &Default::default(), &random_seed_bytes).unwrap();
4002 assert_eq!(route.paths[0].hops.len(), 2);
4004 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
4005 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
4006 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
4007 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
4008 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]);
4009 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
4011 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4012 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
4013 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4014 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
4015 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4016 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
4019 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
4020 let zero_fees = RoutingFees {
4022 proportional_millionths: 0,
4024 vec![RouteHint(vec![RouteHintHop {
4025 src_node_id: nodes[3],
4026 short_channel_id: 8,
4028 cltv_expiry_delta: (8 << 4) | 1,
4029 htlc_minimum_msat: None,
4030 htlc_maximum_msat: None,
4032 ]), RouteHint(vec![RouteHintHop {
4033 src_node_id: nodes[4],
4034 short_channel_id: 9,
4037 proportional_millionths: 0,
4039 cltv_expiry_delta: (9 << 4) | 1,
4040 htlc_minimum_msat: None,
4041 htlc_maximum_msat: None,
4042 }]), RouteHint(vec![RouteHintHop {
4043 src_node_id: nodes[5],
4044 short_channel_id: 10,
4046 cltv_expiry_delta: (10 << 4) | 1,
4047 htlc_minimum_msat: None,
4048 htlc_maximum_msat: None,
4052 fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
4053 let zero_fees = RoutingFees {
4055 proportional_millionths: 0,
4057 vec![RouteHint(vec![RouteHintHop {
4058 src_node_id: nodes[2],
4059 short_channel_id: 5,
4062 proportional_millionths: 0,
4064 cltv_expiry_delta: (5 << 4) | 1,
4065 htlc_minimum_msat: None,
4066 htlc_maximum_msat: None,
4068 src_node_id: nodes[3],
4069 short_channel_id: 8,
4071 cltv_expiry_delta: (8 << 4) | 1,
4072 htlc_minimum_msat: None,
4073 htlc_maximum_msat: None,
4075 ]), RouteHint(vec![RouteHintHop {
4076 src_node_id: nodes[4],
4077 short_channel_id: 9,
4080 proportional_millionths: 0,
4082 cltv_expiry_delta: (9 << 4) | 1,
4083 htlc_minimum_msat: None,
4084 htlc_maximum_msat: None,
4085 }]), RouteHint(vec![RouteHintHop {
4086 src_node_id: nodes[5],
4087 short_channel_id: 10,
4089 cltv_expiry_delta: (10 << 4) | 1,
4090 htlc_minimum_msat: None,
4091 htlc_maximum_msat: None,
4096 fn partial_route_hint_test() {
4097 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4098 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4099 let scorer = ln_test_utils::TestScorer::new();
4100 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4101 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4103 // Simple test across 2, 3, 5, and 4 via a last_hop channel
4104 // Tests the behaviour when the RouteHint contains a suboptimal hop.
4105 // RouteHint may be partially used by the algo to build the best path.
4107 // First check that last hop can't have its source as the payee.
4108 let invalid_last_hop = RouteHint(vec![RouteHintHop {
4109 src_node_id: nodes[6],
4110 short_channel_id: 8,
4113 proportional_millionths: 0,
4115 cltv_expiry_delta: (8 << 4) | 1,
4116 htlc_minimum_msat: None,
4117 htlc_maximum_msat: None,
4120 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
4121 invalid_last_hops.push(invalid_last_hop);
4123 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
4124 .with_route_hints(invalid_last_hops).unwrap();
4125 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4126 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
4127 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
4128 &Default::default(), &random_seed_bytes) {
4129 assert_eq!(err, "Route hint cannot have the payee as the source.");
4130 } else { panic!(); }
4133 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
4134 .with_route_hints(last_hops_multi_private_channels(&nodes)).unwrap();
4135 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4136 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4137 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4138 assert_eq!(route.paths[0].hops.len(), 5);
4140 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4141 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4142 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
4143 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4144 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4145 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4147 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4148 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4149 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
4150 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
4151 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4152 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4154 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
4155 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
4156 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4157 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
4158 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
4159 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
4161 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
4162 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
4163 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
4164 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
4165 // If we have a peer in the node map, we'll use their features here since we don't have
4166 // a way of figuring out their features from the invoice:
4167 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
4168 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
4170 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
4171 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
4172 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
4173 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
4174 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4175 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4178 fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
4179 let zero_fees = RoutingFees {
4181 proportional_millionths: 0,
4183 vec![RouteHint(vec![RouteHintHop {
4184 src_node_id: nodes[3],
4185 short_channel_id: 8,
4187 cltv_expiry_delta: (8 << 4) | 1,
4188 htlc_minimum_msat: None,
4189 htlc_maximum_msat: None,
4190 }]), RouteHint(vec![
4192 ]), RouteHint(vec![RouteHintHop {
4193 src_node_id: nodes[5],
4194 short_channel_id: 10,
4196 cltv_expiry_delta: (10 << 4) | 1,
4197 htlc_minimum_msat: None,
4198 htlc_maximum_msat: None,
4203 fn ignores_empty_last_hops_test() {
4204 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4205 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4206 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(empty_last_hop(&nodes)).unwrap();
4207 let scorer = ln_test_utils::TestScorer::new();
4208 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4209 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4211 // Test handling of an empty RouteHint passed in Invoice.
4212 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4213 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4214 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4215 assert_eq!(route.paths[0].hops.len(), 5);
4217 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4218 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4219 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
4220 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4221 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4222 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4224 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4225 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4226 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
4227 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
4228 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4229 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4231 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
4232 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
4233 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4234 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
4235 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
4236 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
4238 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
4239 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
4240 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
4241 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
4242 // If we have a peer in the node map, we'll use their features here since we don't have
4243 // a way of figuring out their features from the invoice:
4244 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
4245 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
4247 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
4248 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
4249 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
4250 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
4251 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4252 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4255 /// Builds a trivial last-hop hint that passes through the two nodes given, with channel 0xff00
4257 fn multi_hop_last_hops_hint(hint_hops: [PublicKey; 2]) -> Vec<RouteHint> {
4258 let zero_fees = RoutingFees {
4260 proportional_millionths: 0,
4262 vec![RouteHint(vec![RouteHintHop {
4263 src_node_id: hint_hops[0],
4264 short_channel_id: 0xff00,
4267 proportional_millionths: 0,
4269 cltv_expiry_delta: (5 << 4) | 1,
4270 htlc_minimum_msat: None,
4271 htlc_maximum_msat: None,
4273 src_node_id: hint_hops[1],
4274 short_channel_id: 0xff01,
4276 cltv_expiry_delta: (8 << 4) | 1,
4277 htlc_minimum_msat: None,
4278 htlc_maximum_msat: None,
4283 fn multi_hint_last_hops_test() {
4284 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4285 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4286 let last_hops = multi_hop_last_hops_hint([nodes[2], nodes[3]]);
4287 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
4288 let scorer = ln_test_utils::TestScorer::new();
4289 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4290 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4291 // Test through channels 2, 3, 0xff00, 0xff01.
4292 // Test shows that multiple hop hints are considered.
4294 // Disabling channels 6 & 7 by flags=2
4295 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4296 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4297 short_channel_id: 6,
4299 flags: 2, // to disable
4300 cltv_expiry_delta: 0,
4301 htlc_minimum_msat: 0,
4302 htlc_maximum_msat: MAX_VALUE_MSAT,
4304 fee_proportional_millionths: 0,
4305 excess_data: Vec::new()
4307 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4308 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4309 short_channel_id: 7,
4311 flags: 2, // to disable
4312 cltv_expiry_delta: 0,
4313 htlc_minimum_msat: 0,
4314 htlc_maximum_msat: MAX_VALUE_MSAT,
4316 fee_proportional_millionths: 0,
4317 excess_data: Vec::new()
4320 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4321 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4322 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4323 assert_eq!(route.paths[0].hops.len(), 4);
4325 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4326 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4327 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
4328 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, 65);
4329 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4330 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4332 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4333 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4334 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4335 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 81);
4336 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4337 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4339 assert_eq!(route.paths[0].hops[2].pubkey, nodes[3]);
4340 assert_eq!(route.paths[0].hops[2].short_channel_id, last_hops[0].0[0].short_channel_id);
4341 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4342 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 129);
4343 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(4));
4344 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4346 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
4347 assert_eq!(route.paths[0].hops[3].short_channel_id, last_hops[0].0[1].short_channel_id);
4348 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
4349 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
4350 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4351 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4355 fn private_multi_hint_last_hops_test() {
4356 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4357 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4359 let non_announced_privkey = SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02x}", 0xf0).repeat(32)).unwrap()[..]).unwrap();
4360 let non_announced_pubkey = PublicKey::from_secret_key(&secp_ctx, &non_announced_privkey);
4362 let last_hops = multi_hop_last_hops_hint([nodes[2], non_announced_pubkey]);
4363 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
4364 let scorer = ln_test_utils::TestScorer::new();
4365 // Test through channels 2, 3, 0xff00, 0xff01.
4366 // Test shows that multiple hop hints are considered.
4368 // Disabling channels 6 & 7 by flags=2
4369 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4370 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4371 short_channel_id: 6,
4373 flags: 2, // to disable
4374 cltv_expiry_delta: 0,
4375 htlc_minimum_msat: 0,
4376 htlc_maximum_msat: MAX_VALUE_MSAT,
4378 fee_proportional_millionths: 0,
4379 excess_data: Vec::new()
4381 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4382 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4383 short_channel_id: 7,
4385 flags: 2, // to disable
4386 cltv_expiry_delta: 0,
4387 htlc_minimum_msat: 0,
4388 htlc_maximum_msat: MAX_VALUE_MSAT,
4390 fee_proportional_millionths: 0,
4391 excess_data: Vec::new()
4394 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4395 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4396 Arc::clone(&logger), &scorer, &Default::default(), &[42u8; 32]).unwrap();
4397 assert_eq!(route.paths[0].hops.len(), 4);
4399 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4400 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4401 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
4402 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, 65);
4403 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4404 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4406 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4407 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4408 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4409 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 81);
4410 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4411 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4413 assert_eq!(route.paths[0].hops[2].pubkey, non_announced_pubkey);
4414 assert_eq!(route.paths[0].hops[2].short_channel_id, last_hops[0].0[0].short_channel_id);
4415 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4416 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 129);
4417 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4418 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4420 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
4421 assert_eq!(route.paths[0].hops[3].short_channel_id, last_hops[0].0[1].short_channel_id);
4422 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
4423 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
4424 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4425 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4428 fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
4429 let zero_fees = RoutingFees {
4431 proportional_millionths: 0,
4433 vec![RouteHint(vec![RouteHintHop {
4434 src_node_id: nodes[4],
4435 short_channel_id: 11,
4437 cltv_expiry_delta: (11 << 4) | 1,
4438 htlc_minimum_msat: None,
4439 htlc_maximum_msat: None,
4441 src_node_id: nodes[3],
4442 short_channel_id: 8,
4444 cltv_expiry_delta: (8 << 4) | 1,
4445 htlc_minimum_msat: None,
4446 htlc_maximum_msat: None,
4447 }]), RouteHint(vec![RouteHintHop {
4448 src_node_id: nodes[4],
4449 short_channel_id: 9,
4452 proportional_millionths: 0,
4454 cltv_expiry_delta: (9 << 4) | 1,
4455 htlc_minimum_msat: None,
4456 htlc_maximum_msat: None,
4457 }]), RouteHint(vec![RouteHintHop {
4458 src_node_id: nodes[5],
4459 short_channel_id: 10,
4461 cltv_expiry_delta: (10 << 4) | 1,
4462 htlc_minimum_msat: None,
4463 htlc_maximum_msat: None,
4468 fn last_hops_with_public_channel_test() {
4469 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4470 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4471 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops_with_public_channel(&nodes)).unwrap();
4472 let scorer = ln_test_utils::TestScorer::new();
4473 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4474 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4475 // This test shows that public routes can be present in the invoice
4476 // which would be handled in the same manner.
4478 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4479 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4480 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4481 assert_eq!(route.paths[0].hops.len(), 5);
4483 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4484 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4485 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
4486 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4487 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4488 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4490 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4491 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4492 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
4493 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
4494 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4495 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4497 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
4498 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
4499 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4500 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
4501 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
4502 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
4504 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
4505 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
4506 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
4507 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
4508 // If we have a peer in the node map, we'll use their features here since we don't have
4509 // a way of figuring out their features from the invoice:
4510 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
4511 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
4513 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
4514 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
4515 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
4516 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
4517 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4518 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4522 fn our_chans_last_hop_connect_test() {
4523 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4524 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4525 let scorer = ln_test_utils::TestScorer::new();
4526 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4527 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4529 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
4530 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
4531 let mut last_hops = last_hops(&nodes);
4532 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
4533 .with_route_hints(last_hops.clone()).unwrap();
4534 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4535 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
4536 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
4537 &Default::default(), &random_seed_bytes).unwrap();
4538 assert_eq!(route.paths[0].hops.len(), 2);
4540 assert_eq!(route.paths[0].hops[0].pubkey, nodes[3]);
4541 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
4542 assert_eq!(route.paths[0].hops[0].fee_msat, 0);
4543 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (8 << 4) | 1);
4544 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]);
4545 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
4547 assert_eq!(route.paths[0].hops[1].pubkey, nodes[6]);
4548 assert_eq!(route.paths[0].hops[1].short_channel_id, 8);
4549 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4550 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
4551 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4552 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4554 last_hops[0].0[0].fees.base_msat = 1000;
4556 // Revert to via 6 as the fee on 8 goes up
4557 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
4558 .with_route_hints(last_hops).unwrap();
4559 let route_params = RouteParameters::from_payment_params_and_value(
4560 payment_params.clone(), 100);
4561 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4562 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4563 assert_eq!(route.paths[0].hops.len(), 4);
4565 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4566 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4567 assert_eq!(route.paths[0].hops[0].fee_msat, 200); // fee increased as its % of value transferred across node
4568 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4569 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4570 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4572 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4573 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4574 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4575 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (7 << 4) | 1);
4576 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4577 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4579 assert_eq!(route.paths[0].hops[2].pubkey, nodes[5]);
4580 assert_eq!(route.paths[0].hops[2].short_channel_id, 7);
4581 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4582 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (10 << 4) | 1);
4583 // If we have a peer in the node map, we'll use their features here since we don't have
4584 // a way of figuring out their features from the invoice:
4585 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(6));
4586 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(7));
4588 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
4589 assert_eq!(route.paths[0].hops[3].short_channel_id, 10);
4590 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
4591 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
4592 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4593 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4595 // ...but still use 8 for larger payments as 6 has a variable feerate
4596 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 2000);
4597 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4598 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4599 assert_eq!(route.paths[0].hops.len(), 5);
4601 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4602 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4603 assert_eq!(route.paths[0].hops[0].fee_msat, 3000);
4604 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4605 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4606 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4608 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4609 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4610 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
4611 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
4612 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4613 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4615 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
4616 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
4617 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4618 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
4619 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
4620 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
4622 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
4623 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
4624 assert_eq!(route.paths[0].hops[3].fee_msat, 1000);
4625 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
4626 // If we have a peer in the node map, we'll use their features here since we don't have
4627 // a way of figuring out their features from the invoice:
4628 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
4629 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
4631 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
4632 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
4633 assert_eq!(route.paths[0].hops[4].fee_msat, 2000);
4634 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
4635 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4636 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4639 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> {
4640 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
4641 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
4642 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
4644 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
4645 let last_hops = RouteHint(vec![RouteHintHop {
4646 src_node_id: middle_node_id,
4647 short_channel_id: 8,
4650 proportional_millionths: last_hop_fee_prop,
4652 cltv_expiry_delta: (8 << 4) | 1,
4653 htlc_minimum_msat: None,
4654 htlc_maximum_msat: last_hop_htlc_max,
4656 let payment_params = PaymentParameters::from_node_id(target_node_id, 42).with_route_hints(vec![last_hops]).unwrap();
4657 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
4658 let scorer = ln_test_utils::TestScorer::new();
4659 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4660 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4661 let logger = ln_test_utils::TestLogger::new();
4662 let network_graph = NetworkGraph::new(Network::Testnet, &logger);
4663 let route_params = RouteParameters::from_payment_params_and_value(payment_params, route_val);
4664 let route = get_route(&source_node_id, &route_params, &network_graph.read_only(),
4665 Some(&our_chans.iter().collect::<Vec<_>>()), &logger, &scorer, &Default::default(),
4666 &random_seed_bytes);
4671 fn unannounced_path_test() {
4672 // We should be able to send a payment to a destination without any help of a routing graph
4673 // if we have a channel with a common counterparty that appears in the first and last hop
4675 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
4677 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
4678 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
4679 assert_eq!(route.paths[0].hops.len(), 2);
4681 assert_eq!(route.paths[0].hops[0].pubkey, middle_node_id);
4682 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
4683 assert_eq!(route.paths[0].hops[0].fee_msat, 1001);
4684 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (8 << 4) | 1);
4685 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &[0b11]);
4686 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
4688 assert_eq!(route.paths[0].hops[1].pubkey, target_node_id);
4689 assert_eq!(route.paths[0].hops[1].short_channel_id, 8);
4690 assert_eq!(route.paths[0].hops[1].fee_msat, 1000000);
4691 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
4692 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4693 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
4697 fn overflow_unannounced_path_test_liquidity_underflow() {
4698 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
4699 // the last-hop had a fee which overflowed a u64, we'd panic.
4700 // This was due to us adding the first-hop from us unconditionally, causing us to think
4701 // we'd built a path (as our node is in the "best candidate" set), when we had not.
4702 // In this test, we previously hit a subtraction underflow due to having less available
4703 // liquidity at the last hop than 0.
4704 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());
4708 fn overflow_unannounced_path_test_feerate_overflow() {
4709 // This tests for the same case as above, except instead of hitting a subtraction
4710 // underflow, we hit a case where the fee charged at a hop overflowed.
4711 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());
4715 fn available_amount_while_routing_test() {
4716 // Tests whether we choose the correct available channel amount while routing.
4718 let (secp_ctx, network_graph, gossip_sync, chain_monitor, logger) = build_graph();
4719 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4720 let scorer = ln_test_utils::TestScorer::new();
4721 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4722 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4723 let config = UserConfig::default();
4724 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
4725 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
4728 // We will use a simple single-path route from
4729 // our node to node2 via node0: channels {1, 3}.
4731 // First disable all other paths.
4732 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4733 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4734 short_channel_id: 2,
4737 cltv_expiry_delta: 0,
4738 htlc_minimum_msat: 0,
4739 htlc_maximum_msat: 100_000,
4741 fee_proportional_millionths: 0,
4742 excess_data: Vec::new()
4744 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4745 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4746 short_channel_id: 12,
4749 cltv_expiry_delta: 0,
4750 htlc_minimum_msat: 0,
4751 htlc_maximum_msat: 100_000,
4753 fee_proportional_millionths: 0,
4754 excess_data: Vec::new()
4757 // Make the first channel (#1) very permissive,
4758 // and we will be testing all limits on the second channel.
4759 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4760 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4761 short_channel_id: 1,
4764 cltv_expiry_delta: 0,
4765 htlc_minimum_msat: 0,
4766 htlc_maximum_msat: 1_000_000_000,
4768 fee_proportional_millionths: 0,
4769 excess_data: Vec::new()
4772 // First, let's see if routing works if we have absolutely no idea about the available amount.
4773 // In this case, it should be set to 250_000 sats.
4774 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4775 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4776 short_channel_id: 3,
4779 cltv_expiry_delta: 0,
4780 htlc_minimum_msat: 0,
4781 htlc_maximum_msat: 250_000_000,
4783 fee_proportional_millionths: 0,
4784 excess_data: Vec::new()
4788 // Attempt to route more than available results in a failure.
4789 let route_params = RouteParameters::from_payment_params_and_value(
4790 payment_params.clone(), 250_000_001);
4791 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4792 &our_id, &route_params, &network_graph.read_only(), None,
4793 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
4794 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4795 } else { panic!(); }
4799 // Now, attempt to route an exact amount we have should be fine.
4800 let route_params = RouteParameters::from_payment_params_and_value(
4801 payment_params.clone(), 250_000_000);
4802 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4803 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4804 assert_eq!(route.paths.len(), 1);
4805 let path = route.paths.last().unwrap();
4806 assert_eq!(path.hops.len(), 2);
4807 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4808 assert_eq!(path.final_value_msat(), 250_000_000);
4811 // Check that setting next_outbound_htlc_limit_msat in first_hops limits the channels.
4812 // Disable channel #1 and use another first hop.
4813 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4814 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4815 short_channel_id: 1,
4818 cltv_expiry_delta: 0,
4819 htlc_minimum_msat: 0,
4820 htlc_maximum_msat: 1_000_000_000,
4822 fee_proportional_millionths: 0,
4823 excess_data: Vec::new()
4826 // Now, limit the first_hop by the next_outbound_htlc_limit_msat of 200_000 sats.
4827 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
4830 // Attempt to route more than available results in a failure.
4831 let route_params = RouteParameters::from_payment_params_and_value(
4832 payment_params.clone(), 200_000_001);
4833 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4834 &our_id, &route_params, &network_graph.read_only(),
4835 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
4836 &Default::default(), &random_seed_bytes) {
4837 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4838 } else { panic!(); }
4842 // Now, attempt to route an exact amount we have should be fine.
4843 let route_params = RouteParameters::from_payment_params_and_value(
4844 payment_params.clone(), 200_000_000);
4845 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
4846 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
4847 &Default::default(), &random_seed_bytes).unwrap();
4848 assert_eq!(route.paths.len(), 1);
4849 let path = route.paths.last().unwrap();
4850 assert_eq!(path.hops.len(), 2);
4851 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4852 assert_eq!(path.final_value_msat(), 200_000_000);
4855 // Enable channel #1 back.
4856 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4857 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4858 short_channel_id: 1,
4861 cltv_expiry_delta: 0,
4862 htlc_minimum_msat: 0,
4863 htlc_maximum_msat: 1_000_000_000,
4865 fee_proportional_millionths: 0,
4866 excess_data: Vec::new()
4870 // Now let's see if routing works if we know only htlc_maximum_msat.
4871 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4872 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4873 short_channel_id: 3,
4876 cltv_expiry_delta: 0,
4877 htlc_minimum_msat: 0,
4878 htlc_maximum_msat: 15_000,
4880 fee_proportional_millionths: 0,
4881 excess_data: Vec::new()
4885 // Attempt to route more than available results in a failure.
4886 let route_params = RouteParameters::from_payment_params_and_value(
4887 payment_params.clone(), 15_001);
4888 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4889 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4890 &scorer, &Default::default(), &random_seed_bytes) {
4891 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4892 } else { panic!(); }
4896 // Now, attempt to route an exact amount we have should be fine.
4897 let route_params = RouteParameters::from_payment_params_and_value(
4898 payment_params.clone(), 15_000);
4899 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4900 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4901 assert_eq!(route.paths.len(), 1);
4902 let path = route.paths.last().unwrap();
4903 assert_eq!(path.hops.len(), 2);
4904 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4905 assert_eq!(path.final_value_msat(), 15_000);
4908 // Now let's see if routing works if we know only capacity from the UTXO.
4910 // We can't change UTXO capacity on the fly, so we'll disable
4911 // the existing channel and add another one with the capacity we need.
4912 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4913 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4914 short_channel_id: 3,
4917 cltv_expiry_delta: 0,
4918 htlc_minimum_msat: 0,
4919 htlc_maximum_msat: MAX_VALUE_MSAT,
4921 fee_proportional_millionths: 0,
4922 excess_data: Vec::new()
4925 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
4926 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
4927 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
4928 .push_opcode(opcodes::all::OP_PUSHNUM_2)
4929 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
4931 *chain_monitor.utxo_ret.lock().unwrap() =
4932 UtxoResult::Sync(Ok(TxOut { value: 15, script_pubkey: good_script.clone() }));
4933 gossip_sync.add_utxo_lookup(Some(chain_monitor));
4935 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
4936 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4937 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4938 short_channel_id: 333,
4941 cltv_expiry_delta: (3 << 4) | 1,
4942 htlc_minimum_msat: 0,
4943 htlc_maximum_msat: 15_000,
4945 fee_proportional_millionths: 0,
4946 excess_data: Vec::new()
4948 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4949 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4950 short_channel_id: 333,
4953 cltv_expiry_delta: (3 << 4) | 2,
4954 htlc_minimum_msat: 0,
4955 htlc_maximum_msat: 15_000,
4957 fee_proportional_millionths: 0,
4958 excess_data: Vec::new()
4962 // Attempt to route more than available results in a failure.
4963 let route_params = RouteParameters::from_payment_params_and_value(
4964 payment_params.clone(), 15_001);
4965 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4966 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4967 &scorer, &Default::default(), &random_seed_bytes) {
4968 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4969 } else { panic!(); }
4973 // Now, attempt to route an exact amount we have should be fine.
4974 let route_params = RouteParameters::from_payment_params_and_value(
4975 payment_params.clone(), 15_000);
4976 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4977 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4978 assert_eq!(route.paths.len(), 1);
4979 let path = route.paths.last().unwrap();
4980 assert_eq!(path.hops.len(), 2);
4981 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4982 assert_eq!(path.final_value_msat(), 15_000);
4985 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
4986 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4987 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4988 short_channel_id: 333,
4991 cltv_expiry_delta: 0,
4992 htlc_minimum_msat: 0,
4993 htlc_maximum_msat: 10_000,
4995 fee_proportional_millionths: 0,
4996 excess_data: Vec::new()
5000 // Attempt to route more than available results in a failure.
5001 let route_params = RouteParameters::from_payment_params_and_value(
5002 payment_params.clone(), 10_001);
5003 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5004 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5005 &scorer, &Default::default(), &random_seed_bytes) {
5006 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5007 } else { panic!(); }
5011 // Now, attempt to route an exact amount we have should be fine.
5012 let route_params = RouteParameters::from_payment_params_and_value(
5013 payment_params.clone(), 10_000);
5014 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5015 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5016 assert_eq!(route.paths.len(), 1);
5017 let path = route.paths.last().unwrap();
5018 assert_eq!(path.hops.len(), 2);
5019 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5020 assert_eq!(path.final_value_msat(), 10_000);
5025 fn available_liquidity_last_hop_test() {
5026 // Check that available liquidity properly limits the path even when only
5027 // one of the latter hops is limited.
5028 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5029 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5030 let scorer = ln_test_utils::TestScorer::new();
5031 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5032 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5033 let config = UserConfig::default();
5034 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
5035 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5038 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
5039 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
5040 // Total capacity: 50 sats.
5042 // Disable other potential paths.
5043 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5044 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5045 short_channel_id: 2,
5048 cltv_expiry_delta: 0,
5049 htlc_minimum_msat: 0,
5050 htlc_maximum_msat: 100_000,
5052 fee_proportional_millionths: 0,
5053 excess_data: Vec::new()
5055 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5056 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5057 short_channel_id: 7,
5060 cltv_expiry_delta: 0,
5061 htlc_minimum_msat: 0,
5062 htlc_maximum_msat: 100_000,
5064 fee_proportional_millionths: 0,
5065 excess_data: Vec::new()
5070 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5071 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5072 short_channel_id: 12,
5075 cltv_expiry_delta: 0,
5076 htlc_minimum_msat: 0,
5077 htlc_maximum_msat: 100_000,
5079 fee_proportional_millionths: 0,
5080 excess_data: Vec::new()
5082 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5083 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5084 short_channel_id: 13,
5087 cltv_expiry_delta: 0,
5088 htlc_minimum_msat: 0,
5089 htlc_maximum_msat: 100_000,
5091 fee_proportional_millionths: 0,
5092 excess_data: Vec::new()
5095 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5096 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5097 short_channel_id: 6,
5100 cltv_expiry_delta: 0,
5101 htlc_minimum_msat: 0,
5102 htlc_maximum_msat: 50_000,
5104 fee_proportional_millionths: 0,
5105 excess_data: Vec::new()
5107 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5108 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5109 short_channel_id: 11,
5112 cltv_expiry_delta: 0,
5113 htlc_minimum_msat: 0,
5114 htlc_maximum_msat: 100_000,
5116 fee_proportional_millionths: 0,
5117 excess_data: Vec::new()
5120 // Attempt to route more than available results in a failure.
5121 let route_params = RouteParameters::from_payment_params_and_value(
5122 payment_params.clone(), 60_000);
5123 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5124 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5125 &scorer, &Default::default(), &random_seed_bytes) {
5126 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5127 } else { panic!(); }
5131 // Now, attempt to route 49 sats (just a bit below the capacity).
5132 let route_params = RouteParameters::from_payment_params_and_value(
5133 payment_params.clone(), 49_000);
5134 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5135 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5136 assert_eq!(route.paths.len(), 1);
5137 let mut total_amount_paid_msat = 0;
5138 for path in &route.paths {
5139 assert_eq!(path.hops.len(), 4);
5140 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5141 total_amount_paid_msat += path.final_value_msat();
5143 assert_eq!(total_amount_paid_msat, 49_000);
5147 // Attempt to route an exact amount is also fine
5148 let route_params = RouteParameters::from_payment_params_and_value(
5149 payment_params, 50_000);
5150 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5151 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5152 assert_eq!(route.paths.len(), 1);
5153 let mut total_amount_paid_msat = 0;
5154 for path in &route.paths {
5155 assert_eq!(path.hops.len(), 4);
5156 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5157 total_amount_paid_msat += path.final_value_msat();
5159 assert_eq!(total_amount_paid_msat, 50_000);
5164 fn ignore_fee_first_hop_test() {
5165 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5166 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5167 let scorer = ln_test_utils::TestScorer::new();
5168 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5169 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5170 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
5172 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
5173 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5174 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5175 short_channel_id: 1,
5178 cltv_expiry_delta: 0,
5179 htlc_minimum_msat: 0,
5180 htlc_maximum_msat: 100_000,
5181 fee_base_msat: 1_000_000,
5182 fee_proportional_millionths: 0,
5183 excess_data: Vec::new()
5185 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5186 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5187 short_channel_id: 3,
5190 cltv_expiry_delta: 0,
5191 htlc_minimum_msat: 0,
5192 htlc_maximum_msat: 50_000,
5194 fee_proportional_millionths: 0,
5195 excess_data: Vec::new()
5199 let route_params = RouteParameters::from_payment_params_and_value(
5200 payment_params, 50_000);
5201 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5202 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5203 assert_eq!(route.paths.len(), 1);
5204 let mut total_amount_paid_msat = 0;
5205 for path in &route.paths {
5206 assert_eq!(path.hops.len(), 2);
5207 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5208 total_amount_paid_msat += path.final_value_msat();
5210 assert_eq!(total_amount_paid_msat, 50_000);
5215 fn simple_mpp_route_test() {
5216 let (secp_ctx, _, _, _, _) = build_graph();
5217 let (_, _, _, nodes) = get_nodes(&secp_ctx);
5218 let config = UserConfig::default();
5219 let clear_payment_params = PaymentParameters::from_node_id(nodes[2], 42)
5220 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5222 do_simple_mpp_route_test(clear_payment_params);
5224 // MPP to a 1-hop blinded path for nodes[2]
5225 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
5226 let blinded_path = BlindedPath {
5227 introduction_node_id: nodes[2],
5228 blinding_point: ln_test_utils::pubkey(42),
5229 blinded_hops: vec![BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }],
5231 let blinded_payinfo = BlindedPayInfo { // These fields are ignored for 1-hop blinded paths
5233 fee_proportional_millionths: 0,
5234 htlc_minimum_msat: 0,
5235 htlc_maximum_msat: 0,
5236 cltv_expiry_delta: 0,
5237 features: BlindedHopFeatures::empty(),
5239 let one_hop_blinded_payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), blinded_path.clone())])
5240 .with_bolt12_features(bolt12_features.clone()).unwrap();
5241 do_simple_mpp_route_test(one_hop_blinded_payment_params.clone());
5243 // MPP to 3 2-hop blinded paths
5244 let mut blinded_path_node_0 = blinded_path.clone();
5245 blinded_path_node_0.introduction_node_id = nodes[0];
5246 blinded_path_node_0.blinded_hops.push(blinded_path.blinded_hops[0].clone());
5247 let mut node_0_payinfo = blinded_payinfo.clone();
5248 node_0_payinfo.htlc_maximum_msat = 50_000;
5250 let mut blinded_path_node_7 = blinded_path_node_0.clone();
5251 blinded_path_node_7.introduction_node_id = nodes[7];
5252 let mut node_7_payinfo = blinded_payinfo.clone();
5253 node_7_payinfo.htlc_maximum_msat = 60_000;
5255 let mut blinded_path_node_1 = blinded_path_node_0.clone();
5256 blinded_path_node_1.introduction_node_id = nodes[1];
5257 let mut node_1_payinfo = blinded_payinfo.clone();
5258 node_1_payinfo.htlc_maximum_msat = 180_000;
5260 let two_hop_blinded_payment_params = PaymentParameters::blinded(
5262 (node_0_payinfo, blinded_path_node_0),
5263 (node_7_payinfo, blinded_path_node_7),
5264 (node_1_payinfo, blinded_path_node_1)
5266 .with_bolt12_features(bolt12_features).unwrap();
5267 do_simple_mpp_route_test(two_hop_blinded_payment_params);
5271 fn do_simple_mpp_route_test(payment_params: PaymentParameters) {
5272 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5273 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5274 let scorer = ln_test_utils::TestScorer::new();
5275 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5276 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5278 // We need a route consisting of 3 paths:
5279 // From our node to node2 via node0, node7, node1 (three paths one hop each).
5280 // To achieve this, the amount being transferred should be around
5281 // the total capacity of these 3 paths.
5283 // First, we set limits on these (previously unlimited) channels.
5284 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
5286 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
5287 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5288 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5289 short_channel_id: 1,
5292 cltv_expiry_delta: 0,
5293 htlc_minimum_msat: 0,
5294 htlc_maximum_msat: 100_000,
5296 fee_proportional_millionths: 0,
5297 excess_data: Vec::new()
5299 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5300 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5301 short_channel_id: 3,
5304 cltv_expiry_delta: 0,
5305 htlc_minimum_msat: 0,
5306 htlc_maximum_msat: 50_000,
5308 fee_proportional_millionths: 0,
5309 excess_data: Vec::new()
5312 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
5313 // (total limit 60).
5314 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5315 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5316 short_channel_id: 12,
5319 cltv_expiry_delta: 0,
5320 htlc_minimum_msat: 0,
5321 htlc_maximum_msat: 60_000,
5323 fee_proportional_millionths: 0,
5324 excess_data: Vec::new()
5326 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5327 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5328 short_channel_id: 13,
5331 cltv_expiry_delta: 0,
5332 htlc_minimum_msat: 0,
5333 htlc_maximum_msat: 60_000,
5335 fee_proportional_millionths: 0,
5336 excess_data: Vec::new()
5339 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
5340 // (total capacity 180 sats).
5341 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5342 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5343 short_channel_id: 2,
5346 cltv_expiry_delta: 0,
5347 htlc_minimum_msat: 0,
5348 htlc_maximum_msat: 200_000,
5350 fee_proportional_millionths: 0,
5351 excess_data: Vec::new()
5353 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5354 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5355 short_channel_id: 4,
5358 cltv_expiry_delta: 0,
5359 htlc_minimum_msat: 0,
5360 htlc_maximum_msat: 180_000,
5362 fee_proportional_millionths: 0,
5363 excess_data: Vec::new()
5367 // Attempt to route more than available results in a failure.
5368 let route_params = RouteParameters::from_payment_params_and_value(
5369 payment_params.clone(), 300_000);
5370 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5371 &our_id, &route_params, &network_graph.read_only(), None,
5372 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
5373 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5374 } else { panic!(); }
5378 // Attempt to route while setting max_path_count to 0 results in a failure.
5379 let zero_payment_params = payment_params.clone().with_max_path_count(0);
5380 let route_params = RouteParameters::from_payment_params_and_value(
5381 zero_payment_params, 100);
5382 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5383 &our_id, &route_params, &network_graph.read_only(), None,
5384 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
5385 assert_eq!(err, "Can't find a route with no paths allowed.");
5386 } else { panic!(); }
5390 // Attempt to route while setting max_path_count to 3 results in a failure.
5391 // This is the case because the minimal_value_contribution_msat would require each path
5392 // to account for 1/3 of the total value, which is violated by 2 out of 3 paths.
5393 let fail_payment_params = payment_params.clone().with_max_path_count(3);
5394 let route_params = RouteParameters::from_payment_params_and_value(
5395 fail_payment_params, 250_000);
5396 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5397 &our_id, &route_params, &network_graph.read_only(), None,
5398 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
5399 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5400 } else { panic!(); }
5404 // Now, attempt to route 250 sats (just a bit below the capacity).
5405 // Our algorithm should provide us with these 3 paths.
5406 let route_params = RouteParameters::from_payment_params_and_value(
5407 payment_params.clone(), 250_000);
5408 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5409 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5410 assert_eq!(route.paths.len(), 3);
5411 let mut total_amount_paid_msat = 0;
5412 for path in &route.paths {
5413 if let Some(bt) = &path.blinded_tail {
5414 assert_eq!(path.hops.len() + if bt.hops.len() == 1 { 0 } else { 1 }, 2);
5416 assert_eq!(path.hops.len(), 2);
5417 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5419 total_amount_paid_msat += path.final_value_msat();
5421 assert_eq!(total_amount_paid_msat, 250_000);
5425 // Attempt to route an exact amount is also fine
5426 let route_params = RouteParameters::from_payment_params_and_value(
5427 payment_params.clone(), 290_000);
5428 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5429 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5430 assert_eq!(route.paths.len(), 3);
5431 let mut total_amount_paid_msat = 0;
5432 for path in &route.paths {
5433 if payment_params.payee.blinded_route_hints().len() != 0 {
5434 assert!(path.blinded_tail.is_some()) } else { assert!(path.blinded_tail.is_none()) }
5435 if let Some(bt) = &path.blinded_tail {
5436 assert_eq!(path.hops.len() + if bt.hops.len() == 1 { 0 } else { 1 }, 2);
5437 if bt.hops.len() > 1 {
5438 assert_eq!(path.hops.last().unwrap().pubkey,
5439 payment_params.payee.blinded_route_hints().iter()
5440 .find(|(p, _)| p.htlc_maximum_msat == path.final_value_msat())
5441 .map(|(_, p)| p.introduction_node_id).unwrap());
5443 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5446 assert_eq!(path.hops.len(), 2);
5447 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5449 total_amount_paid_msat += path.final_value_msat();
5451 assert_eq!(total_amount_paid_msat, 290_000);
5456 fn long_mpp_route_test() {
5457 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5458 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5459 let scorer = ln_test_utils::TestScorer::new();
5460 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5461 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5462 let config = UserConfig::default();
5463 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
5464 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5467 // We need a route consisting of 3 paths:
5468 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
5469 // Note that these paths overlap (channels 5, 12, 13).
5470 // We will route 300 sats.
5471 // Each path will have 100 sats capacity, those channels which
5472 // are used twice will have 200 sats capacity.
5474 // Disable other potential paths.
5475 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5476 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5477 short_channel_id: 2,
5480 cltv_expiry_delta: 0,
5481 htlc_minimum_msat: 0,
5482 htlc_maximum_msat: 100_000,
5484 fee_proportional_millionths: 0,
5485 excess_data: Vec::new()
5487 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5488 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5489 short_channel_id: 7,
5492 cltv_expiry_delta: 0,
5493 htlc_minimum_msat: 0,
5494 htlc_maximum_msat: 100_000,
5496 fee_proportional_millionths: 0,
5497 excess_data: Vec::new()
5500 // Path via {node0, node2} is channels {1, 3, 5}.
5501 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5502 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5503 short_channel_id: 1,
5506 cltv_expiry_delta: 0,
5507 htlc_minimum_msat: 0,
5508 htlc_maximum_msat: 100_000,
5510 fee_proportional_millionths: 0,
5511 excess_data: Vec::new()
5513 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5514 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5515 short_channel_id: 3,
5518 cltv_expiry_delta: 0,
5519 htlc_minimum_msat: 0,
5520 htlc_maximum_msat: 100_000,
5522 fee_proportional_millionths: 0,
5523 excess_data: Vec::new()
5526 // Capacity of 200 sats because this channel will be used by 3rd path as well.
5527 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5528 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5529 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5530 short_channel_id: 5,
5533 cltv_expiry_delta: 0,
5534 htlc_minimum_msat: 0,
5535 htlc_maximum_msat: 200_000,
5537 fee_proportional_millionths: 0,
5538 excess_data: Vec::new()
5541 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
5542 // Add 100 sats to the capacities of {12, 13}, because these channels
5543 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
5544 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5545 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5546 short_channel_id: 12,
5549 cltv_expiry_delta: 0,
5550 htlc_minimum_msat: 0,
5551 htlc_maximum_msat: 200_000,
5553 fee_proportional_millionths: 0,
5554 excess_data: Vec::new()
5556 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5557 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5558 short_channel_id: 13,
5561 cltv_expiry_delta: 0,
5562 htlc_minimum_msat: 0,
5563 htlc_maximum_msat: 200_000,
5565 fee_proportional_millionths: 0,
5566 excess_data: Vec::new()
5569 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5570 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5571 short_channel_id: 6,
5574 cltv_expiry_delta: 0,
5575 htlc_minimum_msat: 0,
5576 htlc_maximum_msat: 100_000,
5578 fee_proportional_millionths: 0,
5579 excess_data: Vec::new()
5581 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5582 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5583 short_channel_id: 11,
5586 cltv_expiry_delta: 0,
5587 htlc_minimum_msat: 0,
5588 htlc_maximum_msat: 100_000,
5590 fee_proportional_millionths: 0,
5591 excess_data: Vec::new()
5594 // Path via {node7, node2} is channels {12, 13, 5}.
5595 // We already limited them to 200 sats (they are used twice for 100 sats).
5596 // Nothing to do here.
5599 // Attempt to route more than available results in a failure.
5600 let route_params = RouteParameters::from_payment_params_and_value(
5601 payment_params.clone(), 350_000);
5602 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5603 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5604 &scorer, &Default::default(), &random_seed_bytes) {
5605 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5606 } else { panic!(); }
5610 // Now, attempt to route 300 sats (exact amount we can route).
5611 // Our algorithm should provide us with these 3 paths, 100 sats each.
5612 let route_params = RouteParameters::from_payment_params_and_value(
5613 payment_params, 300_000);
5614 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5615 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5616 assert_eq!(route.paths.len(), 3);
5618 let mut total_amount_paid_msat = 0;
5619 for path in &route.paths {
5620 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5621 total_amount_paid_msat += path.final_value_msat();
5623 assert_eq!(total_amount_paid_msat, 300_000);
5629 fn mpp_cheaper_route_test() {
5630 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5631 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5632 let scorer = ln_test_utils::TestScorer::new();
5633 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5634 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5635 let config = UserConfig::default();
5636 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
5637 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5640 // This test checks that if we have two cheaper paths and one more expensive path,
5641 // so that liquidity-wise any 2 of 3 combination is sufficient,
5642 // two cheaper paths will be taken.
5643 // These paths have equal available liquidity.
5645 // We need a combination of 3 paths:
5646 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
5647 // Note that these paths overlap (channels 5, 12, 13).
5648 // Each path will have 100 sats capacity, those channels which
5649 // are used twice will have 200 sats capacity.
5651 // Disable other potential paths.
5652 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5653 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5654 short_channel_id: 2,
5657 cltv_expiry_delta: 0,
5658 htlc_minimum_msat: 0,
5659 htlc_maximum_msat: 100_000,
5661 fee_proportional_millionths: 0,
5662 excess_data: Vec::new()
5664 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5665 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5666 short_channel_id: 7,
5669 cltv_expiry_delta: 0,
5670 htlc_minimum_msat: 0,
5671 htlc_maximum_msat: 100_000,
5673 fee_proportional_millionths: 0,
5674 excess_data: Vec::new()
5677 // Path via {node0, node2} is channels {1, 3, 5}.
5678 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5679 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5680 short_channel_id: 1,
5683 cltv_expiry_delta: 0,
5684 htlc_minimum_msat: 0,
5685 htlc_maximum_msat: 100_000,
5687 fee_proportional_millionths: 0,
5688 excess_data: Vec::new()
5690 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5691 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5692 short_channel_id: 3,
5695 cltv_expiry_delta: 0,
5696 htlc_minimum_msat: 0,
5697 htlc_maximum_msat: 100_000,
5699 fee_proportional_millionths: 0,
5700 excess_data: Vec::new()
5703 // Capacity of 200 sats because this channel will be used by 3rd path as well.
5704 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5705 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5706 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5707 short_channel_id: 5,
5710 cltv_expiry_delta: 0,
5711 htlc_minimum_msat: 0,
5712 htlc_maximum_msat: 200_000,
5714 fee_proportional_millionths: 0,
5715 excess_data: Vec::new()
5718 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
5719 // Add 100 sats to the capacities of {12, 13}, because these channels
5720 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
5721 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5722 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5723 short_channel_id: 12,
5726 cltv_expiry_delta: 0,
5727 htlc_minimum_msat: 0,
5728 htlc_maximum_msat: 200_000,
5730 fee_proportional_millionths: 0,
5731 excess_data: Vec::new()
5733 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5734 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5735 short_channel_id: 13,
5738 cltv_expiry_delta: 0,
5739 htlc_minimum_msat: 0,
5740 htlc_maximum_msat: 200_000,
5742 fee_proportional_millionths: 0,
5743 excess_data: Vec::new()
5746 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5747 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5748 short_channel_id: 6,
5751 cltv_expiry_delta: 0,
5752 htlc_minimum_msat: 0,
5753 htlc_maximum_msat: 100_000,
5754 fee_base_msat: 1_000,
5755 fee_proportional_millionths: 0,
5756 excess_data: Vec::new()
5758 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5759 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5760 short_channel_id: 11,
5763 cltv_expiry_delta: 0,
5764 htlc_minimum_msat: 0,
5765 htlc_maximum_msat: 100_000,
5767 fee_proportional_millionths: 0,
5768 excess_data: Vec::new()
5771 // Path via {node7, node2} is channels {12, 13, 5}.
5772 // We already limited them to 200 sats (they are used twice for 100 sats).
5773 // Nothing to do here.
5776 // Now, attempt to route 180 sats.
5777 // Our algorithm should provide us with these 2 paths.
5778 let route_params = RouteParameters::from_payment_params_and_value(
5779 payment_params, 180_000);
5780 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5781 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5782 assert_eq!(route.paths.len(), 2);
5784 let mut total_value_transferred_msat = 0;
5785 let mut total_paid_msat = 0;
5786 for path in &route.paths {
5787 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5788 total_value_transferred_msat += path.final_value_msat();
5789 for hop in &path.hops {
5790 total_paid_msat += hop.fee_msat;
5793 // If we paid fee, this would be higher.
5794 assert_eq!(total_value_transferred_msat, 180_000);
5795 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
5796 assert_eq!(total_fees_paid, 0);
5801 fn fees_on_mpp_route_test() {
5802 // This test makes sure that MPP algorithm properly takes into account
5803 // fees charged on the channels, by making the fees impactful:
5804 // if the fee is not properly accounted for, the behavior is different.
5805 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5806 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5807 let scorer = ln_test_utils::TestScorer::new();
5808 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5809 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5810 let config = UserConfig::default();
5811 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
5812 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5815 // We need a route consisting of 2 paths:
5816 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
5817 // We will route 200 sats, Each path will have 100 sats capacity.
5819 // This test is not particularly stable: e.g.,
5820 // there's a way to route via {node0, node2, node4}.
5821 // It works while pathfinding is deterministic, but can be broken otherwise.
5822 // It's fine to ignore this concern for now.
5824 // Disable other potential paths.
5825 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5826 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5827 short_channel_id: 2,
5830 cltv_expiry_delta: 0,
5831 htlc_minimum_msat: 0,
5832 htlc_maximum_msat: 100_000,
5834 fee_proportional_millionths: 0,
5835 excess_data: Vec::new()
5838 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5839 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5840 short_channel_id: 7,
5843 cltv_expiry_delta: 0,
5844 htlc_minimum_msat: 0,
5845 htlc_maximum_msat: 100_000,
5847 fee_proportional_millionths: 0,
5848 excess_data: Vec::new()
5851 // Path via {node0, node2} is channels {1, 3, 5}.
5852 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5853 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5854 short_channel_id: 1,
5857 cltv_expiry_delta: 0,
5858 htlc_minimum_msat: 0,
5859 htlc_maximum_msat: 100_000,
5861 fee_proportional_millionths: 0,
5862 excess_data: Vec::new()
5864 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5865 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5866 short_channel_id: 3,
5869 cltv_expiry_delta: 0,
5870 htlc_minimum_msat: 0,
5871 htlc_maximum_msat: 100_000,
5873 fee_proportional_millionths: 0,
5874 excess_data: Vec::new()
5877 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5878 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5879 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5880 short_channel_id: 5,
5883 cltv_expiry_delta: 0,
5884 htlc_minimum_msat: 0,
5885 htlc_maximum_msat: 100_000,
5887 fee_proportional_millionths: 0,
5888 excess_data: Vec::new()
5891 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
5892 // All channels should be 100 sats capacity. But for the fee experiment,
5893 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
5894 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
5895 // 100 sats (and pay 150 sats in fees for the use of channel 6),
5896 // so no matter how large are other channels,
5897 // the whole path will be limited by 100 sats with just these 2 conditions:
5898 // - channel 12 capacity is 250 sats
5899 // - fee for channel 6 is 150 sats
5900 // Let's test this by enforcing these 2 conditions and removing other limits.
5901 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5902 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5903 short_channel_id: 12,
5906 cltv_expiry_delta: 0,
5907 htlc_minimum_msat: 0,
5908 htlc_maximum_msat: 250_000,
5910 fee_proportional_millionths: 0,
5911 excess_data: Vec::new()
5913 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5914 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5915 short_channel_id: 13,
5918 cltv_expiry_delta: 0,
5919 htlc_minimum_msat: 0,
5920 htlc_maximum_msat: MAX_VALUE_MSAT,
5922 fee_proportional_millionths: 0,
5923 excess_data: Vec::new()
5926 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5927 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5928 short_channel_id: 6,
5931 cltv_expiry_delta: 0,
5932 htlc_minimum_msat: 0,
5933 htlc_maximum_msat: MAX_VALUE_MSAT,
5934 fee_base_msat: 150_000,
5935 fee_proportional_millionths: 0,
5936 excess_data: Vec::new()
5938 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5939 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5940 short_channel_id: 11,
5943 cltv_expiry_delta: 0,
5944 htlc_minimum_msat: 0,
5945 htlc_maximum_msat: MAX_VALUE_MSAT,
5947 fee_proportional_millionths: 0,
5948 excess_data: Vec::new()
5952 // Attempt to route more than available results in a failure.
5953 let route_params = RouteParameters::from_payment_params_and_value(
5954 payment_params.clone(), 210_000);
5955 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5956 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5957 &scorer, &Default::default(), &random_seed_bytes) {
5958 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5959 } else { panic!(); }
5963 // Attempt to route while setting max_total_routing_fee_msat to 149_999 results in a failure.
5964 let route_params = RouteParameters { payment_params: payment_params.clone(), final_value_msat: 200_000,
5965 max_total_routing_fee_msat: Some(149_999) };
5966 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5967 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5968 &scorer, &Default::default(), &random_seed_bytes) {
5969 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5970 } else { panic!(); }
5974 // Now, attempt to route 200 sats (exact amount we can route).
5975 let route_params = RouteParameters { payment_params: payment_params.clone(), final_value_msat: 200_000,
5976 max_total_routing_fee_msat: Some(150_000) };
5977 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5978 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5979 assert_eq!(route.paths.len(), 2);
5981 let mut total_amount_paid_msat = 0;
5982 for path in &route.paths {
5983 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5984 total_amount_paid_msat += path.final_value_msat();
5986 assert_eq!(total_amount_paid_msat, 200_000);
5987 assert_eq!(route.get_total_fees(), 150_000);
5992 fn mpp_with_last_hops() {
5993 // Previously, if we tried to send an MPP payment to a destination which was only reachable
5994 // via a single last-hop route hint, we'd fail to route if we first collected routes
5995 // totaling close but not quite enough to fund the full payment.
5997 // This was because we considered last-hop hints to have exactly the sought payment amount
5998 // instead of the amount we were trying to collect, needlessly limiting our path searching
5999 // at the very first hop.
6001 // Specifically, this interacted with our "all paths must fund at least 5% of total target"
6002 // criterion to cause us to refuse all routes at the last hop hint which would be considered
6003 // to only have the remaining to-collect amount in available liquidity.
6005 // This bug appeared in production in some specific channel configurations.
6006 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6007 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
6008 let scorer = ln_test_utils::TestScorer::new();
6009 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6010 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6011 let config = UserConfig::default();
6012 let payment_params = PaymentParameters::from_node_id(PublicKey::from_slice(&[02; 33]).unwrap(), 42)
6013 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap()
6014 .with_route_hints(vec![RouteHint(vec![RouteHintHop {
6015 src_node_id: nodes[2],
6016 short_channel_id: 42,
6017 fees: RoutingFees { base_msat: 0, proportional_millionths: 0 },
6018 cltv_expiry_delta: 42,
6019 htlc_minimum_msat: None,
6020 htlc_maximum_msat: None,
6021 }])]).unwrap().with_max_channel_saturation_power_of_half(0);
6023 // Keep only two paths from us to nodes[2], both with a 99sat HTLC maximum, with one with
6024 // no fee and one with a 1msat fee. Previously, trying to route 100 sats to nodes[2] here
6025 // would first use the no-fee route and then fail to find a path along the second route as
6026 // we think we can only send up to 1 additional sat over the last-hop but refuse to as its
6027 // under 5% of our payment amount.
6028 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6029 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6030 short_channel_id: 1,
6033 cltv_expiry_delta: (5 << 4) | 5,
6034 htlc_minimum_msat: 0,
6035 htlc_maximum_msat: 99_000,
6036 fee_base_msat: u32::max_value(),
6037 fee_proportional_millionths: u32::max_value(),
6038 excess_data: Vec::new()
6040 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6041 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6042 short_channel_id: 2,
6045 cltv_expiry_delta: (5 << 4) | 3,
6046 htlc_minimum_msat: 0,
6047 htlc_maximum_msat: 99_000,
6048 fee_base_msat: u32::max_value(),
6049 fee_proportional_millionths: u32::max_value(),
6050 excess_data: Vec::new()
6052 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6053 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6054 short_channel_id: 4,
6057 cltv_expiry_delta: (4 << 4) | 1,
6058 htlc_minimum_msat: 0,
6059 htlc_maximum_msat: MAX_VALUE_MSAT,
6061 fee_proportional_millionths: 0,
6062 excess_data: Vec::new()
6064 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
6065 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6066 short_channel_id: 13,
6068 flags: 0|2, // Channel disabled
6069 cltv_expiry_delta: (13 << 4) | 1,
6070 htlc_minimum_msat: 0,
6071 htlc_maximum_msat: MAX_VALUE_MSAT,
6073 fee_proportional_millionths: 2000000,
6074 excess_data: Vec::new()
6077 // Get a route for 100 sats and check that we found the MPP route no problem and didn't
6079 let route_params = RouteParameters::from_payment_params_and_value(
6080 payment_params, 100_000);
6081 let mut route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6082 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6083 assert_eq!(route.paths.len(), 2);
6084 route.paths.sort_by_key(|path| path.hops[0].short_channel_id);
6085 // Paths are manually ordered ordered by SCID, so:
6086 // * the first is channel 1 (0 fee, but 99 sat maximum) -> channel 3 -> channel 42
6087 // * the second is channel 2 (1 msat fee) -> channel 4 -> channel 42
6088 assert_eq!(route.paths[0].hops[0].short_channel_id, 1);
6089 assert_eq!(route.paths[0].hops[0].fee_msat, 0);
6090 assert_eq!(route.paths[0].hops[2].fee_msat, 99_000);
6091 assert_eq!(route.paths[1].hops[0].short_channel_id, 2);
6092 assert_eq!(route.paths[1].hops[0].fee_msat, 1);
6093 assert_eq!(route.paths[1].hops[2].fee_msat, 1_000);
6094 assert_eq!(route.get_total_fees(), 1);
6095 assert_eq!(route.get_total_amount(), 100_000);
6099 fn drop_lowest_channel_mpp_route_test() {
6100 // This test checks that low-capacity channel is dropped when after
6101 // path finding we realize that we found more capacity than we need.
6102 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6103 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
6104 let scorer = ln_test_utils::TestScorer::new();
6105 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6106 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6107 let config = UserConfig::default();
6108 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
6109 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
6111 .with_max_channel_saturation_power_of_half(0);
6113 // We need a route consisting of 3 paths:
6114 // From our node to node2 via node0, node7, node1 (three paths one hop each).
6116 // The first and the second paths should be sufficient, but the third should be
6117 // cheaper, so that we select it but drop later.
6119 // First, we set limits on these (previously unlimited) channels.
6120 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
6122 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
6123 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6124 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6125 short_channel_id: 1,
6128 cltv_expiry_delta: 0,
6129 htlc_minimum_msat: 0,
6130 htlc_maximum_msat: 100_000,
6132 fee_proportional_millionths: 0,
6133 excess_data: Vec::new()
6135 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
6136 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6137 short_channel_id: 3,
6140 cltv_expiry_delta: 0,
6141 htlc_minimum_msat: 0,
6142 htlc_maximum_msat: 50_000,
6144 fee_proportional_millionths: 0,
6145 excess_data: Vec::new()
6148 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
6149 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6150 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6151 short_channel_id: 12,
6154 cltv_expiry_delta: 0,
6155 htlc_minimum_msat: 0,
6156 htlc_maximum_msat: 60_000,
6158 fee_proportional_millionths: 0,
6159 excess_data: Vec::new()
6161 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
6162 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6163 short_channel_id: 13,
6166 cltv_expiry_delta: 0,
6167 htlc_minimum_msat: 0,
6168 htlc_maximum_msat: 60_000,
6170 fee_proportional_millionths: 0,
6171 excess_data: Vec::new()
6174 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
6175 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6176 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6177 short_channel_id: 2,
6180 cltv_expiry_delta: 0,
6181 htlc_minimum_msat: 0,
6182 htlc_maximum_msat: 20_000,
6184 fee_proportional_millionths: 0,
6185 excess_data: Vec::new()
6187 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6188 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6189 short_channel_id: 4,
6192 cltv_expiry_delta: 0,
6193 htlc_minimum_msat: 0,
6194 htlc_maximum_msat: 20_000,
6196 fee_proportional_millionths: 0,
6197 excess_data: Vec::new()
6201 // Attempt to route more than available results in a failure.
6202 let route_params = RouteParameters::from_payment_params_and_value(
6203 payment_params.clone(), 150_000);
6204 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
6205 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
6206 &scorer, &Default::default(), &random_seed_bytes) {
6207 assert_eq!(err, "Failed to find a sufficient route to the given destination");
6208 } else { panic!(); }
6212 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
6213 // Our algorithm should provide us with these 3 paths.
6214 let route_params = RouteParameters::from_payment_params_and_value(
6215 payment_params.clone(), 125_000);
6216 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6217 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6218 assert_eq!(route.paths.len(), 3);
6219 let mut total_amount_paid_msat = 0;
6220 for path in &route.paths {
6221 assert_eq!(path.hops.len(), 2);
6222 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
6223 total_amount_paid_msat += path.final_value_msat();
6225 assert_eq!(total_amount_paid_msat, 125_000);
6229 // Attempt to route without the last small cheap channel
6230 let route_params = RouteParameters::from_payment_params_and_value(
6231 payment_params, 90_000);
6232 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6233 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6234 assert_eq!(route.paths.len(), 2);
6235 let mut total_amount_paid_msat = 0;
6236 for path in &route.paths {
6237 assert_eq!(path.hops.len(), 2);
6238 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
6239 total_amount_paid_msat += path.final_value_msat();
6241 assert_eq!(total_amount_paid_msat, 90_000);
6246 fn min_criteria_consistency() {
6247 // Test that we don't use an inconsistent metric between updating and walking nodes during
6248 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
6249 // was updated with a different criterion from the heap sorting, resulting in loops in
6250 // calculated paths. We test for that specific case here.
6252 // We construct a network that looks like this:
6254 // node2 -1(3)2- node3
6258 // node1 -1(5)2- node4 -1(1)2- node6
6264 // We create a loop on the side of our real path - our destination is node 6, with a
6265 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
6266 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
6267 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
6268 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
6269 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
6270 // "previous hop" being set to node 3, creating a loop in the path.
6271 let secp_ctx = Secp256k1::new();
6272 let logger = Arc::new(ln_test_utils::TestLogger::new());
6273 let network = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
6274 let gossip_sync = P2PGossipSync::new(Arc::clone(&network), None, Arc::clone(&logger));
6275 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
6276 let scorer = ln_test_utils::TestScorer::new();
6277 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6278 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6279 let payment_params = PaymentParameters::from_node_id(nodes[6], 42);
6281 add_channel(&gossip_sync, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
6282 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6283 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6284 short_channel_id: 6,
6287 cltv_expiry_delta: (6 << 4) | 0,
6288 htlc_minimum_msat: 0,
6289 htlc_maximum_msat: MAX_VALUE_MSAT,
6291 fee_proportional_millionths: 0,
6292 excess_data: Vec::new()
6294 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
6296 add_channel(&gossip_sync, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
6297 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6298 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6299 short_channel_id: 5,
6302 cltv_expiry_delta: (5 << 4) | 0,
6303 htlc_minimum_msat: 0,
6304 htlc_maximum_msat: MAX_VALUE_MSAT,
6306 fee_proportional_millionths: 0,
6307 excess_data: Vec::new()
6309 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
6311 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
6312 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
6313 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6314 short_channel_id: 4,
6317 cltv_expiry_delta: (4 << 4) | 0,
6318 htlc_minimum_msat: 0,
6319 htlc_maximum_msat: MAX_VALUE_MSAT,
6321 fee_proportional_millionths: 0,
6322 excess_data: Vec::new()
6324 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
6326 add_channel(&gossip_sync, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
6327 update_channel(&gossip_sync, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
6328 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6329 short_channel_id: 3,
6332 cltv_expiry_delta: (3 << 4) | 0,
6333 htlc_minimum_msat: 0,
6334 htlc_maximum_msat: MAX_VALUE_MSAT,
6336 fee_proportional_millionths: 0,
6337 excess_data: Vec::new()
6339 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
6341 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
6342 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
6343 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6344 short_channel_id: 2,
6347 cltv_expiry_delta: (2 << 4) | 0,
6348 htlc_minimum_msat: 0,
6349 htlc_maximum_msat: MAX_VALUE_MSAT,
6351 fee_proportional_millionths: 0,
6352 excess_data: Vec::new()
6355 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
6356 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
6357 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6358 short_channel_id: 1,
6361 cltv_expiry_delta: (1 << 4) | 0,
6362 htlc_minimum_msat: 100,
6363 htlc_maximum_msat: MAX_VALUE_MSAT,
6365 fee_proportional_millionths: 0,
6366 excess_data: Vec::new()
6368 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
6371 // Now ensure the route flows simply over nodes 1 and 4 to 6.
6372 let route_params = RouteParameters::from_payment_params_and_value(
6373 payment_params, 10_000);
6374 let route = get_route(&our_id, &route_params, &network.read_only(), None,
6375 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6376 assert_eq!(route.paths.len(), 1);
6377 assert_eq!(route.paths[0].hops.len(), 3);
6379 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
6380 assert_eq!(route.paths[0].hops[0].short_channel_id, 6);
6381 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
6382 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (5 << 4) | 0);
6383 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(1));
6384 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(6));
6386 assert_eq!(route.paths[0].hops[1].pubkey, nodes[4]);
6387 assert_eq!(route.paths[0].hops[1].short_channel_id, 5);
6388 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
6389 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (1 << 4) | 0);
6390 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(4));
6391 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(5));
6393 assert_eq!(route.paths[0].hops[2].pubkey, nodes[6]);
6394 assert_eq!(route.paths[0].hops[2].short_channel_id, 1);
6395 assert_eq!(route.paths[0].hops[2].fee_msat, 10_000);
6396 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 42);
6397 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(6));
6398 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(1));
6404 fn exact_fee_liquidity_limit() {
6405 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
6406 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
6407 // we calculated fees on a higher value, resulting in us ignoring such paths.
6408 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6409 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
6410 let scorer = ln_test_utils::TestScorer::new();
6411 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6412 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6413 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
6415 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
6417 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6418 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6419 short_channel_id: 2,
6422 cltv_expiry_delta: 0,
6423 htlc_minimum_msat: 0,
6424 htlc_maximum_msat: 85_000,
6426 fee_proportional_millionths: 0,
6427 excess_data: Vec::new()
6430 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6431 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6432 short_channel_id: 12,
6435 cltv_expiry_delta: (4 << 4) | 1,
6436 htlc_minimum_msat: 0,
6437 htlc_maximum_msat: 270_000,
6439 fee_proportional_millionths: 1000000,
6440 excess_data: Vec::new()
6444 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
6445 // 200% fee charged channel 13 in the 1-to-2 direction.
6446 let mut route_params = RouteParameters::from_payment_params_and_value(
6447 payment_params, 90_000);
6448 route_params.max_total_routing_fee_msat = Some(90_000*2);
6449 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6450 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6451 assert_eq!(route.paths.len(), 1);
6452 assert_eq!(route.paths[0].hops.len(), 2);
6454 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
6455 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
6456 assert_eq!(route.paths[0].hops[0].fee_msat, 90_000*2);
6457 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
6458 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(8));
6459 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(12));
6461 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
6462 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
6463 assert_eq!(route.paths[0].hops[1].fee_msat, 90_000);
6464 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
6465 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
6466 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
6471 fn htlc_max_reduction_below_min() {
6472 // Test that if, while walking the graph, we reduce the value being sent to meet an
6473 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
6474 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
6475 // resulting in us thinking there is no possible path, even if other paths exist.
6476 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6477 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
6478 let scorer = ln_test_utils::TestScorer::new();
6479 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6480 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6481 let config = UserConfig::default();
6482 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
6483 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
6486 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
6487 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
6488 // then try to send 90_000.
6489 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6490 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6491 short_channel_id: 2,
6494 cltv_expiry_delta: 0,
6495 htlc_minimum_msat: 0,
6496 htlc_maximum_msat: 80_000,
6498 fee_proportional_millionths: 0,
6499 excess_data: Vec::new()
6501 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6502 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6503 short_channel_id: 4,
6506 cltv_expiry_delta: (4 << 4) | 1,
6507 htlc_minimum_msat: 90_000,
6508 htlc_maximum_msat: MAX_VALUE_MSAT,
6510 fee_proportional_millionths: 0,
6511 excess_data: Vec::new()
6515 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
6516 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
6517 // expensive) channels 12-13 path.
6518 let mut route_params = RouteParameters::from_payment_params_and_value(
6519 payment_params, 90_000);
6520 route_params.max_total_routing_fee_msat = Some(90_000*2);
6521 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6522 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6523 assert_eq!(route.paths.len(), 1);
6524 assert_eq!(route.paths[0].hops.len(), 2);
6526 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
6527 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
6528 assert_eq!(route.paths[0].hops[0].fee_msat, 90_000*2);
6529 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
6530 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(8));
6531 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(12));
6533 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
6534 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
6535 assert_eq!(route.paths[0].hops[1].fee_msat, 90_000);
6536 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
6537 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), channelmanager::provided_bolt11_invoice_features(&config).le_flags());
6538 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
6543 fn multiple_direct_first_hops() {
6544 // Previously we'd only ever considered one first hop path per counterparty.
6545 // However, as we don't restrict users to one channel per peer, we really need to support
6546 // looking at all first hop paths.
6547 // Here we test that we do not ignore all-but-the-last first hop paths per counterparty (as
6548 // we used to do by overwriting the `first_hop_targets` hashmap entry) and that we can MPP
6549 // route over multiple channels with the same first hop.
6550 let secp_ctx = Secp256k1::new();
6551 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6552 let logger = Arc::new(ln_test_utils::TestLogger::new());
6553 let network_graph = NetworkGraph::new(Network::Testnet, Arc::clone(&logger));
6554 let scorer = ln_test_utils::TestScorer::new();
6555 let config = UserConfig::default();
6556 let payment_params = PaymentParameters::from_node_id(nodes[0], 42)
6557 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
6559 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6560 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6563 let route_params = RouteParameters::from_payment_params_and_value(
6564 payment_params.clone(), 100_000);
6565 let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
6566 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 200_000),
6567 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 10_000),
6568 ]), Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6569 assert_eq!(route.paths.len(), 1);
6570 assert_eq!(route.paths[0].hops.len(), 1);
6572 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
6573 assert_eq!(route.paths[0].hops[0].short_channel_id, 3);
6574 assert_eq!(route.paths[0].hops[0].fee_msat, 100_000);
6577 let route_params = RouteParameters::from_payment_params_and_value(
6578 payment_params.clone(), 100_000);
6579 let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
6580 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6581 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6582 ]), Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6583 assert_eq!(route.paths.len(), 2);
6584 assert_eq!(route.paths[0].hops.len(), 1);
6585 assert_eq!(route.paths[1].hops.len(), 1);
6587 assert!((route.paths[0].hops[0].short_channel_id == 3 && route.paths[1].hops[0].short_channel_id == 2) ||
6588 (route.paths[0].hops[0].short_channel_id == 2 && route.paths[1].hops[0].short_channel_id == 3));
6590 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
6591 assert_eq!(route.paths[0].hops[0].fee_msat, 50_000);
6593 assert_eq!(route.paths[1].hops[0].pubkey, nodes[0]);
6594 assert_eq!(route.paths[1].hops[0].fee_msat, 50_000);
6598 // If we have a bunch of outbound channels to the same node, where most are not
6599 // sufficient to pay the full payment, but one is, we should default to just using the
6600 // one single channel that has sufficient balance, avoiding MPP.
6602 // If we have several options above the 3xpayment value threshold, we should pick the
6603 // smallest of them, avoiding further fragmenting our available outbound balance to
6605 let route_params = RouteParameters::from_payment_params_and_value(
6606 payment_params, 100_000);
6607 let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
6608 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6609 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6610 &get_channel_details(Some(5), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6611 &get_channel_details(Some(6), nodes[0], channelmanager::provided_init_features(&config), 300_000),
6612 &get_channel_details(Some(7), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6613 &get_channel_details(Some(8), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6614 &get_channel_details(Some(9), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6615 &get_channel_details(Some(4), nodes[0], channelmanager::provided_init_features(&config), 1_000_000),
6616 ]), Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6617 assert_eq!(route.paths.len(), 1);
6618 assert_eq!(route.paths[0].hops.len(), 1);
6620 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
6621 assert_eq!(route.paths[0].hops[0].short_channel_id, 6);
6622 assert_eq!(route.paths[0].hops[0].fee_msat, 100_000);
6627 fn prefers_shorter_route_with_higher_fees() {
6628 let (secp_ctx, network_graph, _, _, logger) = build_graph();
6629 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6630 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
6632 // Without penalizing each hop 100 msats, a longer path with lower fees is chosen.
6633 let scorer = ln_test_utils::TestScorer::new();
6634 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6635 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6636 let route_params = RouteParameters::from_payment_params_and_value(
6637 payment_params.clone(), 100);
6638 let route = get_route( &our_id, &route_params, &network_graph.read_only(), None,
6639 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6640 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6642 assert_eq!(route.get_total_fees(), 100);
6643 assert_eq!(route.get_total_amount(), 100);
6644 assert_eq!(path, vec![2, 4, 6, 11, 8]);
6646 // Applying a 100 msat penalty to each hop results in taking channels 7 and 10 to nodes[6]
6647 // from nodes[2] rather than channel 6, 11, and 8, even though the longer path is cheaper.
6648 let scorer = FixedPenaltyScorer::with_penalty(100);
6649 let route_params = RouteParameters::from_payment_params_and_value(
6650 payment_params, 100);
6651 let route = get_route( &our_id, &route_params, &network_graph.read_only(), None,
6652 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6653 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6655 assert_eq!(route.get_total_fees(), 300);
6656 assert_eq!(route.get_total_amount(), 100);
6657 assert_eq!(path, vec![2, 4, 7, 10]);
6660 struct BadChannelScorer {
6661 short_channel_id: u64,
6665 impl Writeable for BadChannelScorer {
6666 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
6668 impl ScoreLookUp for BadChannelScorer {
6669 type ScoreParams = ();
6670 fn channel_penalty_msat(&self, candidate: &CandidateRouteHop, _: ChannelUsage, _score_params:&Self::ScoreParams) -> u64 {
6671 if candidate.short_channel_id() == Some(self.short_channel_id) { u64::max_value() } else { 0 }
6675 struct BadNodeScorer {
6680 impl Writeable for BadNodeScorer {
6681 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
6684 impl ScoreLookUp for BadNodeScorer {
6685 type ScoreParams = ();
6686 fn channel_penalty_msat(&self, candidate: &CandidateRouteHop, _: ChannelUsage, _score_params:&Self::ScoreParams) -> u64 {
6687 if candidate.target() == Some(self.node_id) { u64::max_value() } else { 0 }
6692 fn avoids_routing_through_bad_channels_and_nodes() {
6693 let (secp_ctx, network, _, _, logger) = build_graph();
6694 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6695 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
6696 let network_graph = network.read_only();
6698 // A path to nodes[6] exists when no penalties are applied to any channel.
6699 let scorer = ln_test_utils::TestScorer::new();
6700 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6701 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6702 let route_params = RouteParameters::from_payment_params_and_value(
6703 payment_params, 100);
6704 let route = get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6705 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6706 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6708 assert_eq!(route.get_total_fees(), 100);
6709 assert_eq!(route.get_total_amount(), 100);
6710 assert_eq!(path, vec![2, 4, 6, 11, 8]);
6712 // A different path to nodes[6] exists if channel 6 cannot be routed over.
6713 let scorer = BadChannelScorer { short_channel_id: 6 };
6714 let route = get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6715 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6716 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6718 assert_eq!(route.get_total_fees(), 300);
6719 assert_eq!(route.get_total_amount(), 100);
6720 assert_eq!(path, vec![2, 4, 7, 10]);
6722 // A path to nodes[6] does not exist if nodes[2] cannot be routed through.
6723 let scorer = BadNodeScorer { node_id: NodeId::from_pubkey(&nodes[2]) };
6724 match get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6725 &scorer, &Default::default(), &random_seed_bytes) {
6726 Err(LightningError { err, .. } ) => {
6727 assert_eq!(err, "Failed to find a path to the given destination");
6729 Ok(_) => panic!("Expected error"),
6734 fn total_fees_single_path() {
6736 paths: vec![Path { hops: vec![
6738 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
6739 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6740 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0, maybe_announced_channel: true,
6743 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
6744 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6745 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0, maybe_announced_channel: true,
6748 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
6749 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6750 short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0, maybe_announced_channel: true,
6752 ], blinded_tail: None }],
6756 assert_eq!(route.get_total_fees(), 250);
6757 assert_eq!(route.get_total_amount(), 225);
6761 fn total_fees_multi_path() {
6763 paths: vec![Path { hops: vec![
6765 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
6766 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6767 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0, maybe_announced_channel: true,
6770 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
6771 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6772 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0, maybe_announced_channel: true,
6774 ], blinded_tail: None }, Path { hops: vec![
6776 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
6777 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6778 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0, maybe_announced_channel: true,
6781 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
6782 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6783 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0, maybe_announced_channel: true,
6785 ], blinded_tail: None }],
6789 assert_eq!(route.get_total_fees(), 200);
6790 assert_eq!(route.get_total_amount(), 300);
6794 fn total_empty_route_no_panic() {
6795 // In an earlier version of `Route::get_total_fees` and `Route::get_total_amount`, they
6796 // would both panic if the route was completely empty. We test to ensure they return 0
6797 // here, even though its somewhat nonsensical as a route.
6798 let route = Route { paths: Vec::new(), route_params: None };
6800 assert_eq!(route.get_total_fees(), 0);
6801 assert_eq!(route.get_total_amount(), 0);
6805 fn limits_total_cltv_delta() {
6806 let (secp_ctx, network, _, _, logger) = build_graph();
6807 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6808 let network_graph = network.read_only();
6810 let scorer = ln_test_utils::TestScorer::new();
6812 // Make sure that generally there is at least one route available
6813 let feasible_max_total_cltv_delta = 1008;
6814 let feasible_payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
6815 .with_max_total_cltv_expiry_delta(feasible_max_total_cltv_delta);
6816 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6817 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6818 let route_params = RouteParameters::from_payment_params_and_value(
6819 feasible_payment_params, 100);
6820 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6821 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6822 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6823 assert_ne!(path.len(), 0);
6825 // But not if we exclude all paths on the basis of their accumulated CLTV delta
6826 let fail_max_total_cltv_delta = 23;
6827 let fail_payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
6828 .with_max_total_cltv_expiry_delta(fail_max_total_cltv_delta);
6829 let route_params = RouteParameters::from_payment_params_and_value(
6830 fail_payment_params, 100);
6831 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
6832 &Default::default(), &random_seed_bytes)
6834 Err(LightningError { err, .. } ) => {
6835 assert_eq!(err, "Failed to find a path to the given destination");
6837 Ok(_) => panic!("Expected error"),
6842 fn avoids_recently_failed_paths() {
6843 // Ensure that the router always avoids all of the `previously_failed_channels` channels by
6844 // randomly inserting channels into it until we can't find a route anymore.
6845 let (secp_ctx, network, _, _, logger) = build_graph();
6846 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6847 let network_graph = network.read_only();
6849 let scorer = ln_test_utils::TestScorer::new();
6850 let mut payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
6851 .with_max_path_count(1);
6852 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6853 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6855 // We should be able to find a route initially, and then after we fail a few random
6856 // channels eventually we won't be able to any longer.
6857 let route_params = RouteParameters::from_payment_params_and_value(
6858 payment_params.clone(), 100);
6859 assert!(get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6860 &scorer, &Default::default(), &random_seed_bytes).is_ok());
6862 let route_params = RouteParameters::from_payment_params_and_value(
6863 payment_params.clone(), 100);
6864 if let Ok(route) = get_route(&our_id, &route_params, &network_graph, None,
6865 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes)
6867 for chan in route.paths[0].hops.iter() {
6868 assert!(!payment_params.previously_failed_channels.contains(&chan.short_channel_id));
6870 let victim = (u64::from_ne_bytes(random_seed_bytes[0..8].try_into().unwrap()) as usize)
6871 % route.paths[0].hops.len();
6872 payment_params.previously_failed_channels.push(route.paths[0].hops[victim].short_channel_id);
6878 fn limits_path_length() {
6879 let (secp_ctx, network, _, _, logger) = build_line_graph();
6880 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6881 let network_graph = network.read_only();
6883 let scorer = ln_test_utils::TestScorer::new();
6884 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6885 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6887 // First check we can actually create a long route on this graph.
6888 let feasible_payment_params = PaymentParameters::from_node_id(nodes[18], 0);
6889 let route_params = RouteParameters::from_payment_params_and_value(
6890 feasible_payment_params, 100);
6891 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6892 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6893 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6894 assert!(path.len() == MAX_PATH_LENGTH_ESTIMATE.into());
6896 // But we can't create a path surpassing the MAX_PATH_LENGTH_ESTIMATE limit.
6897 let fail_payment_params = PaymentParameters::from_node_id(nodes[19], 0);
6898 let route_params = RouteParameters::from_payment_params_and_value(
6899 fail_payment_params, 100);
6900 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
6901 &Default::default(), &random_seed_bytes)
6903 Err(LightningError { err, .. } ) => {
6904 assert_eq!(err, "Failed to find a path to the given destination");
6906 Ok(_) => panic!("Expected error"),
6911 fn adds_and_limits_cltv_offset() {
6912 let (secp_ctx, network_graph, _, _, logger) = build_graph();
6913 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6915 let scorer = ln_test_utils::TestScorer::new();
6917 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
6918 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6919 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6920 let route_params = RouteParameters::from_payment_params_and_value(
6921 payment_params.clone(), 100);
6922 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6923 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6924 assert_eq!(route.paths.len(), 1);
6926 let cltv_expiry_deltas_before = route.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
6928 // Check whether the offset added to the last hop by default is in [1 .. DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA]
6929 let mut route_default = route.clone();
6930 add_random_cltv_offset(&mut route_default, &payment_params, &network_graph.read_only(), &random_seed_bytes);
6931 let cltv_expiry_deltas_default = route_default.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
6932 assert_eq!(cltv_expiry_deltas_before.split_last().unwrap().1, cltv_expiry_deltas_default.split_last().unwrap().1);
6933 assert!(cltv_expiry_deltas_default.last() > cltv_expiry_deltas_before.last());
6934 assert!(cltv_expiry_deltas_default.last().unwrap() <= &DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA);
6936 // Check that no offset is added when we restrict the max_total_cltv_expiry_delta
6937 let mut route_limited = route.clone();
6938 let limited_max_total_cltv_expiry_delta = cltv_expiry_deltas_before.iter().sum();
6939 let limited_payment_params = payment_params.with_max_total_cltv_expiry_delta(limited_max_total_cltv_expiry_delta);
6940 add_random_cltv_offset(&mut route_limited, &limited_payment_params, &network_graph.read_only(), &random_seed_bytes);
6941 let cltv_expiry_deltas_limited = route_limited.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
6942 assert_eq!(cltv_expiry_deltas_before, cltv_expiry_deltas_limited);
6946 fn adds_plausible_cltv_offset() {
6947 let (secp_ctx, network, _, _, logger) = build_graph();
6948 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6949 let network_graph = network.read_only();
6950 let network_nodes = network_graph.nodes();
6951 let network_channels = network_graph.channels();
6952 let scorer = ln_test_utils::TestScorer::new();
6953 let payment_params = PaymentParameters::from_node_id(nodes[3], 0);
6954 let keys_manager = ln_test_utils::TestKeysInterface::new(&[4u8; 32], Network::Testnet);
6955 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6957 let route_params = RouteParameters::from_payment_params_and_value(
6958 payment_params.clone(), 100);
6959 let mut route = get_route(&our_id, &route_params, &network_graph, None,
6960 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6961 add_random_cltv_offset(&mut route, &payment_params, &network_graph, &random_seed_bytes);
6963 let mut path_plausibility = vec![];
6965 for p in route.paths {
6966 // 1. Select random observation point
6967 let mut prng = ChaCha20::new(&random_seed_bytes, &[0u8; 12]);
6968 let mut random_bytes = [0u8; ::core::mem::size_of::<usize>()];
6970 prng.process_in_place(&mut random_bytes);
6971 let random_path_index = usize::from_be_bytes(random_bytes).wrapping_rem(p.hops.len());
6972 let observation_point = NodeId::from_pubkey(&p.hops.get(random_path_index).unwrap().pubkey);
6974 // 2. Calculate what CLTV expiry delta we would observe there
6975 let observed_cltv_expiry_delta: u32 = p.hops[random_path_index..].iter().map(|h| h.cltv_expiry_delta).sum();
6977 // 3. Starting from the observation point, find candidate paths
6978 let mut candidates: VecDeque<(NodeId, Vec<u32>)> = VecDeque::new();
6979 candidates.push_back((observation_point, vec![]));
6981 let mut found_plausible_candidate = false;
6983 'candidate_loop: while let Some((cur_node_id, cur_path_cltv_deltas)) = candidates.pop_front() {
6984 if let Some(remaining) = observed_cltv_expiry_delta.checked_sub(cur_path_cltv_deltas.iter().sum::<u32>()) {
6985 if remaining == 0 || remaining.wrapping_rem(40) == 0 || remaining.wrapping_rem(144) == 0 {
6986 found_plausible_candidate = true;
6987 break 'candidate_loop;
6991 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
6992 for channel_id in &cur_node.channels {
6993 if let Some(channel_info) = network_channels.get(&channel_id) {
6994 if let Some((dir_info, next_id)) = channel_info.as_directed_from(&cur_node_id) {
6995 let next_cltv_expiry_delta = dir_info.direction().cltv_expiry_delta as u32;
6996 if cur_path_cltv_deltas.iter().sum::<u32>()
6997 .saturating_add(next_cltv_expiry_delta) <= observed_cltv_expiry_delta {
6998 let mut new_path_cltv_deltas = cur_path_cltv_deltas.clone();
6999 new_path_cltv_deltas.push(next_cltv_expiry_delta);
7000 candidates.push_back((*next_id, new_path_cltv_deltas));
7008 path_plausibility.push(found_plausible_candidate);
7010 assert!(path_plausibility.iter().all(|x| *x));
7014 fn builds_correct_path_from_hops() {
7015 let (secp_ctx, network, _, _, logger) = build_graph();
7016 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7017 let network_graph = network.read_only();
7019 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7020 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7022 let payment_params = PaymentParameters::from_node_id(nodes[3], 0);
7023 let hops = [nodes[1], nodes[2], nodes[4], nodes[3]];
7024 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
7025 let route = build_route_from_hops_internal(&our_id, &hops, &route_params, &network_graph,
7026 Arc::clone(&logger), &random_seed_bytes).unwrap();
7027 let route_hop_pubkeys = route.paths[0].hops.iter().map(|hop| hop.pubkey).collect::<Vec<_>>();
7028 assert_eq!(hops.len(), route.paths[0].hops.len());
7029 for (idx, hop_pubkey) in hops.iter().enumerate() {
7030 assert!(*hop_pubkey == route_hop_pubkeys[idx]);
7035 fn avoids_saturating_channels() {
7036 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
7037 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
7038 let decay_params = ProbabilisticScoringDecayParameters::default();
7039 let scorer = ProbabilisticScorer::new(decay_params, &*network_graph, Arc::clone(&logger));
7041 // Set the fee on channel 13 to 100% to match channel 4 giving us two equivalent paths (us
7042 // -> node 7 -> node2 and us -> node 1 -> node 2) which we should balance over.
7043 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
7044 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
7045 short_channel_id: 4,
7048 cltv_expiry_delta: (4 << 4) | 1,
7049 htlc_minimum_msat: 0,
7050 htlc_maximum_msat: 250_000_000,
7052 fee_proportional_millionths: 0,
7053 excess_data: Vec::new()
7055 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
7056 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
7057 short_channel_id: 13,
7060 cltv_expiry_delta: (13 << 4) | 1,
7061 htlc_minimum_msat: 0,
7062 htlc_maximum_msat: 250_000_000,
7064 fee_proportional_millionths: 0,
7065 excess_data: Vec::new()
7068 let config = UserConfig::default();
7069 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
7070 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
7072 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7073 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7074 // 100,000 sats is less than the available liquidity on each channel, set above.
7075 let route_params = RouteParameters::from_payment_params_and_value(
7076 payment_params, 100_000_000);
7077 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
7078 Arc::clone(&logger), &scorer, &ProbabilisticScoringFeeParameters::default(), &random_seed_bytes).unwrap();
7079 assert_eq!(route.paths.len(), 2);
7080 assert!((route.paths[0].hops[1].short_channel_id == 4 && route.paths[1].hops[1].short_channel_id == 13) ||
7081 (route.paths[1].hops[1].short_channel_id == 4 && route.paths[0].hops[1].short_channel_id == 13));
7084 #[cfg(not(feature = "no-std"))]
7085 pub(super) fn random_init_seed() -> u64 {
7086 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
7087 use core::hash::{BuildHasher, Hasher};
7088 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
7089 println!("Using seed of {}", seed);
7094 #[cfg(not(feature = "no-std"))]
7095 fn generate_routes() {
7096 use crate::routing::scoring::ProbabilisticScoringFeeParameters;
7098 let logger = ln_test_utils::TestLogger::new();
7099 let (graph, mut scorer) = match super::bench_utils::read_graph_scorer(&logger) {
7107 let params = ProbabilisticScoringFeeParameters::default();
7108 let features = super::Bolt11InvoiceFeatures::empty();
7110 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 0, 2);
7114 #[cfg(not(feature = "no-std"))]
7115 fn generate_routes_mpp() {
7116 use crate::routing::scoring::ProbabilisticScoringFeeParameters;
7118 let logger = ln_test_utils::TestLogger::new();
7119 let (graph, mut scorer) = match super::bench_utils::read_graph_scorer(&logger) {
7127 let params = ProbabilisticScoringFeeParameters::default();
7128 let features = channelmanager::provided_bolt11_invoice_features(&UserConfig::default());
7130 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 0, 2);
7134 #[cfg(not(feature = "no-std"))]
7135 fn generate_large_mpp_routes() {
7136 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
7138 let logger = ln_test_utils::TestLogger::new();
7139 let (graph, mut scorer) = match super::bench_utils::read_graph_scorer(&logger) {
7147 let params = ProbabilisticScoringFeeParameters::default();
7148 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &*graph, &logger);
7149 let features = channelmanager::provided_bolt11_invoice_features(&UserConfig::default());
7151 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 1_000_000, 2);
7155 fn honors_manual_penalties() {
7156 let (secp_ctx, network_graph, _, _, logger) = build_line_graph();
7157 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7159 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7160 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7162 let mut scorer_params = ProbabilisticScoringFeeParameters::default();
7163 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), Arc::clone(&network_graph), Arc::clone(&logger));
7165 // First check set manual penalties are returned by the scorer.
7166 let usage = ChannelUsage {
7168 inflight_htlc_msat: 0,
7169 effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_024_000, htlc_maximum_msat: 1_000 },
7171 scorer_params.set_manual_penalty(&NodeId::from_pubkey(&nodes[3]), 123);
7172 scorer_params.set_manual_penalty(&NodeId::from_pubkey(&nodes[4]), 456);
7173 let network_graph = network_graph.read_only();
7174 let channels = network_graph.channels();
7175 let channel = channels.get(&5).unwrap();
7176 let info = channel.as_directed_from(&NodeId::from_pubkey(&nodes[3])).unwrap();
7177 let candidate: CandidateRouteHop = CandidateRouteHop::PublicHop(CandidatePublicHop {
7179 short_channel_id: 5,
7181 assert_eq!(scorer.channel_penalty_msat(&candidate, usage, &scorer_params), 456);
7183 // Then check we can get a normal route
7184 let payment_params = PaymentParameters::from_node_id(nodes[10], 42);
7185 let route_params = RouteParameters::from_payment_params_and_value(
7186 payment_params, 100);
7187 let route = get_route(&our_id, &route_params, &network_graph, None,
7188 Arc::clone(&logger), &scorer, &scorer_params, &random_seed_bytes);
7189 assert!(route.is_ok());
7191 // Then check that we can't get a route if we ban an intermediate node.
7192 scorer_params.add_banned(&NodeId::from_pubkey(&nodes[3]));
7193 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer, &scorer_params,&random_seed_bytes);
7194 assert!(route.is_err());
7196 // Finally make sure we can route again, when we remove the ban.
7197 scorer_params.remove_banned(&NodeId::from_pubkey(&nodes[3]));
7198 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer, &scorer_params,&random_seed_bytes);
7199 assert!(route.is_ok());
7203 fn abide_by_route_hint_max_htlc() {
7204 // Check that we abide by any htlc_maximum_msat provided in the route hints of the payment
7205 // params in the final route.
7206 let (secp_ctx, network_graph, _, _, logger) = build_graph();
7207 let netgraph = network_graph.read_only();
7208 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7209 let scorer = ln_test_utils::TestScorer::new();
7210 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7211 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7212 let config = UserConfig::default();
7214 let max_htlc_msat = 50_000;
7215 let route_hint_1 = RouteHint(vec![RouteHintHop {
7216 src_node_id: nodes[2],
7217 short_channel_id: 42,
7220 proportional_millionths: 0,
7222 cltv_expiry_delta: 10,
7223 htlc_minimum_msat: None,
7224 htlc_maximum_msat: Some(max_htlc_msat),
7226 let dest_node_id = ln_test_utils::pubkey(42);
7227 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
7228 .with_route_hints(vec![route_hint_1.clone()]).unwrap()
7229 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
7232 // Make sure we'll error if our route hints don't have enough liquidity according to their
7233 // htlc_maximum_msat.
7234 let mut route_params = RouteParameters::from_payment_params_and_value(
7235 payment_params, max_htlc_msat + 1);
7236 route_params.max_total_routing_fee_msat = None;
7237 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
7238 &route_params, &netgraph, None, Arc::clone(&logger), &scorer, &Default::default(),
7241 assert_eq!(err, "Failed to find a sufficient route to the given destination");
7242 } else { panic!(); }
7244 // Make sure we'll split an MPP payment across route hints if their htlc_maximum_msat warrants.
7245 let mut route_hint_2 = route_hint_1.clone();
7246 route_hint_2.0[0].short_channel_id = 43;
7247 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
7248 .with_route_hints(vec![route_hint_1, route_hint_2]).unwrap()
7249 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
7251 let mut route_params = RouteParameters::from_payment_params_and_value(
7252 payment_params, max_htlc_msat + 1);
7253 route_params.max_total_routing_fee_msat = Some(max_htlc_msat * 2);
7254 let route = get_route(&our_id, &route_params, &netgraph, None, Arc::clone(&logger),
7255 &scorer, &Default::default(), &random_seed_bytes).unwrap();
7256 assert_eq!(route.paths.len(), 2);
7257 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
7258 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
7262 fn direct_channel_to_hints_with_max_htlc() {
7263 // Check that if we have a first hop channel peer that's connected to multiple provided route
7264 // hints, that we properly split the payment between the route hints if needed.
7265 let logger = Arc::new(ln_test_utils::TestLogger::new());
7266 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7267 let scorer = ln_test_utils::TestScorer::new();
7268 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7269 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7270 let config = UserConfig::default();
7272 let our_node_id = ln_test_utils::pubkey(42);
7273 let intermed_node_id = ln_test_utils::pubkey(43);
7274 let first_hop = vec![get_channel_details(Some(42), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), 10_000_000)];
7276 let amt_msat = 900_000;
7277 let max_htlc_msat = 500_000;
7278 let route_hint_1 = RouteHint(vec![RouteHintHop {
7279 src_node_id: intermed_node_id,
7280 short_channel_id: 44,
7283 proportional_millionths: 0,
7285 cltv_expiry_delta: 10,
7286 htlc_minimum_msat: None,
7287 htlc_maximum_msat: Some(max_htlc_msat),
7289 src_node_id: intermed_node_id,
7290 short_channel_id: 45,
7293 proportional_millionths: 0,
7295 cltv_expiry_delta: 10,
7296 htlc_minimum_msat: None,
7297 // Check that later route hint max htlcs don't override earlier ones
7298 htlc_maximum_msat: Some(max_htlc_msat - 50),
7300 let mut route_hint_2 = route_hint_1.clone();
7301 route_hint_2.0[0].short_channel_id = 46;
7302 route_hint_2.0[1].short_channel_id = 47;
7303 let dest_node_id = ln_test_utils::pubkey(44);
7304 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
7305 .with_route_hints(vec![route_hint_1, route_hint_2]).unwrap()
7306 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
7309 let route_params = RouteParameters::from_payment_params_and_value(
7310 payment_params, amt_msat);
7311 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
7312 Some(&first_hop.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7313 &Default::default(), &random_seed_bytes).unwrap();
7314 assert_eq!(route.paths.len(), 2);
7315 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
7316 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
7317 assert_eq!(route.get_total_amount(), amt_msat);
7319 // Re-run but with two first hop channels connected to the same route hint peers that must be
7321 let first_hops = vec![
7322 get_channel_details(Some(42), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), amt_msat - 10),
7323 get_channel_details(Some(43), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), amt_msat - 10),
7325 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
7326 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7327 &Default::default(), &random_seed_bytes).unwrap();
7328 assert_eq!(route.paths.len(), 2);
7329 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
7330 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
7331 assert_eq!(route.get_total_amount(), amt_msat);
7333 // Make sure this works for blinded route hints.
7334 let blinded_path = BlindedPath {
7335 introduction_node_id: intermed_node_id,
7336 blinding_point: ln_test_utils::pubkey(42),
7338 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42), encrypted_payload: vec![] },
7339 BlindedHop { blinded_node_id: ln_test_utils::pubkey(43), encrypted_payload: vec![] },
7342 let blinded_payinfo = BlindedPayInfo {
7344 fee_proportional_millionths: 0,
7345 htlc_minimum_msat: 1,
7346 htlc_maximum_msat: max_htlc_msat,
7347 cltv_expiry_delta: 10,
7348 features: BlindedHopFeatures::empty(),
7350 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7351 let payment_params = PaymentParameters::blinded(vec![
7352 (blinded_payinfo.clone(), blinded_path.clone()),
7353 (blinded_payinfo.clone(), blinded_path.clone())])
7354 .with_bolt12_features(bolt12_features).unwrap();
7355 let route_params = RouteParameters::from_payment_params_and_value(
7356 payment_params, amt_msat);
7357 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
7358 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7359 &Default::default(), &random_seed_bytes).unwrap();
7360 assert_eq!(route.paths.len(), 2);
7361 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
7362 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
7363 assert_eq!(route.get_total_amount(), amt_msat);
7367 fn blinded_route_ser() {
7368 let blinded_path_1 = BlindedPath {
7369 introduction_node_id: ln_test_utils::pubkey(42),
7370 blinding_point: ln_test_utils::pubkey(43),
7372 BlindedHop { blinded_node_id: ln_test_utils::pubkey(44), encrypted_payload: Vec::new() },
7373 BlindedHop { blinded_node_id: ln_test_utils::pubkey(45), encrypted_payload: Vec::new() }
7376 let blinded_path_2 = BlindedPath {
7377 introduction_node_id: ln_test_utils::pubkey(46),
7378 blinding_point: ln_test_utils::pubkey(47),
7380 BlindedHop { blinded_node_id: ln_test_utils::pubkey(48), encrypted_payload: Vec::new() },
7381 BlindedHop { blinded_node_id: ln_test_utils::pubkey(49), encrypted_payload: Vec::new() }
7384 // (De)serialize a Route with 1 blinded path out of two total paths.
7385 let mut route = Route { paths: vec![Path {
7386 hops: vec![RouteHop {
7387 pubkey: ln_test_utils::pubkey(50),
7388 node_features: NodeFeatures::empty(),
7389 short_channel_id: 42,
7390 channel_features: ChannelFeatures::empty(),
7392 cltv_expiry_delta: 0,
7393 maybe_announced_channel: true,
7395 blinded_tail: Some(BlindedTail {
7396 hops: blinded_path_1.blinded_hops,
7397 blinding_point: blinded_path_1.blinding_point,
7398 excess_final_cltv_expiry_delta: 40,
7399 final_value_msat: 100,
7401 hops: vec![RouteHop {
7402 pubkey: ln_test_utils::pubkey(51),
7403 node_features: NodeFeatures::empty(),
7404 short_channel_id: 43,
7405 channel_features: ChannelFeatures::empty(),
7407 cltv_expiry_delta: 0,
7408 maybe_announced_channel: true,
7409 }], blinded_tail: None }],
7412 let encoded_route = route.encode();
7413 let decoded_route: Route = Readable::read(&mut Cursor::new(&encoded_route[..])).unwrap();
7414 assert_eq!(decoded_route.paths[0].blinded_tail, route.paths[0].blinded_tail);
7415 assert_eq!(decoded_route.paths[1].blinded_tail, route.paths[1].blinded_tail);
7417 // (De)serialize a Route with two paths, each containing a blinded tail.
7418 route.paths[1].blinded_tail = Some(BlindedTail {
7419 hops: blinded_path_2.blinded_hops,
7420 blinding_point: blinded_path_2.blinding_point,
7421 excess_final_cltv_expiry_delta: 41,
7422 final_value_msat: 101,
7424 let encoded_route = route.encode();
7425 let decoded_route: Route = Readable::read(&mut Cursor::new(&encoded_route[..])).unwrap();
7426 assert_eq!(decoded_route.paths[0].blinded_tail, route.paths[0].blinded_tail);
7427 assert_eq!(decoded_route.paths[1].blinded_tail, route.paths[1].blinded_tail);
7431 fn blinded_path_inflight_processing() {
7432 // Ensure we'll score the channel that's inbound to a blinded path's introduction node, and
7433 // account for the blinded tail's final amount_msat.
7434 let mut inflight_htlcs = InFlightHtlcs::new();
7435 let blinded_path = BlindedPath {
7436 introduction_node_id: ln_test_utils::pubkey(43),
7437 blinding_point: ln_test_utils::pubkey(48),
7438 blinded_hops: vec![BlindedHop { blinded_node_id: ln_test_utils::pubkey(49), encrypted_payload: Vec::new() }],
7441 hops: vec![RouteHop {
7442 pubkey: ln_test_utils::pubkey(42),
7443 node_features: NodeFeatures::empty(),
7444 short_channel_id: 42,
7445 channel_features: ChannelFeatures::empty(),
7447 cltv_expiry_delta: 0,
7448 maybe_announced_channel: false,
7451 pubkey: blinded_path.introduction_node_id,
7452 node_features: NodeFeatures::empty(),
7453 short_channel_id: 43,
7454 channel_features: ChannelFeatures::empty(),
7456 cltv_expiry_delta: 0,
7457 maybe_announced_channel: false,
7459 blinded_tail: Some(BlindedTail {
7460 hops: blinded_path.blinded_hops,
7461 blinding_point: blinded_path.blinding_point,
7462 excess_final_cltv_expiry_delta: 0,
7463 final_value_msat: 200,
7466 inflight_htlcs.process_path(&path, ln_test_utils::pubkey(44));
7467 assert_eq!(*inflight_htlcs.0.get(&(42, true)).unwrap(), 301);
7468 assert_eq!(*inflight_htlcs.0.get(&(43, false)).unwrap(), 201);
7472 fn blinded_path_cltv_shadow_offset() {
7473 // Make sure we add a shadow offset when sending to blinded paths.
7474 let blinded_path = BlindedPath {
7475 introduction_node_id: ln_test_utils::pubkey(43),
7476 blinding_point: ln_test_utils::pubkey(44),
7478 BlindedHop { blinded_node_id: ln_test_utils::pubkey(45), encrypted_payload: Vec::new() },
7479 BlindedHop { blinded_node_id: ln_test_utils::pubkey(46), encrypted_payload: Vec::new() }
7482 let mut route = Route { paths: vec![Path {
7483 hops: vec![RouteHop {
7484 pubkey: ln_test_utils::pubkey(42),
7485 node_features: NodeFeatures::empty(),
7486 short_channel_id: 42,
7487 channel_features: ChannelFeatures::empty(),
7489 cltv_expiry_delta: 0,
7490 maybe_announced_channel: false,
7493 pubkey: blinded_path.introduction_node_id,
7494 node_features: NodeFeatures::empty(),
7495 short_channel_id: 43,
7496 channel_features: ChannelFeatures::empty(),
7498 cltv_expiry_delta: 0,
7499 maybe_announced_channel: false,
7502 blinded_tail: Some(BlindedTail {
7503 hops: blinded_path.blinded_hops,
7504 blinding_point: blinded_path.blinding_point,
7505 excess_final_cltv_expiry_delta: 0,
7506 final_value_msat: 200,
7508 }], route_params: None};
7510 let payment_params = PaymentParameters::from_node_id(ln_test_utils::pubkey(47), 18);
7511 let (_, network_graph, _, _, _) = build_line_graph();
7512 add_random_cltv_offset(&mut route, &payment_params, &network_graph.read_only(), &[0; 32]);
7513 assert_eq!(route.paths[0].blinded_tail.as_ref().unwrap().excess_final_cltv_expiry_delta, 40);
7514 assert_eq!(route.paths[0].hops.last().unwrap().cltv_expiry_delta, 40);
7518 fn simple_blinded_route_hints() {
7519 do_simple_blinded_route_hints(1);
7520 do_simple_blinded_route_hints(2);
7521 do_simple_blinded_route_hints(3);
7524 fn do_simple_blinded_route_hints(num_blinded_hops: usize) {
7525 // Check that we can generate a route to a blinded path with the expected hops.
7526 let (secp_ctx, network, _, _, logger) = build_graph();
7527 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7528 let network_graph = network.read_only();
7530 let scorer = ln_test_utils::TestScorer::new();
7531 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7532 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7534 let mut blinded_path = BlindedPath {
7535 introduction_node_id: nodes[2],
7536 blinding_point: ln_test_utils::pubkey(42),
7537 blinded_hops: Vec::with_capacity(num_blinded_hops),
7539 for i in 0..num_blinded_hops {
7540 blinded_path.blinded_hops.push(
7541 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 + i as u8), encrypted_payload: Vec::new() },
7544 let blinded_payinfo = BlindedPayInfo {
7546 fee_proportional_millionths: 500,
7547 htlc_minimum_msat: 1000,
7548 htlc_maximum_msat: 100_000_000,
7549 cltv_expiry_delta: 15,
7550 features: BlindedHopFeatures::empty(),
7553 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), blinded_path.clone())]);
7554 let route_params = RouteParameters::from_payment_params_and_value(
7555 payment_params, 1001);
7556 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
7557 &scorer, &Default::default(), &random_seed_bytes).unwrap();
7558 assert_eq!(route.paths.len(), 1);
7559 assert_eq!(route.paths[0].hops.len(), 2);
7561 let tail = route.paths[0].blinded_tail.as_ref().unwrap();
7562 assert_eq!(tail.hops, blinded_path.blinded_hops);
7563 assert_eq!(tail.excess_final_cltv_expiry_delta, 0);
7564 assert_eq!(tail.final_value_msat, 1001);
7566 let final_hop = route.paths[0].hops.last().unwrap();
7567 assert_eq!(final_hop.pubkey, blinded_path.introduction_node_id);
7568 if tail.hops.len() > 1 {
7569 assert_eq!(final_hop.fee_msat,
7570 blinded_payinfo.fee_base_msat as u64 + blinded_payinfo.fee_proportional_millionths as u64 * tail.final_value_msat / 1000000);
7571 assert_eq!(final_hop.cltv_expiry_delta, blinded_payinfo.cltv_expiry_delta as u32);
7573 assert_eq!(final_hop.fee_msat, 0);
7574 assert_eq!(final_hop.cltv_expiry_delta, 0);
7579 fn blinded_path_routing_errors() {
7580 // Check that we can generate a route to a blinded path with the expected hops.
7581 let (secp_ctx, network, _, _, logger) = build_graph();
7582 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7583 let network_graph = network.read_only();
7585 let scorer = ln_test_utils::TestScorer::new();
7586 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7587 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7589 let mut invalid_blinded_path = BlindedPath {
7590 introduction_node_id: nodes[2],
7591 blinding_point: ln_test_utils::pubkey(42),
7593 BlindedHop { blinded_node_id: ln_test_utils::pubkey(43), encrypted_payload: vec![0; 43] },
7596 let blinded_payinfo = BlindedPayInfo {
7598 fee_proportional_millionths: 500,
7599 htlc_minimum_msat: 1000,
7600 htlc_maximum_msat: 100_000_000,
7601 cltv_expiry_delta: 15,
7602 features: BlindedHopFeatures::empty(),
7605 let mut invalid_blinded_path_2 = invalid_blinded_path.clone();
7606 invalid_blinded_path_2.introduction_node_id = ln_test_utils::pubkey(45);
7607 let payment_params = PaymentParameters::blinded(vec![
7608 (blinded_payinfo.clone(), invalid_blinded_path.clone()),
7609 (blinded_payinfo.clone(), invalid_blinded_path_2)]);
7610 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
7611 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
7612 &scorer, &Default::default(), &random_seed_bytes)
7614 Err(LightningError { err, .. }) => {
7615 assert_eq!(err, "1-hop blinded paths must all have matching introduction node ids");
7617 _ => panic!("Expected error")
7620 invalid_blinded_path.introduction_node_id = our_id;
7621 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), invalid_blinded_path.clone())]);
7622 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
7623 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
7624 &Default::default(), &random_seed_bytes)
7626 Err(LightningError { err, .. }) => {
7627 assert_eq!(err, "Cannot generate a route to blinded paths if we are the introduction node to all of them");
7629 _ => panic!("Expected error")
7632 invalid_blinded_path.introduction_node_id = ln_test_utils::pubkey(46);
7633 invalid_blinded_path.blinded_hops.clear();
7634 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo, invalid_blinded_path)]);
7635 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
7636 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
7637 &Default::default(), &random_seed_bytes)
7639 Err(LightningError { err, .. }) => {
7640 assert_eq!(err, "0-hop blinded path provided");
7642 _ => panic!("Expected error")
7647 fn matching_intro_node_paths_provided() {
7648 // Check that if multiple blinded paths with the same intro node are provided in payment
7649 // parameters, we'll return the correct paths in the resulting MPP route.
7650 let (secp_ctx, network, _, _, logger) = build_graph();
7651 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7652 let network_graph = network.read_only();
7654 let scorer = ln_test_utils::TestScorer::new();
7655 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7656 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7657 let config = UserConfig::default();
7659 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7660 let blinded_path_1 = BlindedPath {
7661 introduction_node_id: nodes[2],
7662 blinding_point: ln_test_utils::pubkey(42),
7664 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7665 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7668 let blinded_payinfo_1 = BlindedPayInfo {
7670 fee_proportional_millionths: 0,
7671 htlc_minimum_msat: 0,
7672 htlc_maximum_msat: 30_000,
7673 cltv_expiry_delta: 0,
7674 features: BlindedHopFeatures::empty(),
7677 let mut blinded_path_2 = blinded_path_1.clone();
7678 blinded_path_2.blinding_point = ln_test_utils::pubkey(43);
7679 let mut blinded_payinfo_2 = blinded_payinfo_1.clone();
7680 blinded_payinfo_2.htlc_maximum_msat = 70_000;
7682 let blinded_hints = vec![
7683 (blinded_payinfo_1.clone(), blinded_path_1.clone()),
7684 (blinded_payinfo_2.clone(), blinded_path_2.clone()),
7686 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7687 .with_bolt12_features(bolt12_features).unwrap();
7689 let mut route_params = RouteParameters::from_payment_params_and_value(payment_params, 100_000);
7690 route_params.max_total_routing_fee_msat = Some(100_000);
7691 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
7692 &scorer, &Default::default(), &random_seed_bytes).unwrap();
7693 assert_eq!(route.paths.len(), 2);
7694 let mut total_amount_paid_msat = 0;
7695 for path in route.paths.into_iter() {
7696 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
7697 if let Some(bt) = &path.blinded_tail {
7698 assert_eq!(bt.blinding_point,
7699 blinded_hints.iter().find(|(p, _)| p.htlc_maximum_msat == path.final_value_msat())
7700 .map(|(_, bp)| bp.blinding_point).unwrap());
7701 } else { panic!(); }
7702 total_amount_paid_msat += path.final_value_msat();
7704 assert_eq!(total_amount_paid_msat, 100_000);
7708 fn direct_to_intro_node() {
7709 // This previously caused a debug panic in the router when asserting
7710 // `used_liquidity_msat <= hop_max_msat`, because when adding first_hop<>blinded_route_hint
7711 // direct channels we failed to account for the fee charged for use of the blinded path.
7714 // node0 -1(1)2 - node1
7715 // such that there isn't enough liquidity to reach node1, but the router thinks there is if it
7716 // doesn't account for the blinded path fee.
7718 let secp_ctx = Secp256k1::new();
7719 let logger = Arc::new(ln_test_utils::TestLogger::new());
7720 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7721 let gossip_sync = P2PGossipSync::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
7722 let scorer = ln_test_utils::TestScorer::new();
7723 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7724 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7726 let amt_msat = 10_000_000;
7727 let (_, _, privkeys, nodes) = get_nodes(&secp_ctx);
7728 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[1],
7729 ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
7730 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
7731 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
7732 short_channel_id: 1,
7735 cltv_expiry_delta: 42,
7736 htlc_minimum_msat: 1_000,
7737 htlc_maximum_msat: 10_000_000,
7739 fee_proportional_millionths: 0,
7740 excess_data: Vec::new()
7742 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
7743 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
7744 short_channel_id: 1,
7747 cltv_expiry_delta: 42,
7748 htlc_minimum_msat: 1_000,
7749 htlc_maximum_msat: 10_000_000,
7751 fee_proportional_millionths: 0,
7752 excess_data: Vec::new()
7754 let first_hops = vec![
7755 get_channel_details(Some(1), nodes[1], InitFeatures::from_le_bytes(vec![0b11]), 10_000_000)];
7757 let blinded_path = BlindedPath {
7758 introduction_node_id: nodes[1],
7759 blinding_point: ln_test_utils::pubkey(42),
7761 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7762 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7765 let blinded_payinfo = BlindedPayInfo {
7766 fee_base_msat: 1000,
7767 fee_proportional_millionths: 0,
7768 htlc_minimum_msat: 1000,
7769 htlc_maximum_msat: MAX_VALUE_MSAT,
7770 cltv_expiry_delta: 0,
7771 features: BlindedHopFeatures::empty(),
7773 let blinded_hints = vec![(blinded_payinfo.clone(), blinded_path)];
7775 let payment_params = PaymentParameters::blinded(blinded_hints.clone());
7777 let netgraph = network_graph.read_only();
7778 let route_params = RouteParameters::from_payment_params_and_value(
7779 payment_params.clone(), amt_msat);
7780 if let Err(LightningError { err, .. }) = get_route(&nodes[0], &route_params, &netgraph,
7781 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7782 &Default::default(), &random_seed_bytes) {
7783 assert_eq!(err, "Failed to find a path to the given destination");
7784 } else { panic!("Expected error") }
7786 // Sending an exact amount accounting for the blinded path fee works.
7787 let amt_minus_blinded_path_fee = amt_msat - blinded_payinfo.fee_base_msat as u64;
7788 let route_params = RouteParameters::from_payment_params_and_value(
7789 payment_params, amt_minus_blinded_path_fee);
7790 let route = get_route(&nodes[0], &route_params, &netgraph,
7791 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7792 &Default::default(), &random_seed_bytes).unwrap();
7793 assert_eq!(route.get_total_fees(), blinded_payinfo.fee_base_msat as u64);
7794 assert_eq!(route.get_total_amount(), amt_minus_blinded_path_fee);
7798 fn direct_to_matching_intro_nodes() {
7799 // This previously caused us to enter `unreachable` code in the following situation:
7800 // 1. We add a route candidate for intro_node contributing a high amount
7801 // 2. We add a first_hop<>intro_node route candidate for the same high amount
7802 // 3. We see a cheaper blinded route hint for the same intro node but a much lower contribution
7803 // amount, and update our route candidate for intro_node for the lower amount
7804 // 4. We then attempt to update the aforementioned first_hop<>intro_node route candidate for the
7805 // lower contribution amount, but fail (this was previously caused by failure to account for
7806 // blinded path fees when adding first_hop<>intro_node candidates)
7807 // 5. We go to construct the path from these route candidates and our first_hop<>intro_node
7808 // candidate still thinks its path is contributing the original higher amount. This caused us
7809 // to hit an `unreachable` overflow when calculating the cheaper intro_node fees over the
7811 let secp_ctx = Secp256k1::new();
7812 let logger = Arc::new(ln_test_utils::TestLogger::new());
7813 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7814 let scorer = ln_test_utils::TestScorer::new();
7815 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7816 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7817 let config = UserConfig::default();
7819 // Values are taken from the fuzz input that uncovered this panic.
7820 let amt_msat = 21_7020_5185_1403_2640;
7821 let (_, _, _, nodes) = get_nodes(&secp_ctx);
7822 let first_hops = vec![
7823 get_channel_details(Some(1), nodes[1], channelmanager::provided_init_features(&config),
7824 18446744073709551615)];
7826 let blinded_path = BlindedPath {
7827 introduction_node_id: nodes[1],
7828 blinding_point: ln_test_utils::pubkey(42),
7830 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7831 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7834 let blinded_payinfo = BlindedPayInfo {
7835 fee_base_msat: 5046_2720,
7836 fee_proportional_millionths: 0,
7837 htlc_minimum_msat: 4503_5996_2737_0496,
7838 htlc_maximum_msat: 45_0359_9627_3704_9600,
7839 cltv_expiry_delta: 0,
7840 features: BlindedHopFeatures::empty(),
7842 let mut blinded_hints = vec![
7843 (blinded_payinfo.clone(), blinded_path.clone()),
7844 (blinded_payinfo.clone(), blinded_path.clone()),
7846 blinded_hints[1].0.fee_base_msat = 419_4304;
7847 blinded_hints[1].0.fee_proportional_millionths = 257;
7848 blinded_hints[1].0.htlc_minimum_msat = 280_8908_6115_8400;
7849 blinded_hints[1].0.htlc_maximum_msat = 2_8089_0861_1584_0000;
7850 blinded_hints[1].0.cltv_expiry_delta = 0;
7852 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7853 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7854 .with_bolt12_features(bolt12_features).unwrap();
7856 let netgraph = network_graph.read_only();
7857 let route_params = RouteParameters::from_payment_params_and_value(
7858 payment_params, amt_msat);
7859 let route = get_route(&nodes[0], &route_params, &netgraph,
7860 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7861 &Default::default(), &random_seed_bytes).unwrap();
7862 assert_eq!(route.get_total_fees(), blinded_payinfo.fee_base_msat as u64);
7863 assert_eq!(route.get_total_amount(), amt_msat);
7867 fn we_are_intro_node_candidate_hops() {
7868 // This previously led to a panic in the router because we'd generate a Path with only a
7869 // BlindedTail and 0 unblinded hops, due to the only candidate hops being blinded route hints
7870 // where the origin node is the intro node. We now fully disallow considering candidate hops
7871 // where the origin node is the intro node.
7872 let (secp_ctx, network_graph, _, _, logger) = build_graph();
7873 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7874 let scorer = ln_test_utils::TestScorer::new();
7875 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7876 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7877 let config = UserConfig::default();
7879 // Values are taken from the fuzz input that uncovered this panic.
7880 let amt_msat = 21_7020_5185_1423_0019;
7882 let blinded_path = BlindedPath {
7883 introduction_node_id: our_id,
7884 blinding_point: ln_test_utils::pubkey(42),
7886 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7887 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7890 let blinded_payinfo = BlindedPayInfo {
7891 fee_base_msat: 5052_9027,
7892 fee_proportional_millionths: 0,
7893 htlc_minimum_msat: 21_7020_5185_1423_0019,
7894 htlc_maximum_msat: 1844_6744_0737_0955_1615,
7895 cltv_expiry_delta: 0,
7896 features: BlindedHopFeatures::empty(),
7898 let mut blinded_hints = vec![
7899 (blinded_payinfo.clone(), blinded_path.clone()),
7900 (blinded_payinfo.clone(), blinded_path.clone()),
7902 blinded_hints[1].1.introduction_node_id = nodes[6];
7904 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7905 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7906 .with_bolt12_features(bolt12_features.clone()).unwrap();
7908 let netgraph = network_graph.read_only();
7909 let route_params = RouteParameters::from_payment_params_and_value(
7910 payment_params, amt_msat);
7911 if let Err(LightningError { err, .. }) = get_route(
7912 &our_id, &route_params, &netgraph, None, Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes
7914 assert_eq!(err, "Failed to find a path to the given destination");
7919 fn we_are_intro_node_bp_in_final_path_fee_calc() {
7920 // This previously led to a debug panic in the router because we'd find an invalid Path with
7921 // 0 unblinded hops and a blinded tail, leading to the generation of a final
7922 // PaymentPathHop::fee_msat that included both the blinded path fees and the final value of
7923 // the payment, when it was intended to only include the final value of the payment.
7924 let (secp_ctx, network_graph, _, _, logger) = build_graph();
7925 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7926 let scorer = ln_test_utils::TestScorer::new();
7927 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7928 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7929 let config = UserConfig::default();
7931 // Values are taken from the fuzz input that uncovered this panic.
7932 let amt_msat = 21_7020_5185_1423_0019;
7934 let blinded_path = BlindedPath {
7935 introduction_node_id: our_id,
7936 blinding_point: ln_test_utils::pubkey(42),
7938 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7939 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7942 let blinded_payinfo = BlindedPayInfo {
7943 fee_base_msat: 10_4425_1395,
7944 fee_proportional_millionths: 0,
7945 htlc_minimum_msat: 21_7301_9934_9094_0931,
7946 htlc_maximum_msat: 1844_6744_0737_0955_1615,
7947 cltv_expiry_delta: 0,
7948 features: BlindedHopFeatures::empty(),
7950 let mut blinded_hints = vec![
7951 (blinded_payinfo.clone(), blinded_path.clone()),
7952 (blinded_payinfo.clone(), blinded_path.clone()),
7953 (blinded_payinfo.clone(), blinded_path.clone()),
7955 blinded_hints[1].0.fee_base_msat = 5052_9027;
7956 blinded_hints[1].0.htlc_minimum_msat = 21_7020_5185_1423_0019;
7957 blinded_hints[1].0.htlc_maximum_msat = 1844_6744_0737_0955_1615;
7959 blinded_hints[2].1.introduction_node_id = nodes[6];
7961 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7962 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7963 .with_bolt12_features(bolt12_features.clone()).unwrap();
7965 let netgraph = network_graph.read_only();
7966 let route_params = RouteParameters::from_payment_params_and_value(
7967 payment_params, amt_msat);
7968 if let Err(LightningError { err, .. }) = get_route(
7969 &our_id, &route_params, &netgraph, None, Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes
7971 assert_eq!(err, "Failed to find a path to the given destination");
7976 fn min_htlc_overpay_violates_max_htlc() {
7977 do_min_htlc_overpay_violates_max_htlc(true);
7978 do_min_htlc_overpay_violates_max_htlc(false);
7980 fn do_min_htlc_overpay_violates_max_htlc(blinded_payee: bool) {
7981 // Test that if overpaying to meet a later hop's min_htlc and causes us to violate an earlier
7982 // hop's max_htlc, we don't consider that candidate hop valid. Previously we would add this hop
7983 // to `targets` and build an invalid path with it, and subsquently hit a debug panic asserting
7984 // that the used liquidity for a hop was less than its available liquidity limit.
7985 let secp_ctx = Secp256k1::new();
7986 let logger = Arc::new(ln_test_utils::TestLogger::new());
7987 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7988 let scorer = ln_test_utils::TestScorer::new();
7989 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7990 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7991 let config = UserConfig::default();
7993 // Values are taken from the fuzz input that uncovered this panic.
7994 let amt_msat = 7_4009_8048;
7995 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7996 let first_hop_outbound_capacity = 2_7345_2000;
7997 let first_hops = vec![get_channel_details(
7998 Some(200), nodes[0], channelmanager::provided_init_features(&config),
7999 first_hop_outbound_capacity
8002 let base_fee = 1_6778_3453;
8003 let htlc_min = 2_5165_8240;
8004 let payment_params = if blinded_payee {
8005 let blinded_path = BlindedPath {
8006 introduction_node_id: nodes[0],
8007 blinding_point: ln_test_utils::pubkey(42),
8009 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
8010 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
8013 let blinded_payinfo = BlindedPayInfo {
8014 fee_base_msat: base_fee,
8015 fee_proportional_millionths: 0,
8016 htlc_minimum_msat: htlc_min,
8017 htlc_maximum_msat: htlc_min * 1000,
8018 cltv_expiry_delta: 0,
8019 features: BlindedHopFeatures::empty(),
8021 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
8022 PaymentParameters::blinded(vec![(blinded_payinfo, blinded_path)])
8023 .with_bolt12_features(bolt12_features.clone()).unwrap()
8025 let route_hint = RouteHint(vec![RouteHintHop {
8026 src_node_id: nodes[0],
8027 short_channel_id: 42,
8029 base_msat: base_fee,
8030 proportional_millionths: 0,
8032 cltv_expiry_delta: 10,
8033 htlc_minimum_msat: Some(htlc_min),
8034 htlc_maximum_msat: None,
8037 PaymentParameters::from_node_id(nodes[1], 42)
8038 .with_route_hints(vec![route_hint]).unwrap()
8039 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap()
8042 let netgraph = network_graph.read_only();
8043 let route_params = RouteParameters::from_payment_params_and_value(
8044 payment_params, amt_msat);
8045 if let Err(LightningError { err, .. }) = get_route(
8046 &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
8047 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes
8049 assert_eq!(err, "Failed to find a path to the given destination");
8054 fn previously_used_liquidity_violates_max_htlc() {
8055 do_previously_used_liquidity_violates_max_htlc(true);
8056 do_previously_used_liquidity_violates_max_htlc(false);
8059 fn do_previously_used_liquidity_violates_max_htlc(blinded_payee: bool) {
8060 // Test that if a candidate first_hop<>route_hint_src_node channel does not have enough
8061 // contribution amount to cover the next hop's min_htlc plus fees, we will not consider that
8062 // candidate. In this case, the candidate does not have enough due to a previous path taking up
8063 // some of its liquidity. Previously we would construct an invalid path and hit a debug panic
8064 // asserting that the used liquidity for a hop was less than its available liquidity limit.
8065 let secp_ctx = Secp256k1::new();
8066 let logger = Arc::new(ln_test_utils::TestLogger::new());
8067 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
8068 let scorer = ln_test_utils::TestScorer::new();
8069 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
8070 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8071 let config = UserConfig::default();
8073 // Values are taken from the fuzz input that uncovered this panic.
8074 let amt_msat = 52_4288;
8075 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
8076 let first_hops = vec![get_channel_details(
8077 Some(161), nodes[0], channelmanager::provided_init_features(&config), 486_4000
8078 ), get_channel_details(
8079 Some(122), nodes[0], channelmanager::provided_init_features(&config), 179_5000
8082 let base_fees = [0, 425_9840, 0, 0];
8083 let htlc_mins = [1_4392, 19_7401, 1027, 6_5535];
8084 let payment_params = if blinded_payee {
8085 let blinded_path = BlindedPath {
8086 introduction_node_id: nodes[0],
8087 blinding_point: ln_test_utils::pubkey(42),
8089 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
8090 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
8093 let mut blinded_hints = Vec::new();
8094 for (base_fee, htlc_min) in base_fees.iter().zip(htlc_mins.iter()) {
8095 blinded_hints.push((BlindedPayInfo {
8096 fee_base_msat: *base_fee,
8097 fee_proportional_millionths: 0,
8098 htlc_minimum_msat: *htlc_min,
8099 htlc_maximum_msat: htlc_min * 100,
8100 cltv_expiry_delta: 10,
8101 features: BlindedHopFeatures::empty(),
8102 }, blinded_path.clone()));
8104 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
8105 PaymentParameters::blinded(blinded_hints.clone())
8106 .with_bolt12_features(bolt12_features.clone()).unwrap()
8108 let mut route_hints = Vec::new();
8109 for (idx, (base_fee, htlc_min)) in base_fees.iter().zip(htlc_mins.iter()).enumerate() {
8110 route_hints.push(RouteHint(vec![RouteHintHop {
8111 src_node_id: nodes[0],
8112 short_channel_id: 42 + idx as u64,
8114 base_msat: *base_fee,
8115 proportional_millionths: 0,
8117 cltv_expiry_delta: 10,
8118 htlc_minimum_msat: Some(*htlc_min),
8119 htlc_maximum_msat: Some(htlc_min * 100),
8122 PaymentParameters::from_node_id(nodes[1], 42)
8123 .with_route_hints(route_hints).unwrap()
8124 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap()
8127 let netgraph = network_graph.read_only();
8128 let route_params = RouteParameters::from_payment_params_and_value(
8129 payment_params, amt_msat);
8131 let route = get_route(
8132 &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
8133 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes
8135 assert_eq!(route.paths.len(), 1);
8136 assert_eq!(route.get_total_amount(), amt_msat);
8140 fn candidate_path_min() {
8141 // Test that if a candidate first_hop<>network_node channel does not have enough contribution
8142 // amount to cover the next channel's min htlc plus fees, we will not consider that candidate.
8143 // Previously, we were storing RouteGraphNodes with a path_min that did not include fees, and
8144 // would add a connecting first_hop node that did not have enough contribution amount, leading
8145 // to a debug panic upon invalid path construction.
8146 let secp_ctx = Secp256k1::new();
8147 let logger = Arc::new(ln_test_utils::TestLogger::new());
8148 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
8149 let gossip_sync = P2PGossipSync::new(network_graph.clone(), None, logger.clone());
8150 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), network_graph.clone(), logger.clone());
8151 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
8152 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8153 let config = UserConfig::default();
8155 // Values are taken from the fuzz input that uncovered this panic.
8156 let amt_msat = 7_4009_8048;
8157 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
8158 let first_hops = vec![get_channel_details(
8159 Some(200), nodes[0], channelmanager::provided_init_features(&config), 2_7345_2000
8162 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
8163 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
8164 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8165 short_channel_id: 6,
8168 cltv_expiry_delta: (6 << 4) | 0,
8169 htlc_minimum_msat: 0,
8170 htlc_maximum_msat: MAX_VALUE_MSAT,
8172 fee_proportional_millionths: 0,
8173 excess_data: Vec::new()
8175 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[0], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
8177 let htlc_min = 2_5165_8240;
8178 let blinded_hints = vec![
8180 fee_base_msat: 1_6778_3453,
8181 fee_proportional_millionths: 0,
8182 htlc_minimum_msat: htlc_min,
8183 htlc_maximum_msat: htlc_min * 100,
8184 cltv_expiry_delta: 10,
8185 features: BlindedHopFeatures::empty(),
8187 introduction_node_id: nodes[0],
8188 blinding_point: ln_test_utils::pubkey(42),
8190 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
8191 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
8195 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
8196 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
8197 .with_bolt12_features(bolt12_features.clone()).unwrap();
8198 let route_params = RouteParameters::from_payment_params_and_value(
8199 payment_params, amt_msat);
8200 let netgraph = network_graph.read_only();
8202 if let Err(LightningError { err, .. }) = get_route(
8203 &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
8204 Arc::clone(&logger), &scorer, &ProbabilisticScoringFeeParameters::default(),
8207 assert_eq!(err, "Failed to find a path to the given destination");
8212 fn path_contribution_includes_min_htlc_overpay() {
8213 // Previously, the fuzzer hit a debug panic because we wouldn't include the amount overpaid to
8214 // meet a last hop's min_htlc in the total collected paths value. We now include this value and
8215 // also penalize hops along the overpaying path to ensure that it gets deprioritized in path
8216 // selection, both tested here.
8217 let secp_ctx = Secp256k1::new();
8218 let logger = Arc::new(ln_test_utils::TestLogger::new());
8219 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
8220 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), network_graph.clone(), logger.clone());
8221 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
8222 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8223 let config = UserConfig::default();
8225 // Values are taken from the fuzz input that uncovered this panic.
8226 let amt_msat = 562_0000;
8227 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
8228 let first_hops = vec![
8229 get_channel_details(
8230 Some(83), nodes[0], channelmanager::provided_init_features(&config), 2199_0000,
8234 let htlc_mins = [49_0000, 1125_0000];
8235 let payment_params = {
8236 let blinded_path = BlindedPath {
8237 introduction_node_id: nodes[0],
8238 blinding_point: ln_test_utils::pubkey(42),
8240 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
8241 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
8244 let mut blinded_hints = Vec::new();
8245 for htlc_min in htlc_mins.iter() {
8246 blinded_hints.push((BlindedPayInfo {
8248 fee_proportional_millionths: 0,
8249 htlc_minimum_msat: *htlc_min,
8250 htlc_maximum_msat: *htlc_min * 100,
8251 cltv_expiry_delta: 10,
8252 features: BlindedHopFeatures::empty(),
8253 }, blinded_path.clone()));
8255 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
8256 PaymentParameters::blinded(blinded_hints.clone())
8257 .with_bolt12_features(bolt12_features.clone()).unwrap()
8260 let netgraph = network_graph.read_only();
8261 let route_params = RouteParameters::from_payment_params_and_value(
8262 payment_params, amt_msat);
8263 let route = get_route(
8264 &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
8265 Arc::clone(&logger), &scorer, &ProbabilisticScoringFeeParameters::default(),
8268 assert_eq!(route.paths.len(), 1);
8269 assert_eq!(route.get_total_amount(), amt_msat);
8273 fn first_hop_preferred_over_hint() {
8274 // Check that if we have a first hop to a peer we'd always prefer that over a route hint
8275 // they gave us, but we'd still consider all subsequent hints if they are more attractive.
8276 let secp_ctx = Secp256k1::new();
8277 let logger = Arc::new(ln_test_utils::TestLogger::new());
8278 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
8279 let gossip_sync = P2PGossipSync::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
8280 let scorer = ln_test_utils::TestScorer::new();
8281 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
8282 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8283 let config = UserConfig::default();
8285 let amt_msat = 1_000_000;
8286 let (our_privkey, our_node_id, privkeys, nodes) = get_nodes(&secp_ctx);
8288 add_channel(&gossip_sync, &secp_ctx, &our_privkey, &privkeys[0],
8289 ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
8290 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
8291 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8292 short_channel_id: 1,
8295 cltv_expiry_delta: 42,
8296 htlc_minimum_msat: 1_000,
8297 htlc_maximum_msat: 10_000_000,
8299 fee_proportional_millionths: 0,
8300 excess_data: Vec::new()
8302 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
8303 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8304 short_channel_id: 1,
8307 cltv_expiry_delta: 42,
8308 htlc_minimum_msat: 1_000,
8309 htlc_maximum_msat: 10_000_000,
8311 fee_proportional_millionths: 0,
8312 excess_data: Vec::new()
8315 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[1],
8316 ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 2);
8317 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
8318 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8319 short_channel_id: 2,
8322 cltv_expiry_delta: 42,
8323 htlc_minimum_msat: 1_000,
8324 htlc_maximum_msat: 10_000_000,
8326 fee_proportional_millionths: 0,
8327 excess_data: Vec::new()
8329 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
8330 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8331 short_channel_id: 2,
8334 cltv_expiry_delta: 42,
8335 htlc_minimum_msat: 1_000,
8336 htlc_maximum_msat: 10_000_000,
8338 fee_proportional_millionths: 0,
8339 excess_data: Vec::new()
8342 let dest_node_id = nodes[2];
8344 let route_hint = RouteHint(vec![RouteHintHop {
8345 src_node_id: our_node_id,
8346 short_channel_id: 44,
8349 proportional_millionths: 0,
8351 cltv_expiry_delta: 10,
8352 htlc_minimum_msat: None,
8353 htlc_maximum_msat: Some(5_000_000),
8356 src_node_id: nodes[0],
8357 short_channel_id: 45,
8360 proportional_millionths: 0,
8362 cltv_expiry_delta: 10,
8363 htlc_minimum_msat: None,
8364 htlc_maximum_msat: None,
8367 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
8368 .with_route_hints(vec![route_hint]).unwrap()
8369 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap();
8370 let route_params = RouteParameters::from_payment_params_and_value(
8371 payment_params, amt_msat);
8373 // First create an insufficient first hop for channel with SCID 1 and check we'd use the
8375 let first_hop = get_channel_details(Some(1), nodes[0],
8376 channelmanager::provided_init_features(&config), 999_999);
8377 let first_hops = vec![first_hop];
8379 let route = get_route(&our_node_id, &route_params.clone(), &network_graph.read_only(),
8380 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
8381 &Default::default(), &random_seed_bytes).unwrap();
8382 assert_eq!(route.paths.len(), 1);
8383 assert_eq!(route.get_total_amount(), amt_msat);
8384 assert_eq!(route.paths[0].hops.len(), 2);
8385 assert_eq!(route.paths[0].hops[0].short_channel_id, 44);
8386 assert_eq!(route.paths[0].hops[1].short_channel_id, 45);
8387 assert_eq!(route.get_total_fees(), 123);
8389 // Now check we would trust our first hop info, i.e., fail if we detect the route hint is
8390 // for a first hop channel.
8391 let mut first_hop = get_channel_details(Some(1), nodes[0], channelmanager::provided_init_features(&config), 999_999);
8392 first_hop.outbound_scid_alias = Some(44);
8393 let first_hops = vec![first_hop];
8395 let route_res = get_route(&our_node_id, &route_params.clone(), &network_graph.read_only(),
8396 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
8397 &Default::default(), &random_seed_bytes);
8398 assert!(route_res.is_err());
8400 // Finally check we'd use the first hop if has sufficient outbound capacity. But we'd stil
8401 // use the cheaper second hop of the route hint.
8402 let mut first_hop = get_channel_details(Some(1), nodes[0],
8403 channelmanager::provided_init_features(&config), 10_000_000);
8404 first_hop.outbound_scid_alias = Some(44);
8405 let first_hops = vec![first_hop];
8407 let route = get_route(&our_node_id, &route_params.clone(), &network_graph.read_only(),
8408 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
8409 &Default::default(), &random_seed_bytes).unwrap();
8410 assert_eq!(route.paths.len(), 1);
8411 assert_eq!(route.get_total_amount(), amt_msat);
8412 assert_eq!(route.paths[0].hops.len(), 2);
8413 assert_eq!(route.paths[0].hops[0].short_channel_id, 1);
8414 assert_eq!(route.paths[0].hops[1].short_channel_id, 45);
8415 assert_eq!(route.get_total_fees(), 123);
8419 fn allow_us_being_first_hint() {
8420 // Check that we consider a route hint even if we are the src of the first hop.
8421 let secp_ctx = Secp256k1::new();
8422 let logger = Arc::new(ln_test_utils::TestLogger::new());
8423 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
8424 let scorer = ln_test_utils::TestScorer::new();
8425 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
8426 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8427 let config = UserConfig::default();
8429 let (_, our_node_id, _, nodes) = get_nodes(&secp_ctx);
8431 let amt_msat = 1_000_000;
8432 let dest_node_id = nodes[1];
8434 let first_hop = get_channel_details(Some(1), nodes[0], channelmanager::provided_init_features(&config), 10_000_000);
8435 let first_hops = vec![first_hop];
8437 let route_hint = RouteHint(vec![RouteHintHop {
8438 src_node_id: our_node_id,
8439 short_channel_id: 44,
8442 proportional_millionths: 0,
8444 cltv_expiry_delta: 10,
8445 htlc_minimum_msat: None,
8446 htlc_maximum_msat: None,
8449 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
8450 .with_route_hints(vec![route_hint]).unwrap()
8451 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap();
8453 let route_params = RouteParameters::from_payment_params_and_value(
8454 payment_params, amt_msat);
8457 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
8458 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
8459 &Default::default(), &random_seed_bytes).unwrap();
8461 assert_eq!(route.paths.len(), 1);
8462 assert_eq!(route.get_total_amount(), amt_msat);
8463 assert_eq!(route.get_total_fees(), 0);
8464 assert_eq!(route.paths[0].hops.len(), 1);
8466 assert_eq!(route.paths[0].hops[0].short_channel_id, 44);
8470 #[cfg(all(any(test, ldk_bench), not(feature = "no-std")))]
8471 pub(crate) mod bench_utils {
8475 use bitcoin::hashes::Hash;
8476 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
8478 use crate::chain::transaction::OutPoint;
8479 use crate::routing::scoring::ScoreUpdate;
8480 use crate::sign::{EntropySource, KeysManager};
8481 use crate::ln::ChannelId;
8482 use crate::ln::channelmanager::{self, ChannelCounterparty, ChannelDetails};
8483 use crate::ln::features::Bolt11InvoiceFeatures;
8484 use crate::routing::gossip::NetworkGraph;
8485 use crate::routing::scoring::ProbabilisticScorer;
8486 use crate::util::config::UserConfig;
8487 use crate::util::ser::ReadableArgs;
8488 use crate::util::test_utils::TestLogger;
8489 use crate::sync::Arc;
8491 /// Tries to open a network graph file, or panics with a URL to fetch it.
8492 pub(crate) fn get_graph_scorer_file() -> Result<(std::fs::File, std::fs::File), &'static str> {
8493 let load_file = |fname, err_str| {
8494 File::open(fname) // By default we're run in RL/lightning
8495 .or_else(|_| File::open(&format!("lightning/{}", fname))) // We may be run manually in RL/
8496 .or_else(|_| { // Fall back to guessing based on the binary location
8497 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
8498 let mut path = std::env::current_exe().unwrap();
8499 path.pop(); // lightning-...
8501 path.pop(); // debug
8502 path.pop(); // target
8503 path.push("lightning");
8507 .or_else(|_| { // Fall back to guessing based on the binary location for a subcrate
8508 // path is likely something like .../rust-lightning/bench/target/debug/deps/bench..
8509 let mut path = std::env::current_exe().unwrap();
8510 path.pop(); // bench...
8512 path.pop(); // debug
8513 path.pop(); // target
8514 path.pop(); // bench
8515 path.push("lightning");
8519 .map_err(|_| err_str)
8521 let graph_res = load_file(
8522 "net_graph-2023-12-10.bin",
8523 "Please fetch https://bitcoin.ninja/ldk-net_graph-v0.0.118-2023-12-10.bin and place it at lightning/net_graph-2023-12-10.bin"
8525 let scorer_res = load_file(
8526 "scorer-2023-12-10.bin",
8527 "Please fetch https://bitcoin.ninja/ldk-scorer-v0.0.118-2023-12-10.bin and place it at scorer-2023-12-10.bin"
8529 #[cfg(require_route_graph_test)]
8530 return Ok((graph_res.unwrap(), scorer_res.unwrap()));
8531 #[cfg(not(require_route_graph_test))]
8532 return Ok((graph_res?, scorer_res?));
8535 pub(crate) fn read_graph_scorer(logger: &TestLogger)
8536 -> Result<(Arc<NetworkGraph<&TestLogger>>, ProbabilisticScorer<Arc<NetworkGraph<&TestLogger>>, &TestLogger>), &'static str> {
8537 let (mut graph_file, mut scorer_file) = get_graph_scorer_file()?;
8538 let graph = Arc::new(NetworkGraph::read(&mut graph_file, logger).unwrap());
8539 let scorer_args = (Default::default(), Arc::clone(&graph), logger);
8540 let scorer = ProbabilisticScorer::read(&mut scorer_file, scorer_args).unwrap();
8544 pub(crate) fn payer_pubkey() -> PublicKey {
8545 let secp_ctx = Secp256k1::new();
8546 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
8550 pub(crate) fn first_hop(node_id: PublicKey) -> ChannelDetails {
8552 channel_id: ChannelId::new_zero(),
8553 counterparty: ChannelCounterparty {
8554 features: channelmanager::provided_init_features(&UserConfig::default()),
8556 unspendable_punishment_reserve: 0,
8557 forwarding_info: None,
8558 outbound_htlc_minimum_msat: None,
8559 outbound_htlc_maximum_msat: None,
8561 funding_txo: Some(OutPoint {
8562 txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0
8565 short_channel_id: Some(1),
8566 inbound_scid_alias: None,
8567 outbound_scid_alias: None,
8568 channel_value_satoshis: 10_000_000_000,
8570 balance_msat: 10_000_000_000,
8571 outbound_capacity_msat: 10_000_000_000,
8572 next_outbound_htlc_minimum_msat: 0,
8573 next_outbound_htlc_limit_msat: 10_000_000_000,
8574 inbound_capacity_msat: 0,
8575 unspendable_punishment_reserve: None,
8576 confirmations_required: None,
8577 confirmations: None,
8578 force_close_spend_delay: None,
8580 is_channel_ready: true,
8583 inbound_htlc_minimum_msat: None,
8584 inbound_htlc_maximum_msat: None,
8586 feerate_sat_per_1000_weight: None,
8587 channel_shutdown_state: Some(channelmanager::ChannelShutdownState::NotShuttingDown),
8591 pub(crate) fn generate_test_routes<S: ScoreLookUp + ScoreUpdate>(graph: &NetworkGraph<&TestLogger>, scorer: &mut S,
8592 score_params: &S::ScoreParams, features: Bolt11InvoiceFeatures, mut seed: u64,
8593 starting_amount: u64, route_count: usize,
8594 ) -> Vec<(ChannelDetails, PaymentParameters, u64)> {
8595 let payer = payer_pubkey();
8596 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
8597 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8599 let nodes = graph.read_only().nodes().clone();
8600 let mut route_endpoints = Vec::new();
8601 for _ in 0..route_count {
8603 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
8604 let src = PublicKey::from_slice(nodes.unordered_keys()
8605 .skip((seed as usize) % nodes.len()).next().unwrap().as_slice()).unwrap();
8606 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
8607 let dst = PublicKey::from_slice(nodes.unordered_keys()
8608 .skip((seed as usize) % nodes.len()).next().unwrap().as_slice()).unwrap();
8609 let params = PaymentParameters::from_node_id(dst, 42)
8610 .with_bolt11_features(features.clone()).unwrap();
8611 let first_hop = first_hop(src);
8612 let amt_msat = starting_amount + seed % 1_000_000;
8613 let route_params = RouteParameters::from_payment_params_and_value(
8614 params.clone(), amt_msat);
8616 get_route(&payer, &route_params, &graph.read_only(), Some(&[&first_hop]),
8617 &TestLogger::new(), scorer, score_params, &random_seed_bytes).is_ok();
8619 route_endpoints.push((first_hop, params, amt_msat));
8625 // Because we've changed channel scores, it's possible we'll take different routes to the
8626 // selected destinations, possibly causing us to fail because, eg, the newly-selected path
8627 // requires a too-high CLTV delta.
8628 route_endpoints.retain(|(first_hop, params, amt_msat)| {
8629 let route_params = RouteParameters::from_payment_params_and_value(
8630 params.clone(), *amt_msat);
8631 get_route(&payer, &route_params, &graph.read_only(), Some(&[first_hop]),
8632 &TestLogger::new(), scorer, score_params, &random_seed_bytes).is_ok()
8634 route_endpoints.truncate(route_count);
8635 assert_eq!(route_endpoints.len(), route_count);
8643 use crate::routing::scoring::{ScoreUpdate, ScoreLookUp};
8644 use crate::sign::{EntropySource, KeysManager};
8645 use crate::ln::channelmanager;
8646 use crate::ln::features::Bolt11InvoiceFeatures;
8647 use crate::routing::gossip::NetworkGraph;
8648 use crate::routing::scoring::{FixedPenaltyScorer, ProbabilisticScoringFeeParameters};
8649 use crate::util::config::UserConfig;
8650 use crate::util::logger::{Logger, Record};
8651 use crate::util::test_utils::TestLogger;
8653 use criterion::Criterion;
8655 struct DummyLogger {}
8656 impl Logger for DummyLogger {
8657 fn log(&self, _record: Record) {}
8660 pub fn generate_routes_with_zero_penalty_scorer(bench: &mut Criterion) {
8661 let logger = TestLogger::new();
8662 let (network_graph, _) = bench_utils::read_graph_scorer(&logger).unwrap();
8663 let scorer = FixedPenaltyScorer::with_penalty(0);
8664 generate_routes(bench, &network_graph, scorer, &Default::default(),
8665 Bolt11InvoiceFeatures::empty(), 0, "generate_routes_with_zero_penalty_scorer");
8668 pub fn generate_mpp_routes_with_zero_penalty_scorer(bench: &mut Criterion) {
8669 let logger = TestLogger::new();
8670 let (network_graph, _) = bench_utils::read_graph_scorer(&logger).unwrap();
8671 let scorer = FixedPenaltyScorer::with_penalty(0);
8672 generate_routes(bench, &network_graph, scorer, &Default::default(),
8673 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 0,
8674 "generate_mpp_routes_with_zero_penalty_scorer");
8677 pub fn generate_routes_with_probabilistic_scorer(bench: &mut Criterion) {
8678 let logger = TestLogger::new();
8679 let (network_graph, scorer) = bench_utils::read_graph_scorer(&logger).unwrap();
8680 let params = ProbabilisticScoringFeeParameters::default();
8681 generate_routes(bench, &network_graph, scorer, ¶ms, Bolt11InvoiceFeatures::empty(), 0,
8682 "generate_routes_with_probabilistic_scorer");
8685 pub fn generate_mpp_routes_with_probabilistic_scorer(bench: &mut Criterion) {
8686 let logger = TestLogger::new();
8687 let (network_graph, scorer) = bench_utils::read_graph_scorer(&logger).unwrap();
8688 let params = ProbabilisticScoringFeeParameters::default();
8689 generate_routes(bench, &network_graph, scorer, ¶ms,
8690 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 0,
8691 "generate_mpp_routes_with_probabilistic_scorer");
8694 pub fn generate_large_mpp_routes_with_probabilistic_scorer(bench: &mut Criterion) {
8695 let logger = TestLogger::new();
8696 let (network_graph, scorer) = bench_utils::read_graph_scorer(&logger).unwrap();
8697 let params = ProbabilisticScoringFeeParameters::default();
8698 generate_routes(bench, &network_graph, scorer, ¶ms,
8699 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 100_000_000,
8700 "generate_large_mpp_routes_with_probabilistic_scorer");
8703 pub fn generate_routes_with_nonlinear_probabilistic_scorer(bench: &mut Criterion) {
8704 let logger = TestLogger::new();
8705 let (network_graph, scorer) = bench_utils::read_graph_scorer(&logger).unwrap();
8706 let mut params = ProbabilisticScoringFeeParameters::default();
8707 params.linear_success_probability = false;
8708 generate_routes(bench, &network_graph, scorer, ¶ms,
8709 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 0,
8710 "generate_routes_with_nonlinear_probabilistic_scorer");
8713 pub fn generate_mpp_routes_with_nonlinear_probabilistic_scorer(bench: &mut Criterion) {
8714 let logger = TestLogger::new();
8715 let (network_graph, scorer) = bench_utils::read_graph_scorer(&logger).unwrap();
8716 let mut params = ProbabilisticScoringFeeParameters::default();
8717 params.linear_success_probability = false;
8718 generate_routes(bench, &network_graph, scorer, ¶ms,
8719 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 0,
8720 "generate_mpp_routes_with_nonlinear_probabilistic_scorer");
8723 pub fn generate_large_mpp_routes_with_nonlinear_probabilistic_scorer(bench: &mut Criterion) {
8724 let logger = TestLogger::new();
8725 let (network_graph, scorer) = bench_utils::read_graph_scorer(&logger).unwrap();
8726 let mut params = ProbabilisticScoringFeeParameters::default();
8727 params.linear_success_probability = false;
8728 generate_routes(bench, &network_graph, scorer, ¶ms,
8729 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 100_000_000,
8730 "generate_large_mpp_routes_with_nonlinear_probabilistic_scorer");
8733 fn generate_routes<S: ScoreLookUp + ScoreUpdate>(
8734 bench: &mut Criterion, graph: &NetworkGraph<&TestLogger>, mut scorer: S,
8735 score_params: &S::ScoreParams, features: Bolt11InvoiceFeatures, starting_amount: u64,
8736 bench_name: &'static str,
8738 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
8739 let route_endpoints = bench_utils::generate_test_routes(graph, &mut scorer, score_params, features, 0xdeadbeef, starting_amount, 50);
8741 // ...then benchmark finding paths between the nodes we learned.
8742 do_route_bench(bench, graph, scorer, score_params, bench_name, route_endpoints);
8746 fn do_route_bench<S: ScoreLookUp + ScoreUpdate>(
8747 bench: &mut Criterion, graph: &NetworkGraph<&TestLogger>, scorer: S,
8748 score_params: &S::ScoreParams, bench_name: &'static str,
8749 route_endpoints: Vec<(ChannelDetails, PaymentParameters, u64)>,
8751 let payer = bench_utils::payer_pubkey();
8752 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
8753 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8756 bench.bench_function(bench_name, |b| b.iter(|| {
8757 let (first_hop, params, amt) = &route_endpoints[idx % route_endpoints.len()];
8758 let route_params = RouteParameters::from_payment_params_and_value(params.clone(), *amt);
8759 assert!(get_route(&payer, &route_params, &graph.read_only(), Some(&[first_hop]),
8760 &DummyLogger{}, &scorer, score_params, &random_seed_bytes).is_ok());